1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-29 22:01:14 +03:00

Split the core crate

This commit is contained in:
Quentin Gliech
2021-12-17 18:04:30 +01:00
parent ceb17d3646
commit 2f97ca685d
45 changed files with 418 additions and 408 deletions

View File

@ -0,0 +1,56 @@
[package]
name = "mas-handlers"
version = "0.1.0"
authors = ["Quentin Gliech <quenting@element.io>"]
edition = "2021"
license = "Apache-2.0"
[features]
dev = ["mas-static-files/dev", "mas-templates/dev"]
[dependencies]
# Async runtime
tokio = { version = "1.14.0", features = ["macros"] }
# Logging and tracing
tracing = "0.1.29"
# Error management
thiserror = "1.0.30"
anyhow = "1.0.51"
# Web server
warp = "0.3.2"
hyper = { version = "0.14.16", features = ["full"] }
# Database access
sqlx = { version = "0.5.9", features = ["runtime-tokio-rustls", "postgres"] }
# Various structure (de)serialization
serde = { version = "1.0.131", features = ["derive"] }
serde_with = { version = "1.11.0", features = ["hex", "chrono"] }
serde_json = "1.0.72"
serde_urlencoded = "0.7.0"
# Password hashing
argon2 = { version = "0.3.2", features = ["password-hash"] }
# Crypto, hashing and signing stuff
sha2 = "0.10.0"
jwt-compact = { version = "0.5.0-beta.1", features = ["with_rsa", "k256"] }
# Various data types and utilities
data-encoding = "2.3.2"
chrono = { version = "0.4.19", features = ["serde"] }
url = { version = "2.2.2", features = ["serde"] }
mime = "0.3.16"
rand = "0.8.4"
headers = "0.3.5"
oauth2-types = { path = "../oauth2-types" }
mas-config = { path = "../config" }
mas-data-model = { path = "../data-model" }
mas-templates = { path = "../templates" }
mas-static-files = { path = "../static-files" }
mas-storage = { path = "../storage" }
mas-warp-utils = { path = "../warp-utils" }

View File

@ -0,0 +1,39 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use hyper::header::CONTENT_TYPE;
use mas_warp_utils::{errors::WrapError, filters::database::connection};
use mime::TEXT_PLAIN;
use sqlx::{pool::PoolConnection, PgPool, Postgres};
use tracing::{info_span, Instrument};
use warp::{filters::BoxedFilter, reply::with_header, Filter, Rejection, Reply};
pub fn filter(pool: &PgPool) -> BoxedFilter<(impl Reply,)> {
warp::path!("health")
.and(warp::get())
.and(connection(pool))
.and_then(get)
.boxed()
}
async fn get(mut conn: PoolConnection<Postgres>) -> Result<impl Reply, Rejection> {
sqlx::query("SELECT $1")
.bind(1_i64)
.execute(&mut conn)
.instrument(info_span!("DB health"))
.await
.wrap_error()?;
Ok(with_header("ok", CONTENT_TYPE, TEXT_PLAIN.to_string()))
}

View File

@ -0,0 +1,55 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![forbid(unsafe_code)]
#![deny(clippy::all)]
#![deny(rustdoc::broken_intra_doc_links)]
#![warn(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::implicit_hasher)]
#![allow(clippy::unused_async)] // Some warp filters need that
use mas_config::RootConfig;
use mas_static_files::filter as static_files;
use mas_templates::Templates;
use sqlx::PgPool;
use warp::{filters::BoxedFilter, Filter, Reply};
mod health;
mod oauth2;
mod views;
use self::{health::filter as health, oauth2::filter as oauth2, views::filter as views};
#[must_use]
pub fn root(
pool: &PgPool,
templates: &Templates,
config: &RootConfig,
) -> BoxedFilter<(impl Reply,)> {
health(pool)
.or(oauth2(pool, templates, &config.oauth2, &config.cookies))
.or(views(
pool,
templates,
&config.oauth2,
&config.csrf,
&config.cookies,
))
.or(static_files(config.http.web_root.clone()))
.with(warp::log(module_path!()))
.boxed()
}

View File

@ -0,0 +1,570 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::{HashMap, HashSet};
use chrono::Duration;
use hyper::{
header::LOCATION,
http::uri::{Parts, PathAndQuery, Uri},
StatusCode,
};
use mas_config::{CookiesConfig, OAuth2ClientConfig, OAuth2Config};
use mas_data_model::{
Authentication, AuthorizationCode, AuthorizationGrant, AuthorizationGrantStage, BrowserSession,
Pkce, StorageBackend, TokenType,
};
use mas_storage::{
oauth2::{
access_token::add_access_token,
authorization_grant::{
derive_session, fulfill_grant, get_grant_by_id, new_authorization_grant,
},
refresh_token::add_refresh_token,
},
PostgresqlBackend,
};
use mas_templates::{FormPostContext, Templates};
use mas_warp_utils::{
errors::WrapError,
filters::{
database::transaction,
session::{optional_session, session},
with_templates,
},
};
use oauth2_types::{
errors::{
ErrorResponse, InvalidGrant, InvalidRequest, LoginRequired, OAuth2Error,
RegistrationNotSupported, RequestNotSupported, RequestUriNotSupported,
},
pkce,
requests::{
AccessTokenResponse, AuthorizationRequest, AuthorizationResponse, Prompt, ResponseMode,
ResponseType,
},
scope::ScopeToken,
};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::{PgExecutor, PgPool, Postgres, Transaction};
use url::Url;
use warp::{
redirect::see_other,
reject::InvalidQuery,
reply::{html, with_header},
Filter, Rejection, Reply,
};
use crate::views::{LoginRequest, PostAuthAction, ReauthRequest};
#[derive(Deserialize)]
struct PartialParams {
client_id: Option<String>,
redirect_uri: Option<String>,
state: Option<String>,
/*
response_type: Option<String>,
response_mode: Option<String>,
*/
}
enum ReplyOrBackToClient {
Reply(Box<dyn Reply>),
BackToClient {
params: Value,
redirect_uri: Url,
response_mode: ResponseMode,
state: Option<String>,
},
Error(Box<dyn OAuth2Error>),
}
async fn back_to_client<T>(
mut redirect_uri: Url,
response_mode: ResponseMode,
state: Option<String>,
params: T,
templates: &Templates,
) -> anyhow::Result<Box<dyn Reply>>
where
T: Serialize,
{
#[derive(Serialize)]
struct AllParams<'s, T> {
#[serde(flatten, skip_serializing_if = "Option::is_none")]
existing: Option<HashMap<&'s str, &'s str>>,
#[serde(skip_serializing_if = "Option::is_none")]
state: Option<String>,
#[serde(flatten)]
params: T,
}
#[derive(Serialize)]
struct ParamsWithState<T> {
#[serde(skip_serializing_if = "Option::is_none")]
state: Option<String>,
#[serde(flatten)]
params: T,
}
match response_mode {
ResponseMode::Query => {
let existing: Option<HashMap<&str, &str>> = redirect_uri
.query()
.map(serde_urlencoded::from_str)
.transpose()?;
let merged = AllParams {
existing,
state,
params,
};
let new_qs = serde_urlencoded::to_string(merged)?;
redirect_uri.set_query(Some(&new_qs));
Ok(Box::new(with_header(
StatusCode::SEE_OTHER,
LOCATION,
redirect_uri.as_str(),
)))
}
ResponseMode::Fragment => {
let existing: Option<HashMap<&str, &str>> = redirect_uri
.fragment()
.map(serde_urlencoded::from_str)
.transpose()?;
let merged = AllParams {
existing,
state,
params,
};
let new_qs = serde_urlencoded::to_string(merged)?;
redirect_uri.set_fragment(Some(&new_qs));
Ok(Box::new(with_header(
StatusCode::SEE_OTHER,
LOCATION,
redirect_uri.as_str(),
)))
}
ResponseMode::FormPost => {
let merged = ParamsWithState { state, params };
let ctx = FormPostContext::new(redirect_uri, merged);
let rendered = templates.render_form_post(&ctx).await?;
Ok(Box::new(html(rendered)))
}
}
}
#[derive(Deserialize)]
struct Params {
#[serde(flatten)]
auth: AuthorizationRequest,
#[serde(flatten)]
pkce: Option<pkce::AuthorizationRequest>,
}
/// Given a list of response types and an optional user-defined response mode,
/// figure out what response mode must be used, and emit an error if the
/// suggested response mode isn't allowed for the given response types.
fn resolve_response_mode(
response_type: &HashSet<ResponseType>,
suggested_response_mode: Option<ResponseMode>,
) -> anyhow::Result<ResponseMode> {
use ResponseMode as M;
use ResponseType as T;
// If the response type includes either "token" or "id_token", the default
// response mode is "fragment" and the response mode "query" must not be
// used
if response_type.contains(&T::Token) || response_type.contains(&T::IdToken) {
match suggested_response_mode {
None => Ok(M::Fragment),
Some(M::Query) => Err(anyhow::anyhow!("invalid response mode")),
Some(mode) => Ok(mode),
}
} else {
// In other cases, all response modes are allowed, defaulting to "query"
Ok(suggested_response_mode.unwrap_or(M::Query))
}
}
pub fn filter(
pool: &PgPool,
templates: &Templates,
oauth2_config: &OAuth2Config,
cookies_config: &CookiesConfig,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let clients = oauth2_config.clients.clone();
let authorize = warp::path!("oauth2" / "authorize")
.and(warp::get())
.map(move || clients.clone())
.and(warp::query())
.and(optional_session(pool, cookies_config))
.and(transaction(pool))
.and_then(get);
let step = warp::path!("oauth2" / "authorize" / "step")
.and(warp::get())
.and(warp::query())
.and(session(pool, cookies_config))
.and(transaction(pool))
.and_then(step);
let clients = oauth2_config.clients.clone();
authorize
.or(step)
.unify()
.recover(recover)
.unify()
.and(warp::query())
.and(warp::any().map(move || clients.clone()))
.and(with_templates(templates))
.and_then(actually_reply)
}
async fn recover(rejection: Rejection) -> Result<ReplyOrBackToClient, Rejection> {
if rejection.find::<InvalidQuery>().is_some() {
Ok(ReplyOrBackToClient::Error(Box::new(InvalidRequest)))
} else {
Err(rejection)
}
}
async fn actually_reply(
rep: ReplyOrBackToClient,
q: PartialParams,
clients: Vec<OAuth2ClientConfig>,
templates: Templates,
) -> Result<impl Reply, Rejection> {
let (redirect_uri, response_mode, state, params) = match rep {
ReplyOrBackToClient::Reply(r) => return Ok(r),
ReplyOrBackToClient::BackToClient {
redirect_uri,
response_mode,
params,
state,
} => (redirect_uri, response_mode, state, params),
ReplyOrBackToClient::Error(error) => {
let PartialParams {
client_id,
redirect_uri,
state,
..
} = q;
// First, disover the client
let client = client_id.and_then(|client_id| {
clients
.into_iter()
.find(|client| client.client_id == client_id)
});
let client = match client {
Some(client) => client,
None => return Ok(Box::new(html(templates.render_error(&error.into()).await?))),
};
let redirect_uri: Result<Option<Url>, _> = redirect_uri.map(|r| r.parse()).transpose();
let redirect_uri = match redirect_uri {
Ok(r) => r,
Err(_) => return Ok(Box::new(html(templates.render_error(&error.into()).await?))),
};
let redirect_uri = client.resolve_redirect_uri(&redirect_uri);
let redirect_uri = match redirect_uri {
Ok(r) => r,
Err(_) => return Ok(Box::new(html(templates.render_error(&error.into()).await?))),
};
let reply: ErrorResponse = error.into();
let reply = serde_json::to_value(&reply).wrap_error()?;
// TODO: resolve response mode
(redirect_uri.clone(), ResponseMode::Query, state, reply)
}
};
back_to_client(redirect_uri, response_mode, state, params, &templates)
.await
.wrap_error()
}
async fn get(
clients: Vec<OAuth2ClientConfig>,
params: Params,
maybe_session: Option<BrowserSession<PostgresqlBackend>>,
mut txn: Transaction<'_, Postgres>,
) -> Result<ReplyOrBackToClient, Rejection> {
// Check if the request/request_uri/registration params are used. If so, reply
// with the right error since we don't support them.
if params.auth.request.is_some() {
return Ok(ReplyOrBackToClient::Error(Box::new(RequestNotSupported)));
}
if params.auth.request_uri.is_some() {
return Ok(ReplyOrBackToClient::Error(Box::new(RequestUriNotSupported)));
}
if params.auth.registration.is_some() {
return Ok(ReplyOrBackToClient::Error(Box::new(
RegistrationNotSupported,
)));
}
// First, find out what client it is
let client = clients
.into_iter()
.find(|client| client.client_id == params.auth.client_id)
.ok_or_else(|| anyhow::anyhow!("could not find client"))
.wrap_error()?;
let redirect_uri = client
.resolve_redirect_uri(&params.auth.redirect_uri)
.wrap_error()?;
let response_type = &params.auth.response_type;
let response_mode =
resolve_response_mode(response_type, params.auth.response_mode).wrap_error()?;
let code: Option<AuthorizationCode> = if response_type.contains(&ResponseType::Code) {
// 32 random alphanumeric characters, about 190bit of entropy
let code: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(32)
.map(char::from)
.collect();
let pkce = params.pkce.map(|p| Pkce {
challenge: p.code_challenge,
challenge_method: p.code_challenge_method,
});
Some(AuthorizationCode { code, pkce })
} else {
// If the request had PKCE params but no code asked, it should get back with an
// error
if params.pkce.is_some() {
return Ok(ReplyOrBackToClient::Error(Box::new(InvalidGrant)));
}
None
};
// Generate the device ID
// TODO: this should probably be done somewhere else?
let device_id: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.map(char::from)
.collect();
let device_scope: ScopeToken = format!("urn:matrix:device:{}", device_id)
.parse()
.wrap_error()?;
let scope = {
let mut s = params.auth.scope.clone();
s.insert(device_scope);
s
};
let grant = new_authorization_grant(
&mut txn,
client.client_id.clone(),
redirect_uri.clone(),
scope,
code,
params.auth.state,
params.auth.nonce,
params.auth.max_age,
None,
response_mode,
response_type.contains(&ResponseType::Token),
response_type.contains(&ResponseType::IdToken),
)
.await
.wrap_error()?;
let next = ContinueAuthorizationGrant::from_authorization_grant(grant);
match (maybe_session, params.auth.prompt) {
(None, Some(Prompt::None)) => {
// If there is no session and prompt=none was asked, go back to the client
txn.commit().await.wrap_error()?;
Ok(ReplyOrBackToClient::Error(Box::new(LoginRequired)))
}
(Some(_), Some(Prompt::Login | Prompt::Consent | Prompt::SelectAccount)) => {
// We're already logged in but login|consent|select_account was asked, reauth
// TODO: better pages here
txn.commit().await.wrap_error()?;
let next: PostAuthAction<_> = next.into();
let next: ReauthRequest<_> = next.into();
let next = next.build_uri().wrap_error()?;
Ok(ReplyOrBackToClient::Reply(Box::new(see_other(next))))
}
(Some(user_session), _) => {
// Other cases where we already have a session
step(next, user_session, txn).await
}
(None, _) => {
// Other cases where we don't have a session, ask for a login
txn.commit().await.wrap_error()?;
let next: PostAuthAction<_> = next.into();
let next: LoginRequest<_> = next.into();
let next = next.build_uri().wrap_error()?;
Ok(ReplyOrBackToClient::Reply(Box::new(see_other(next))))
}
}
}
#[derive(Serialize, Deserialize, Clone)]
pub(crate) struct ContinueAuthorizationGrant<S: StorageBackend> {
#[serde(
with = "serde_with::rust::display_fromstr",
bound(
deserialize = "S::AuthorizationGrantData: std::str::FromStr,
<S::AuthorizationGrantData as std::str::FromStr>::Err: std::fmt::Display",
serialize = "S::AuthorizationGrantData: std::fmt::Display"
)
)]
data: S::AuthorizationGrantData,
}
impl<S: StorageBackend> ContinueAuthorizationGrant<S> {
pub fn from_authorization_grant(grant: AuthorizationGrant<S>) -> Self {
Self { data: grant.data }
}
pub fn build_uri(&self) -> anyhow::Result<Uri>
where
S::AuthorizationGrantData: std::fmt::Display,
{
let qs = serde_urlencoded::to_string(self)?;
let path_and_query = PathAndQuery::try_from(format!("/oauth2/authorize/step?{}", qs))?;
let uri = Uri::from_parts({
let mut parts = Parts::default();
parts.path_and_query = Some(path_and_query);
parts
})?;
Ok(uri)
}
}
impl ContinueAuthorizationGrant<PostgresqlBackend> {
pub async fn fetch_authorization_grant(
&self,
executor: impl PgExecutor<'_>,
) -> anyhow::Result<AuthorizationGrant<PostgresqlBackend>> {
get_grant_by_id(executor, self.data).await
}
}
async fn step(
next: ContinueAuthorizationGrant<PostgresqlBackend>,
browser_session: BrowserSession<PostgresqlBackend>,
mut txn: Transaction<'_, Postgres>,
) -> Result<ReplyOrBackToClient, Rejection> {
// TODO: we should check if the grant here was started by the browser doing that
// request using a signed cookie
let grant = next
.fetch_authorization_grant(&mut txn)
.await
.wrap_error()?;
if !matches!(grant.stage, AuthorizationGrantStage::Pending) {
return Err(anyhow::anyhow!("authorization grant not pending")).wrap_error();
}
let reply = match browser_session.last_authentication {
Some(Authentication { created_at, .. }) if created_at > grant.max_auth_time() => {
let session = derive_session(&mut txn, &grant, browser_session)
.await
.wrap_error()?;
let grant = fulfill_grant(&mut txn, grant, session.clone())
.await
.wrap_error()?;
// Yep! Let's complete the auth now
let mut params = AuthorizationResponse::default();
// Did they request an auth code?
if let Some(code) = grant.code {
params.code = Some(code.code);
}
// Did they request an access token?
if grant.response_type_token {
let ttl = Duration::minutes(5);
let (access_token_str, refresh_token_str) = {
let mut rng = thread_rng();
(
TokenType::AccessToken.generate(&mut rng),
TokenType::RefreshToken.generate(&mut rng),
)
};
let access_token = add_access_token(&mut txn, &session, &access_token_str, ttl)
.await
.wrap_error()?;
let _refresh_token =
add_refresh_token(&mut txn, &session, access_token, &refresh_token_str)
.await
.wrap_error()?;
params.response = Some(
AccessTokenResponse::new(access_token_str)
.with_expires_in(ttl)
.with_refresh_token(refresh_token_str),
);
}
// Did they request an ID token?
if grant.response_type_id_token {
todo!("id tokens are not implemented yet");
}
let params = serde_json::to_value(&params).unwrap();
ReplyOrBackToClient::BackToClient {
redirect_uri: grant.redirect_uri,
response_mode: grant.response_mode,
state: grant.state,
params,
}
}
_ => {
let next: PostAuthAction<_> = next.into();
let next: ReauthRequest<_> = next.into();
let next = next.build_uri().wrap_error()?;
ReplyOrBackToClient::Reply(Box::new(see_other(next)))
}
};
txn.commit().await.wrap_error()?;
Ok(reply)
}

View File

@ -0,0 +1,105 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use hyper::Method;
use mas_config::OAuth2Config;
use mas_warp_utils::filters::cors::cors;
use oauth2_types::{
oidc::{Metadata, SigningAlgorithm},
pkce::CodeChallengeMethod,
requests::{ClientAuthenticationMethod, GrantType, ResponseMode},
};
use warp::{Filter, Rejection, Reply};
pub(super) fn filter(
config: &OAuth2Config,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let base = config.issuer.clone();
let response_modes_supported = Some({
let mut s = HashSet::new();
s.insert(ResponseMode::FormPost);
s.insert(ResponseMode::Query);
s.insert(ResponseMode::Fragment);
s
});
let response_types_supported = Some({
let mut s = HashSet::new();
s.insert("code".to_string());
s.insert("token".to_string());
s.insert("id_token".to_string());
s.insert("code token".to_string());
s.insert("code id_token".to_string());
s.insert("token id_token".to_string());
s.insert("code token id_token".to_string());
s
});
let grant_types_supported = Some({
let mut s = HashSet::new();
s.insert(GrantType::AuthorizationCode);
s.insert(GrantType::RefreshToken);
s
});
let token_endpoint_auth_methods_supported = Some({
let mut s = HashSet::new();
s.insert(ClientAuthenticationMethod::ClientSecretBasic);
s.insert(ClientAuthenticationMethod::ClientSecretPost);
s.insert(ClientAuthenticationMethod::ClientSecretJwt);
s.insert(ClientAuthenticationMethod::None);
s
});
let token_endpoint_auth_signing_alg_values_supported = Some({
let mut s = HashSet::new();
s.insert(SigningAlgorithm::Hs256);
s.insert(SigningAlgorithm::Hs384);
s.insert(SigningAlgorithm::Hs512);
s
});
let code_challenge_methods_supported = Some({
let mut s = HashSet::new();
s.insert(CodeChallengeMethod::Plain);
s.insert(CodeChallengeMethod::S256);
s
});
let metadata = Metadata {
authorization_endpoint: base.join("oauth2/authorize").ok(),
token_endpoint: base.join("oauth2/token").ok(),
jwks_uri: base.join("oauth2/keys.json").ok(),
introspection_endpoint: base.join("oauth2/introspect").ok(),
userinfo_endpoint: base.join("oauth2/userinfo").ok(),
issuer: base,
registration_endpoint: None,
scopes_supported: None,
response_types_supported,
response_modes_supported,
grant_types_supported,
token_endpoint_auth_methods_supported,
token_endpoint_auth_signing_alg_values_supported,
code_challenge_methods_supported,
};
warp::path!(".well-known" / "openid-configuration").and(
warp::get()
.map(move || warp::reply::json(&metadata))
.with(cors().allow_method(Method::GET)),
)
}

View File

@ -0,0 +1,142 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use hyper::Method;
use mas_config::{OAuth2ClientConfig, OAuth2Config};
use mas_data_model::TokenType;
use mas_storage::oauth2::{
access_token::lookup_active_access_token, refresh_token::lookup_active_refresh_token,
};
use mas_warp_utils::{
errors::WrapError,
filters::{client::client_authentication, cors::cors, database::connection},
};
use oauth2_types::requests::{
ClientAuthenticationMethod, IntrospectionRequest, IntrospectionResponse, TokenTypeHint,
};
use sqlx::{pool::PoolConnection, PgPool, Postgres};
use tracing::{info, warn};
use warp::{Filter, Rejection, Reply};
pub fn filter(
pool: &PgPool,
oauth2_config: &OAuth2Config,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let audience = oauth2_config
.issuer
.join("/oauth2/introspect")
.unwrap()
.to_string();
warp::path!("oauth2" / "introspect").and(
warp::post()
.and(connection(pool))
.and(client_authentication(oauth2_config, audience))
.and_then(introspect)
.recover(recover)
.with(cors().allow_method(Method::POST)),
)
}
const INACTIVE: IntrospectionResponse = IntrospectionResponse {
active: false,
scope: None,
client_id: None,
username: None,
token_type: None,
exp: None,
iat: None,
nbf: None,
sub: None,
aud: None,
iss: None,
jti: None,
};
async fn introspect(
mut conn: PoolConnection<Postgres>,
auth: ClientAuthenticationMethod,
client: OAuth2ClientConfig,
params: IntrospectionRequest,
) -> Result<impl Reply, Rejection> {
// Token introspection is only allowed by confidential clients
if auth.public() {
warn!(?client, "Client tried to introspect");
// TODO: have a nice error here
return Ok(warp::reply::json(&INACTIVE));
}
let token = &params.token;
let token_type = TokenType::check(token).wrap_error()?;
if let Some(hint) = params.token_type_hint {
if token_type != hint {
info!("Token type hint did not match");
return Ok(warp::reply::json(&INACTIVE));
}
}
let reply = match token_type {
TokenType::AccessToken => {
let (token, session) = lookup_active_access_token(&mut conn, token)
.await
.wrap_error()?;
let exp = token.exp();
IntrospectionResponse {
active: true,
scope: Some(session.scope),
client_id: Some(session.client.client_id),
username: Some(session.browser_session.user.username),
token_type: Some(TokenTypeHint::AccessToken),
exp: Some(exp),
iat: Some(token.created_at),
nbf: Some(token.created_at),
sub: Some(session.browser_session.user.sub),
aud: None,
iss: None,
jti: None,
}
}
TokenType::RefreshToken => {
let (token, session) = lookup_active_refresh_token(&mut conn, token)
.await
.wrap_error()?;
IntrospectionResponse {
active: true,
scope: Some(session.scope),
client_id: Some(session.client.client_id),
username: Some(session.browser_session.user.username),
token_type: Some(TokenTypeHint::RefreshToken),
exp: None,
iat: Some(token.created_at),
nbf: Some(token.created_at),
sub: Some(session.browser_session.user.sub),
aud: None,
iss: None,
jti: None,
}
}
};
Ok(warp::reply::json(&reply))
}
async fn recover(rejection: Rejection) -> Result<impl Reply, Rejection> {
if rejection.is_not_found() {
Err(rejection)
} else {
Ok(warp::reply::json(&INACTIVE))
}
}

View File

@ -0,0 +1,30 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use hyper::Method;
use mas_config::OAuth2Config;
use mas_warp_utils::filters::cors::cors;
use warp::{Filter, Rejection, Reply};
pub(super) fn filter(
config: &OAuth2Config,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let jwks = config.keys.to_public_jwks();
warp::path!("oauth2" / "keys.json").and(
warp::get()
.map(move || warp::reply::json(&jwks))
.with(cors().allow_method(Method::GET)),
)
}

View File

@ -0,0 +1,52 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use mas_config::{CookiesConfig, OAuth2Config};
use mas_templates::Templates;
use sqlx::PgPool;
use warp::{filters::BoxedFilter, Filter, Reply};
mod authorization;
mod discovery;
mod introspection;
mod keys;
mod token;
mod userinfo;
pub(crate) use self::authorization::ContinueAuthorizationGrant;
use self::{
authorization::filter as authorization, discovery::filter as discovery,
introspection::filter as introspection, keys::filter as keys, token::filter as token,
userinfo::filter as userinfo,
};
pub fn filter(
pool: &PgPool,
templates: &Templates,
oauth2_config: &OAuth2Config,
cookies_config: &CookiesConfig,
) -> BoxedFilter<(impl Reply,)> {
discovery(oauth2_config)
.or(keys(oauth2_config))
.or(authorization(
pool,
templates,
oauth2_config,
cookies_config,
))
.or(userinfo(pool, oauth2_config))
.or(introspection(pool, oauth2_config))
.or(token(pool, oauth2_config))
.boxed()
}

View File

@ -0,0 +1,341 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use anyhow::Context;
use chrono::{DateTime, Duration, Utc};
use data_encoding::BASE64URL_NOPAD;
use headers::{CacheControl, Pragma};
use hyper::{Method, StatusCode};
use jwt_compact::{Claims, Header, TimeOptions};
use mas_config::{KeySet, OAuth2ClientConfig, OAuth2Config};
use mas_data_model::{AuthorizationGrantStage, TokenType};
use mas_storage::{
oauth2::{
access_token::{add_access_token, revoke_access_token},
authorization_grant::{exchange_grant, lookup_grant_by_code},
refresh_token::{add_refresh_token, lookup_active_refresh_token, replace_refresh_token},
},
DatabaseInconsistencyError,
};
use mas_warp_utils::{
errors::WrapError,
filters::{client::client_authentication, cors::cors, database::connection, with_keys},
reply::with_typed_header,
};
use oauth2_types::{
errors::{InvalidGrant, InvalidRequest, OAuth2Error, OAuth2ErrorCode, UnauthorizedClient},
requests::{
AccessTokenRequest, AccessTokenResponse, AuthorizationCodeGrant,
ClientAuthenticationMethod, RefreshTokenGrant,
},
scope::OPENID,
};
use rand::thread_rng;
use serde::Serialize;
use serde_with::{serde_as, skip_serializing_none};
use sha2::{Digest, Sha256};
use sqlx::{pool::PoolConnection, Acquire, PgPool, Postgres};
use tracing::debug;
use url::Url;
use warp::{
reject::Reject,
reply::{json, with_status},
Filter, Rejection, Reply,
};
#[serde_as]
#[skip_serializing_none]
#[derive(Serialize, Debug)]
struct CustomClaims {
#[serde(rename = "iss")]
issuer: Url,
#[serde(rename = "sub")]
subject: String,
#[serde(rename = "aud")]
audiences: Vec<String>,
nonce: Option<String>,
#[serde_as(as = "Option<serde_with::TimestampSeconds>")]
auth_time: Option<DateTime<Utc>>,
at_hash: String,
c_hash: String,
}
#[derive(Debug)]
struct Error {
json: serde_json::Value,
status: StatusCode,
}
impl Reject for Error {}
fn error<T, E>(e: E) -> Result<T, Rejection>
where
E: OAuth2ErrorCode + 'static,
{
let status = e.status();
let json = serde_json::to_value(e.into_response()).wrap_error()?;
Err(Error { json, status }.into())
}
pub fn filter(
pool: &PgPool,
oauth2_config: &OAuth2Config,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let audience = oauth2_config
.issuer
.join("/oauth2/token")
.unwrap()
.to_string();
let issuer = oauth2_config.issuer.clone();
warp::path!("oauth2" / "token").and(
warp::post()
.and(client_authentication(oauth2_config, audience))
.and(with_keys(oauth2_config))
.and(warp::any().map(move || issuer.clone()))
.and(connection(pool))
.and_then(token)
.recover(recover)
.with(cors().allow_method(Method::POST)),
)
}
async fn recover(rejection: Rejection) -> Result<impl Reply, Rejection> {
if let Some(Error { json, status }) = rejection.find::<Error>() {
Ok(with_status(warp::reply::json(json), *status))
} else {
Err(rejection)
}
}
async fn token(
_auth: ClientAuthenticationMethod,
client: OAuth2ClientConfig,
req: AccessTokenRequest,
keys: KeySet,
issuer: Url,
mut conn: PoolConnection<Postgres>,
) -> Result<impl Reply, Rejection> {
let reply = match req {
AccessTokenRequest::AuthorizationCode(grant) => {
let reply = authorization_code_grant(&grant, &client, &keys, issuer, &mut conn).await?;
json(&reply)
}
AccessTokenRequest::RefreshToken(grant) => {
let reply = refresh_token_grant(&grant, &client, &mut conn).await?;
json(&reply)
}
_ => {
let reply = InvalidGrant.into_response();
json(&reply)
}
};
let reply = with_typed_header(CacheControl::new().with_no_store(), reply);
let reply = with_typed_header(Pragma::no_cache(), reply);
Ok(reply)
}
fn hash<H: Digest>(mut hasher: H, token: &str) -> anyhow::Result<String> {
hasher.update(token);
let hash = hasher.finalize();
// Left-most 128bit
let bits = hash
.get(..16)
.context("failed to get first 128 bits of hash")?;
Ok(BASE64URL_NOPAD.encode(bits))
}
async fn authorization_code_grant(
grant: &AuthorizationCodeGrant,
client: &OAuth2ClientConfig,
keys: &KeySet,
issuer: Url,
conn: &mut PoolConnection<Postgres>,
) -> Result<AccessTokenResponse, Rejection> {
// TODO: there is a bunch of unnecessary cloning here
let mut txn = conn.begin().await.wrap_error()?;
// TODO: handle "not found" cases
let authz_grant = lookup_grant_by_code(&mut txn, &grant.code)
.await
.wrap_error()?;
let session = match authz_grant.stage {
AuthorizationGrantStage::Cancelled { cancelled_at } => {
debug!(%cancelled_at, "Authorization grant was cancelled");
return error(InvalidGrant);
}
AuthorizationGrantStage::Exchanged {
exchanged_at,
fulfilled_at,
session: _,
} => {
// TODO: we should invalidate the existing session if a code is used twice after
// some period of time. See the `oidcc-codereuse-30seconds` test from the
// conformance suite
debug!(%exchanged_at, %fulfilled_at, "Authorization code was already exchanged");
return error(InvalidGrant);
}
AuthorizationGrantStage::Pending => {
debug!("Authorization grant has not been fulfilled yet");
return error(InvalidGrant);
}
AuthorizationGrantStage::Fulfilled {
ref session,
fulfilled_at: _,
} => {
// TODO: we should check that the session was not fullfilled too long ago
// (30s to 1min?). The main problem is getting a timestamp from the database
session
}
};
// This should never happen, since we looked up in the database using the code
let code = authz_grant
.code
.as_ref()
.ok_or(DatabaseInconsistencyError)
.wrap_error()?;
if client.client_id != session.client.client_id {
return error(UnauthorizedClient);
}
match (code.pkce.as_ref(), grant.code_verifier.as_ref()) {
(None, None) => {}
// We have a challenge but no verifier (or vice-versa)? Bad request.
(Some(_), None) | (None, Some(_)) => return error(InvalidRequest),
// If we have both, we need to check the code validity
(Some(pkce), Some(verifier)) => {
if !pkce.verify(verifier) {
return error(InvalidRequest);
}
}
};
let browser_session = &session.browser_session;
let ttl = Duration::minutes(5);
let (access_token_str, refresh_token_str) = {
let mut rng = thread_rng();
(
TokenType::AccessToken.generate(&mut rng),
TokenType::RefreshToken.generate(&mut rng),
)
};
let access_token = add_access_token(&mut txn, session, &access_token_str, ttl)
.await
.wrap_error()?;
let _refresh_token = add_refresh_token(&mut txn, session, access_token, &refresh_token_str)
.await
.wrap_error()?;
let id_token = if session.scope.contains(&OPENID) {
let header = Header::default();
let options = TimeOptions::default();
let claims = Claims::new(CustomClaims {
issuer,
subject: browser_session.user.sub.clone(),
audiences: vec![client.client_id.clone()],
nonce: authz_grant.nonce.clone(),
auth_time: browser_session
.last_authentication
.as_ref()
.map(|a| a.created_at),
at_hash: hash(Sha256::new(), &access_token_str).wrap_error()?,
c_hash: hash(Sha256::new(), &grant.code).wrap_error()?,
})
.set_duration_and_issuance(&options, Duration::minutes(30));
let id_token = keys
.token(mas_config::Algorithm::Rs256, header, claims)
.await
.context("could not sign ID token")
.wrap_error()?;
Some(id_token)
} else {
None
};
let mut params = AccessTokenResponse::new(access_token_str)
.with_expires_in(ttl)
.with_refresh_token(refresh_token_str)
.with_scope(session.scope.clone());
if let Some(id_token) = id_token {
params = params.with_id_token(id_token);
}
exchange_grant(&mut txn, authz_grant).await.wrap_error()?;
txn.commit().await.wrap_error()?;
Ok(params)
}
async fn refresh_token_grant(
grant: &RefreshTokenGrant,
client: &OAuth2ClientConfig,
conn: &mut PoolConnection<Postgres>,
) -> Result<AccessTokenResponse, Rejection> {
let mut txn = conn.begin().await.wrap_error()?;
let (refresh_token, session) = lookup_active_refresh_token(&mut txn, &grant.refresh_token)
.await
.wrap_error()?;
if client.client_id != session.client.client_id {
// As per https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
return error(InvalidGrant);
}
let ttl = Duration::minutes(5);
let (access_token_str, refresh_token_str) = {
let mut rng = thread_rng();
(
TokenType::AccessToken.generate(&mut rng),
TokenType::RefreshToken.generate(&mut rng),
)
};
let new_access_token = add_access_token(&mut txn, &session, &access_token_str, ttl)
.await
.wrap_error()?;
let new_refresh_token =
add_refresh_token(&mut txn, &session, new_access_token, &refresh_token_str)
.await
.wrap_error()?;
replace_refresh_token(&mut txn, &refresh_token, &new_refresh_token)
.await
.wrap_error()?;
if let Some(access_token) = refresh_token.access_token {
revoke_access_token(&mut txn, &access_token)
.await
.wrap_error()?;
}
let params = AccessTokenResponse::new(access_token_str)
.with_expires_in(ttl)
.with_refresh_token(refresh_token_str)
.with_scope(session.scope);
txn.commit().await.wrap_error()?;
Ok(params)
}

View File

@ -0,0 +1,57 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use hyper::Method;
use mas_config::OAuth2Config;
use mas_data_model::{AccessToken, Session};
use mas_storage::PostgresqlBackend;
use mas_warp_utils::filters::{
authenticate::{authentication, recover_unauthorized},
cors::cors,
};
use serde::Serialize;
use sqlx::PgPool;
use warp::{Filter, Rejection, Reply};
#[derive(Serialize)]
struct UserInfo {
sub: String,
username: String,
}
pub(super) fn filter(
pool: &PgPool,
_config: &OAuth2Config,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
warp::path!("oauth2" / "userinfo").and(
warp::get()
.or(warp::post())
.unify()
.and(authentication(pool))
.and_then(userinfo)
.recover(recover_unauthorized)
.with(cors().allow_methods([Method::GET, Method::POST])),
)
}
async fn userinfo(
_token: AccessToken<PostgresqlBackend>,
session: Session<PostgresqlBackend>,
) -> Result<impl Reply, Rejection> {
let user = session.browser_session.user;
Ok(warp::reply::json(&UserInfo {
sub: user.sub,
username: user.username,
}))
}

View File

@ -0,0 +1,132 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use argon2::Argon2;
use mas_config::{CookiesConfig, CsrfConfig};
use mas_data_model::BrowserSession;
use mas_storage::{
user::{authenticate_session, count_active_sessions, set_password},
PostgresqlBackend,
};
use mas_templates::{AccountContext, TemplateContext, Templates};
use mas_warp_utils::{
errors::WrapError,
filters::{
cookies::{encrypted_cookie_saver, EncryptedCookieSaver},
csrf::{protected_form, updated_csrf_token},
database::{connection, transaction},
session::session,
with_templates, CsrfToken,
},
};
use serde::Deserialize;
use sqlx::{pool::PoolConnection, PgExecutor, PgPool, Postgres, Transaction};
use warp::{reply::html, Filter, Rejection, Reply};
pub(super) fn filter(
pool: &PgPool,
templates: &Templates,
csrf_config: &CsrfConfig,
cookies_config: &CookiesConfig,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let get = with_templates(templates)
.and(encrypted_cookie_saver(cookies_config))
.and(updated_csrf_token(cookies_config, csrf_config))
.and(session(pool, cookies_config))
.and(connection(pool))
.and_then(get)
.with(warp::filters::trace::trace(|_info| {
tracing::info_span!("GET /account")
}));
let post = with_templates(templates)
.and(encrypted_cookie_saver(cookies_config))
.and(updated_csrf_token(cookies_config, csrf_config))
.and(session(pool, cookies_config))
.and(transaction(pool))
.and(protected_form(cookies_config))
.and_then(post)
.with(warp::filters::trace::trace(|_info| {
tracing::info_span!("POST /account")
}));
let filter = warp::get().and(get).or(warp::post().and(post));
warp::path!("account").and(filter)
}
#[derive(Deserialize)]
struct Form {
current_password: String,
new_password: String,
new_password_confirm: String,
}
async fn get(
templates: Templates,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
session: BrowserSession<PostgresqlBackend>,
mut conn: PoolConnection<Postgres>,
) -> Result<Box<dyn Reply>, Rejection> {
render(templates, cookie_saver, csrf_token, session, &mut conn).await
}
async fn render(
templates: Templates,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
session: BrowserSession<PostgresqlBackend>,
executor: impl PgExecutor<'_>,
) -> Result<Box<dyn Reply>, Rejection> {
let active_sessions = count_active_sessions(executor, &session.user)
.await
.wrap_error()?;
let ctx = AccountContext::new(active_sessions)
.with_session(session)
.with_csrf(csrf_token.form_value());
let content = templates.render_account(&ctx).await?;
let reply = html(content);
let reply = cookie_saver.save_encrypted(&csrf_token, reply)?;
Ok(Box::new(reply))
}
async fn post(
templates: Templates,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
mut session: BrowserSession<PostgresqlBackend>,
mut txn: Transaction<'_, Postgres>,
form: Form,
) -> Result<Box<dyn Reply>, Rejection> {
authenticate_session(&mut txn, &mut session, form.current_password)
.await
.wrap_error()?;
// TODO: display nice form errors
if form.new_password != form.new_password_confirm {
return Err(anyhow::anyhow!("password mismatch")).wrap_error();
}
let phf = Argon2::default();
set_password(&mut txn, phf, &session.user, &form.new_password)
.await
.wrap_error()?;
let reply = render(templates, cookie_saver, csrf_token, session, &mut txn).await?;
txn.commit().await.wrap_error()?;
Ok(reply)
}

View File

@ -0,0 +1,62 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use mas_config::{CookiesConfig, CsrfConfig, OAuth2Config};
use mas_data_model::BrowserSession;
use mas_storage::PostgresqlBackend;
use mas_templates::{IndexContext, TemplateContext, Templates};
use mas_warp_utils::filters::{
cookies::{encrypted_cookie_saver, EncryptedCookieSaver},
csrf::updated_csrf_token,
session::optional_session,
with_templates, CsrfToken,
};
use sqlx::PgPool;
use url::Url;
use warp::{reply::html, Filter, Rejection, Reply};
pub(super) fn filter(
pool: &PgPool,
templates: &Templates,
oauth2_config: &OAuth2Config,
csrf_config: &CsrfConfig,
cookies_config: &CookiesConfig,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let discovery_url = oauth2_config.discovery_url();
warp::path::end()
.and(warp::get())
.map(move || discovery_url.clone())
.and(with_templates(templates))
.and(encrypted_cookie_saver(cookies_config))
.and(updated_csrf_token(cookies_config, csrf_config))
.and(optional_session(pool, cookies_config))
.and_then(get)
}
async fn get(
discovery_url: Url,
templates: Templates,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
maybe_session: Option<BrowserSession<PostgresqlBackend>>,
) -> Result<impl Reply, Rejection> {
let ctx = IndexContext::new(discovery_url)
.maybe_with_session(maybe_session)
.with_csrf(csrf_token.form_value());
let content = templates.render_index(&ctx).await?;
let reply = html(content);
let reply = cookie_saver.save_encrypted(&csrf_token, reply)?;
Ok(Box::new(reply))
}

View File

@ -0,0 +1,194 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use hyper::http::uri::{Parts, PathAndQuery, Uri};
use mas_config::{CookiesConfig, CsrfConfig};
use mas_data_model::{errors::WrapFormError, BrowserSession, StorageBackend};
use mas_storage::{user::login, PostgresqlBackend};
use mas_templates::{LoginContext, LoginFormField, TemplateContext, Templates};
use mas_warp_utils::{
errors::WrapError,
filters::{
cookies::{encrypted_cookie_saver, EncryptedCookieSaver},
csrf::{protected_form, updated_csrf_token},
database::connection,
session::{optional_session, SessionCookie},
with_templates, CsrfToken,
},
};
use serde::Deserialize;
use sqlx::{pool::PoolConnection, PgPool, Postgres};
use warp::{reply::html, Filter, Rejection, Reply};
use super::{shared::PostAuthAction, RegisterRequest};
#[derive(Deserialize)]
#[serde(bound(deserialize = "S::AuthorizationGrantData: std::str::FromStr,
<S::AuthorizationGrantData as std::str::FromStr>::Err: std::fmt::Display"))]
pub(crate) struct LoginRequest<S: StorageBackend> {
#[serde(flatten)]
post_auth_action: Option<PostAuthAction<S>>,
}
impl<S: StorageBackend> From<PostAuthAction<S>> for LoginRequest<S> {
fn from(post_auth_action: PostAuthAction<S>) -> Self {
Self {
post_auth_action: Some(post_auth_action),
}
}
}
impl<S: StorageBackend> LoginRequest<S> {
pub fn build_uri(&self) -> anyhow::Result<Uri>
where
S::AuthorizationGrantData: std::fmt::Display,
{
let path_and_query = if let Some(next) = &self.post_auth_action {
let qs = serde_urlencoded::to_string(next)?;
PathAndQuery::try_from(format!("/login?{}", qs))?
} else {
PathAndQuery::from_static("/login")
};
let uri = Uri::from_parts({
let mut parts = Parts::default();
parts.path_and_query = Some(path_and_query);
parts
})?;
Ok(uri)
}
fn redirect(self) -> Result<impl Reply, Rejection>
where
S::AuthorizationGrantData: std::fmt::Display,
{
let uri = self
.post_auth_action
.as_ref()
.map(PostAuthAction::build_uri)
.transpose()
.wrap_error()?
.unwrap_or_else(|| Uri::from_static("/"));
Ok(warp::redirect::see_other(uri))
}
}
#[derive(Deserialize)]
struct LoginForm {
username: String,
password: String,
}
pub(super) fn filter(
pool: &PgPool,
templates: &Templates,
csrf_config: &CsrfConfig,
cookies_config: &CookiesConfig,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let get = warp::get()
.and(with_templates(templates))
.and(connection(pool))
.and(encrypted_cookie_saver(cookies_config))
.and(updated_csrf_token(cookies_config, csrf_config))
.and(warp::query())
.and(optional_session(pool, cookies_config))
.and_then(get);
let post = warp::post()
.and(with_templates(templates))
.and(connection(pool))
.and(encrypted_cookie_saver(cookies_config))
.and(updated_csrf_token(cookies_config, csrf_config))
.and(protected_form(cookies_config))
.and(warp::query())
.and_then(post);
warp::path!("login").and(get.or(post))
}
async fn get(
templates: Templates,
mut conn: PoolConnection<Postgres>,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
query: LoginRequest<PostgresqlBackend>,
maybe_session: Option<BrowserSession<PostgresqlBackend>>,
) -> Result<Box<dyn Reply>, Rejection> {
if maybe_session.is_some() {
Ok(Box::new(query.redirect()?))
} else {
let ctx = LoginContext::default();
let ctx = match query.post_auth_action {
Some(next) => {
let register_link = RegisterRequest::from(next.clone())
.build_uri()
.wrap_error()?;
let next = next.load_context(&mut conn).await.wrap_error()?;
ctx.with_post_action(next)
.with_register_link(register_link.to_string())
}
None => ctx,
};
let ctx = ctx.with_csrf(csrf_token.form_value());
let content = templates.render_login(&ctx).await?;
let reply = html(content);
let reply = cookie_saver.save_encrypted(&csrf_token, reply)?;
Ok(Box::new(reply))
}
}
async fn post(
templates: Templates,
mut conn: PoolConnection<Postgres>,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
form: LoginForm,
query: LoginRequest<PostgresqlBackend>,
) -> Result<Box<dyn Reply>, Rejection> {
use mas_storage::user::LoginError;
// TODO: recover
match login(&mut conn, &form.username, form.password).await {
Ok(session_info) => {
let session_cookie = SessionCookie::from_session(&session_info);
let reply = query.redirect()?;
let reply = cookie_saver.save_encrypted(&session_cookie, reply)?;
Ok(Box::new(reply))
}
Err(e) => {
let errored_form = match e {
LoginError::NotFound { .. } => e.on_field(LoginFormField::Username),
LoginError::Authentication { .. } => e.on_field(LoginFormField::Password),
LoginError::Other(_) => e.on_form(),
};
let ctx = LoginContext::default()
.with_form_error(errored_form)
.with_csrf(csrf_token.form_value());
let content = templates.render_login(&ctx).await?;
let reply = html(content);
let reply = cookie_saver.save_encrypted(&csrf_token, reply)?;
Ok(Box::new(reply))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialize_login_request() {
let res: Result<LoginRequest<PostgresqlBackend>, _> =
serde_urlencoded::from_str("next=continue_authorization_grant&data=13");
res.unwrap().post_auth_action.unwrap();
}
}

View File

@ -0,0 +1,46 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use mas_config::CookiesConfig;
use mas_data_model::BrowserSession;
use mas_storage::{user::end_session, PostgresqlBackend};
use mas_warp_utils::{
errors::WrapError,
filters::{csrf::protected_form, database::transaction, session::session},
};
use sqlx::{PgPool, Postgres, Transaction};
use warp::{hyper::Uri, Filter, Rejection, Reply};
pub(super) fn filter(
pool: &PgPool,
cookies_config: &CookiesConfig,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
warp::path!("logout")
.and(warp::post())
.and(session(pool, cookies_config))
.and(transaction(pool))
.and(protected_form(cookies_config))
.and_then(post)
}
async fn post(
session: BrowserSession<PostgresqlBackend>,
mut txn: Transaction<'_, Postgres>,
_form: (),
) -> Result<impl Reply, Rejection> {
end_session(&mut txn, &session).await.wrap_error()?;
txn.commit().await.wrap_error()?;
Ok(warp::redirect(Uri::from_static("/login")))
}

View File

@ -0,0 +1,50 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use mas_config::{CookiesConfig, CsrfConfig, OAuth2Config};
use mas_templates::Templates;
use sqlx::PgPool;
use warp::{filters::BoxedFilter, Filter, Reply};
mod account;
mod index;
mod login;
mod logout;
mod reauth;
mod register;
mod shared;
use self::{
account::filter as account, index::filter as index, login::filter as login,
logout::filter as logout, reauth::filter as reauth, register::filter as register,
};
pub(crate) use self::{
login::LoginRequest, reauth::ReauthRequest, register::RegisterRequest, shared::PostAuthAction,
};
pub(super) fn filter(
pool: &PgPool,
templates: &Templates,
oauth2_config: &OAuth2Config,
csrf_config: &CsrfConfig,
cookies_config: &CookiesConfig,
) -> BoxedFilter<(impl Reply,)> {
index(pool, templates, oauth2_config, csrf_config, cookies_config)
.or(account(pool, templates, csrf_config, cookies_config))
.or(login(pool, templates, csrf_config, cookies_config))
.or(register(pool, templates, csrf_config, cookies_config))
.or(logout(pool, cookies_config))
.or(reauth(pool, templates, csrf_config, cookies_config))
.boxed()
}

View File

@ -0,0 +1,153 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use hyper::http::uri::{Parts, PathAndQuery};
use mas_config::{CookiesConfig, CsrfConfig};
use mas_data_model::{BrowserSession, StorageBackend};
use mas_storage::{user::authenticate_session, PostgresqlBackend};
use mas_templates::{ReauthContext, TemplateContext, Templates};
use mas_warp_utils::{
errors::WrapError,
filters::{
cookies::{encrypted_cookie_saver, EncryptedCookieSaver},
csrf::{protected_form, updated_csrf_token},
database::{connection, transaction},
session::session,
with_templates, CsrfToken,
},
};
use serde::Deserialize;
use sqlx::{pool::PoolConnection, PgPool, Postgres, Transaction};
use warp::{hyper::Uri, reply::html, Filter, Rejection, Reply};
use super::PostAuthAction;
#[derive(Deserialize)]
#[serde(bound(deserialize = "S::AuthorizationGrantData: std::str::FromStr,
<S::AuthorizationGrantData as std::str::FromStr>::Err: std::fmt::Display"))]
pub(crate) struct ReauthRequest<S: StorageBackend> {
#[serde(flatten)]
post_auth_action: Option<PostAuthAction<S>>,
}
impl<S: StorageBackend> From<PostAuthAction<S>> for ReauthRequest<S> {
fn from(post_auth_action: PostAuthAction<S>) -> Self {
Self {
post_auth_action: Some(post_auth_action),
}
}
}
impl<S: StorageBackend> ReauthRequest<S> {
pub fn build_uri(&self) -> anyhow::Result<Uri>
where
S::AuthorizationGrantData: std::fmt::Display,
{
let path_and_query = if let Some(next) = &self.post_auth_action {
let qs = serde_urlencoded::to_string(next)?;
PathAndQuery::try_from(format!("/reauth?{}", qs))?
} else {
PathAndQuery::from_static("/reauth")
};
let uri = Uri::from_parts({
let mut parts = Parts::default();
parts.path_and_query = Some(path_and_query);
parts
})?;
Ok(uri)
}
fn redirect(self) -> Result<impl Reply, Rejection>
where
S::AuthorizationGrantData: std::fmt::Display,
{
let uri = self
.post_auth_action
.as_ref()
.map(PostAuthAction::build_uri)
.transpose()
.wrap_error()?
.unwrap_or_else(|| Uri::from_static("/"));
Ok(warp::redirect::see_other(uri))
}
}
#[derive(Deserialize, Debug)]
struct ReauthForm {
password: String,
}
pub(super) fn filter(
pool: &PgPool,
templates: &Templates,
csrf_config: &CsrfConfig,
cookies_config: &CookiesConfig,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let get = warp::get()
.and(with_templates(templates))
.and(connection(pool))
.and(encrypted_cookie_saver(cookies_config))
.and(updated_csrf_token(cookies_config, csrf_config))
.and(session(pool, cookies_config))
.and(warp::query())
.and_then(get);
let post = warp::post()
.and(session(pool, cookies_config))
.and(transaction(pool))
.and(protected_form(cookies_config))
.and(warp::query())
.and_then(post);
warp::path!("reauth").and(get.or(post))
}
async fn get(
templates: Templates,
mut conn: PoolConnection<Postgres>,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
session: BrowserSession<PostgresqlBackend>,
query: ReauthRequest<PostgresqlBackend>,
) -> Result<impl Reply, Rejection> {
let ctx = ReauthContext::default();
let ctx = match query.post_auth_action {
Some(next) => {
let next = next.load_context(&mut conn).await.wrap_error()?;
ctx.with_post_action(next)
}
None => ctx,
};
let ctx = ctx.with_session(session).with_csrf(csrf_token.form_value());
let content = templates.render_reauth(&ctx).await?;
let reply = html(content);
let reply = cookie_saver.save_encrypted(&csrf_token, reply)?;
Ok(reply)
}
async fn post(
mut session: BrowserSession<PostgresqlBackend>,
mut txn: Transaction<'_, Postgres>,
form: ReauthForm,
query: ReauthRequest<PostgresqlBackend>,
) -> Result<impl Reply, Rejection> {
// TODO: recover from errors here
authenticate_session(&mut txn, &mut session, form.password)
.await
.wrap_error()?;
txn.commit().await.wrap_error()?;
Ok(query.redirect()?)
}

View File

@ -0,0 +1,176 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use argon2::Argon2;
use hyper::http::uri::{Parts, PathAndQuery, Uri};
use mas_config::{CookiesConfig, CsrfConfig};
use mas_data_model::{BrowserSession, StorageBackend};
use mas_storage::{
user::{register_user, start_session},
PostgresqlBackend,
};
use mas_templates::{RegisterContext, TemplateContext, Templates};
use mas_warp_utils::{
errors::WrapError,
filters::{
cookies::{encrypted_cookie_saver, EncryptedCookieSaver},
csrf::{protected_form, updated_csrf_token},
database::{connection, transaction},
session::{optional_session, SessionCookie},
with_templates, CsrfToken,
},
};
use serde::Deserialize;
use sqlx::{pool::PoolConnection, PgPool, Postgres, Transaction};
use warp::{reply::html, Filter, Rejection, Reply};
use super::{LoginRequest, PostAuthAction};
#[derive(Deserialize)]
#[serde(bound(deserialize = "S::AuthorizationGrantData: std::str::FromStr,
<S::AuthorizationGrantData as std::str::FromStr>::Err: std::fmt::Display"))]
pub struct RegisterRequest<S: StorageBackend> {
#[serde(flatten)]
post_auth_action: Option<PostAuthAction<S>>,
}
impl<S: StorageBackend> From<PostAuthAction<S>> for RegisterRequest<S> {
fn from(post_auth_action: PostAuthAction<S>) -> Self {
Self {
post_auth_action: Some(post_auth_action),
}
}
}
impl<S: StorageBackend> RegisterRequest<S> {
#[allow(dead_code)]
pub fn build_uri(&self) -> anyhow::Result<Uri>
where
S::AuthorizationGrantData: std::fmt::Display,
{
let path_and_query = if let Some(next) = &self.post_auth_action {
let qs = serde_urlencoded::to_string(next)?;
PathAndQuery::try_from(format!("/register?{}", qs))?
} else {
PathAndQuery::from_static("/register")
};
let uri = Uri::from_parts({
let mut parts = Parts::default();
parts.path_and_query = Some(path_and_query);
parts
})?;
Ok(uri)
}
fn redirect(self) -> Result<impl Reply, Rejection>
where
S::AuthorizationGrantData: std::fmt::Display,
{
let uri = self
.post_auth_action
.as_ref()
.map(PostAuthAction::build_uri)
.transpose()
.wrap_error()?
.unwrap_or_else(|| Uri::from_static("/"));
Ok(warp::redirect::see_other(uri))
}
}
#[derive(Deserialize)]
struct RegisterForm {
username: String,
password: String,
password_confirm: String,
}
pub(super) fn filter(
pool: &PgPool,
templates: &Templates,
csrf_config: &CsrfConfig,
cookies_config: &CookiesConfig,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone + Send + Sync + 'static {
let get = warp::get()
.and(with_templates(templates))
.and(connection(pool))
.and(encrypted_cookie_saver(cookies_config))
.and(updated_csrf_token(cookies_config, csrf_config))
.and(warp::query())
.and(optional_session(pool, cookies_config))
.and_then(get);
let post = warp::post()
.and(transaction(pool))
.and(encrypted_cookie_saver(cookies_config))
.and(protected_form(cookies_config))
.and(warp::query())
.and_then(post);
warp::path!("register").and(get.or(post))
}
async fn get(
templates: Templates,
mut conn: PoolConnection<Postgres>,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
query: RegisterRequest<PostgresqlBackend>,
maybe_session: Option<BrowserSession<PostgresqlBackend>>,
) -> Result<Box<dyn Reply>, Rejection> {
if maybe_session.is_some() {
Ok(Box::new(query.redirect()?))
} else {
let ctx = RegisterContext::default();
let ctx = match query.post_auth_action {
Some(next) => {
let login_link = LoginRequest::from(next.clone()).build_uri().wrap_error()?;
let next = next.load_context(&mut conn).await.wrap_error()?;
ctx.with_post_action(next)
.with_login_link(login_link.to_string())
}
None => ctx,
};
let ctx = ctx.with_csrf(csrf_token.form_value());
let content = templates.render_register(&ctx).await?;
let reply = html(content);
let reply = cookie_saver.save_encrypted(&csrf_token, reply)?;
Ok(Box::new(reply))
}
}
async fn post(
mut txn: Transaction<'_, Postgres>,
cookie_saver: EncryptedCookieSaver,
form: RegisterForm,
query: RegisterRequest<PostgresqlBackend>,
) -> Result<impl Reply, Rejection> {
// TODO: display nice form errors
if form.password != form.password_confirm {
return Err(anyhow::anyhow!("password mismatch")).wrap_error();
}
let pfh = Argon2::default();
let user = register_user(&mut txn, pfh, &form.username, &form.password)
.await
.wrap_error()?;
let session_info = start_session(&mut txn, user).await.wrap_error()?;
txn.commit().await.wrap_error()?;
let session_cookie = SessionCookie::from_session(&session_info);
let reply = query.redirect()?;
let reply = cookie_saver.save_encrypted(&session_cookie, reply)?;
Ok(reply)
}

View File

@ -0,0 +1,65 @@
// Copyright 2021 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use hyper::Uri;
use mas_data_model::StorageBackend;
use mas_storage::PostgresqlBackend;
use mas_templates::PostAuthContext;
use serde::{Deserialize, Serialize};
use sqlx::PgExecutor;
use super::super::oauth2::ContinueAuthorizationGrant;
#[derive(Deserialize, Serialize, Clone)]
#[serde(rename_all = "snake_case", tag = "next")]
pub(crate) enum PostAuthAction<S: StorageBackend> {
#[serde(bound(
deserialize = "S::AuthorizationGrantData: std::str::FromStr,
<S::AuthorizationGrantData as std::str::FromStr>::Err: std::fmt::Display",
serialize = "S::AuthorizationGrantData: std::fmt::Display"
))]
ContinueAuthorizationGrant(ContinueAuthorizationGrant<S>),
}
impl<S: StorageBackend> PostAuthAction<S> {
pub fn build_uri(&self) -> anyhow::Result<Uri>
where
S::AuthorizationGrantData: std::fmt::Display,
{
match self {
PostAuthAction::ContinueAuthorizationGrant(c) => c.build_uri(),
}
}
}
impl<S: StorageBackend> From<ContinueAuthorizationGrant<S>> for PostAuthAction<S> {
fn from(g: ContinueAuthorizationGrant<S>) -> Self {
Self::ContinueAuthorizationGrant(g)
}
}
impl PostAuthAction<PostgresqlBackend> {
pub async fn load_context<'e>(
&self,
executor: impl PgExecutor<'e>,
) -> anyhow::Result<PostAuthContext> {
match self {
Self::ContinueAuthorizationGrant(c) => {
let grant = c.fetch_authorization_grant(executor).await?;
let grant = grant.into();
Ok(PostAuthContext::ContinueAuthorizationGrant { grant })
}
}
}
}