1
use std::sync::Arc;
2

            
3
use axum::{
4
    Extension, Json,
5
    extract::State,
6
    http::{HeaderMap, HeaderValue, header},
7
    response::IntoResponse,
8
};
9
use axum_extra::extract::{
10
    CookieJar,
11
    cookie::{Cookie, SameSite},
12
};
13
use redis::AsyncCommands;
14
use serde_json::json;
15

            
16
use crate::{
17
    AppState, Config,
18
    jwt_auth::{
19
        JWTAuthMiddleware, REUSE_GRACE_SECS, Redemption, Rotation, end_session, mint_failed,
20
        rotate_refresh,
21
    },
22
    response::{UNAVAILABLE_MESSAGE, WebError},
23
    token::{TokenDetails, TokenType},
24
};
25
use rust_i18n::t;
26

            
27
/// Appends one `Set-Cookie` per rendered cookie. A cookie we built ourselves
28
/// always parses, so a value that somehow does not is dropped rather than
29
/// panicking the request.
30
9
pub(crate) fn append_set_cookies(
31
9
    headers: &mut HeaderMap,
32
9
    cookies: impl IntoIterator<Item = String>,
33
9
) {
34
9
    for cookie in cookies {
35
18
        if let Ok(value) = cookie.parse() {
36
18
            headers.append(header::SET_COOKIE, value);
37
        }
38
    }
39
9
}
40

            
41
/// The two cookies of a session: the access and the refresh token.
42
5
pub(crate) fn session_cookies(conf: &Config, access: String, refresh: String) -> [String; 2] {
43
10
    let build = |name: &'static str, value: String, max_age: i64| {
44
10
        Cookie::build((name, value))
45
10
            .path("/")
46
10
            .max_age(time::Duration::minutes(max_age))
47
10
            .same_site(SameSite::Lax)
48
10
            .secure(crate::auth_keys::secure_cookies())
49
10
            .http_only(true)
50
10
            .to_string()
51
10
    };
52
5
    [
53
5
        build("access_token", access, conf.access_token_max_age),
54
5
        build("refresh_token", refresh, conf.refresh_token_max_age),
55
5
    ]
56
5
}
57

            
58
4
pub(crate) async fn mint_token(
59
4
    user_id: uuid::Uuid,
60
4
    max_age: i64,
61
4
    token_type: TokenType,
62
4
    generation: i32,
63
4
) -> Result<TokenDetails, WebError> {
64
4
    crate::auth_keys::mint(user_id, max_age, token_type, generation)
65
4
        .await
66
4
        .map_err(mint_failed)
67
4
}
68

            
69
pub(crate) async fn save_token_data_to_redis(
70
    data: &Arc<AppState>,
71
    token_details: &TokenDetails,
72
    max_age: i64,
73
) -> Result<(), WebError> {
74
    let mut redis_client = redis_connection(data).await?;
75
    redis_client
76
        .set_ex::<_, _, ()>(
77
            token_details.token_uuid.to_string(),
78
            token_details.user_id.to_string(),
79
            (max_age * 60) as u64,
80
        )
81
        .await
82
        .map_err(|e| WebError::internal("Saving the session failed", e))
83
}
84

            
85
3
async fn redis_connection(
86
3
    data: &Arc<AppState>,
87
3
) -> Result<redis::aio::MultiplexedConnection, WebError> {
88
3
    data.redis_client
89
3
        .get_multiplexed_async_connection()
90
3
        .await
91
        .map_err(|e| {
92
            tracing::error!("Session store unreachable: {e}");
93
            WebError::unavailable(UNAVAILABLE_MESSAGE)
94
        })
95
3
}
96

            
97
5
fn expired() -> WebError {
98
5
    WebError::unauthorized(t!("Token is invalid or session has expired").to_string())
99
5
}
100

            
101
/// The caller's own refresh token, verified and bound to the authenticated user.
102
///
103
/// Binding matters: a client must not present user A's access token with user
104
/// B's refresh token to touch B's session.
105
8
async fn own_refresh_token(
106
8
    cookie_jar: &CookieJar,
107
8
    user_id: uuid::Uuid,
108
8
) -> Result<TokenDetails, WebError> {
109
8
    let refresh_token = cookie_jar
110
8
        .get("refresh_token")
111
4
        .map(|cookie| cookie.value().to_string())
112
8
        .ok_or_else(expired)?;
113

            
114
4
    let details = crate::auth_keys::verify(&refresh_token, TokenType::Refresh)
115
4
        .await
116
        // An unreadable directory is not an expired session.
117
        .map_err(|e| {
118
            tracing::error!("Token directory unreadable: {e}");
119
            WebError::unavailable(UNAVAILABLE_MESSAGE)
120
        })?
121
4
        .ok_or_else(expired)?;
122

            
123
3
    if details.user_id != user_id {
124
        return Err(expired());
125
3
    }
126
3
    Ok(details)
127
8
}
128

            
129
2
fn refreshed_by_session() -> (HeaderMap, Json<serde_json::Value>) {
130
2
    (
131
2
        HeaderMap::new(),
132
2
        Json(json!({"status": "success", "refreshed_by": "session"})),
133
2
    )
134
2
}
135

            
136
6
pub async fn refresh_access_token_handler(
137
6
    cookie_jar: CookieJar,
138
6
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
139
6
    State(data): State<Arc<AppState>>,
140
6
) -> Result<impl IntoResponse, WebError> {
141
    // The middleware ahead of this handler refreshes a dead access token on the
142
    // way in, consuming the cookie this request still carries: report that
143
    // refresh instead of redeeming a token that is already gone.
144
6
    if jwt_auth.refreshed {
145
1
        return Ok(refreshed_by_session());
146
5
    }
147

            
148
5
    let refresh_token_details = own_refresh_token(&cookie_jar, jwt_auth.user.id).await?;
149
2
    let mut redis_client = redis_connection(&data).await?;
150
2
    let user_id = jwt_auth.user.id;
151

            
152
    // Minted BEFORE the rotation: minting touches the tenant database, and a
153
    // failure after the old session is consumed would log the user out. A
154
    // token minted and never registered is inert.
155
2
    let access_token_details = mint_token(
156
2
        user_id,
157
2
        data.conf.access_token_max_age,
158
2
        TokenType::Access,
159
2
        refresh_token_details.generation,
160
2
    )
161
2
    .await?;
162
2
    let new_refresh_details = mint_token(
163
2
        user_id,
164
2
        data.conf.refresh_token_max_age,
165
2
        TokenType::Refresh,
166
2
        refresh_token_details.generation,
167
2
    )
168
2
    .await?;
169

            
170
2
    let redemption = rotate_refresh(
171
2
        &mut redis_client,
172
2
        &Rotation {
173
2
            token_uuid: refresh_token_details.token_uuid,
174
2
            owner: user_id,
175
2
            successor: new_refresh_details.token_uuid,
176
2
            access_uuid: access_token_details.token_uuid,
177
2
            superseded: Some(jwt_auth.access_token_uuid),
178
2
            refresh_ttl: (data.conf.refresh_token_max_age * 60) as u64,
179
2
            access_ttl: (data.conf.access_token_max_age * 60) as u64,
180
2
            grace: REUSE_GRACE_SECS,
181
2
        },
182
2
    )
183
2
    .await?;
184
2
    match redemption {
185
1
        Redemption::Rotated => {}
186
1
        Redemption::Reused => return Ok(refreshed_by_session()),
187
        Redemption::Refused => return Err(expired()),
188
    }
189

            
190
1
    let access = access_token_details.token.unwrap_or_default();
191
1
    let mut headers = HeaderMap::new();
192
1
    append_set_cookies(
193
1
        &mut headers,
194
1
        session_cookies(
195
1
            &data.conf,
196
1
            access.clone(),
197
1
            new_refresh_details.token.unwrap_or_default(),
198
1
        ),
199
1
    );
200
1
    Ok((
201
1
        headers,
202
1
        Json(json!({"status": "success", "access_token": access})),
203
1
    ))
204
6
}
205

            
206
1
pub async fn logout_handler(
207
1
    cookie_jar: CookieJar,
208
1
    Extension(auth_guard): Extension<JWTAuthMiddleware>,
209
1
    State(data): State<Arc<AppState>>,
210
1
) -> Result<impl IntoResponse, WebError> {
211
1
    let refresh_token_details = own_refresh_token(&cookie_jar, auth_guard.user.id).await?;
212
1
    let mut redis_client = redis_connection(&data).await?;
213

            
214
1
    end_session(
215
1
        &mut redis_client,
216
1
        refresh_token_details.token_uuid,
217
1
        auth_guard.access_token_uuid,
218
1
        auth_guard.user.id,
219
1
    )
220
1
    .await?;
221

            
222
1
    Ok((session_end_headers("/"), Json(json!({"status": "success"}))))
223
1
}
224

            
225
/// Ends the session: expires all three cookies and redirects. Shared by logout
226
/// and the password change, which revokes the very token that made its request
227
/// and so must not leave the caller on a page whose every fetch now 401s.
228
4
pub fn session_end_headers(target: &'static str) -> HeaderMap {
229
8
    let expire = |name: &'static str| {
230
8
        Cookie::build((name, ""))
231
8
            .path("/")
232
8
            .max_age(time::Duration::minutes(-1))
233
8
            .same_site(SameSite::Lax)
234
8
            .secure(crate::auth_keys::secure_cookies())
235
8
            .http_only(true)
236
8
            .to_string()
237
8
    };
238

            
239
4
    let mut headers = HeaderMap::new();
240
4
    append_set_cookies(&mut headers, ["access_token", "refresh_token"].map(expire));
241
4
    headers.append("HX-Redirect", HeaderValue::from_static(target));
242
4
    headers
243
4
}
244

            
245
#[derive(serde::Deserialize)]
246
pub struct ChangePasswordSchema {
247
    pub current_password: String,
248
    pub new_password: String,
249
    pub confirm_password: String,
250
}
251

            
252
/// Maps a refused password change: a wrong password is the caller's, anything
253
/// else is ours and must not read as a wrong password.
254
4
fn password_change_error(user_id: uuid::Uuid, e: server::command::CmdError) -> WebError {
255
4
    tracing::warn!("password change refused for user_id={user_id}: {e}");
256
4
    match e {
257
        server::command::CmdError::Args(_) => {
258
2
            WebError::bad_request(t!("Invalid email or password").to_string())
259
        }
260
2
        e => WebError::from(e),
261
    }
262
4
}
263

            
264
/// Replaces the caller's password and kills every session including this one.
265
///
266
/// The bump invalidates the token that made this request, so the response
267
/// clears the cookies and the client is expected to log in again — leaving the
268
/// caller on a page whose every request has just started failing is worse than
269
/// sending them to `/login`.
270
2
pub async fn change_password_handler(
271
2
    Extension(jwtauth): Extension<JWTAuthMiddleware>,
272
2
    Json(body): Json<ChangePasswordSchema>,
273
2
) -> Result<impl IntoResponse, WebError> {
274
    // Confirmed before anything is written: the change revokes every session
275
    // and there is no self-service recovery, so a single typo would lock the
276
    // account out until an operator resets it by hand.
277
2
    if body.new_password != body.confirm_password {
278
2
        return Err(WebError::bad_request(
279
2
            t!("The new passwords do not match").to_string(),
280
2
        ));
281
    }
282

            
283
    server::command::user::change_password(
284
        jwtauth.user.id,
285
        &body.current_password,
286
        &body.new_password,
287
    )
288
    .await
289
    .map_err(|e| password_change_error(jwtauth.user.id, e))?;
290

            
291
    Ok((
292
        session_end_headers("/login"),
293
        Json(json!({ "status": "success" })),
294
    ))
295
2
}
296

            
297
#[cfg(test)]
298
#[path = "session_tests.rs"]
299
mod tests;