aboutsummaryrefslogtreecommitdiffstats
path: root/src/api/login.rs
blob: 1907bac28c8054b9b9a05c7f529dd4609afa5031 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! `/auth`: logging in on this node for a token every node of the swarm takes
//! (`access::token`, `access.md`, Tokens), and using it.
//!
//! * `POST /auth/login`, as a user this node lets in (`--htpasswd`, `--user-header`):
//!   a token, signed by this node, valid for `--token-lifetime`, refreshable until
//!   `--session-lifetime` after the login. Optionally less than the user may do
//!   (`{"limit": [{"path": [...], "rights": [...]}, …]}`).
//! * `POST /auth/challenge` and `POST /auth/login/key`, without a password: a challenge
//!   to sign with one of the user's keys, then the same token for it, signed
//!   (`access::challenge`).
//! * `POST /auth/refresh`, with a token: a new one for the same login, signed by this
//!   node, optionally narrower still (`limit`, within the token's).
//! * `POST /auth/logout`: every token of the user, of every login, no longer taken
//!   (`_continuum/logouts/<name>`, `registry::logouts_path`).
//! * `GET /auth/whoami`: who the request's user is, how it proved it, what it may do.
//!
//! * `POST /auth/session`, with a token: `refresh`, and the new token kept in the
//!   browser as a cookie (`SESSION_COOKIE`), so its pages (the dashboard) are let in by
//!   it; `DELETE /auth/session` forgets it. The login page (`GET /login`, without
//!   authentication, with the dashboard) gets one by password or from a token pasted.
//!
//! Every request may bring a token instead of a password: `Authorization: Bearer ct1…`,
//! or, with no `Authorization`, the session cookie (`bearer`).

use crate::document::signatures::Sign;
use std::sync::Arc;

use axum::{
    Extension, Json,
    body::Body,
    extract::State,
    http::{Request, StatusCode, header::AUTHORIZATION},
    response::{IntoResponse, Response},
};
use serde::Deserialize;
use serde_json::{Value as JsonValue, json};
use tracing::{debug, info};

use super::auth::{AuthenticatedUser, Via};
use super::users::CapRequest;
use super::{ApiError, error_response};
use crate::access::token::{self, Claims};
use crate::access::{Capability, challenge, registry};
use crate::locks::MutexExt;
use crate::state::AppState;

/// The token a request came with, as taken (a request extension, set by `bearer`).
#[derive(Clone, Debug)]
pub(crate) struct Token {
    pub(crate) claims: Arc<Claims>,
}

/// The cookie a browser keeps its session's token in (`POST /auth/session`):
/// `HttpOnly`, `SameSite=Strict`, so no script and no other site's page sends it.
pub(crate) const SESSION_COOKIE: &str = "continuum-token";

/// Whether the session cookie lets `request` in: one that reads (`GET`, `HEAD`), or
/// renews or ends the session. One that changes anything brings the token itself
/// (`Authorization`), as a page of another site, or of another port of the same host
/// (which a cookie doesn't tell apart), can't make a browser send it.
fn cookie_lets_in(request: &Request<Body>) -> bool {
    use axum::http::Method;
    let method = request.method();
    method == Method::GET || method == Method::HEAD || request.uri().path() == "/auth/session"
}

/// The session cookie's token, if the request brings one.
fn session_cookie(request: &Request<Body>) -> Option<String> {
    request
        .headers()
        .get_all(axum::http::header::COOKIE)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .flat_map(|value| value.split(';'))
        .filter_map(|pair| pair.trim().split_once('='))
        .find(|(name, _)| *name == SESSION_COOKIE)
        .map(|(_, token)| token.to_owned())
}

/// A request with `Authorization: Bearer <token>`: its user is the token's, if this
/// node takes it (`token::verify`); `401`, saying why, if not. One without
/// `Authorization` but with the session cookie: the cookie's token's, if taken (if not,
/// as if it brought none), for reading only (`cookie_lets_in`). Others go on to
/// `auth::basic_auth`.
pub(crate) async fn bearer(
    State(state): State<AppState>,
    mut request: Request<Body>,
    next: axum::middleware::Next,
) -> Response {
    let authorization = request.headers().get(AUTHORIZATION).cloned();
    let (text, cookie) = match authorization {
        Some(value) => match value
            .to_str()
            .ok()
            .and_then(|value| value.strip_prefix("Bearer "))
        {
            Some(text) => (text.to_owned(), false),
            None => return next.run(request).await,
        },
        None => match session_cookie(&request).filter(|_| cookie_lets_in(&request)) {
            Some(text) => (text, true),
            None => return next.run(request).await,
        },
    };
    let Some(swarm) = state.swarm_id().await else {
        return error_response(
            StatusCode::SERVICE_UNAVAILABLE,
            "not in a swarm yet: tokens are taken once it is",
            None,
        );
    };
    let now = state.clock.now_millis().as_u64();
    let verified = {
        let replica = state.doc.read().await;
        token::verify(&replica.doc, &text, &swarm, now)
    };
    match verified {
        Ok(claims) => {
            request
                .extensions_mut()
                .insert(AuthenticatedUser(claims.user.clone()));
            request.extensions_mut().insert(Via("token"));
            request.extensions_mut().insert(Token {
                claims: Arc::new(claims),
            });
            next.run(request).await
        }
        // A stale session: as if there were none (the login page, a password).
        Err(refused) if cookie => {
            debug!(reason = %refused, "Ignored the session cookie's token");
            next.run(request).await
        }
        Err(refused) => {
            debug!(reason = %refused, "Refused a token");
            error_response(
                StatusCode::UNAUTHORIZED,
                format!("token refused: {refused}"),
                None,
            )
        }
    }
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct LimitRequest {
    #[serde(default)]
    limit: Option<Vec<CapRequest>>,
}

impl LimitRequest {
    fn limit(&self) -> Result<Option<Vec<Capability>>, ApiError> {
        self.limit
            .as_ref()
            .map(|caps| caps.iter().map(|cap| cap.capability("", 0)).collect())
            .transpose()
    }
}

/// `limit` as a token may say it, within `earlier`'s (a refreshed one says no more): each
/// of its capabilities at or below one of `earlier`'s, with some of its rights.
fn within(limit: &[Capability], earlier: &[Capability]) -> bool {
    limit.iter().all(|cap| {
        earlier
            .iter()
            .any(|outer| cap.path.starts_with(&outer.path) && cap.rights.is_subset(&outer.rights))
    })
}

/// `claims` (issued now, by this node), signed, as the answer to a login or refresh.
fn answer(state: &AppState, claims: &Claims) -> Result<Response, ApiError> {
    let key = state
        .node_key
        .as_ref()
        .ok_or(ApiError(StatusCode::SERVICE_UNAVAILABLE, None))?;
    Ok(Json(json!({
        "token": token::issue(key, claims),
        "user": claims.user,
        "issuer": claims.issuer,
        "expiresAt": claims.exp,
        "sessionExpiresAt": claims.session_exp,
        "limit": claims.limit,
    }))
    .into_response())
}

/// The swarm, now, and this node's ID, to issue a token; `503` while not ready.
async fn issuing(state: &AppState) -> Result<(String, u64), ApiError> {
    if !state.is_ready().await || state.node_key.is_none() {
        return Err(StatusCode::SERVICE_UNAVAILABLE.into());
    }
    let swarm = state
        .swarm_id()
        .await
        .ok_or(ApiError(StatusCode::SERVICE_UNAVAILABLE, None))?;
    Ok((swarm, state.clock.now_millis().as_u64()))
}

/// `POST /auth/login`.
pub(crate) async fn login(
    State(state): State<AppState>,
    Extension(user): Extension<AuthenticatedUser>,
    Extension(via): Extension<Via>,
    body: Option<Json<LimitRequest>>,
) -> Result<Response, ApiError> {
    if via == Via("token") {
        return Err(ApiError(
            StatusCode::BAD_REQUEST,
            Some("log in with a password or through the proxy; a token is refreshed at /auth/refresh".to_owned()),
        ));
    }
    let limit = body.map(|Json(body)| body).unwrap_or_default().limit()?;
    let (swarm, now) = issuing(&state).await?;
    {
        let replica = state.doc.read().await;
        if registry::exists(&replica.doc)
            && registry::user(&replica.doc, &user.0).is_none_or(|entry| entry.disabled)
        {
            return Err(ApiError(
                StatusCode::FORBIDDEN,
                Some("not a registered, enabled user (docs/access.md)".to_owned()),
            ));
        }
    }
    let claims = new_login(&state, swarm, now, &user.0, via.0, limit);
    info!(user = %user.0, login = via.0, session = %claims.session, "Logged in");
    answer(&state, &claims)
}

/// The claims of a new login of `user`, by `login`, now: a session of its own.
fn new_login(
    state: &AppState,
    swarm: String,
    now: u64,
    user: &str,
    login: &str,
    limit: Option<Vec<Capability>>,
) -> Claims {
    let session_exp = now.saturating_add(state.session_lifetime.as_millis() as u64);
    Claims {
        v: 1,
        swarm,
        issuer: state.local_id().to_owned(),
        user: user.to_owned(),
        login: login.to_owned(),
        iat: now,
        exp: now
            .saturating_add(state.token_lifetime.as_millis() as u64)
            .min(session_exp),
        session: token::new_session(),
        session_exp,
        limit,
    }
}

/// `POST /auth/challenge`: one to sign for a login by key, valid for five minutes.
pub(crate) async fn challenge(State(state): State<AppState>) -> Result<Response, ApiError> {
    let (_, now) = issuing(&state).await?;
    let key = state
        .node_key
        .as_ref()
        .ok_or(ApiError(StatusCode::SERVICE_UNAVAILABLE, None))?;
    let (challenge, exp) = challenge::issue(key, now);
    Ok(Json(json!({
        "challenge": challenge,
        "namespace": challenge::NAMESPACE,
        "expiresAt": exp,
    }))
    .into_response())
}

/// A login by key's request.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct KeyLogin {
    user: String,
    /// As `POST /auth/challenge` gave it.
    challenge: String,
    /// The user's signature of it, armored, as `ssh-keygen -Y sign -n continuum-login`
    /// writes it.
    signature: String,
    #[serde(default)]
    limit: Option<Vec<CapRequest>>,
}

/// `POST /auth/login/key`: a token, as `POST /auth/login` gives one, for a challenge
/// signed by one of the user's keys (`401` if not, saying why); `409` in a swarm without
/// a registry, which holds no keys.
pub(crate) async fn login_key(
    State(state): State<AppState>,
    Json(request): Json<KeyLogin>,
) -> Result<Response, ApiError> {
    let limit = LimitRequest {
        limit: request.limit,
    }
    .limit()?;
    let (swarm, now) = issuing(&state).await?;
    let key = state
        .node_key
        .as_ref()
        .ok_or(ApiError(StatusCode::SERVICE_UNAVAILABLE, None))?;
    {
        let replica = state.doc.read().await;
        if !registry::exists(&replica.doc) {
            return Err(ApiError(
                StatusCode::CONFLICT,
                Some("no user registry, which holds the users' keys".to_owned()),
            ));
        }
        let mut used = state.challenges.lock_or_recover();
        challenge::take(
            &replica.doc,
            key,
            &request.challenge,
            &request.signature,
            &request.user,
            now,
            &mut used,
        )
        .map_err(|why| {
            debug!(user = %request.user, reason = %why, "Refused a login by key");
            ApiError(StatusCode::UNAUTHORIZED, Some(why))
        })?;
    }
    let claims = new_login(&state, swarm, now, &request.user, "key", limit);
    info!(user = %request.user, login = "key", session = %claims.session, "Logged in");
    answer(&state, &claims)
}

/// `POST /auth/refresh`.
pub(crate) async fn refresh(
    State(state): State<AppState>,
    token: Option<Extension<Token>>,
    body: Option<Json<LimitRequest>>,
) -> Result<Response, ApiError> {
    let claims = refreshed(&state, token, body).await?;
    answer(&state, &claims)
}

/// `POST /auth/session`: `refresh`, and the new token kept as the session cookie, for as
/// long as it is valid.
pub(crate) async fn session(
    State(state): State<AppState>,
    token: Option<Extension<Token>>,
    body: Option<Json<LimitRequest>>,
) -> Result<Response, ApiError> {
    let claims = refreshed(&state, token, body).await?;
    let mut response = answer(&state, &claims)?;
    let key = state
        .node_key
        .as_ref()
        .ok_or(ApiError(StatusCode::SERVICE_UNAVAILABLE, None))?;
    let max_age = claims.exp.saturating_sub(claims.iat) / 1000;
    let cookie = format!(
        "{SESSION_COOKIE}={}; Path=/; HttpOnly; SameSite=Strict; Max-Age={max_age}",
        token::issue(key, &claims)
    );
    if let Ok(value) = axum::http::HeaderValue::from_str(&cookie) {
        response
            .headers_mut()
            .append(axum::http::header::SET_COOKIE, value);
    }
    Ok(response)
}

/// `DELETE /auth/session`: the session cookie forgotten (the token itself stays valid
/// until it expires; `POST /auth/logout` ends every one). A stale one is ignored anyway.
pub(crate) async fn end_session() -> Response {
    (
        StatusCode::NO_CONTENT,
        [(
            axum::http::header::SET_COOKIE,
            format!("{SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0"),
        )],
    )
        .into_response()
}

/// The claims a refresh of `token` gives (`limit` within its own).
async fn refreshed(
    state: &AppState,
    token: Option<Extension<Token>>,
    body: Option<Json<LimitRequest>>,
) -> Result<Claims, ApiError> {
    let Some(Extension(token)) = token else {
        return Err(ApiError(
            StatusCode::BAD_REQUEST,
            Some("refreshing takes a token (Authorization: Bearer …)".to_owned()),
        ));
    };
    let (swarm, now) = issuing(state).await?;
    let earlier = &token.claims;
    if earlier.session_exp <= now {
        return Err(ApiError(
            StatusCode::UNAUTHORIZED,
            Some("the login ended: log in again".to_owned()),
        ));
    }
    let limit = match body.map(|Json(body)| body).unwrap_or_default().limit()? {
        None => earlier.limit.clone(),
        Some(limit) => {
            if earlier
                .limit
                .as_ref()
                .is_some_and(|earlier| !within(&limit, earlier))
            {
                return Err(ApiError(
                    StatusCode::BAD_REQUEST,
                    Some("a refreshed token says no more than the one it comes from".to_owned()),
                ));
            }
            Some(limit)
        }
    };
    let claims = Claims {
        v: 1,
        swarm,
        issuer: state.local_id().to_owned(),
        iat: now,
        exp: now
            .saturating_add(state.token_lifetime.as_millis() as u64)
            .min(earlier.session_exp),
        limit,
        ..(**earlier).clone()
    };
    Ok(claims)
}

/// `POST /auth/logout`.
pub(crate) async fn logout(
    State(state): State<AppState>,
    Extension(user): Extension<AuthenticatedUser>,
) -> Result<StatusCode, ApiError> {
    revoke_tokens(&state, &user.0, &user.0).await?;
    Ok(StatusCode::NO_CONTENT)
}

/// Makes every token of user `name` issued until now no longer taken
/// (`registry::User::tokens_not_before`), as `by`. `409` in a swarm without a
/// registry: there, a token is taken until it expires.
pub(crate) async fn revoke_tokens(state: &AppState, name: &str, by: &str) -> Result<(), ApiError> {
    if !state.is_ready().await {
        return Err(StatusCode::SERVICE_UNAVAILABLE.into());
    }
    let entry = registry::user_path(name);
    let logouts = registry::logouts_path(name);
    // Issued in this very millisecond: revoked too.
    let after = state.clock.now_millis().as_u64() + 1;
    state
        .mutate_doc_for(Some(by.to_owned()), Sign::Protocol, move |doc| {
            if !registry::exists(&*doc) {
                return Err(ApiError(
                    StatusCode::CONFLICT,
                    Some(
                        "no user registry: tokens are taken until they expire (docs/access.md)"
                            .to_owned(),
                    ),
                ));
            }
            if crate::document::store::read_path(&*doc, &entry)?.is_none() {
                return Err(ApiError(StatusCode::NOT_FOUND, None));
            }
            crate::document::store::write_path(doc, &logouts, &json!(after))?;
            Ok(())
        })
        .await?;
    info!(user = %name, by = %by, "Revoked every token of a user");
    Ok(())
}

/// `GET /auth/whoami`.
pub(crate) async fn whoami(
    State(state): State<AppState>,
    Extension(user): Extension<AuthenticatedUser>,
    Extension(via): Extension<Via>,
    token: Option<Extension<Token>>,
) -> Json<JsonValue> {
    let replica = state.doc.read().await;
    let entry = registry::user(&replica.doc, &user.0);
    let token = token.map(|Extension(token)| {
        json!({
            "issuer": token.claims.issuer,
            "login": token.claims.login,
            "issuedAt": token.claims.iat,
            "expiresAt": token.claims.exp,
            "session": token.claims.session,
            "sessionExpiresAt": token.claims.session_exp,
            "limit": token.claims.limit,
        })
    });
    Json(json!({
        "user": user.0,
        "via": via.0,
        "registry": registry::exists(&replica.doc),
        "caps": entry.as_ref().map(|entry| &entry.caps),
        "disabled": entry.as_ref().map(|entry| entry.disabled),
        "token": token,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cap(path: &[&str], rights: &[&str]) -> Capability {
        Capability {
            path: path.iter().map(|s| (*s).to_owned()).collect(),
            rights: rights.iter().map(|s| (*s).to_owned()).collect(),
            by: String::new(),
            since: 0,
        }
    }

    #[test]
    fn a_refreshed_token_says_no_more() {
        let earlier = [cap(&["notes"], &["read", "write"])];
        assert!(within(&[cap(&["notes", "a"], &["read"])], &earlier));
        assert!(within(&[cap(&["notes"], &["read", "write"])], &earlier));
        assert!(!within(&[cap(&[], &["read"])], &earlier));
        assert!(!within(&[cap(&["logs"], &["read"])], &earlier));
        assert!(!within(&[cap(&["notes"], &["read", "grant"])], &earlier));
    }
}