Lines
81.46 %
Functions
37.04 %
Branches
100 %
use std::sync::Arc;
use axum::{
Extension, Json,
extract::State,
http::{HeaderMap, HeaderValue, header},
response::IntoResponse,
};
use axum_extra::extract::{
CookieJar,
cookie::{Cookie, SameSite},
use redis::AsyncCommands;
use serde_json::json;
use crate::{
AppState, Config,
jwt_auth::{
JWTAuthMiddleware, REUSE_GRACE_SECS, Redemption, Rotation, end_session, mint_failed,
rotate_refresh,
},
response::{UNAVAILABLE_MESSAGE, WebError},
token::{TokenDetails, TokenType},
use rust_i18n::t;
/// Appends one `Set-Cookie` per rendered cookie. A cookie we built ourselves
/// always parses, so a value that somehow does not is dropped rather than
/// panicking the request.
pub(crate) fn append_set_cookies(
headers: &mut HeaderMap,
cookies: impl IntoIterator<Item = String>,
) {
for cookie in cookies {
if let Ok(value) = cookie.parse() {
headers.append(header::SET_COOKIE, value);
}
/// The two cookies of a session: the access and the refresh token.
pub(crate) fn session_cookies(conf: &Config, access: String, refresh: String) -> [String; 2] {
let build = |name: &'static str, value: String, max_age: i64| {
Cookie::build((name, value))
.path("/")
.max_age(time::Duration::minutes(max_age))
.same_site(SameSite::Lax)
.secure(crate::auth_keys::secure_cookies())
.http_only(true)
.to_string()
[
build("access_token", access, conf.access_token_max_age),
build("refresh_token", refresh, conf.refresh_token_max_age),
]
pub(crate) async fn mint_token(
user_id: uuid::Uuid,
max_age: i64,
token_type: TokenType,
generation: i32,
) -> Result<TokenDetails, WebError> {
crate::auth_keys::mint(user_id, max_age, token_type, generation)
.await
.map_err(mint_failed)
pub(crate) async fn save_token_data_to_redis(
data: &Arc<AppState>,
token_details: &TokenDetails,
) -> Result<(), WebError> {
let mut redis_client = redis_connection(data).await?;
redis_client
.set_ex::<_, _, ()>(
token_details.token_uuid.to_string(),
token_details.user_id.to_string(),
(max_age * 60) as u64,
)
.map_err(|e| WebError::internal("Saving the session failed", e))
async fn redis_connection(
) -> Result<redis::aio::MultiplexedConnection, WebError> {
data.redis_client
.get_multiplexed_async_connection()
.map_err(|e| {
tracing::error!("Session store unreachable: {e}");
WebError::unavailable(UNAVAILABLE_MESSAGE)
})
fn expired() -> WebError {
WebError::unauthorized(t!("Token is invalid or session has expired").to_string())
/// The caller's own refresh token, verified and bound to the authenticated user.
///
/// Binding matters: a client must not present user A's access token with user
/// B's refresh token to touch B's session.
async fn own_refresh_token(
cookie_jar: &CookieJar,
let refresh_token = cookie_jar
.get("refresh_token")
.map(|cookie| cookie.value().to_string())
.ok_or_else(expired)?;
let details = crate::auth_keys::verify(&refresh_token, TokenType::Refresh)
// An unreadable directory is not an expired session.
tracing::error!("Token directory unreadable: {e}");
})?
if details.user_id != user_id {
return Err(expired());
Ok(details)
fn refreshed_by_session() -> (HeaderMap, Json<serde_json::Value>) {
(
HeaderMap::new(),
Json(json!({"status": "success", "refreshed_by": "session"})),
pub async fn refresh_access_token_handler(
cookie_jar: CookieJar,
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
State(data): State<Arc<AppState>>,
) -> Result<impl IntoResponse, WebError> {
// The middleware ahead of this handler refreshes a dead access token on the
// way in, consuming the cookie this request still carries: report that
// refresh instead of redeeming a token that is already gone.
if jwt_auth.refreshed {
return Ok(refreshed_by_session());
let refresh_token_details = own_refresh_token(&cookie_jar, jwt_auth.user.id).await?;
let mut redis_client = redis_connection(&data).await?;
let user_id = jwt_auth.user.id;
// Minted BEFORE the rotation: minting touches the tenant database, and a
// failure after the old session is consumed would log the user out. A
// token minted and never registered is inert.
let access_token_details = mint_token(
user_id,
data.conf.access_token_max_age,
TokenType::Access,
refresh_token_details.generation,
.await?;
let new_refresh_details = mint_token(
data.conf.refresh_token_max_age,
TokenType::Refresh,
let redemption = rotate_refresh(
&mut redis_client,
&Rotation {
token_uuid: refresh_token_details.token_uuid,
owner: user_id,
successor: new_refresh_details.token_uuid,
access_uuid: access_token_details.token_uuid,
superseded: Some(jwt_auth.access_token_uuid),
refresh_ttl: (data.conf.refresh_token_max_age * 60) as u64,
access_ttl: (data.conf.access_token_max_age * 60) as u64,
grace: REUSE_GRACE_SECS,
match redemption {
Redemption::Rotated => {}
Redemption::Reused => return Ok(refreshed_by_session()),
Redemption::Refused => return Err(expired()),
let access = access_token_details.token.unwrap_or_default();
let mut headers = HeaderMap::new();
append_set_cookies(
&mut headers,
session_cookies(
&data.conf,
access.clone(),
new_refresh_details.token.unwrap_or_default(),
),
);
Ok((
headers,
Json(json!({"status": "success", "access_token": access})),
))
pub async fn logout_handler(
Extension(auth_guard): Extension<JWTAuthMiddleware>,
let refresh_token_details = own_refresh_token(&cookie_jar, auth_guard.user.id).await?;
end_session(
refresh_token_details.token_uuid,
auth_guard.access_token_uuid,
auth_guard.user.id,
Ok((session_end_headers("/"), Json(json!({"status": "success"}))))
/// Ends the session: expires all three cookies and redirects. Shared by logout
/// and the password change, which revokes the very token that made its request
/// and so must not leave the caller on a page whose every fetch now 401s.
pub fn session_end_headers(target: &'static str) -> HeaderMap {
let expire = |name: &'static str| {
Cookie::build((name, ""))
.max_age(time::Duration::minutes(-1))
append_set_cookies(&mut headers, ["access_token", "refresh_token"].map(expire));
headers.append("HX-Redirect", HeaderValue::from_static(target));
headers
#[derive(serde::Deserialize)]
pub struct ChangePasswordSchema {
pub current_password: String,
pub new_password: String,
pub confirm_password: String,
/// Maps a refused password change: a wrong password is the caller's, anything
/// else is ours and must not read as a wrong password.
fn password_change_error(user_id: uuid::Uuid, e: server::command::CmdError) -> WebError {
tracing::warn!("password change refused for user_id={user_id}: {e}");
match e {
server::command::CmdError::Args(_) => {
WebError::bad_request(t!("Invalid email or password").to_string())
e => WebError::from(e),
/// Replaces the caller's password and kills every session including this one.
/// The bump invalidates the token that made this request, so the response
/// clears the cookies and the client is expected to log in again — leaving the
/// caller on a page whose every request has just started failing is worse than
/// sending them to `/login`.
pub async fn change_password_handler(
Extension(jwtauth): Extension<JWTAuthMiddleware>,
Json(body): Json<ChangePasswordSchema>,
// Confirmed before anything is written: the change revokes every session
// and there is no self-service recovery, so a single typo would lock the
// account out until an operator resets it by hand.
if body.new_password != body.confirm_password {
return Err(WebError::bad_request(
t!("The new passwords do not match").to_string(),
));
server::command::user::change_password(
jwtauth.user.id,
&body.current_password,
&body.new_password,
.map_err(|e| password_change_error(jwtauth.user.id, e))?;
session_end_headers("/login"),
Json(json!({ "status": "success" })),
#[cfg(test)]
#[path = "session_tests.rs"]
mod tests;