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
//! Operator management for the web admin: create, list, re-password, set the
//! privilege tier, enable, disable, delete, and the password check the login
//! path runs.
//!
//! The operation layer, not a front end: no printing, no HTTP, no terminal.
//! `src/cli/webadmin.rs` and `crates/admin/src/webadmin/handlers/session.rs` both dispatch
//! here, which is what keeps the password policy, the duplicate check and the
//! rehash-on-login identical between them.

use std::io::BufRead;
use std::sync::Arc;

use tracing::{info, warn};

use crate::admin::password::{self, PasswordContext};
use crate::admin::prompt::confirm;
use acme_proxy_store::admin_session::AdminSession;
use acme_proxy_store::admin_user::AdminRole;
use acme_proxy_store::admin_user::AdminStatus;
use acme_proxy_store::admin_user::AdminUser;
use acme_proxy_store::db::Database;

/// Why creating or re-passwording an operator failed.
#[derive(Debug, thiserror::Error)]
pub enum UserError {
    #[error("database error: {0}")]
    Database(sqlx::Error),
    /// The password did not satisfy [`password::check_password_policy`]. The
    /// string is the operator-facing reason.
    #[error("{0}")]
    Policy(String),
    /// A user by that name already exists. Caught before the INSERT so the
    /// operator reads a sentence rather than a UNIQUE violation.
    #[error("an admin user named `{0}` already exists")]
    DuplicateUsername(String),
    /// A contact address that does not parse as a mailbox.
    #[error("{0}")]
    InvalidContact(String),
}

impl From<sqlx::Error> for UserError {
    fn from(error: sqlx::Error) -> Self {
        Self::Database(error)
    }
}

/// The result of checking a username and password.
///
/// Every variant but [`AuthOutcome::Authenticated`] must be reported to the
/// client identically -- one `invalid_credentials`, never "no such user" --
/// but they are kept apart here so the *log* can say which happened. A caller
/// that collapses them into the response and not into the log is doing the
/// right thing with both.
#[derive(Debug)]
pub enum AuthOutcome {
    /// Password verified and the account is usable.
    Authenticated(Box<AdminUser>),
    /// No such username. The KDF ran anyway -- see [`authenticate`].
    UnknownUser,
    /// The username exists; the password did not match.
    WrongPassword(Box<AdminUser>),
    /// The password was right, but the account is `disabled`.
    Disabled(Box<AdminUser>),
}

/// Whether a normalized username is one the web admin can address.
///
/// The panel routes every colleague operation at `/ui/operators/{username}/…`
/// and builds those paths by interpolation, so a name holding `/`, `?`, `#` or
/// a space produces a URL that matches no route — the operator is creatable
/// from the host and then unmanageable from the panel. minijinja escapes HTML,
/// not URL syntax, so the templates cannot rescue it either.
///
/// The same rule this tree already applies wherever a configured name becomes a
/// path or an environment segment (`valid_profile_name`,
/// `valid_config_key_name`), widened by `_` and `.` because an operator name is
/// a person's, not a slug — `a.smith` and `a_smith` are ordinary and neither
/// means anything to a URL.
///
/// Checked at creation only. An existing row is left alone: refusing to *load*
/// a username would lock somebody out of a panel they are already using, which
/// is the opposite of what this is for.
#[must_use]
pub fn valid_username(username: &str) -> bool {
    !username.is_empty()
        && username
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_' | '.'))
}

/// Creates an operator at `role`, or at [`AdminRole::Admin`] when none is
/// named.
///
/// Order matters: the policy is checked before the duplicate lookup, and the
/// duplicate lookup before the (expensive) hash, so a rejected request never
/// pays 600 000 iterations.
///
/// **One write.** This used to create at `admin` and call [`set_role`]
/// afterwards, which made `admin user create --role viewer` two statements: a
/// failure between them left an operator at full authority with their password
/// already set, and the second statement had to be exempted from `set_role`'s
/// last-admin guard, since the row it was demoting was the admin it had just
/// created.
pub async fn create_user(
    username: &str,
    plaintext: &str,
    context: &PasswordContext,
    role: Option<AdminRole>,
    database: Arc<Database>,
) -> Result<AdminUser, UserError> {
    password::check_password_policy(plaintext, context).map_err(UserError::Policy)?;

    let normalized = username.trim().to_lowercase();
    if normalized.is_empty() {
        return Err(UserError::Policy("username must not be empty".to_string()));
    }
    if !valid_username(&normalized) {
        return Err(UserError::Policy(format!(
            "invalid username `{normalized}`: use lowercase letters, digits, `-`, `_` and `.` \
             (the name is a URL segment on the web admin)"
        )));
    }
    if AdminUser::find_by_username(&normalized, &database)
        .await?
        .is_some()
    {
        return Err(UserError::DuplicateUsername(normalized));
    }

    let hash = password::hash_password(plaintext);
    Ok(AdminUser::create(&normalized, &hash, role, &database).await?)
}

/// Sets an operator's privilege tier and **revokes every session they hold**.
///
/// The revocation matches `set_status("disabled")` and `set_password`: a
/// demotion that left a live `admin` session alive would take effect only when
/// that cookie happened to expire. It is belt-and-braces rather than
/// load-bearing -- the write extractors re-read `role` from `admin_users` on
/// every request -- but this layer already holds that convention. `None` when
/// there is no such user; otherwise the operator and **how many sessions went
/// with the change**, which the caller records as its own `session_revoked`
/// audit row (this layer is front-end agnostic and does not know the actor).
/// Demoting the **last** `admin` is refused: `/operators/*` is `admin`-only on
/// both web surfaces, so a deployment with none has no way to manage operators
/// from the panel at all. Recoverable from this host — which is why it is a
/// refusal here rather than a `CHECK` — but the operator should hear about it
/// before it happens rather than after.
pub async fn set_role(
    username: &str,
    role: AdminRole,
    database: Arc<Database>,
) -> Result<Option<(AdminUser, u64)>, UserError> {
    let Some(mut user) = AdminUser::find_by_username(username, &database).await? else {
        return Ok(None);
    };

    if user.role() == AdminRole::Admin && role != AdminRole::Admin {
        let admins = AdminUser::list_all(&database)
            .await?
            .iter()
            .filter(|other| other.role() == AdminRole::Admin)
            .count();
        if admins <= 1 {
            return Err(UserError::Policy(format!(
                "`{}` is the only admin: demoting them would leave the panel with no one who \
                 can manage operators. Promote somebody else first.",
                user.username
            )));
        }
    }

    user.set_role(role, &database).await?;
    let revoked = AdminSession::delete_for_user(user.id, &database).await?;
    Ok(Some((user, revoked)))
}

/// Sets (`Some`) or clears (`None` / empty / whitespace) the address an
/// operator receives security notifications at. `Some` is validated as a
/// mailbox — the same parse [`acme_proxy_jobs::notify::email`] does before it sends —
/// so a malformed address is refused here rather than becoming a permanent
/// delivery failure later. Not a credential: sessions are left alone.
///
/// `None` when there is no such operator.
pub async fn set_contact_email(
    username: &str,
    contact: Option<&str>,
    database: Arc<Database>,
) -> Result<Option<AdminUser>, UserError> {
    let trimmed = contact.map(str::trim).filter(|value| !value.is_empty());
    if let Some(address) = trimmed {
        address
            .parse::<lettre::message::Mailbox>()
            .map_err(|error| {
                UserError::InvalidContact(format!(
                    "`{address}` is not a valid email address: {error}"
                ))
            })?;
    }

    let Some(mut user) = AdminUser::find_by_username(username, &database).await? else {
        return Ok(None);
    };
    user.set_contact_email(trimmed, &database).await?;
    Ok(Some(user))
}

/// One page of the operators, oldest first, plus the total the table holds.
///
/// The direction is [`AdminUser::search`]'s and is the one listing in the
/// binary that does not put the newest row on top.
pub async fn list_users(
    limit: i64,
    offset: i64,
    database: Arc<Database>,
) -> Result<(Vec<AdminUser>, i64), sqlx::Error> {
    AdminUser::search(limit, offset, &database).await
}

/// Replaces an operator's password and **revokes every session they hold**.
///
/// The revocation is the point: a password changed because it may have leaked,
/// that left the leaked session alive, would be a change in name only. Returns
/// `None` when there is no such user; otherwise the operator and how many
/// sessions the change took with it, for the caller's `session_revoked` row.
pub async fn set_password(
    username: &str,
    plaintext: &str,
    context: &PasswordContext,
    database: Arc<Database>,
) -> Result<Option<(AdminUser, u64)>, UserError> {
    password::check_password_policy(plaintext, context).map_err(UserError::Policy)?;

    let Some(mut user) = AdminUser::find_by_username(username, &database).await? else {
        return Ok(None);
    };

    let hash = password::hash_password(plaintext);
    user.set_password_hash(&hash, &database).await?;
    let revoked = AdminSession::delete_for_user(user.id, &database).await?;
    Ok(Some((user, revoked)))
}

/// Changes an operator's own password, keeping the session that requested it
/// alive and revoking every other one.
///
/// The self-service counterpart to [`set_password`]: that one is the CLI's,
/// trusted because it already runs as the process that can rewrite the row,
/// and it revokes *every* session including any the operator is currently
/// using elsewhere. This one is reached over a live session, so the caller's
/// own session must survive the change or the panel would sign its own
/// operator out from under them mid-edit -- the `confirm_totp_enrolment`/
/// `disable_totp` shape, not `set_password`'s.
///
/// Does **not** verify the current password: that check (ASVS V6.2.3) happens
/// one layer up, in the web handler, where the rate limiter and the client
/// address live.
pub async fn change_own_password(
    user: &mut AdminUser,
    new_password: &str,
    context: &PasswordContext,
    keep_session: &str,
    database: Arc<Database>,
) -> Result<(), UserError> {
    password::check_password_policy(new_password, context).map_err(UserError::Policy)?;

    let hash = password::hash_password(new_password);
    user.set_password_hash(&hash, &database).await?;
    AdminSession::delete_for_user_except(user.id, keep_session, &database).await?;
    Ok(())
}

/// Moves an operator between `active` and `disabled`.
///
/// Disabling also drops their sessions: leaving them live would mean a
/// disabled operator kept working until their cookie happened to expire. That
/// revocation is audited by the caller as a `session_revoked` row, since only
/// the front end knows who asked for it.
///
/// Takes an [`AdminStatus`] rather than the `&str` five call sites used to
/// spell by hand. `AdminUser::set_status` below this still takes a string, and
/// deliberately: it is the raw column write, and the test that a value outside
/// the migration's `CHECK` is refused by SQLite has to be able to pass one.
/// This layer is where a typo should stop being expressible — a mistyped
/// `"enable"` here would have written a status no `is_active` accepts, i.e. a
/// permanent lockout dressed as a successful re-enable.
pub async fn set_status(
    username: &str,
    status: AdminStatus,
    database: Arc<Database>,
) -> Result<Option<(AdminUser, u64)>, sqlx::Error> {
    let Some(mut user) = AdminUser::find_by_username(username, &database).await? else {
        return Ok(None);
    };

    user.set_status(status.as_str(), &database).await?;
    let revoked = if status == AdminStatus::Disabled {
        AdminSession::delete_for_user(user.id, &database).await?
    } else {
        0
    };
    Ok(Some((user, revoked)))
}

/// How many operators have no `contact_email` on file.
///
/// The `[admin.notify]` security events (`admin_sign_in`,
/// `admin_credential_changed`) name their own recipient, and for an operator
/// with no address that recipient is `None` — the message then falls back to
/// `notify.email.to` or, if that is empty too, goes nowhere at all. Both are
/// legitimate configurations, and neither is visible from anywhere: the panel
/// has no contact form and nothing warns. This is what
/// `announce_admin_listener` counts to say so, the shape
/// [`crate::admin::mfa::operators_without_a_factor`] already has.
pub async fn operators_without_a_contact(database: Arc<Database>) -> Result<usize, sqlx::Error> {
    Ok(AdminUser::list_all(&database)
        .await?
        .iter()
        .filter(|user| user.contact_email.is_none())
        .count())
}

/// Revokes every session one operator holds, without touching the account.
/// `None` when there is no such user.
pub async fn revoke_sessions(
    username: &str,
    database: Arc<Database>,
) -> Result<Option<u64>, sqlx::Error> {
    let Some(user) = AdminUser::find_by_username(username, &database).await? else {
        return Ok(None);
    };
    Ok(Some(
        AdminSession::delete_for_user(user.id, &database).await?,
    ))
}

/// Deletes an operator, cascading to their sessions. `false` when there was no
/// such user.
///
/// The bare form, for a caller with nobody to ask -- see the note above the
/// deletes in [`crate::admin::ops`].
pub async fn delete_user(username: &str, database: Arc<Database>) -> Result<bool, sqlx::Error> {
    let Some(user) = AdminUser::find_by_username(username, &database).await? else {
        return Ok(false);
    };
    AdminUser::delete(user.id, &database).await
}

/// What [`confirm_delete_user`] did.
///
/// [`DeleteOutcome`](crate::admin::ops::DeleteOutcome) less its `LiveCertificates` refusal: an operator holds no
/// certificate, so a caller matching on that variant here had only an
/// `unreachable!` to put in the arm.
#[derive(Debug, PartialEq, Eq)]
pub enum UserDeleteOutcome {
    NotFound,
    Cancelled,
    /// Deleted, carrying the sessions that cascaded with it.
    Deleted(crate::admin::ops::Deleted),
}

/// [`delete_user`], asking first and naming what goes with it.
pub async fn confirm_delete_user(
    username: &str,
    assume_yes: bool,
    reader: &mut impl BufRead,
    database: Arc<Database>,
) -> Result<UserDeleteOutcome, sqlx::Error> {
    let Some(user) = AdminUser::find_by_username(username, &database).await? else {
        return Ok(UserDeleteOutcome::NotFound);
    };
    let sessions = AdminSession::list_all(Some(user.id), &database)
        .await?
        .len();
    let prompt = format!(
        "Delete admin user {} (status: {}, {sessions} session(s) will cascade)?",
        user.username, user.status
    );
    if !confirm(&prompt, assume_yes, reader) {
        return Ok(UserDeleteOutcome::Cancelled);
    }
    AdminUser::delete(user.id, &database).await?;
    Ok(UserDeleteOutcome::Deleted(crate::admin::ops::Deleted {
        cascaded: sessions as u64,
    }))
}

/// Checks a username and password, re-hashing the stored digest if it was
/// written under parameters this build has moved past.
///
/// **The KDF runs even when the username is unknown**, against
/// [`password::dummy_hash`]. Without that, an unknown user answers in
/// microseconds and a known one in a quarter-second, and login latency
/// enumerates the operator table.
///
/// Does **not** stamp `last_login_at` or create a session: a login is not
/// complete until a session exists, which for a user with a second factor is
/// two requests away. The caller decides when that happened.
pub async fn authenticate(
    username: &str,
    plaintext: &str,
    database: Arc<Database>,
) -> Result<AuthOutcome, sqlx::Error> {
    let Some(mut user) = AdminUser::find_by_username(username, &database).await? else {
        // Deliberately discarded: the point is the time it took.
        let _ = password::verify_password_off_runtime(password::dummy_hash(), plaintext).await;
        return Ok(AuthOutcome::UnknownUser);
    };

    let verified = match password::verify_password_off_runtime(&user.password_hash, plaintext).await
    {
        Ok(verified) => verified,
        Err(error) => {
            // A corrupt row is not a wrong password. Refuse the login, but say
            // so loudly -- nobody will ever guess this from a 401, and the
            // account is unusable until `admin user passwd` rewrites it.
            warn!(event = "admin_password_hash_unreadable",
                  outcome = "failure",
                  user_id = %user.id,
                  username = %user.username,
                  error = %error,
                  "stored password hash could not be decoded; \
                   run `acme-proxy admin user passwd` to rewrite it");
            return Ok(AuthOutcome::WrongPassword(Box::new(user)));
        }
    };

    if !verified {
        return Ok(AuthOutcome::WrongPassword(Box::new(user)));
    }
    if !user.is_active() {
        return Ok(AuthOutcome::Disabled(Box::new(user)));
    }

    // The one place a stored hash is ever upgraded. Doing it here, on a
    // verified password, is the only moment the plaintext is available to
    // re-derive from.
    if password::needs_rehash(&user.password_hash)
        && let Some(rehashed) = password::hash_password_off_runtime(plaintext).await
    {
        user.set_password_hash(&rehashed, &database).await?;
        info!(event = "admin_password_rehashed", outcome = "success", user_id = %user.id);
    }

    Ok(AuthOutcome::Authenticated(Box::new(user)))
}

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

    const GOOD: &str = "a-long-enough-password";

    async fn db() -> Arc<Database> {
        Arc::new(Database::connect_in_memory().await.unwrap())
    }

    /// Writes a row whose hash is cheap, so the tests that only care about
    /// *which branch* `authenticate` takes do not each pay 600 000 iterations.
    /// The stored form is the real one; only the cost differs.
    async fn user_with_cheap_password(
        username: &str,
        plaintext: &str,
        database: Arc<Database>,
    ) -> AdminUser {
        // 1 iteration, but encoded exactly as production encodes it -- which
        // also means `needs_rehash` reports true, so any test using this and
        // then authenticating successfully is exercising the rehash path.
        let salt = [3u8; 16];
        let mut digest = [0u8; 32];
        ring::pbkdf2::derive(
            ring::pbkdf2::PBKDF2_HMAC_SHA256,
            std::num::NonZeroU32::new(1).unwrap(),
            &salt,
            plaintext.as_bytes(),
            &mut digest,
        );
        let encoded = format!(
            "pbkdf2-sha256$1${}${}",
            base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, salt),
            base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, digest),
        );
        AdminUser::create(username, &encoded, None, &database)
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn set_contact_email_stores_clears_and_validates() {
        let db = db().await;
        create_user("alice", GOOD, &PasswordContext::empty(), None, db.clone())
            .await
            .unwrap();

        // Unknown operator -> None.
        assert!(
            set_contact_email("nobody", Some("x@example.com"), db.clone())
                .await
                .unwrap()
                .is_none()
        );

        // A malformed address is refused here, not on delivery.
        let error = set_contact_email("alice", Some("not an address"), db.clone())
            .await
            .unwrap_err();
        assert!(matches!(error, UserError::InvalidContact(_)), "{error}");

        // A good address is stored and synced.
        let user = set_contact_email("alice", Some("  alice@example.com  "), db.clone())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(user.contact_email.as_deref(), Some("alice@example.com"));

        // An empty value clears it, as does `None`.
        for cleared in [Some("  "), None] {
            let user = set_contact_email("alice", cleared, db.clone())
                .await
                .unwrap()
                .unwrap();
            assert_eq!(user.contact_email, None);
            set_contact_email("alice", Some("alice@example.com"), db.clone())
                .await
                .unwrap();
        }
    }

    #[tokio::test]
    async fn create_user_normalizes_and_hashes() {
        let db = db().await;
        let user = create_user(
            "  Alice ",
            GOOD,
            &PasswordContext::empty(),
            None,
            db.clone(),
        )
        .await
        .unwrap();
        assert_eq!(user.username, "alice");
        assert!(user.is_active());
        // Stored one-way: the plaintext appears nowhere.
        assert!(!user.password_hash.contains(GOOD));
        assert_eq!(
            password::verify_password(&user.password_hash, GOOD),
            Ok(true)
        );
    }

    #[tokio::test]
    async fn create_user_refuses_a_password_below_the_policy() {
        let db = db().await;
        let error = create_user(
            "alice",
            "short",
            &PasswordContext::empty(),
            None,
            db.clone(),
        )
        .await
        .unwrap_err();
        assert!(matches!(error, UserError::Policy(_)));
        assert!(error.to_string().contains("at least 12"));
        // Nothing was written.
        assert_eq!(list_users(50, 0, db).await.unwrap().1, 0);
    }

    /// The other two policy rules reach this layer through the same
    /// `UserError::Policy`, and leave the table as untouched as the length
    /// rule does.
    #[tokio::test]
    async fn create_user_refuses_a_common_password_and_a_deployment_word() {
        let db = db().await;

        let error = create_user(
            "alice",
            "passwordpassword",
            &PasswordContext::empty(),
            None,
            db.clone(),
        )
        .await
        .unwrap_err();
        assert!(matches!(error, UserError::Policy(_)));
        assert!(error.to_string().contains("commonly used"));

        let mut config = acme_proxy_core::config::Config::default();
        config.server.base_url = "https://ca.example.com".to_string();
        let context = PasswordContext::from_config(&config, "alice");
        let error = create_user("alice", "acmeproxy2026!!", &context, None, db.clone())
            .await
            .unwrap_err();
        assert!(matches!(error, UserError::Policy(_)));
        assert!(error.to_string().contains("names this deployment"));

        // Neither attempt wrote a row.
        assert_eq!(list_users(50, 0, db).await.unwrap().1, 0);
    }

    /// `set_password` checks the policy before the user lookup, so all three
    /// rules answer the same way for a name that does not exist.
    #[tokio::test]
    async fn set_password_refuses_a_common_password_before_looking_the_user_up() {
        let db = db().await;
        let error = set_password(
            "nobody",
            "passwordpassword",
            &PasswordContext::empty(),
            db.clone(),
        )
        .await
        .unwrap_err();
        assert!(error.to_string().contains("commonly used"), "got: {error}");
    }

    #[tokio::test]
    async fn create_user_refuses_an_empty_username() {
        let db = db().await;
        let error = create_user("   ", GOOD, &PasswordContext::empty(), None, db)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("username must not be empty"));
    }

    #[tokio::test]
    async fn create_user_refuses_a_duplicate_in_words_not_a_unique_violation() {
        let db = db().await;
        create_user("alice", GOOD, &PasswordContext::empty(), None, db.clone())
            .await
            .unwrap();
        let error = create_user("ALICE", GOOD, &PasswordContext::empty(), None, db)
            .await
            .unwrap_err();
        assert!(matches!(error, UserError::DuplicateUsername(_)));
        assert_eq!(
            error.to_string(),
            "an admin user named `alice` already exists"
        );
    }

    #[tokio::test]
    async fn set_password_revokes_every_session_of_that_user() {
        let db = db().await;
        let user = user_with_cheap_password("alice", "old-password", db.clone()).await;
        AdminSession::create(
            NewSession {
                user_id: user.id,
                token_hash: "hash-a",
                csrf_token: "csrf",
                created_ip: None,
                user_agent: None,
            },
            std::time::Duration::from_secs(60),
            &db,
        )
        .await
        .unwrap();

        assert!(
            set_password("alice", GOOD, &PasswordContext::empty(), db.clone())
                .await
                .unwrap()
                .is_some()
        );
        assert!(
            AdminSession::list_all(Some(user.id), &db)
                .await
                .unwrap()
                .is_empty(),
            "a password change that left sessions alive would be a change in name only"
        );

        let reloaded = AdminUser::find_by_username("alice", &db)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            password::verify_password(&reloaded.password_hash, GOOD),
            Ok(true)
        );
    }

    /// The self-service counterpart to `set_password_revokes_every_session_of_that_user`:
    /// the same revocation, except the caller's own session is the one
    /// exemption. A panel that signed its own operator out mid-edit would be
    /// indistinguishable from a bug in the form.
    #[tokio::test]
    async fn change_own_password_keeps_the_calling_session_and_drops_every_other() {
        let db = db().await;
        let mut user = user_with_cheap_password("alice", "old-password", db.clone()).await;

        let kept = AdminSession::create(
            NewSession {
                user_id: user.id,
                token_hash: "kept-hash",
                csrf_token: "csrf",
                created_ip: None,
                user_agent: None,
            },
            std::time::Duration::from_secs(3600),
            &db,
        )
        .await
        .unwrap();
        AdminSession::create(
            NewSession {
                user_id: user.id,
                token_hash: "other-hash",
                csrf_token: "csrf",
                created_ip: None,
                user_agent: None,
            },
            std::time::Duration::from_secs(3600),
            &db,
        )
        .await
        .unwrap();

        change_own_password(
            &mut user,
            GOOD,
            &PasswordContext::empty(),
            &kept.token_hash,
            db.clone(),
        )
        .await
        .unwrap();

        let live = AdminSession::list_all(Some(user.id), &db).await.unwrap();
        assert_eq!(live.len(), 1, "every other session must be revoked");
        assert_eq!(live[0].token_hash, "kept-hash");

        let reloaded = AdminUser::find_by_username("alice", &db)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            password::verify_password(&reloaded.password_hash, GOOD),
            Ok(true)
        );
        assert_eq!(
            password::verify_password(&reloaded.password_hash, "old-password"),
            Ok(false)
        );
    }

    /// The policy still runs, and a rejected password writes nothing -- the
    /// same rule `set_password` and `create_user` both hold.
    #[tokio::test]
    async fn change_own_password_checks_the_policy() {
        let db = db().await;
        let mut user = user_with_cheap_password("alice", "old-password", db.clone()).await;
        let before = user.password_hash.clone();

        let error = change_own_password(
            &mut user,
            "short",
            &PasswordContext::empty(),
            "kept-hash",
            db.clone(),
        )
        .await
        .unwrap_err();
        assert!(matches!(error, UserError::Policy(_)));

        let reloaded = AdminUser::find_by_username("alice", &db)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(reloaded.password_hash, before);
    }

    #[tokio::test]
    async fn set_password_of_an_unknown_user_is_none_and_checks_the_policy_first() {
        let db = db().await;
        assert!(
            set_password("nobody", GOOD, &PasswordContext::empty(), db.clone())
                .await
                .unwrap()
                .is_none()
        );
        // The policy is checked before the lookup, so a bad password for an
        // unknown user is a policy error rather than a silent `None`.
        assert!(matches!(
            set_password("nobody", "short", &PasswordContext::empty(), db)
                .await
                .unwrap_err(),
            UserError::Policy(_)
        ));
    }

    #[tokio::test]
    async fn disabling_a_user_drops_their_sessions_but_enabling_does_not() {
        let db = db().await;
        let user = user_with_cheap_password("alice", "pw", db.clone()).await;
        AdminSession::create(
            NewSession {
                user_id: user.id,
                token_hash: "hash-a",
                csrf_token: "csrf",
                created_ip: None,
                user_agent: None,
            },
            std::time::Duration::from_secs(60),
            &db,
        )
        .await
        .unwrap();

        set_status("alice", AdminStatus::Disabled, db.clone())
            .await
            .unwrap();
        assert!(
            AdminSession::list_all(Some(user.id), &db)
                .await
                .unwrap()
                .is_empty()
        );

        // Re-enabling is just a status change; there is nothing to drop.
        let reenabled = set_status("alice", AdminStatus::Active, db.clone())
            .await
            .unwrap()
            .unwrap();
        assert!(reenabled.0.is_active());
        assert!(
            set_status("nobody", AdminStatus::Disabled, db)
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn set_role_changes_the_tier_and_revokes_every_session() {
        let db = db().await;
        let user = user_with_cheap_password("alice", "pw", db.clone()).await;
        assert_eq!(user.role(), AdminRole::Admin, "a fresh row reads as admin");
        // A second admin, so demoting the first is not the last-admin case --
        // that has its own test below.
        user_with_cheap_password("root", "pw", db.clone()).await;
        AdminSession::create(
            NewSession {
                user_id: user.id,
                token_hash: "hash-a",
                csrf_token: "csrf",
                created_ip: None,
                user_agent: None,
            },
            std::time::Duration::from_secs(60),
            &db,
        )
        .await
        .unwrap();

        let updated = set_role("alice", AdminRole::Viewer, db.clone())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(updated.0.role(), AdminRole::Viewer);
        assert!(
            AdminSession::list_all(Some(user.id), &db)
                .await
                .unwrap()
                .is_empty(),
            "a demotion that left an admin session live would take effect only on expiry"
        );

        assert!(
            set_role("nobody", AdminRole::Operator, db)
                .await
                .unwrap()
                .is_none()
        );
    }

    /// `/operators/*` is `admin`-only on both web surfaces, so a deployment
    /// with no admin cannot manage operators from the panel at all. Demoting
    /// the last one is refused rather than discovered.
    #[tokio::test]
    async fn demoting_the_last_admin_is_refused() {
        let db = db().await;
        user_with_cheap_password("alice", "pw", db.clone()).await;

        let error = set_role("alice", AdminRole::Viewer, db.clone())
            .await
            .expect_err("the only admin cannot be demoted");
        assert!(error.to_string().contains("only admin"), "{error}");
        // And nothing moved.
        assert_eq!(
            AdminUser::find_by_username("alice", &db)
                .await
                .unwrap()
                .unwrap()
                .role(),
            AdminRole::Admin
        );

        // With a colleague at the same tier, the same call goes through.
        user_with_cheap_password("root", "pw", db.clone()).await;
        let (updated, _) = set_role("alice", AdminRole::Viewer, db.clone())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(updated.role(), AdminRole::Viewer);

        // Promoting is never refused, whoever is left.
        assert!(set_role("alice", AdminRole::Admin, db).await.is_ok());
    }

    #[tokio::test]
    async fn revoke_sessions_counts_what_it_removed() {
        let db = db().await;
        let user = user_with_cheap_password("alice", "pw", db.clone()).await;
        for hash in ["a", "b"] {
            AdminSession::create(
                NewSession {
                    user_id: user.id,
                    token_hash: hash,
                    csrf_token: "csrf",
                    created_ip: None,
                    user_agent: None,
                },
                std::time::Duration::from_secs(60),
                &db,
            )
            .await
            .unwrap();
        }

        assert_eq!(revoke_sessions("alice", db.clone()).await.unwrap(), Some(2));
        assert_eq!(revoke_sessions("alice", db.clone()).await.unwrap(), Some(0));
        assert_eq!(revoke_sessions("nobody", db).await.unwrap(), None);
    }

    #[tokio::test]
    async fn delete_user_removes_the_row_and_reports_whether_it_existed() {
        let db = db().await;
        user_with_cheap_password("alice", "pw", db.clone()).await;
        assert!(delete_user("alice", db.clone()).await.unwrap());
        assert!(!delete_user("alice", db).await.unwrap());
    }

    #[tokio::test]
    async fn confirm_delete_user_covers_its_three_outcomes() {
        let db = db().await;
        let mut empty: &[u8] = &[];
        assert_eq!(
            confirm_delete_user("nobody", true, &mut empty, db.clone())
                .await
                .unwrap(),
            UserDeleteOutcome::NotFound
        );

        user_with_cheap_password("alice", "pw", db.clone()).await;
        let mut no = b"n\n".as_slice();
        assert_eq!(
            confirm_delete_user("alice", false, &mut no, db.clone())
                .await
                .unwrap(),
            UserDeleteOutcome::Cancelled
        );
        assert!(
            AdminUser::find_by_username("alice", &db)
                .await
                .unwrap()
                .is_some()
        );

        let mut empty: &[u8] = &[];
        assert_eq!(
            confirm_delete_user("alice", true, &mut empty, db.clone())
                .await
                .unwrap(),
            UserDeleteOutcome::Deleted(crate::admin::ops::Deleted { cascaded: 0 })
        );
        assert!(
            AdminUser::find_by_username("alice", &db)
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn authenticate_accepts_the_right_password() {
        let db = db().await;
        user_with_cheap_password("alice", "the-password", db.clone()).await;
        let outcome = authenticate("alice", "the-password", db).await.unwrap();
        assert!(matches!(outcome, AuthOutcome::Authenticated(_)));
    }

    #[tokio::test]
    async fn authenticate_distinguishes_its_failures_for_the_log() {
        let db = db().await;
        user_with_cheap_password("alice", "the-password", db.clone()).await;

        assert!(matches!(
            authenticate("alice", "wrong", db.clone()).await.unwrap(),
            AuthOutcome::WrongPassword(_)
        ));
        assert!(matches!(
            authenticate("nobody", "the-password", db.clone())
                .await
                .unwrap(),
            AuthOutcome::UnknownUser
        ));

        set_status("alice", AdminStatus::Disabled, db.clone())
            .await
            .unwrap();
        assert!(matches!(
            authenticate("alice", "the-password", db).await.unwrap(),
            AuthOutcome::Disabled(_)
        ));
    }

    #[tokio::test]
    async fn authenticate_is_case_insensitive_in_the_username() {
        let db = db().await;
        user_with_cheap_password("alice", "the-password", db.clone()).await;
        assert!(matches!(
            authenticate("ALICE", "the-password", db).await.unwrap(),
            AuthOutcome::Authenticated(_)
        ));
    }

    #[tokio::test]
    async fn a_successful_login_rehashes_a_row_written_under_older_parameters() {
        let db = db().await;
        let before = user_with_cheap_password("alice", "the-password", db.clone()).await;
        assert!(password::needs_rehash(&before.password_hash));

        let outcome = authenticate("alice", "the-password", db.clone())
            .await
            .unwrap();
        let AuthOutcome::Authenticated(user) = outcome else {
            panic!("expected a successful authentication");
        };
        assert!(!password::needs_rehash(&user.password_hash));

        // Persisted, not just updated in memory -- and the new digest still
        // verifies against the same password.
        let reloaded = AdminUser::find_by_username("alice", &db)
            .await
            .unwrap()
            .unwrap();
        assert!(!password::needs_rehash(&reloaded.password_hash));
        assert_eq!(
            password::verify_password(&reloaded.password_hash, "the-password"),
            Ok(true)
        );
    }

    #[tokio::test]
    async fn a_corrupt_stored_hash_refuses_the_login_rather_than_erroring() {
        let db = db().await;
        AdminUser::create("alice", "not-a-valid-encoded-hash", None, &db)
            .await
            .unwrap();
        // Not an Err: a mangled row must not take the whole login endpoint
        // down, and it must not read as "correct password" either.
        assert!(matches!(
            authenticate("alice", "anything", db).await.unwrap(),
            AuthOutcome::WrongPassword(_)
        ));
    }

    #[test]
    fn every_user_error_renders() {
        assert!(
            UserError::Database(sqlx::Error::RowNotFound)
                .to_string()
                .starts_with("database error:")
        );
        assert_eq!(
            UserError::Policy("too short".to_string()).to_string(),
            "too short"
        );
        assert_eq!(
            UserError::DuplicateUsername("bob".to_string()).to_string(),
            "an admin user named `bob` already exists"
        );
    }
}