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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
//! Session tokens, the cookie they travel in, the extractors that resolve
//! them, the CSRF check, and the login rate limiter.
//!
//! ## The token
//!
//! 32 bytes from the system CSPRNG, base64url-unpadded (43 characters, cookie-
//! safe unquoted). Stored as `hex(SHA-256(token))` and never in plaintext, so
//! a read of the database — a backup, a `.dump`, an injection — yields nothing
//! replayable. Not the password KDF: the token has 256 bits of entropy, so
//! there is no dictionary to slow down and a slow hash would buy nothing but
//! latency on every request. Lookup is by the hash, and the value looked up
//! *is* the secret, so that path needs no constant-time comparison — unlike
//! the CSRF token, which is compared against a caller-supplied string.
//!
//! ## CSRF, and why `SameSite=Strict` is not enough
//!
//! The usual answer is that SameSite covers it. It does not, here, and the
//! reason is specific: **SameSite is scoped to the registrable domain, not the
//! origin — different ports of the same host are same-site.** A panel on
//! `:3001` beside anything else on `:8080` of the same box is exactly the
//! configuration it does not protect. So there is a per-session token as well,
//! plus an origin gate that also covers login (which by definition carries no
//! session token yet).
//!
//! Enforcement is **structural**: one of [`AuthenticatedWrite`],
//! [`AdminWrite`] or [`SelfServiceWrite`] is the only way for a mutating
//! handler to reach a session, and constructing any of them runs the origin
//! and CSRF checks. The three differ only in the privilege tier they demand —
//! `operator`+, `admin`, and none (own-account routes) — so a handler that
//! forgets the role check cannot compile. Same reasoning as hoisting the
//! media-type/`crit`/`url`/nonce checks into `AcmeRequest` — a new endpoint
//! cannot forget what it cannot express.

use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Mutex;
use std::time::Duration;

use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::{HeaderMap, header};
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL_SAFE_NO_PAD;
use ring::rand::{SecureRandom, SystemRandom};
use subtle::ConstantTimeEq;
use tracing::{info, warn};

use crate::webadmin::AdminState;
use crate::webadmin::error::AdminError;
use acme_proxy_store::admin_session::AdminSession;
use acme_proxy_store::admin_user::AdminRole;
use acme_proxy_store::admin_user::AdminUser;
use acme_proxy_store::nonce::fingerprint;
use acme_proxy_store::nonce::now_secs;

/// The session cookie's name.
///
/// The `__Host-` prefix is free, browser-enforced hardening: it *requires*
/// `Secure`, `Path=/` and no `Domain`, which is exactly the spec chosen below.
/// A future edit that drops `Secure` therefore breaks the cookie visibly
/// instead of silently widening it.
pub const COOKIE_NAME: &str = "__Host-acme_admin_session";

/// The header carrying the per-session CSRF token on unsafe methods.
pub const CSRF_HEADER: &str = "x-csrf-token";

/// Session token length in bytes. 256 bits — the same size
/// `acme_proxy_store::eab::generate_secret` chooses, and for the same reason.
const TOKEN_LEN: usize = 32;

/// How stale `last_seen_at` may get before a request bothers to advance it.
///
/// Without this, a page polling every few seconds would take the WAL writer
/// lock on every request just to move a timestamp by a second.
const SESSION_TOUCH_INTERVAL: i64 = 60;

/// How long a half-authenticated session may sit unfinished.
///
/// Deliberately **not** `admin.session_ttl_seconds` and deliberately not a
/// configuration key. A `pending_mfa` row is a password that has been accepted
/// and nothing more; it should not outlive the tab that created it. Five
/// minutes is longer than reading a code off a phone and shorter than walking
/// away from the keyboard -- a UI timing constant, not a policy an operator
/// tunes.
///
/// It is also the only per-session bound on code guessing: within it an
/// attacker holding a correct password gets `admin.login_max_attempts` tries
/// from one address, and then the row is gone regardless.
pub const PENDING_MFA_TTL: Duration = Duration::from_secs(300);

/// A freshly minted session token, and the hash to store for it.
pub struct MintedToken {
    /// Goes in the `Set-Cookie` and is never written down.
    pub token: String,
    /// Goes in `admin_sessions.token_hash`.
    pub token_hash: String,
}

/// Mints a session token. RNG failure is unrecoverable, as elsewhere in this
/// crate.
#[must_use]
pub fn mint_token() -> MintedToken {
    let mut bytes = [0u8; TOKEN_LEN];
    SystemRandom::new()
        .fill(&mut bytes)
        .expect("system RNG unavailable");
    let token = BASE64_URL_SAFE_NO_PAD.encode(bytes);
    let token_hash = hash_token(&token);
    MintedToken { token, token_hash }
}

/// Mints a CSRF token. Same entropy as a session token — it is stored in
/// plaintext, but it still has to be unguessable.
#[must_use]
pub fn mint_csrf_token() -> String {
    let mut bytes = [0u8; TOKEN_LEN];
    SystemRandom::new()
        .fill(&mut bytes)
        .expect("system RNG unavailable");
    BASE64_URL_SAFE_NO_PAD.encode(bytes)
}

/// `hex(SHA-256(token))` — the `admin_sessions` primary key.
#[must_use]
pub fn hash_token(token: &str) -> String {
    let digest = ring::digest::digest(&ring::digest::SHA256, token.as_bytes());
    hex::encode(digest.as_ref())
}

/// The `Set-Cookie` value that establishes a session.
#[must_use]
pub fn session_cookie(token: &str, ttl: Duration) -> String {
    format!(
        "{COOKIE_NAME}={token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age={}",
        ttl.as_secs()
    )
}

/// The `Set-Cookie` value that clears one.
#[must_use]
pub fn clearing_cookie() -> String {
    format!("{COOKIE_NAME}=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0")
}

/// Reads the session token out of a `Cookie` header set.
///
/// Hand-rolled rather than pulling in `axum-extra` or `cookie` for twenty
/// lines. Takes the **first** match, across all `Cookie` headers: a crafted
/// request carrying the name twice must not let the second one win, which is a
/// session-fixation vector.
#[must_use]
pub fn cookie_value(headers: &HeaderMap) -> Option<String> {
    for header in headers.get_all(header::COOKIE) {
        let Ok(raw) = header.to_str() else { continue };
        for pair in raw.split(';') {
            let Some((name, value)) = pair.split_once('=') else {
                continue;
            };
            if name.trim() == COOKIE_NAME {
                // A cookie value may be quoted (RFC 6265 §4.1.1).
                let value = value.trim();
                let value = value
                    .strip_prefix('"')
                    .and_then(|v| v.strip_suffix('"'))
                    .unwrap_or(value);
                return Some(value.to_string());
            }
        }
    }
    None
}

/// The client address of an admin request, if the socket carried one.
///
/// Its own extractor rather than [`acme_proxy_core::client::ClientIp`], so a
/// router built without the `[admin.filter]` layer (a test driving one handler)
/// still gets the socket peer rather than `None`.
///
/// **Forwarded headers only from `admin.filter.trusted_proxies`.** That layer
/// resolves the address and records a `ClientIp`, which this prefers; its
/// absence falls back to the peer. Honouring `X-Forwarded-For` from anyone else
/// would let a caller spoof the key the login limiter counts on — and with no
/// trusted proxy listed, the limiter behind a reverse proxy counts the proxy.
#[derive(Debug, Clone, Copy)]
pub struct AdminClientIp(pub Option<IpAddr>);

impl<S: Sync> FromRequestParts<S> for AdminClientIp {
    type Rejection = std::convert::Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        if let Some(acme_proxy_core::client::ClientIp(resolved)) = parts
            .extensions
            .get::<acme_proxy_core::client::ClientIp>()
            .copied()
        {
            return Ok(AdminClientIp(resolved));
        }
        let address = parts
            .extensions
            .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
            // Canonicalized for the same reason `ProxyPolicy::resolve` does it:
            // a dual-stack listener sees an IPv4 client as `::ffff:…`, and two
            // spellings of one address would be two buckets.
            .map(|info| info.0.ip().to_canonical());
        Ok(AdminClientIp(address))
    }
}

/// What still stands between a `pending_mfa` cookie and a usable session.
///
/// Not derivable from the session row alone, which is why it is carried rather
/// than recomputed: both states are one `pending_mfa` row, and the difference
/// is `user.has_totp()`. Making each caller re-derive it is exactly the drift
/// this codebase avoids.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MfaStep {
    /// A confirmed factor exists: prove a code, or spend a recovery code.
    Verify,
    /// `admin.require_mfa` is on and this operator has none: enrol first.
    Enrol,
}

impl MfaStep {
    /// The wire and template spelling.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            MfaStep::Verify => "verify",
            MfaStep::Enrol => "enrol",
        }
    }
}

/// A live session and the operator it belongs to. Read-only handlers take this.
#[derive(Debug)]
pub struct Authenticated {
    pub session: AdminSession,
    pub user: AdminUser,
}

/// [`Authenticated`], the origin gate and the CSRF check, **plus a privilege
/// tier of at least [`AdminRole::Operator`]**.
///
/// Every mutating handler that touches shared or CA state takes this. None of
/// the three checks can be forgotten, because this type is the only way such a
/// handler can reach a session at all. A `viewer` is refused here; the
/// own-account routes a `viewer` may still use take [`SelfServiceWrite`]
/// instead, and the colleague-management routes take [`AdminWrite`].
#[derive(Debug)]
pub struct AuthenticatedWrite(pub Authenticated);

/// [`AuthenticatedWrite`], but requiring the full [`AdminRole::Admin`] tier.
///
/// The four `/operators/*` routes take this: disabling or re-enabling a
/// colleague, resetting their second factor, revoking one of their sessions.
#[derive(Debug)]
pub struct AdminWrite(pub Authenticated);

/// The origin gate, a live `active` session and the CSRF check -- **no
/// privilege check**, so any role including `viewer` passes.
///
/// The own-account routes take this: change your own password, revoke your own
/// sessions, manage your own second factor, log out. A `viewer` has to be able
/// to do these or `admin.require_mfa` enrolment would be unreachable for them.
#[derive(Debug)]
pub struct SelfServiceWrite(pub Authenticated);

/// [`Authenticated`] **plus a privilege tier of [`AdminRole::Admin`]** -- the
/// read-side sibling of [`AdminWrite`], with no CSRF or origin gate, since a
/// `GET` changes nothing.
///
/// The `/operators` read routes take this. What they render is every
/// colleague's role and contact address, the last addresses each signed in
/// from, and every live session's fingerprint, address and last-seen time --
/// "who else is an admin here, and from where do they work" is exactly the
/// reconnaissance a `viewer` tier exists to withhold, so the reads are gated to
/// the same tier as the writes rather than to a live session alone.
///
/// Nothing else on this listener needs it: every other read is either the
/// caller's own (`/account/*`) or CA state a `viewer` is meant to see.
#[derive(Debug)]
pub struct AdminRead(pub Authenticated);

impl FromRequestParts<AdminState> for Authenticated {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        resolve_session(parts, state).await
    }
}

/// The origin gate + live `active` session + CSRF check the three write
/// extractors share. Each then adds (or omits) its own privilege check.
async fn resolve_write(parts: &Parts, state: &AdminState) -> Result<Authenticated, AdminError> {
    // The origin gate first: it is free, and it refuses a cross-origin
    // request before a database lookup happens on its behalf.
    check_origin(&parts.headers, &state.config.admin.base_url)?;
    let authenticated = resolve_session(parts, state).await?;
    check_csrf(&parts.headers, &authenticated.session.csrf_token)?;
    Ok(authenticated)
}

/// The privilege gate. `role()` resolves a `NULL` column to
/// [`AdminRole::Admin`], so an operator that predates the `role` column is
/// unaffected.
fn require_role(user: &AdminUser, minimum: AdminRole) -> Result<(), AdminError> {
    if user.role() >= minimum {
        Ok(())
    } else {
        Err(AdminError::insufficient_role())
    }
}

impl FromRequestParts<AdminState> for AdminRead {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        // No `resolve_write`: there is no body to forge and no state change to
        // ride, so the origin and CSRF gates buy nothing on a read. The tier is
        // the whole of what this adds over `Authenticated`.
        let authenticated = resolve_session(parts, state).await?;
        require_role(&authenticated.user, AdminRole::Admin)?;
        Ok(AdminRead(authenticated))
    }
}

impl FromRequestParts<AdminState> for AuthenticatedWrite {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        let authenticated = resolve_write(parts, state).await?;
        require_role(&authenticated.user, AdminRole::Operator)?;
        Ok(AuthenticatedWrite(authenticated))
    }
}

impl FromRequestParts<AdminState> for AdminWrite {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        let authenticated = resolve_write(parts, state).await?;
        require_role(&authenticated.user, AdminRole::Admin)?;
        Ok(AdminWrite(authenticated))
    }
}

impl FromRequestParts<AdminState> for SelfServiceWrite {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        Ok(SelfServiceWrite(resolve_write(parts, state).await?))
    }
}

/// A session with a verified password and nothing more.
///
/// Its own extractor with its own resolver, because [`resolve_session`] hard-
/// refuses a non-`active` session -- deliberately, so no ordinary route can
/// accept a half-authenticated one. This is its exact mirror image: it refuses
/// an `active` one.
#[derive(Debug)]
pub struct PendingMfa {
    pub session: AdminSession,
    pub user: AdminUser,
    pub step: MfaStep,
}

/// [`PendingMfa`] with the **origin gate only, and no CSRF check.**
///
/// The omission is deliberate, and is the same one `POST /ui/login` already
/// makes one step earlier: the challenge page is a plain form -- sign-in must
/// work with JavaScript off, which `tests/admin_pages.rs` pins for `login.html`
/// -- and [`check_csrf`] reads a header a form cannot set. Teaching it to read a
/// form field instead would be a second CSRF path, which is what
/// `pages::auth`'s whole shape exists to prevent.
///
/// What covers the route is [`check_origin`], and the residual risk is nil: a
/// cross-site forger would need a valid code for a session they cannot read,
/// and success would only complete the victim's own login.
#[derive(Debug)]
pub struct PendingMfaSubmit(pub PendingMfa);

/// A session allowed to *set up* a factor.
///
/// Either an `active` session -- voluntary enrolment, or moving to a new phone
/// -- or a `pending_mfa` one that exists precisely because the operator has none
/// and `admin.require_mfa` is on.
///
/// **The `pending_mfa` case requires `!user.has_totp()`, and that condition is
/// the whole security of this type.** A session that owes a *code* must never
/// reach an enrolment route, or the second factor is bypassable by enrolling a
/// new one over it.
///
/// Runs [`check_origin`] and [`check_csrf`] exactly as [`AuthenticatedWrite`]
/// does: unlike the challenge form, these routes are htmx calls from a page
/// that was handed a token.
#[derive(Debug)]
pub struct EnrolWrite {
    pub session: AdminSession,
    pub user: AdminUser,
    /// `true` when this session is still `pending_mfa`, so the handler knows to
    /// promote it once the enrolment confirms.
    pub pending: bool,
}

impl FromRequestParts<AdminState> for PendingMfa {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        resolve_pending(parts, state).await
    }
}

impl FromRequestParts<AdminState> for PendingMfaSubmit {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        check_origin(&parts.headers, &state.config.admin.base_url)?;
        Ok(PendingMfaSubmit(resolve_pending(parts, state).await?))
    }
}

impl FromRequestParts<AdminState> for EnrolWrite {
    type Rejection = AdminError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AdminState,
    ) -> Result<Self, Self::Rejection> {
        check_origin(&parts.headers, &state.config.admin.base_url)?;
        let (_, session, user) = resolve_live(parts, state).await?;

        // The refusal this type exists for. A `pending_mfa` session whose owner
        // already *has* a factor owes a code, and letting it enrol a second one
        // would make the first optional.
        if !session.is_active() && user.has_totp() {
            return Err(AdminError::session_invalid());
        }

        check_csrf(&parts.headers, &session.csrf_token)?;
        let pending = !session.is_active();
        Ok(EnrolWrite {
            session,
            user,
            pending,
        })
    }
}

/// Cookie → live row → live user.
///
/// Judges *liveness* only -- expiry, idleness, the orphan case, a disabled owner
/// -- and never `state`. That is what lets two extractors sit over one lookup
/// without either being a widening of the other: each adds its own opposite
/// state check on top.
async fn resolve_live(
    parts: &Parts,
    state: &AdminState,
) -> Result<(String, AdminSession, AdminUser), AdminError> {
    let token = cookie_value(&parts.headers).ok_or_else(AdminError::session_invalid)?;
    let token_hash = hash_token(&token);

    let Some(session) = AdminSession::find_by_token_hash(&token_hash, &state.database).await?
    else {
        return Err(AdminError::session_invalid());
    };

    let now = now_secs();
    if session.is_expired(now) {
        AdminSession::delete(&token_hash, &state.database).await?;
        return Err(AdminError::session_expired());
    }
    let idle_timeout = Duration::from_secs(state.config.admin.session_idle_timeout_seconds);
    if session.is_idle(now, idle_timeout) {
        AdminSession::delete(&token_hash, &state.database).await?;
        return Err(AdminError::session_idle());
    }

    let Some(user) = AdminUser::find_by_id(session.user_id, &state.database).await? else {
        // The FK cascade should make this impossible; if it happens, the
        // session is orphaned and must not authenticate anybody.
        warn!(event = "admin_session_orphaned", outcome = "failure", session_fp = %fingerprint(&token_hash));
        AdminSession::delete(&token_hash, &state.database).await?;
        return Err(AdminError::session_invalid());
    };
    if !user.is_active() {
        return Err(AdminError::session_invalid());
    }

    Ok((token_hash, session, user))
}

/// Resolves the cookie to a live, **fully authenticated** session, refusing each
/// way it can be dead with its own code — the client is told to sign in again
/// either way, but the operator reading a log can tell an expiry from a
/// revocation.
async fn resolve_session(parts: &Parts, state: &AdminState) -> Result<Authenticated, AdminError> {
    let (_, mut session, user) = resolve_live(parts, state).await?;

    // `pending_mfa`: a password was accepted and nothing more. Only the routes
    // that finish the login may see such a session, and they go through
    // `resolve_pending` instead.
    if !session.is_active() {
        return Err(AdminError::session_invalid());
    }

    if now_secs() - session.last_seen_at >= SESSION_TOUCH_INTERVAL {
        session.touch(&state.database).await?;
    }

    Ok(Authenticated { session, user })
}

/// [`resolve_session`]'s mirror image: a live session that is **not** yet
/// active.
///
/// Does not touch `last_seen_at`. A pending row has a five-minute absolute
/// deadline, so advancing an idle deadline it will never reach would be pure
/// cost on the login path.
async fn resolve_pending(parts: &Parts, state: &AdminState) -> Result<PendingMfa, AdminError> {
    let (_, session, user) = resolve_live(parts, state).await?;

    if session.is_active() {
        return Err(AdminError::session_invalid());
    }

    let step = if user.has_totp() {
        MfaStep::Verify
    } else {
        MfaStep::Enrol
    };
    Ok(PendingMfa {
        session,
        user,
        step,
    })
}

/// Compares the request's `X-CSRF-Token` against the session's, in constant
/// time.
pub fn check_csrf(headers: &HeaderMap, expected: &str) -> Result<(), AdminError> {
    let Some(supplied) = headers.get(CSRF_HEADER).and_then(|v| v.to_str().ok()) else {
        return Err(AdminError::csrf_failed(format!(
            "this request needs an {CSRF_HEADER} header carrying the session's csrfToken"
        )));
    };

    // `ct_eq` is only constant-time across equal lengths; comparing the
    // lengths first leaks nothing a token's own encoding does not already fix.
    let matches = supplied.len() == expected.len()
        && bool::from(supplied.as_bytes().ct_eq(expected.as_bytes()));
    if !matches {
        return Err(AdminError::csrf_failed(
            "the CSRF token does not match this session",
        ));
    }
    Ok(())
}

/// Refuses a request whose `Origin` or `Sec-Fetch-Site` says it came from
/// somewhere else.
///
/// Both headers are checked only when *present*: a non-browser client (curl,
/// a script) sends neither and is not the threat this addresses. Its value is
/// covering the login request, which carries no session and therefore no CSRF
/// token to check.
pub fn check_origin(headers: &HeaderMap, base_url: &str) -> Result<(), AdminError> {
    if let Some(site) = headers.get("sec-fetch-site").and_then(|v| v.to_str().ok())
        && site != "same-origin"
        && site != "none"
    {
        return Err(AdminError::csrf_failed(format!(
            "cross-origin request refused (Sec-Fetch-Site: {site})"
        )));
    }

    if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
        let expected = url::Url::parse(base_url)
            .map(|u| u.origin().ascii_serialization())
            .unwrap_or_default();
        if origin != expected {
            return Err(AdminError::csrf_failed(format!(
                "cross-origin request refused (Origin: {origin}, expected {expected})"
            )));
        }
    }
    Ok(())
}

/// Fixed-window failed-login counter, keyed by client address.
///
/// In-process on purpose: it protects a listener that defaults to loopback and
/// holds a handful of accounts, and a database-backed counter would add a
/// write to the very path being flooded.
///
/// **An attempt is counted when it starts, not when it fails.** [`begin`]
/// reserves a slot under the lock and refuses once failures *plus attempts
/// still in flight* reach the limit. Counting only finished failures was a
/// check-then-act race: a burst of parallel requests from one address all
/// passed the check before the first of them had paid its 600 000 iterations
/// and recorded anything, so the burst bought as many guesses — and as much
/// KDF time — as it had requests. The slot is a [`LoginAttempt`] guard, so
/// every early return (a database error included) gives it back.
///
/// [`begin`]: LoginLimiter::begin
#[derive(Debug)]
pub struct LoginLimiter {
    max_attempts: u32,
    window: Duration,
    buckets: Mutex<HashMap<IpAddr, Bucket>>,
}

#[derive(Debug, Clone, Copy)]
struct Bucket {
    failures: u32,
    /// Attempts begun and not yet settled. Never carried across a reload: see
    /// [`LoginLimiter::rebuilt`].
    in_flight: u32,
    window_started: i64,
}

/// The bucket an address counts against.
///
/// An IPv6 client is keyed by its /64. A single subscriber routinely holds a
/// whole /64 and can rotate through it at will, so keying the full /128 gave
/// one attacker 2^64 fresh budgets. An IPv4-mapped address is its IPv4 self.
fn bucket_key(client: IpAddr) -> IpAddr {
    match client.to_canonical() {
        IpAddr::V4(v4) => IpAddr::V4(v4),
        IpAddr::V6(v6) => {
            let prefix = u128::from(v6) & (u128::MAX << 64);
            IpAddr::V6(std::net::Ipv6Addr::from(prefix))
        }
    }
}

impl LoginLimiter {
    /// At most `max_attempts` failures per client address (an IPv6 address by
    /// its /64) within `window_seconds`.
    #[must_use]
    pub fn new(max_attempts: u32, window_seconds: u64) -> Self {
        Self {
            max_attempts,
            window: Duration::from_secs(window_seconds),
            buckets: Mutex::new(HashMap::new()),
        }
    }

    /// The same counters under new limits.
    ///
    /// A configuration reload rebuilds the admin router, and with it every value
    /// `AdminState` derives from `[admin]` — which for this type would mean
    /// starting from an empty map. That is a security regression, not a cosmetic
    /// one: a reload in the middle of a brute-force attempt would clear the
    /// attacker's backoff, and `admin.login_*` is exactly the sort of key an
    /// operator edits *because* they are being flooded.
    ///
    /// Carrying the whole limiter across instead would be the other error,
    /// leaving `login_max_attempts` and `login_window_seconds` silently stale.
    /// So the counters move and the limits do not.
    ///
    /// The in-flight counts do **not** move: their guards hold the old limiter
    /// and settle against it, so a count copied here would never be released.
    /// The cost is that an attempt straddling a reload is not counted, once.
    #[must_use]
    pub fn rebuilt(&self, max_attempts: u32, window_seconds: u64) -> Self {
        let mut buckets =
            std::mem::take(&mut *self.buckets.lock().unwrap_or_else(|e| e.into_inner()));
        for bucket in buckets.values_mut() {
            bucket.in_flight = 0;
        }
        Self {
            max_attempts,
            window: Duration::from_secs(window_seconds),
            buckets: Mutex::new(buckets),
        }
    }

    /// Starts a login attempt from this address, or refuses it. `Err` carries
    /// the seconds left in the window.
    ///
    /// Called **before** the password hash runs: 600 000 iterations is a
    /// denial-of-service lever, so a limited caller must not pay it — nor make
    /// the server pay it. The returned guard holds the slot until it is
    /// [`failed`](LoginAttempt::failed) or dropped.
    pub fn begin(&self, client: Option<IpAddr>) -> Result<LoginAttempt<'_>, u64> {
        // No address means no key. This is not a bypass: the limiter is a
        // convenience over the bind address and the session, and an admin
        // listener always has a peer address in practice (`TapIo` carries it
        // through TLS). Failing closed here would lock out every request
        // rather than every attacker.
        let Some(key) = client.map(bucket_key) else {
            return Ok(LoginAttempt {
                limiter: self,
                key: None,
            });
        };
        let now = now_secs();
        let window = self.window.as_secs() as i64;

        let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
        // Pruned under the same lock, so the map cannot grow without bound. A
        // bucket with an attempt in flight is kept, its failures forgotten.
        buckets.retain(|_, bucket| now - bucket.window_started < window || bucket.in_flight > 0);

        let bucket = buckets.entry(key).or_insert(Bucket {
            failures: 0,
            in_flight: 0,
            window_started: now,
        });
        if now - bucket.window_started >= window {
            bucket.failures = 0;
            bucket.window_started = now;
        }
        if bucket.failures.saturating_add(bucket.in_flight) >= self.max_attempts {
            return Err((window - (now - bucket.window_started)).max(1) as u64);
        }
        bucket.in_flight += 1;
        Ok(LoginAttempt {
            limiter: self,
            key: Some(key),
        })
    }

    /// Clears an address's counter after a completed login, so one operator
    /// fumbling their password does not spend the window for the next.
    pub fn record_success(&self, client: Option<IpAddr>) {
        let Some(key) = client.map(bucket_key) else {
            return;
        };
        let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(bucket) = buckets.get_mut(&key) {
            // Another attempt may still be in flight; its guard needs the
            // bucket to settle against.
            bucket.failures = 0;
            if bucket.in_flight == 0 {
                buckets.remove(&key);
            }
        }
    }

    /// Gives back an in-flight slot, and turns it into a failure if `failed`.
    fn settle(&self, key: IpAddr, failed: bool) {
        let mut buckets = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
        // Absent when `rebuilt` emptied this limiter mid-attempt.
        let Some(bucket) = buckets.get_mut(&key) else {
            return;
        };
        bucket.in_flight = bucket.in_flight.saturating_sub(1);
        if failed {
            bucket.failures += 1;
        } else if bucket.failures == 0 && bucket.in_flight == 0 {
            buckets.remove(&key);
        }
    }
}

/// One login attempt's slot in the [`LoginLimiter`].
///
/// Dropping it releases the slot without counting anything: a correct password
/// waiting on its second factor, a refused origin, a database error. Only
/// [`failed`](Self::failed) spends the budget.
#[derive(Debug)]
#[must_use = "dropping the attempt releases its slot at once"]
pub struct LoginAttempt<'a> {
    limiter: &'a LoginLimiter,
    key: Option<IpAddr>,
}

impl LoginAttempt<'_> {
    /// Counts this attempt as a failure against its address.
    pub fn failed(mut self) {
        if let Some(key) = self.key.take() {
            self.limiter.settle(key, true);
        }
    }
}

impl Drop for LoginAttempt<'_> {
    fn drop(&mut self) {
        if let Some(key) = self.key.take() {
            self.limiter.settle(key, false);
        }
    }
}

/// Logs a completed login attempt. One place, so the events cannot drift.
pub fn log_login(succeeded: bool, username: &str, client: Option<IpAddr>, reason: &'static str) {
    if succeeded {
        info!(event = "admin_login_succeeded",
              outcome = "success",
              username = %username,
              client_ip = ?client);
    } else {
        warn!(event = "admin_login_failed",
              outcome = "failure",
              username = %username,
              client_ip = ?client,
              reason = reason);
    }
}

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

    fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in pairs {
            map.append(
                header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
                HeaderValue::from_str(value).unwrap(),
            );
        }
        map
    }

    async fn client_ip_of(request: axum::http::Request<()>) -> Option<IpAddr> {
        let (mut parts, ()) = request.into_parts();
        let AdminClientIp(ip) = AdminClientIp::from_request_parts(&mut parts, &())
            .await
            .unwrap();
        ip
    }

    /// Behind a trusted proxy the `[admin.filter]` layer has resolved the real
    /// client, and that — not the proxy — is what the login limiter must count.
    #[tokio::test]
    async fn the_resolved_client_is_preferred_to_the_peer() {
        let mut request = axum::http::Request::new(());
        request
            .extensions_mut()
            .insert(axum::extract::ConnectInfo(std::net::SocketAddr::from((
                [172, 18, 0, 2],
                4711,
            ))));
        request
            .extensions_mut()
            .insert(acme_proxy_core::client::ClientIp(Some(
                "198.51.100.9".parse().unwrap(),
            )));
        assert_eq!(
            client_ip_of(request).await,
            Some("198.51.100.9".parse().unwrap())
        );
    }

    #[tokio::test]
    async fn without_the_filter_layer_the_peer_is_the_client() {
        let mut request = axum::http::Request::new(());
        request.extensions_mut().insert(axum::extract::ConnectInfo(
            "[::ffff:192.0.2.7]:4711"
                .parse::<std::net::SocketAddr>()
                .unwrap(),
        ));
        assert_eq!(
            client_ip_of(request).await,
            Some("192.0.2.7".parse().unwrap())
        );
    }

    #[test]
    fn a_minted_token_is_43_url_safe_characters_and_hashes_stably() {
        let minted = mint_token();
        assert_eq!(minted.token.len(), 43, "32 bytes, base64url unpadded");
        assert!(!minted.token.contains('='));
        assert!(!minted.token.contains('+'));
        assert!(!minted.token.contains('/'));
        assert_eq!(minted.token_hash, hash_token(&minted.token));
        assert_eq!(minted.token_hash.len(), 64, "SHA-256 as hex");

        // Distinct per call, and the hash never contains the token.
        assert_ne!(mint_token().token, minted.token);
        assert!(!minted.token_hash.contains(&minted.token));
    }

    #[test]
    fn hash_token_matches_a_known_vector() {
        // sha256("") — pins the encoding (hex, lowercase) as well as the digest.
        assert_eq!(
            hash_token(""),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn csrf_tokens_are_unguessable_and_distinct() {
        let first = mint_csrf_token();
        assert_eq!(first.len(), 43);
        assert_ne!(first, mint_csrf_token());
    }

    #[test]
    fn the_session_cookie_carries_every_required_attribute() {
        let cookie = session_cookie("the-token", Duration::from_secs(43_200));
        assert!(cookie.starts_with("__Host-acme_admin_session=the-token;"));
        assert!(cookie.contains("HttpOnly"));
        assert!(cookie.contains("Secure"));
        assert!(cookie.contains("SameSite=Strict"));
        assert!(cookie.contains("Path=/"));
        assert!(cookie.contains("Max-Age=43200"));
        // `__Host-` forbids it, and setting one would widen the cookie to
        // every subdomain.
        assert!(!cookie.contains("Domain"));
    }

    #[test]
    fn the_clearing_cookie_expires_immediately_and_keeps_the_same_attributes() {
        let cookie = clearing_cookie();
        assert!(cookie.starts_with("__Host-acme_admin_session=;"));
        assert!(cookie.contains("Max-Age=0"));
        // A browser matches on name+path+domain, so a clear that dropped these
        // would leave the original cookie in place.
        assert!(cookie.contains("Path=/"));
        assert!(cookie.contains("Secure"));
        assert!(cookie.contains("HttpOnly"));
    }

    /// A parser case: a label, the `Cookie` headers to send, and the value the
    /// parser must pick out.
    type CookieCase = (
        &'static str,
        Vec<(&'static str, String)>,
        Option<&'static str>,
    );

    #[test]
    fn cookie_parsing_is_table_driven() {
        let name = COOKIE_NAME;
        let cases: Vec<CookieCase> = vec![
            ("absent entirely", vec![], None),
            (
                "the only cookie",
                vec![("cookie", format!("{name}=abc"))],
                Some("abc"),
            ),
            (
                "among others",
                vec![("cookie", format!("theme=dark; {name}=abc; lang=en"))],
                Some("abc"),
            ),
            (
                "leading whitespace",
                vec![("cookie", format!("theme=dark;   {name}=abc"))],
                Some("abc"),
            ),
            (
                "a quoted value",
                vec![("cookie", format!("{name}=\"abc\""))],
                Some("abc"),
            ),
            (
                "a segment with no equals sign",
                vec![("cookie", format!("broken; {name}=abc"))],
                Some("abc"),
            ),
            (
                "present but empty",
                vec![("cookie", format!("{name}="))],
                Some(""),
            ),
            (
                "a different cookie only",
                vec![("cookie", "other=abc".to_string())],
                None,
            ),
            (
                // The fixation vector: a crafted header repeating the name
                // must not let the *second* value win.
                "duplicated in one header",
                vec![("cookie", format!("{name}=first; {name}=second"))],
                Some("first"),
            ),
            (
                "duplicated across two headers",
                vec![
                    ("cookie", format!("{name}=first")),
                    ("cookie", format!("{name}=second")),
                ],
                Some("first"),
            ),
            (
                "a name that merely contains ours",
                vec![("cookie", format!("x{name}=nope"))],
                None,
            ),
        ];

        for (label, pairs, expected) in cases {
            let owned: Vec<(&str, &str)> = pairs.iter().map(|(n, v)| (*n, v.as_str())).collect();
            assert_eq!(
                cookie_value(&headers(&owned)).as_deref(),
                expected,
                "case `{label}`"
            );
        }
    }

    #[test]
    fn the_csrf_check_accepts_only_an_exact_match() {
        let expected = "the-expected-token";
        assert!(check_csrf(&headers(&[(CSRF_HEADER, expected)]), expected).is_ok());

        // Missing.
        let error = check_csrf(&HeaderMap::new(), expected).unwrap_err();
        assert_eq!(error.code, "csrf_failed");
        assert!(error.message.contains(CSRF_HEADER));

        // Wrong, and wrong-length (the branch that short-circuits `ct_eq`).
        for supplied in [
            "",
            "wrong",
            "the-expected-token-but-longer",
            "the-expected-toke",
        ] {
            let error = check_csrf(&headers(&[(CSRF_HEADER, supplied)]), expected).unwrap_err();
            assert_eq!(error.code, "csrf_failed", "for `{supplied}`");
        }
    }

    #[test]
    fn the_origin_gate_covers_the_cases_a_browser_produces() {
        let base = "http://localhost:3001";

        // Neither header: a script or curl. Not the threat this addresses.
        assert!(check_origin(&HeaderMap::new(), base).is_ok());

        // Same-origin, both spellings a browser uses.
        assert!(check_origin(&headers(&[("sec-fetch-site", "same-origin")]), base).is_ok());
        assert!(check_origin(&headers(&[("sec-fetch-site", "none")]), base).is_ok());
        assert!(check_origin(&headers(&[("origin", base)]), base).is_ok());

        for site in ["cross-site", "same-site"] {
            let error = check_origin(&headers(&[("sec-fetch-site", site)]), base).unwrap_err();
            assert_eq!(error.code, "csrf_failed", "for {site}");
            // `same-site` is the one SameSite=Strict would have let through:
            // a different port of the same host.
            assert!(error.message.contains(site));
        }

        let error = check_origin(&headers(&[("origin", "http://evil.example")]), base).unwrap_err();
        assert!(error.message.contains("evil.example"));

        // A different port of the same host is a different origin.
        let error =
            check_origin(&headers(&[("origin", "http://localhost:8080")]), base).unwrap_err();
        assert_eq!(error.code, "csrf_failed");
    }

    fn ip(last: u8) -> Option<IpAddr> {
        Some(IpAddr::from([192, 0, 2, last]))
    }

    /// One failed attempt, start to finish.
    fn fail(limiter: &LoginLimiter, client: Option<IpAddr>) {
        limiter.begin(client).unwrap().failed();
    }

    #[test]
    fn the_limiter_permits_up_to_the_limit_then_refuses() {
        let limiter = LoginLimiter::new(3, 300);

        for attempt in 0..3 {
            let slot = limiter.begin(ip(1));
            assert!(slot.is_ok(), "attempt {attempt} must pass");
            slot.unwrap().failed();
        }

        let retry_after = limiter.begin(ip(1)).unwrap_err();
        assert!(retry_after > 0 && retry_after <= 300, "got {retry_after}");

        // Scoped to the address that failed.
        assert!(limiter.begin(ip(2)).is_ok());
    }

    /// The race this type exists to close: a burst whose attempts are all in
    /// flight at once must not each find the budget untouched.
    #[test]
    fn attempts_in_flight_count_against_the_limit() {
        let limiter = LoginLimiter::new(3, 300);
        let held: Vec<_> = (0..3).map(|_| limiter.begin(ip(1)).unwrap()).collect();
        assert!(
            limiter.begin(ip(1)).is_err(),
            "a fourth concurrent attempt must be refused before any has failed"
        );

        // Settled without failing — a right password awaiting its second
        // factor — the slots come back.
        drop(held);
        assert!(limiter.begin(ip(1)).is_ok());
        assert!(
            limiter.buckets.lock().unwrap().is_empty(),
            "a bucket with nothing to remember must not linger"
        );
    }

    #[test]
    fn a_success_clears_the_counter() {
        let limiter = LoginLimiter::new(2, 300);
        fail(&limiter, ip(1));
        limiter.record_success(ip(1));
        fail(&limiter, ip(1));
        assert!(
            limiter.begin(ip(1)).is_ok(),
            "the pre-success failure must not still count"
        );
    }

    /// A success while another attempt is in flight keeps the bucket that
    /// attempt will settle against, so its slot is still released.
    #[test]
    fn a_success_beside_an_attempt_in_flight_keeps_its_slot() {
        let limiter = LoginLimiter::new(1, 300);
        let other = limiter.begin(ip(1)).unwrap();
        limiter.record_success(ip(1));
        assert!(limiter.begin(ip(1)).is_err(), "the slot is still taken");
        drop(other);
        assert!(limiter.begin(ip(1)).is_ok());
    }

    #[test]
    fn the_window_rolls_over_and_prunes() {
        // A one-second window, so the rollover is observable without sleeping
        // on a wall clock the test does not control.
        let limiter = LoginLimiter::new(1, 1);
        fail(&limiter, ip(1));
        assert!(limiter.begin(ip(1)).is_err());

        // Backdate the bucket past the window.
        {
            let mut buckets = limiter.buckets.lock().unwrap();
            buckets.get_mut(&ip(1).unwrap()).unwrap().window_started -= 5;
        }
        assert!(limiter.begin(ip(1)).is_ok(), "the window must roll over");
        assert!(
            limiter.buckets.lock().unwrap().is_empty(),
            "a stale bucket must be pruned, or the map grows without bound"
        );
    }

    #[test]
    fn a_missing_client_address_is_not_limited() {
        let limiter = LoginLimiter::new(1, 300);
        fail(&limiter, None);
        limiter.record_success(None);
        assert!(
            limiter.begin(None).is_ok(),
            "failing closed here would lock out every request, not every attacker"
        );
    }

    /// Rotating through one /64 is one budget; a different /64 is another, and
    /// an IPv4-mapped address is its IPv4 self.
    #[test]
    fn an_ipv6_client_is_limited_by_its_slash_64() {
        let limiter = LoginLimiter::new(1, 300);
        let v6 = |s: &str| Some(s.parse::<IpAddr>().unwrap());

        fail(&limiter, v6("2001:db8:1:2::1"));
        assert!(limiter.begin(v6("2001:db8:1:2:ffff::9")).is_err());
        assert!(limiter.begin(v6("2001:db8:1:3::1")).is_ok());

        fail(&limiter, ip(7));
        assert!(limiter.begin(v6("::ffff:192.0.2.7")).is_err());
    }

    /// The failures cross a reload; the in-flight counts must not, or a slot
    /// held across it would never come back.
    #[test]
    fn a_rebuilt_limiter_keeps_failures_and_drops_slots_in_flight() {
        let old = LoginLimiter::new(2, 300);
        fail(&old, ip(1));
        let straddling = old.begin(ip(1)).unwrap();

        let new = old.rebuilt(2, 300);
        drop(straddling);
        assert!(new.begin(ip(1)).is_ok(), "one failure of two is spent");
        fail(&new, ip(1));
        assert!(new.begin(ip(1)).is_err());
    }

    #[test]
    fn log_login_renders_both_outcomes() {
        // The `tracing` field expressions only execute when something is
        // subscribed; `tests/common` installs a sink, and here the call is
        // simply exercised for its branches.
        log_login(true, "alice", ip(1), "");
        log_login(false, "alice", ip(1), "wrong_password");
        log_login(false, "alice", None, "unknown_user");
    }
}