acme-proxy-admin 0.6.1

The operation layer and web admin panel of acme-proxy (internal crate, no semver promise)
Documentation
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! `POST`/`GET`/`DELETE /api/session` — sign in, whoami, sign out.
//!
//! Every failed sign-in answers one `invalid_credentials`, whatever the cause;
//! the reason (`wrong_password`, `unknown_user`, `account_disabled`) is only in
//! the `admin_login_failed` log line. An operator with a second factor gets a
//! `pending_mfa` session first, which can do nothing but finish the login.

use axum::Json;
use axum::extract::{Query, State};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde::Deserialize;
use serde_json::json;
use std::time::Duration;
use tracing::{info, warn};

use crate::admin::mfa::MfaOutcome;
use crate::admin::users::{self, AuthOutcome};
use crate::webadmin::AdminState;
use crate::webadmin::error::AdminError;
use crate::webadmin::handlers::Caller;
use crate::webadmin::session::{
    AdminClientIp, Authenticated, MfaStep, PENDING_MFA_TTL, PendingMfa, PendingMfaSubmit,
    SelfServiceWrite, check_origin, clearing_cookie, cookie_value, hash_token, log_login,
    mint_csrf_token, mint_token, session_cookie,
};
use acme_proxy_store::admin_session::AdminSession;
use acme_proxy_store::admin_session::NewSession;
use acme_proxy_store::admin_user::AdminUser;

/// The credentials of `POST /api/session`, and of the sign-in page's form.
#[derive(Debug, Deserialize)]
pub struct LoginRequest {
    pub username: String,
    pub password: String,
}

/// The query of a sign-out, `DELETE /api/session` or its page twin.
#[derive(Debug, Deserialize, Default)]
pub struct LogoutQuery {
    /// Sign out of every browser, not just this one.
    #[serde(default)]
    pub all: bool,
}

/// The submission that finishes a login: a TOTP code, or a recovery code. One
/// field, because the operator types whichever they have into the same box.
#[derive(Debug, Deserialize)]
pub struct MfaRequest {
    pub code: String,
}

/// A sign-in: the two rows it produced, and the cookie to set.
pub(crate) struct SignedIn {
    pub user: AdminUser,
    pub session: AdminSession,
    /// The `Set-Cookie` value, built once here so the token itself — which is
    /// never stored — does not have to travel any further than this.
    pub cookie: String,
    /// `None` is a *completed* login and an `active` session — the shape every
    /// caller had before there was a second factor.
    pub pending: Option<MfaStep>,
}

/// Everything a sign-in is, independent of how the credentials arrived.
///
/// Called by [`post_session`] with a JSON body and by
/// [`crate::webadmin::pages::session::post_login`] with a form body. The two
/// front ends must not drift on any of this: the origin gate, the limiter
/// running *before* the 600 000-iteration hash, the indistinguishable failures,
/// or the session-fixation delete.
pub(crate) async fn sign_in(
    state: &AdminState,
    client: Option<std::net::IpAddr>,
    headers: &axum::http::HeaderMap,
    credentials: &LoginRequest,
) -> Result<SignedIn, AdminError> {
    let body = credentials;
    check_origin(headers, &state.config.admin.base_url)?;

    let attempt = match state.logins.begin(client) {
        Ok(attempt) => attempt,
        Err(retry_after) => {
            log_login(false, &body.username, client, "rate_limited");
            return Err(AdminError::rate_limited(retry_after));
        }
    };

    let outcome =
        users::authenticate(&body.username, &body.password, state.database.clone()).await?;

    // Every failure answers identically; only the log says which.
    let refused = match outcome {
        AuthOutcome::Authenticated(user) => Ok(*user),
        AuthOutcome::UnknownUser => Err("unknown_user"),
        AuthOutcome::WrongPassword(_) => Err("wrong_password"),
        AuthOutcome::Disabled(_) => Err("account_disabled"),
    };
    let mut user = match refused {
        Ok(user) => user,
        Err(reason) => {
            attempt.failed();
            log_login(false, &body.username, client, reason);
            return Err(AdminError::invalid_credentials());
        }
    };

    // What still stands between this password and a usable session. An
    // operator who *has* a factor is challenged whether `require_mfa` is set or
    // not: the flag governs only the operator who has none.
    let step = if user.has_totp() {
        Some(MfaStep::Verify)
    } else if state.config.admin.require_mfa {
        Some(MfaStep::Enrol)
    } else {
        None
    };

    // Session fixation: whatever session this request already carried is gone,
    // whether or not it was valid. A login must never keep an attacker-planted
    // cookie alive.
    if let Some(existing) = cookie_value(headers) {
        AdminSession::delete(&hash_token(&existing), &state.database).await?;
    }

    let minted = mint_token();
    let csrf_token = mint_csrf_token();
    let created_ip = client.map(|ip| ip.to_string());
    // Capped: an unauthenticated caller writes this into the session row and
    // into the sign-in notification's durable payload.
    let user_agent = crate::webadmin::user_agent_of(headers);

    let Some(step) = step else {
        let ttl = Duration::from_secs(state.config.admin.session_ttl_seconds);
        let session = AdminSession::create(
            NewSession {
                user_id: user.id,
                token_hash: &minted.token_hash,
                csrf_token: &csrf_token,
                created_ip,
                user_agent: user_agent.clone(),
            },
            ttl,
            &state.database,
        )
        .await?;

        let known_before = user.known_login_ips.clone();
        user.mark_logged_in(client_ip_str(client).as_deref(), &state.database)
            .await?;
        state.logins.record_success(client);
        log_login(true, &user.username, client, "");
        notify_sign_in_from_new_address(state, &user, &known_before, client, user_agent).await;

        return Ok(SignedIn {
            user,
            session,
            cookie: session_cookie(&minted.token, ttl),
            pending: None,
        });
    };

    // Half-authenticated. Three things deliberately do **not** happen here, and
    // each would be a real hole:
    //
    // - `record_success`: it clears this address's limiter bucket, so leaving
    //   it here would let somebody holding a correct password reset their own
    //   budget on every attempt and then guess six-digit codes without limit.
    // - `mark_logged_in`: `last_login_at` should mean "completed a login", not
    //   "typed the right password".
    // - `log_login(true, …)`: the login has not succeeded yet.
    //
    // No `attempt.failed()` either: the password *was* right. Dropping the
    // attempt gives its slot back uncounted.
    let session = AdminSession::create_pending(
        NewSession {
            user_id: user.id,
            token_hash: &minted.token_hash,
            csrf_token: &csrf_token,
            created_ip,
            user_agent,
        },
        PENDING_MFA_TTL,
        &state.database,
    )
    .await?;

    info!(event = "admin_login_mfa_pending",
          outcome = "success",
          username = %user.username,
          client_ip = ?client,
          step = step.as_str());

    Ok(SignedIn {
        user,
        session,
        // The cookie's Max-Age follows the row, not the configured session
        // lifetime: a browser holding it for twelve hours after the row died in
        // five minutes only produces a confusing refusal.
        cookie: session_cookie(&minted.token, PENDING_MFA_TTL),
        pending: Some(step),
    })
}

/// Everything finishing a login is, independent of how the code arrived.
///
/// [`sign_in`]'s twin, and shared by [`post_session_mfa`] and
/// `pages::session::post_login_mfa` for the same reason: the limiter, the
/// indistinguishable failures and the token rotation must not drift between the
/// two front ends.
pub(crate) async fn finish_mfa(
    state: &AdminState,
    client: Option<std::net::IpAddr>,
    pending: PendingMfa,
    submitted: &str,
) -> Result<SignedIn, AdminError> {
    // The origin gate already ran, in `PendingMfaSubmit`'s extractor -- it is
    // what stands in for the CSRF token this route cannot have.
    let attempt = match state.logins.begin(client) {
        Ok(attempt) => attempt,
        Err(retry_after) => {
            log_login(false, &pending.user.username, client, "rate_limited");
            return Err(AdminError::rate_limited(retry_after));
        }
    };

    let mut user = pending.user;
    let outcome =
        crate::admin::mfa::verify_second_factor(&mut user, submitted, state.database.clone())
            .await?;

    let MfaOutcome::Accepted { via, .. } = outcome else {
        attempt.failed();

        // The bound the address-keyed limiter cannot provide. A `pending_mfa`
        // cookie is valid from any address on purpose, so without this an
        // attacker holding the password gets `login_max_attempts` fresh guesses
        // per source address -- 2^64 of them from one IPv6 /64, against a
        // six-digit code with a three-step window. The counter lives on the
        // session, so rotating addresses buys nothing, and it is incremented by
        // a single `UPDATE ... RETURNING`, so concurrent submissions cannot
        // each observe zero.
        let spent = AdminSession::record_mfa_failure(&pending.session.token_hash, &state.database)
            .await?
            .is_some_and(|attempts| attempts >= i64::from(state.config.admin.login_max_attempts));

        if spent {
            // Past the cap the half-authenticated session is over, not merely
            // refused: producing the password again is the only way back to a
            // pending row, and `sign_in`'s limiter bounds *that*.
            AdminSession::delete(&pending.session.token_hash, &state.database).await?;
            warn!(event = "admin_mfa_attempts_exhausted",
                  outcome = "failure",
                  username = %user.username,
                  client_ip = ?client,
                  max_attempts = state.config.admin.login_max_attempts);
        }

        warn!(event = "admin_mfa_failed",
              outcome = "failure",
              username = %user.username,
              client_ip = ?client,
              reason = outcome.reason());

        // Tell the operator: a correct password was entered against their
        // account and only the second factor stopped it (V6.3.5). A lockout is
        // its own, sharper signal.
        let user_agent = pending.session.user_agent.clone();
        notify_sign_in(
            state,
            &user,
            acme_proxy_jobs::notify::AdminSignInOutcome::SecondFactorRefused,
            client,
            user_agent.clone(),
        )
        .await;
        if spent {
            notify_sign_in(
                state,
                &user,
                acme_proxy_jobs::notify::AdminSignInOutcome::LockedOut,
                client,
                user_agent,
            )
            .await;
        }

        // The same answer a wrong password gets, and for the same reason: a
        // wrong code, a spent recovery code and a replayed one are one refusal
        // to the client, and only the log says which. Exhausting the attempts
        // is deliberately not a distinguishable answer either -- the next
        // request will simply find no session.
        return Err(AdminError::invalid_credentials());
    };

    let (session, cookie) = promote_pending(state, &pending.session.token_hash).await?;

    let known_before = user.known_login_ips.clone();
    user.mark_logged_in(client_ip_str(client).as_deref(), &state.database)
        .await?;
    state.logins.record_success(client);
    info!(event = "admin_mfa_verified",
          outcome = "success",
          username = %user.username,
          method = via.as_str());
    log_login(true, &user.username, client, "");
    notify_sign_in_from_new_address(
        state,
        &user,
        &known_before,
        client,
        pending.session.user_agent.clone(),
    )
    .await;

    Ok(SignedIn {
        user,
        session,
        cookie,
        pending: None,
    })
}

/// Rotates a `pending_mfa` session into a fresh `active` one, returning the row
/// and the `Set-Cookie` carrying its new token.
///
/// Shared by [`finish_mfa`] and the enrolment-confirm handler, which is the
/// other way a half-authenticated session becomes usable: under
/// `admin.require_mfa`, an operator with no factor finishes their login by
/// *setting one up*, not by proving one.
pub(crate) async fn promote_pending(
    state: &AdminState,
    pending_token_hash: &str,
) -> Result<(AdminSession, String), AdminError> {
    let ttl = Duration::from_secs(state.config.admin.session_ttl_seconds);
    let minted = mint_token();
    let csrf_token = mint_csrf_token();

    let Some(session) = AdminSession::promote(
        pending_token_hash,
        &minted.token_hash,
        &csrf_token,
        ttl,
        &state.database,
    )
    .await?
    else {
        // Lost the race to a concurrent submission, or the row expired between
        // the extractor and here. Either way there is nothing to promote.
        return Err(AdminError::session_invalid());
    };

    Ok((session, session_cookie(&minted.token, ttl)))
}

/// [`finish_mfa`]'s twin for the other way a login completes: setting a factor
/// up rather than proving one.
///
/// Under `admin.require_mfa` an operator with no factor lands on the enrolment
/// page and their session stays `pending_mfa` until they confirm a code. That
/// confirmation **is** a completed sign-in, and it owes the same three pieces of
/// bookkeeping the code path owes:
///
/// - `mark_logged_in`, so `last_login_at` means "completed a login";
/// - `record_success`, so the operator does not leave their own limiter bucket
///   dirty after signing in;
/// - `log_login(true, …)`, without which a first sign-in — the one that hands
///   out a first factor — produces no `admin_login_succeeded` event at all.
///
/// It exists as a shared function for the reason [`finish_mfa`] does: the JSON
/// and HTML front ends each call it, and before it they had drifted, the API
/// side doing none of the three and the pages side one of them.
pub(crate) async fn finish_enrolment(
    state: &AdminState,
    client: Option<std::net::IpAddr>,
    user: &mut acme_proxy_store::admin_user::AdminUser,
    pending_token_hash: &str,
    user_agent: Option<String>,
) -> Result<(AdminSession, String), AdminError> {
    let (session, cookie) = promote_pending(state, pending_token_hash).await?;
    let known_before = user.known_login_ips.clone();
    user.mark_logged_in(client_ip_str(client).as_deref(), &state.database)
        .await?;
    state.logins.record_success(client);
    info!(event = "admin_mfa_enrolled", outcome = "success", username = %user.username);
    log_login(true, &user.username, client, "");
    notify_sign_in_from_new_address(state, user, &known_before, client, user_agent).await;
    Ok((session, cookie))
}

/// `Option<IpAddr>` -> the string form `known_login_ips` / the payloads carry.
fn client_ip_str(client: Option<std::net::IpAddr>) -> Option<String> {
    client.map(|ip| ip.to_string())
}

/// Queues one web-admin security notification about `outcome` for `user`.
async fn notify_sign_in(
    state: &AdminState,
    user: &AdminUser,
    outcome: acme_proxy_jobs::notify::AdminSignInOutcome,
    client: Option<std::net::IpAddr>,
    user_agent: Option<String>,
) {
    state
        .notify_security(acme_proxy_jobs::notify::NotifyEvent::AdminSignIn(
            acme_proxy_jobs::notify::AdminSignInData {
                profile: acme_proxy_jobs::notify::ADMIN_DISPATCHER_KEY.to_string(),
                username: user.username.clone(),
                recipient: user.contact_email.clone(),
                outcome,
                client_ip: client_ip_str(client),
                user_agent,
                at: acme_proxy_store::nonce::now_secs(),
            },
        ))
        .await;
}

/// [`notify_sign_in`] for a completed login, but only when `client` is an
/// address the operator's recent sign-ins did not come from. `known_before` is
/// `known_login_ips` as it was *before* this login folded the current address
/// in. A first-ever login (`known_before` empty) is silent — there is no
/// baseline to be unusual against.
async fn notify_sign_in_from_new_address(
    state: &AdminState,
    user: &AdminUser,
    known_before: &[String],
    client: Option<std::net::IpAddr>,
    user_agent: Option<String>,
) {
    let Some(ip) = client_ip_str(client) else {
        return;
    };
    if known_before.is_empty() || known_before.contains(&ip) {
        return;
    }
    notify_sign_in(
        state,
        user,
        acme_proxy_jobs::notify::AdminSignInOutcome::SucceededFromNewAddress,
        client,
        user_agent,
    )
    .await;
}

/// `POST /api/session` — exchange a username and password for a session cookie.
///
/// The one route that is reachable without a session, so it carries its own
/// protections: the origin gate (there is no CSRF token yet to check) and the
/// rate limiter, which runs **before** the password hash so a flood does not
/// cost 600 000 iterations per attempt. Both live in [`sign_in`], which the
/// sign-in *page* calls too.
pub async fn post_session(
    State(state): State<AdminState>,
    AdminClientIp(client): AdminClientIp,
    headers: axum::http::HeaderMap,
    Json(body): Json<LoginRequest>,
) -> Result<Response, AdminError> {
    let signed_in = sign_in(&state, client, &headers, &body).await?;
    Ok(signed_in_response(&signed_in))
}

/// `GET /api/session/mfa` — what this half-authenticated cookie still owes.
///
/// Unreachable with an `active` session, and with none at all: `PendingMfa` is
/// `Authenticated`'s exact mirror image.
pub async fn get_session_mfa(pending: PendingMfa) -> Json<serde_json::Value> {
    Json(json!({
        "step": pending.step.as_str(),
        "expiresAt": acme_proxy_core::datetime::rfc3339(pending.session.expires_at),
    }))
}

/// `POST /api/session/mfa` — finish a login with a code.
///
/// Takes the submission whichever it is: the TOTP code is tried first and the
/// recovery codes after, because one is an HMAC and the other is up to ten
/// PBKDF2 runs.
///
/// Deliberately **not** CSRF-checked — see [`PendingMfaSubmit`], whose extractor
/// runs the origin gate in its place.
pub async fn post_session_mfa(
    State(state): State<AdminState>,
    AdminClientIp(client): AdminClientIp,
    PendingMfaSubmit(pending): PendingMfaSubmit,
    Json(body): Json<MfaRequest>,
) -> Result<Response, AdminError> {
    let signed_in = finish_mfa(&state, client, pending, &body.code).await?;
    Ok(signed_in_response(&signed_in))
}

/// The `200` both login steps answer with.
///
/// A pending answer carries **no `user` member**: a half-authenticated session
/// must not read operator metadata. It is not a `401` either -- the password
/// *was* right, and a script has to be able to tell those two apart.
fn signed_in_response(signed_in: &SignedIn) -> Response {
    let body = match signed_in.pending {
        None => session_body(&signed_in.user, &signed_in.session),
        Some(step) => json!({
            "mfaRequired": true,
            "step": step.as_str(),
            "csrfToken": signed_in.session.csrf_token,
            "expiresAt": acme_proxy_core::datetime::rfc3339(signed_in.session.expires_at),
        }),
    };

    (
        StatusCode::OK,
        [(header::SET_COOKIE, signed_in.cookie.clone())],
        Json(body),
    )
        .into_response()
}

/// `GET /api/session` — who am I, and what is my CSRF token.
///
/// The CSRF token is returned here as well as at login so a page reloaded on a
/// still-live cookie can pick it up without signing in again.
pub async fn get_session(auth: Authenticated) -> Json<serde_json::Value> {
    Json(session_body(&auth.user, &auth.session))
}

/// `DELETE /api/session[?all=true]` — sign out.
pub async fn delete_session(
    State(state): State<AdminState>,
    Query(query): Query<LogoutQuery>,
    SelfServiceWrite(auth): SelfServiceWrite,
    request_context: acme_proxy_core::audit::RequestContext,
) -> Result<Response, AdminError> {
    apply_logout(&state, &Caller::api(&auth, &request_context), query.all).await?;
    Ok((
        StatusCode::NO_CONTENT,
        [(header::SET_COOKIE, clearing_cookie())],
    )
        .into_response())
}

/// Signs the caller out: the session making the request, or with `all` every
/// session they hold. Only "everywhere" writes an audit row, since it ends
/// sessions the operator is not holding; a plain logout is not a revoke.
///
/// The caller's front end clears the cookie; this ends the row it named.
pub(crate) async fn apply_logout(
    state: &AdminState,
    caller: &Caller<'_>,
    all: bool,
) -> Result<(), AdminError> {
    let scope = if all {
        let revoked = AdminSession::delete_for_user(caller.auth.user.id, &state.database).await?;
        state
            .record_admin_action(caller.request, caller.username(), |actor, ctx| {
                acme_proxy_jobs::auditor::admin::session_revoked(
                    actor,
                    ctx,
                    acme_proxy_jobs::auditor::admin::SessionScope::AllOf(
                        caller.username().to_string(),
                    ),
                    revoked,
                )
            })
            .await;
        "all"
    } else {
        AdminSession::delete(&caller.auth.session.token_hash, &state.database).await?;
        "one"
    };

    tracing::info!(event = "admin_logout",
                   outcome = "success",
                   surface = caller.surface,
                   username = %caller.username(),
                   scope = scope);
    Ok(())
}

/// The body both `POST` and `GET /api/session` return.
fn session_body(user: &AdminUser, session: &AdminSession) -> serde_json::Value {
    json!({
        "user": crate::admin::render_admin_user_json(user),
        "csrfToken": session.csrf_token,
        "expiresAt": acme_proxy_core::datetime::rfc3339(session.expires_at),
    })
}