1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-31 09:24:31 +03:00

Axum migration: /reauth route

This commit is contained in:
Quentin Gliech
2022-03-25 16:31:40 +01:00
parent 6e7d0a6cfd
commit b4dc2b38d0
4 changed files with 109 additions and 90 deletions

View File

@ -87,6 +87,10 @@ where
get(self::views::login::get).post(self::views::login::post), get(self::views::login::get).post(self::views::login::post),
) )
.route("/logout", post(self::views::logout::post)) .route("/logout", post(self::views::logout::post))
.route(
"/reauth",
get(self::views::reauth::get).post(self::views::reauth::post),
)
.fallback(mas_static_files::Assets) .fallback(mas_static_files::Assets)
.layer(Extension(pool.clone())) .layer(Extension(pool.clone()))
.layer(Extension(templates.clone())) .layer(Extension(templates.clone()))

View File

@ -38,10 +38,14 @@ pub(crate) struct LoginRequest {
impl From<PostAuthAction> for LoginRequest { impl From<PostAuthAction> for LoginRequest {
fn from(post_auth_action: PostAuthAction) -> Self { fn from(post_auth_action: PostAuthAction) -> Self {
Self { Some(post_auth_action).into()
post_auth_action: Some(post_auth_action),
} }
} }
impl From<Option<PostAuthAction>> for LoginRequest {
fn from(post_auth_action: Option<PostAuthAction>) -> Self {
Self { post_auth_action }
}
} }
impl LoginRequest { impl LoginRequest {

View File

@ -27,10 +27,7 @@ pub mod register;
pub mod shared; pub mod shared;
pub mod verify; pub mod verify;
use self::{ use self::{account::filter as account, register::filter as register, verify::filter as verify};
account::filter as account, reauth::filter as reauth, register::filter as register,
verify::filter as verify,
};
pub(crate) use self::{ pub(crate) use self::{
login::LoginRequest, reauth::ReauthRequest, register::RegisterRequest, shared::PostAuthAction, login::LoginRequest, reauth::ReauthRequest, register::RegisterRequest, shared::PostAuthAction,
}; };
@ -45,15 +42,7 @@ pub(super) fn filter(
) -> BoxedFilter<(Box<dyn Reply>,)> { ) -> BoxedFilter<(Box<dyn Reply>,)> {
let account = account(pool, templates, mailer, encrypter, http_config, csrf_config); let account = account(pool, templates, mailer, encrypter, http_config, csrf_config);
let register = register(pool, templates, encrypter, csrf_config); let register = register(pool, templates, encrypter, csrf_config);
let reauth = reauth(pool, templates, encrypter, csrf_config);
let verify = verify(pool, templates, encrypter, csrf_config); let verify = verify(pool, templates, encrypter, csrf_config);
account account.or(register).unify().or(verify).unify().boxed()
.or(register)
.unify()
.or(reauth)
.unify()
.or(verify)
.unify()
.boxed()
} }

View File

@ -12,27 +12,25 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use hyper::http::uri::{Parts, PathAndQuery}; use axum::{
use mas_config::{CsrfConfig, Encrypter}; extract::{Extension, Form, Query},
use mas_data_model::BrowserSession; response::{Html, IntoResponse, Redirect, Response},
use mas_storage::{user::authenticate_session, PostgresqlBackend};
use mas_templates::{ReauthContext, TemplateContext, Templates};
use mas_warp_utils::{
errors::WrapError,
filters::{
self,
cookies::{encrypted_cookie_saver, EncryptedCookieSaver},
csrf::{protected_form, updated_csrf_token},
database::{connection, transaction},
session::session,
with_templates, CsrfToken,
},
}; };
use hyper::{
http::uri::{Parts, PathAndQuery},
Uri,
};
use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
fancy_error, FancyError, PrivateCookieJar, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_storage::user::authenticate_session;
use mas_templates::{ReauthContext, TemplateContext, Templates};
use serde::Deserialize; use serde::Deserialize;
use sqlx::{pool::PoolConnection, PgPool, Postgres, Transaction}; use sqlx::PgPool;
use warp::{filters::BoxedFilter, hyper::Uri, reply::html, Filter, Rejection, Reply};
use super::PostAuthAction; use super::{LoginRequest, PostAuthAction};
#[derive(Deserialize)] #[derive(Deserialize)]
pub(crate) struct ReauthRequest { pub(crate) struct ReauthRequest {
@ -64,85 +62,109 @@ impl ReauthRequest {
Ok(uri) Ok(uri)
} }
fn redirect(self) -> Result<impl Reply, Rejection> { fn redirect(self) -> Result<impl IntoResponse, anyhow::Error> {
let uri = self let uri = if let Some(action) = self.post_auth_action {
.post_auth_action action.build_uri()?
.as_ref() } else {
.map(PostAuthAction::build_uri) Uri::from_static("/")
.transpose() };
.wrap_error()?
.unwrap_or_else(|| Uri::from_static("/")); Ok(Redirect::to(uri))
Ok(warp::redirect::see_other(uri))
} }
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
struct ReauthForm { pub(crate) struct ReauthForm {
password: String, password: String,
} }
pub(super) fn filter( pub(crate) async fn get(
pool: &PgPool, Extension(templates): Extension<Templates>,
templates: &Templates, Extension(pool): Extension<PgPool>,
encrypter: &Encrypter, Query(query): Query<ReauthRequest>,
csrf_config: &CsrfConfig, cookie_jar: PrivateCookieJar<Encrypter>,
) -> BoxedFilter<(Box<dyn Reply>,)> { ) -> Result<Response, FancyError> {
let get = warp::get() let mut conn = pool
.and(filters::trace::name("GET /reauth")) .acquire()
.and(with_templates(templates)) .await
.and(connection(pool)) .map_err(fancy_error(templates.clone()))?;
.and(encrypted_cookie_saver(encrypter))
.and(updated_csrf_token(encrypter, csrf_config))
.and(session(pool, encrypter))
.and(warp::query())
.and_then(get);
let post = warp::post() let (csrf_token, cookie_jar) = cookie_jar.csrf_token();
.and(filters::trace::name("POST /reauth")) let (session_info, cookie_jar) = cookie_jar.session_info();
.and(session(pool, encrypter))
.and(transaction(pool))
.and(protected_form(encrypter))
.and(warp::query())
.and_then(post);
warp::path!("reauth").and(get.or(post).unify()).boxed() let maybe_session = session_info
} .load_session(&mut conn)
.await
.map_err(fancy_error(templates.clone()))?;
let session = if let Some(session) = maybe_session {
session
} else {
// If there is no session, redirect to the login screen, keeping the
// PostAuthAction
let login: LoginRequest = query.post_auth_action.into();
let login = login.build_uri().map_err(fancy_error(templates.clone()))?;
return Ok((cookie_jar.headers(), Redirect::to(login)).into_response());
};
async fn get(
templates: Templates,
mut conn: PoolConnection<Postgres>,
cookie_saver: EncryptedCookieSaver,
csrf_token: CsrfToken,
session: BrowserSession<PostgresqlBackend>,
query: ReauthRequest,
) -> Result<Box<dyn Reply>, Rejection> {
let ctx = ReauthContext::default(); let ctx = ReauthContext::default();
let ctx = match query.post_auth_action { let ctx = match query.post_auth_action {
Some(next) => { Some(next) => {
let next = next.load_context(&mut conn).await.wrap_error()?; let next = next
.load_context(&mut conn)
.await
.map_err(fancy_error(templates.clone()))?;
ctx.with_post_action(next) ctx.with_post_action(next)
} }
None => ctx, None => ctx,
}; };
let ctx = ctx.with_session(session).with_csrf(csrf_token.form_value()); let ctx = ctx.with_session(session).with_csrf(csrf_token.form_value());
let content = templates.render_reauth(&ctx).await?; let content = templates
let reply = html(content); .render_reauth(&ctx)
let reply = cookie_saver.save_encrypted(&csrf_token, reply)?; .await
Ok(Box::new(reply)) .map_err(fancy_error(templates.clone()))?;
Ok((cookie_jar.headers(), Html(content)).into_response())
} }
async fn post( pub(crate) async fn post(
mut session: BrowserSession<PostgresqlBackend>, Extension(templates): Extension<Templates>,
mut txn: Transaction<'_, Postgres>, Extension(pool): Extension<PgPool>,
form: ReauthForm, Query(query): Query<ReauthRequest>,
query: ReauthRequest, cookie_jar: PrivateCookieJar<Encrypter>,
) -> Result<Box<dyn Reply>, Rejection> { Form(form): Form<ProtectedForm<ReauthForm>>,
) -> Result<Response, FancyError> {
let mut txn = pool.begin().await.map_err(fancy_error(templates.clone()))?;
let form = cookie_jar
.verify_form(form)
.map_err(fancy_error(templates.clone()))?;
let (session_info, cookie_jar) = cookie_jar.session_info();
let maybe_session = session_info
.load_session(&mut txn)
.await
.map_err(fancy_error(templates.clone()))?;
let mut session = if let Some(session) = maybe_session {
session
} else {
// If there is no session, redirect to the login screen, keeping the
// PostAuthAction
let login: LoginRequest = query.post_auth_action.into();
let login = login.build_uri().map_err(fancy_error(templates.clone()))?;
return Ok((cookie_jar.headers(), Redirect::to(login)).into_response());
};
// TODO: recover from errors here // TODO: recover from errors here
authenticate_session(&mut txn, &mut session, form.password) authenticate_session(&mut txn, &mut session, form.password)
.await .await
.wrap_error()?; .map_err(fancy_error(templates.clone()))?;
txn.commit().await.wrap_error()?; let cookie_jar = cookie_jar.set_session(&session);
txn.commit().await.map_err(fancy_error(templates.clone()))?;
Ok(Box::new(query.redirect()?)) let redirection = query.redirect().map_err(fancy_error(templates.clone()))?;
Ok((cookie_jar.headers(), redirection).into_response())
} }