kirino 0.7.9

Zero-trust authentication and authorization framework with RBAC and dynamic risk assessment.
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
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
pub mod policy;

use anyhow::Result;
use chrono::Utc;
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
    time::Instant,
};
use tokio::sync::RwLock;
use uuid::Uuid;

use self::policy::PasswordLoginPolicy;
#[cfg(feature = "auth-jwt")]
use crate::auth::credential::basic::JwtManager;
#[cfg(feature = "auth-password")]
use crate::auth::passport::static_password::{hash_password, verify_password};
#[cfg(feature = "rbac-dynamic")]
use crate::rbac::dynamic::arbiter::AuthorizationArbiter;
#[cfg(all(feature = "auth-password", feature = "auth-jwt"))]
use crate::rbac::traits::AssignmentStore;
use crate::{
    error::KirinoError,
    models::identity::Identity,
    rbac::{
        engine::RbacEngine,
        shared::Shared,
        store::{
            memory::InMemoryAssignmentStore,
            registry::{SimpleRole, StaticPermissionRegistry, StaticRoleRegistry},
        },
        subject::StringSubject,
        traits::Permission,
    },
};

#[derive(Debug, Clone)]
struct RateLimitEntry {
    attempts: u32,
    window_start: Instant,
}

/// Fixed-window rate limiter keyed by an opaque string (a username).
///
/// A key accumulates failures; after `max_attempts` failures within
/// `window_secs` the key stays blocked until `window_secs + lockout_secs` have
/// elapsed since the window opened. Two properties shape the threat model:
///
/// - It is per key, not per source address. It slows guessing against one account,
///   but does not by itself stop a spray across many usernames, and anyone who
///   knows a victim's username can use it to keep that account locked out.
/// - State is in-process and unshared. N replicas allow N times the attempts, and a
///   restart clears every lockout, so a deployment that needs a hard guarantee must
///   put a shared limiter (or per-IP limiting) in front of this one.
///
/// The limiter is also not an existence oracle: it counts attempts for any key,
/// whether or not the account exists, and its error carries no account state.
///
/// A limiter additionally carries a
/// [`PasswordLoginPolicy`] (default
/// [`Enabled`](policy::PasswordLoginPolicy::Enabled)); see
/// [`with_policy`](LoginRateLimiter::with_policy) for what `Disabled` skips.
pub struct LoginRateLimiter {
    max_attempts: u32,
    window_secs: u64,
    lockout_secs: u64,
    policy: PasswordLoginPolicy,
    entries: Arc<RwLock<HashMap<String, RateLimitEntry>>>,
}

/// Minimum password length in bytes, enforced by [`validate_password`].
///
/// 8 is the NIST SP 800-63B minimum password length; the length floor, not the
/// character-class rule below, is the control that actually raises guessing cost.
const MIN_PASSWORD_LEN: usize = 8;
/// Maximum password length in bytes.
///
/// Bounds how much attacker-controlled input reaches the Argon2id work function.
/// The 19 MiB memory cost is fixed, so a huge password cannot amplify memory much,
/// but it would still be hashed on every attempt; 128 keeps that cost flat and is
/// generous for both a passphrase and a password-manager value.
const MAX_PASSWORD_LEN: usize = 128;
/// Minimum username length in bytes; a local policy choice (shortest meaningful
/// operator-chosen name), not a security control - basis to be confirmed with
/// security review if any downstream treats it as one.
const MIN_USERNAME_LEN: usize = 2;
/// Maximum username length in bytes.
///
/// Bounds the size of every derived identifier: rate-limiter bucket key (see
/// [`RATE_LIMITER_MAX_ENTRIES`]), audit subject id, store rows and log lines.
const MAX_USERNAME_LEN: usize = 64;

/// Normalize and validate a username, returning the trimmed canonical form.
///
/// Accepts 2..=64 bytes of `[A-Za-z0-9._-]` after trimming, which keeps path
/// separators, whitespace, quotes and shell metacharacters out of every
/// downstream store, log line and file name. The caller must use the returned
/// value - not the input - as the identity, otherwise the rate limiter and the
/// user table can disagree on what the "same" username is.
///
/// # Errors
///
/// [`KirinoError::Validation`] when the trimmed value is empty or too short, too
/// long, or contains a character outside the allowed set.
pub fn validate_username(username: &str) -> Result<String> {
    let trimmed = username.trim();
    if trimmed.is_empty() || trimmed.len() < MIN_USERNAME_LEN {
        return Err(KirinoError::Validation(format!(
            "username must be at least {MIN_USERNAME_LEN} characters"
        ))
        .into());
    }
    if trimmed.len() > MAX_USERNAME_LEN {
        return Err(KirinoError::Validation(format!(
            "username must be at most {MAX_USERNAME_LEN} characters"
        ))
        .into());
    }
    if !trimmed
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
    {
        return Err(KirinoError::Validation(
            "username may only contain alphanumeric characters, underscores, hyphens, and dots"
                .to_string(),
        )
        .into());
    }
    Ok(trimmed.to_string())
}

/// Enforce the password policy: 8..=128 bytes and at least 3 of the 4 character
/// classes (uppercase, lowercase, digit, non-alphanumeric).
///
/// Lengths are counted in bytes, not characters, so a non-ASCII passphrase can
/// clear the floor with fewer than eight characters. The composition rule is a
/// local policy choice - NIST SP 800-63B prefers length and breach checks over
/// composition - and its basis is to be confirmed with security review. This
/// function only checks shape: it cannot tell whether a password is breached,
/// reused or otherwise known.
///
/// # Errors
///
/// [`KirinoError::Validation`] when the length or the class count is out of
/// policy.
pub fn validate_password(password: &str) -> Result<()> {
    if password.len() < MIN_PASSWORD_LEN {
        return Err(KirinoError::Validation(format!(
            "password must be at least {MIN_PASSWORD_LEN} characters"
        ))
        .into());
    }
    if password.len() > MAX_PASSWORD_LEN {
        return Err(KirinoError::Validation(format!(
            "password must be at most {MAX_PASSWORD_LEN} characters"
        ))
        .into());
    }

    let has_uppercase = password.chars().any(|c| c.is_uppercase());
    let has_lowercase = password.chars().any(|c| c.is_lowercase());
    let has_digit = password.chars().any(|c| c.is_ascii_digit());
    let has_special = password.chars().any(|c| !c.is_alphanumeric());

    let categories = [has_uppercase, has_lowercase, has_digit, has_special]
        .iter()
        .filter(|&&x| x)
        .count();

    if categories < 3 {
        return Err(KirinoError::Validation(
            "password must contain at least 3 of: uppercase, lowercase, digit, special character"
                .to_string(),
        )
        .into());
    }

    Ok(())
}

/// Soft cap on how many rate-limit buckets a [`LoginRateLimiter`] tracks.
///
/// At the cap the limiter first drops buckets whose window has fully elapsed and
/// then inserts the new key unconditionally, so this is a memory-hygiene bound,
/// not a hard ceiling: a burst of distinct usernames (credential stuffing, or a
/// scanner walking the namespace) keeps every live bucket and can push the map
/// past 10k. Keys are attacker-supplied and, on the login path, only trimmed -
/// the number of distinct keys is not bounded by the user table, and neither is
/// key length, so both are unbounded inputs and the real ceiling is process
/// memory. Because only elapsed buckets are pruned, the cap can never shorten an
/// active lockout: the failure mode it permits is memory growth, not a weakened
/// block. 10k matches the in-memory audit sink and TTL permission cache
/// defaults, so one process's in-memory security state has a single predictable
/// ceiling; the number itself has no recorded derivation and is to be confirmed
/// with security review before being treated as a DoS control.
const RATE_LIMITER_MAX_ENTRIES: usize = 10_000;

impl LoginRateLimiter {
    /// Create a limiter allowing `max_attempts` failures per `window_secs`, then
    /// blocking the key for `lockout_secs`.
    ///
    /// The three numbers are policy, not derived constants: size them from the
    /// legitimate retry rate (a human mistyping a password) against the online
    /// guessing budget the deployment accepts, and record the reasoning here when
    /// changing them. [`AuthService::new`] constructs the login and registration
    /// limiters with the crate's defaults.
    #[must_use]
    pub fn new(max_attempts: u32, window_secs: u64, lockout_secs: u64) -> Self {
        Self {
            max_attempts,
            window_secs,
            lockout_secs,
            // Default-keep: a limiter built without an explicit policy keeps
            // counting, so every existing caller is unaffected.
            policy: PasswordLoginPolicy::Enabled,
            entries: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Attach a [`PasswordLoginPolicy`] to this
    /// limiter.
    ///
    /// While the policy is `Disabled` both mutation paths become no-ops:
    /// [`check_and_record_failure`](LoginRateLimiter::check_and_record_failure)
    /// returns `Ok(())` without taking the write lock or recording an entry,
    /// and [`reset`](LoginRateLimiter::reset) returns without touching the
    /// map. The intended pairing is a deployment that refuses password login
    /// outright (see
    /// [`AuthService::with_password_login_policy`](AuthService::with_password_login_policy)):
    /// a deployment with no password attempts must not accumulate lockout
    /// state, and an uncounted key can never lock an account out of the
    /// sign-in paths that remain. The no-op is "no bookkeeping", not "no
    /// enforcement" - a caller that keeps accepting password attempts while
    /// the limiter is `Disabled` has disarmed its limiter, so the refusal
    /// belongs in the caller's entry points, which is what `AuthService`
    /// does.
    #[must_use]
    pub fn with_policy(mut self, policy: PasswordLoginPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// The [`PasswordLoginPolicy`] this limiter
    /// was configured with; `Enabled` unless
    /// [`with_policy`](LoginRateLimiter::with_policy) set otherwise.
    #[must_use]
    pub fn policy(&self) -> PasswordLoginPolicy {
        self.policy
    }

    /// Set the policy in place, keeping any recorded state.
    ///
    /// Private: the public path is the [`with_policy`](LoginRateLimiter::with_policy)
    /// builder. `AuthService::with_password_login_policy` uses this to keep its
    /// login limiter in step with the service-level policy without dropping
    /// live lockout windows on the floor.
    fn set_policy(&mut self, policy: PasswordLoginPolicy) {
        self.policy = policy;
    }

    /// Record one failed attempt for `key`, failing while the key is blocked.
    ///
    /// The window is fixed, not sliding: it opens on the first counted failure and is
    /// reset once `window_secs + lockout_secs` have elapsed, or once the window has
    /// passed with fewer than `max_attempts` failures. The counter only advances on
    /// this path, so a successful authentication must call
    /// [`LoginRateLimiter::reset`] (the [`AuthService`] login path does); otherwise
    /// earlier failures keep counting against the key until the window rolls over.
    ///
    /// # Errors
    ///
    /// [`KirinoError::Validation`] while the key is inside its lockout window. The
    /// message states only how long to wait - it never reveals account state and
    /// must stay that way, since callers surface it to unauthenticated clients.
    ///
    /// While this limiter's [`PasswordLoginPolicy`]
    /// is `Disabled` the call is a no-op that returns `Ok(())` without taking
    /// the write lock: see [`with_policy`](LoginRateLimiter::with_policy).
    pub async fn check_and_record_failure(&self, key: &str) -> Result<()> {
        if !self.policy.is_enabled() {
            return Ok(());
        }

        // Audit kirino-R1-A1: the bucket key is case-normalized — case
        // variants of one account name share a lockout, and no consumer
        // call site can forget to normalize (the account lookup itself
        // stays exact-match; only the limiter bucket collapses).
        let key = key.trim().to_lowercase();
        let mut entries = self.entries.write().await;
        let now = Instant::now();

        if entries.len() >= RATE_LIMITER_MAX_ENTRIES {
            let total_window = std::time::Duration::from_secs(self.window_secs + self.lockout_secs);
            entries.retain(|_, entry| now.duration_since(entry.window_start) <= total_window);
        }

        let entry = entries.entry(key.to_string()).or_insert(RateLimitEntry {
            attempts: 0,
            window_start: now,
        });

        let elapsed = now.duration_since(entry.window_start);
        let total_window = std::time::Duration::from_secs(self.window_secs + self.lockout_secs);
        let window_duration = std::time::Duration::from_secs(self.window_secs);

        let should_reset = elapsed > total_window
            || (elapsed > window_duration && entry.attempts < self.max_attempts);

        if should_reset {
            entry.attempts = 0;
            entry.window_start = now;
        }

        if entry.attempts >= self.max_attempts {
            let remaining = total_window.saturating_sub(elapsed);
            if remaining > std::time::Duration::ZERO {
                return Err(KirinoError::Validation(format!(
                    "too many login attempts, try again in {} seconds",
                    remaining.as_secs()
                ))
                .into());
            }
            entry.attempts = 0;
            entry.window_start = now;
        }

        entry.attempts += 1;
        Ok(())
    }

    /// Forget `key`'s failures, clearing any active lockout.
    ///
    /// Call it only after the identity has actually been proven (a successful login
    /// or registration). Resetting on an unverified request would let an attacker
    /// clear the counter at will.
    ///
    /// A no-op while this limiter's
    /// [`PasswordLoginPolicy`] is `Disabled`, since
    /// no entry can exist to forget - see
    /// [`with_policy`](LoginRateLimiter::with_policy).
    pub async fn reset(&self, key: &str) {
        if !self.policy.is_enabled() {
            return;
        }

        // Same normalization as check_and_record_failure: a success for
        // `Admin` must clear the bucket an `admin` failure filled.
        let key = key.trim().to_lowercase();
        let mut entries = self.entries.write().await;
        entries.remove(&key);
    }
}

#[derive(Clone)]
pub struct UserRecord {
    pub id: Uuid,
    pub username: String,
    pub(crate) password_hash: String,
    pub display_name: Option<String>,
    pub is_active: bool,
    pub identity: Identity,
    pub created_at: chrono::DateTime<Utc>,
    pub updated_at: chrono::DateTime<Utc>,
}

impl std::fmt::Debug for UserRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UserRecord")
            .field("id", &self.id)
            .field("username", &self.username)
            .field("password_hash", &"[redacted]")
            .field("display_name", &self.display_name)
            .field("is_active", &self.is_active)
            .field("identity", &self.identity)
            .field("created_at", &self.created_at)
            .field("updated_at", &self.updated_at)
            .finish()
    }
}

impl UserRecord {
    #[must_use]
    pub fn to_public(&self) -> UserInfo {
        UserInfo {
            id: self.id,
            username: self.username.clone(),
            display_name: self.display_name.clone(),
            is_active: self.is_active,
            identity: self.identity.clone(),
            created_at: self.created_at,
            updated_at: self.updated_at,
        }
    }
}

#[derive(Debug, Clone)]
pub struct UserInfo {
    pub id: Uuid,
    pub username: String,
    pub display_name: Option<String>,
    pub is_active: bool,
    pub identity: Identity,
    pub created_at: chrono::DateTime<Utc>,
    pub updated_at: chrono::DateTime<Utc>,
}

#[derive(Debug, Clone)]
pub struct LoginResult {
    pub token: String,
    pub user_id: String,
    pub username: String,
    pub display_name: Option<String>,
    pub roles: Vec<String>,
    #[cfg(feature = "auth-jwt")]
    pub session_id: Option<uuid::Uuid>,
}

/// Authentication service: registration, login, JWT issuance and password change.
///
/// # First user and the invitation-only model
///
/// The deployment model is invitation-only: accounts are created by an administrator who
/// already holds `rbac.manage`, so a fresh install normally has nobody who can administer it.
/// The **first** account is therefore a deliberate, narrow exemption from that model — it is
/// created without an invitation and it must be able to administer the install, otherwise the
/// install cannot be operated at all. This is an exemption, not a change of the model: the
/// second and every later account goes through the normal invitation path.
///
/// The exemption is opt-in, because the kernel cannot know whether an install bootstraps
/// itself or is seeded by an operator out of band:
///
/// * [`AuthService::new`] starts with the exemption **off** (`auto_admin_first_user = false`),
///   so the first account gets `default_role`.
/// * [`AuthService::with_auto_admin_first_user(true)`](AuthService::with_auto_admin_first_user)
///   turns it on: the first account that is registered against an empty user table receives
///   `first_user_role` (conventionally `"admin"`) instead of `default_role`.
///
/// A consumer that wants the forced behaviour must therefore set the switch explicitly; the
/// opt-in is visible in `examples/auth_service.rs` of this repository and in the workspace
/// services. The grant is guarded by both an in-process latch and an empty-table check, so it
/// can only ever hand out one first-user role, and it is applied to registration only: logging
/// in never changes a role.
///
/// # Password login policy
///
/// The service also carries a
/// [`PasswordLoginPolicy`] - whether the password
/// sign-in method is offered at all. It defaults to
/// [`Enabled`](policy::PasswordLoginPolicy::Enabled) (the historical
/// behaviour) and is turned off with
/// [`with_password_login_policy`](AuthService::with_password_login_policy),
/// which makes [`login`](AuthService::login) and
/// [`login_with_session`](AuthService::login_with_session) refuse the attempt
/// before any credential is read. Third-party-only deployments (the family
/// ERP signs in via Feishu only) configure it from their settings; see the
/// [`policy`] module docs for the full contract.
#[cfg(all(feature = "auth-password", feature = "auth-jwt"))]
pub struct AuthService<DB, P, A>
where
    P: Permission,
    A: AssignmentStore<StringSubject, P>,
{
    db: DB,
    jwt: JwtManager,
    engine: Shared<RbacEngine<StringSubject, P, A>>,
    #[cfg(feature = "rbac-dynamic")]
    arbiter: Option<Shared<AuthorizationArbiter>>,
    rate_limiter: LoginRateLimiter,
    register_rate_limiter: LoginRateLimiter,
    password_login_policy: PasswordLoginPolicy,
    first_user_role: String,
    default_role: String,
    auto_admin_first_user: bool,
    has_first_user: std::sync::atomic::AtomicBool,
}

#[cfg(all(feature = "auth-password", feature = "auth-jwt"))]
impl<DB, P, A> AuthService<DB, P, A>
where
    DB: UserDatabase,
    P: Permission,
    A: AssignmentStore<StringSubject, P>,
{
    pub fn new(
        db: DB,
        jwt_secret: &str,
        jwt_expiration_hours: i64,
        engine: Shared<RbacEngine<StringSubject, P, A>>,
        first_user_role: &str,
        default_role: &str,
    ) -> Result<Self> {
        Ok(Self {
            db,
            jwt: JwtManager::new(jwt_secret, jwt_expiration_hours)?,
            engine,
            #[cfg(feature = "rbac-dynamic")]
            arbiter: None,
            // Login: 5 failures per 300 s window, then a 900 s lockout. Rationale:
            // five covers a human mistyping a password a few times, while staying far
            // below what an online guessing session would need; the lockout is 3x the
            // window so the block outlives the observation period instead of expiring
            // with it. The exact numbers have no recorded derivation - treat them as
            // tunable policy defaults pending confirmation with security review.
            rate_limiter: LoginRateLimiter::new(5, 300, 900),
            // Registration: 3 failures per 300 s window, then a 1800 s lockout.
            // Stricter than login because account creation is not a repeated human
            // action and is the more attractive automation target (mass registration,
            // name squatting). A rejected duplicate name also counts as a failure,
            // since only a successful registration resets the key. Same caveat as
            // above: defaults without a recorded derivation, pending security review.
            register_rate_limiter: LoginRateLimiter::new(3, 300, 1800),
            // Default-keep: password login stays enabled unless the consumer
            // opts out, so existing callers behave exactly as before.
            password_login_policy: PasswordLoginPolicy::Enabled,
            first_user_role: first_user_role.to_string(),
            default_role: default_role.to_string(),
            auto_admin_first_user: false,
            has_first_user: std::sync::atomic::AtomicBool::new(false),
        })
    }

    #[must_use]
    pub fn with_rate_limiter(mut self, limiter: LoginRateLimiter) -> Self {
        // Keep the limiter's policy in step with the service's: a limiter
        // built standalone defaults to Enabled, and leaving it there after
        // the service was set to Disabled would resurrect password-attempt
        // bookkeeping the policy just switched off (builder-order trap,
        // flagged by verification round 1 — the service gate still refuses
        // the login itself, so this is consistency, not a security fix).
        let policy = self.password_login_policy;
        self.rate_limiter = limiter;
        self.rate_limiter.set_policy(policy);
        self
    }

    /// Sets whether the password sign-in method is offered at all.
    ///
    /// With [`Disabled`](policy::PasswordLoginPolicy::Disabled)
    /// the password login entry points ([`login`](AuthService::login) and
    /// [`login_with_session`](AuthService::login_with_session)) refuse every
    /// attempt with a validation error before any credential is looked up,
    /// hashed or compared, and the login rate limiter stops recording
    /// password attempts (see
    /// [`LoginRateLimiter::with_policy`]). This is the configuration shape
    /// for third-party-only deployments - the family ERP keeps Feishu
    /// sign-in only - where each service parses the value from its own
    /// settings with [`PasswordLoginPolicy::parse`](policy::PasswordLoginPolicy::parse)
    /// and fails closed on `None`. The default is
    /// [`Enabled`](policy::PasswordLoginPolicy::Enabled); the policy only
    /// governs the login method, it does not delete stored hashes or change
    /// [`change_password`](AuthService::change_password).
    #[must_use]
    pub fn with_password_login_policy(mut self, policy: PasswordLoginPolicy) -> Self {
        self.password_login_policy = policy;
        self.rate_limiter.set_policy(policy);
        self
    }

    /// The [`PasswordLoginPolicy`] this service
    /// was configured with; [`Enabled`](policy::PasswordLoginPolicy::Enabled)
    /// unless [`with_password_login_policy`](AuthService::with_password_login_policy)
    /// set otherwise. A consumer uses it to decide which sign-in options to
    /// offer in its UI.
    #[must_use]
    pub fn password_login_policy(&self) -> PasswordLoginPolicy {
        self.password_login_policy
    }

    /// Refuse password login before any credential work when the policy is
    /// `Disabled`.
    ///
    /// The error is a deliberate validation refusal, not
    /// [`KirinoError::AuthenticationFailed`]: the deployment shape (password
    /// login off, use a third-party provider) is public configuration that a
    /// sign-in UI needs to relay, not a guess about one credential.
    fn ensure_password_login_allowed(&self) -> Result<()> {
        if !self.password_login_policy.is_enabled() {
            return Err(KirinoError::Validation(
                "password login is disabled by policy; sign in with a third-party identity provider"
                    .to_string(),
            )
            .into());
        }
        Ok(())
    }

    /// Enables the first-user exemption from the invitation-only model.
    ///
    /// With `enabled = true`, the first account registered against an empty user table is
    /// assigned `first_user_role` (conventionally `"admin"`) instead of `default_role`, so a
    /// fresh install has an administrator without an invitation. This is the only exemption:
    /// every later account goes through the normal invitation path. The default is `false`
    /// (opt-in), see the [`AuthService`] type docs for the rationale.
    #[must_use]
    pub fn with_auto_admin_first_user(mut self, enabled: bool) -> Self {
        self.auto_admin_first_user = enabled;
        self
    }

    #[must_use]
    #[cfg(feature = "rbac-dynamic")]
    pub fn with_arbiter(mut self, arbiter: AuthorizationArbiter) -> Self {
        self.arbiter = Some(Shared::new(arbiter));
        self
    }

    #[cfg(feature = "rbac-dynamic")]
    #[must_use]
    pub fn arbiter(&self) -> Option<Shared<AuthorizationArbiter>> {
        self.arbiter.clone()
    }

    #[must_use]
    pub fn jwt_manager(&self) -> &JwtManager {
        &self.jwt
    }

    #[must_use]
    pub fn engine(&self) -> Shared<RbacEngine<StringSubject, P, A>> {
        self.engine.clone()
    }

    pub async fn register(
        &self,
        username: &str,
        password: &str,
        display_name: Option<&str>,
    ) -> Result<UserInfo> {
        let username = validate_username(username)?;
        validate_password(password)?;

        self.register_rate_limiter
            .check_and_record_failure(&username)
            .await?;

        let result = self.register_impl(&username, password, display_name).await;

        if result.is_ok() {
            self.register_rate_limiter.reset(&username).await;
        }
        result
    }

    async fn register_impl(
        &self,
        username: &str,
        password: &str,
        display_name: Option<&str>,
    ) -> Result<UserInfo> {
        if self.db.find_by_username(username).await?.is_some() {
            return Err(KirinoError::Validation("username already exists".to_string()).into());
        }

        let password_hash = hash_password(password)?;
        let user_id = Uuid::now_v7();
        let now = Utc::now();
        let identity = Identity::Basic {
            id: user_id,
            created_at: now,
        };

        let user = UserRecord {
            id: user_id,
            username: username.to_string(),
            password_hash,
            display_name: display_name.map(ToString::to_string),
            is_active: true,
            identity,
            created_at: now,
            updated_at: now,
        };

        let is_first = self.auto_admin_first_user
            && !self
                .has_first_user
                .swap(true, std::sync::atomic::Ordering::SeqCst)
            && self.db.count_users().await? == 0;

        self.db.create_user(&user).await?;

        let role_name = if is_first {
            &self.first_user_role
        } else {
            &self.default_role
        };

        let subject = StringSubject::new(user_id.to_string());
        self.engine
            .assignment_store()
            .assign_role(&subject, role_name)
            .await?;

        Ok(user.to_public())
    }

    // A well-formed Argon2id hash with an all-zero salt, verified against when the
    // username does not exist so that path pays the same hashing cost as a real
    // wrong-password check (see `authenticate_user`). Its m/t/p must match
    // `static_password::ARGON2_*` or the unknown-user path becomes measurably
    // cheaper than the known-user one, restoring the enumeration oracle. Removing
    // the verification would do the same.
    const DUMMY_HASH: &str =
        "$argon2id$v=19$m=19456,t=2,p=1$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    async fn authenticate_user(&self, username: &str, password: &str) -> Result<UserRecord> {
        let Some(user) = self.db.find_by_username(username).await? else {
            if let Err(e) = verify_password(password, Self::DUMMY_HASH) {
                tracing::error!(target: "kirino::service::login",
                    error = %e,
                    "dummy hash verification failed"
                );
            }
            return Err(KirinoError::AuthenticationFailed.into());
        };

        if !user.is_active {
            // Timing equalization, not authentication: the deactivated-account path
            // must pay the same Argon2id cost as a wrong password on an active
            // account, otherwise response time becomes an account-state oracle
            // (the unknown-user branch above does the equivalent with DUMMY_HASH).
            // The result is intentionally discarded, and the cost is only paid if
            // `password_hash` is a valid PHC string - which `hash_password`
            // guarantees for anything stored through this crate. Do not remove this
            // call or turn it into an early return.
            let _ = verify_password(password, &user.password_hash);
            return Err(KirinoError::AuthenticationFailed.into());
        }

        if !verify_password(password, &user.password_hash)? {
            return Err(KirinoError::AuthenticationFailed.into());
        }

        self.rate_limiter.reset(username).await;
        Ok(user)
    }

    async fn fetch_user_roles_and_perms(
        &self,
        user_id: &str,
    ) -> Result<(Vec<String>, Vec<String>)> {
        let subject = StringSubject::new(user_id);
        let roles = self
            .engine
            .assignment_store()
            .roles_of(&subject)
            .await
            .map_err(|e| {
                tracing::warn!("failed to fetch roles for user {user_id}: {e}");
                KirinoError::AuthorizationDenied("store unavailable".into())
            })?;

        let perm_names: Vec<String> = self
            .engine
            .effective_permissions(&subject)
            .await
            .map_err(|e| {
                tracing::warn!("failed to fetch effective permissions: {e}");
                KirinoError::AuthorizationDenied("store unavailable".into())
            })?
            .into_iter()
            .map(|p| p.name().to_string())
            .collect();

        Ok((roles, perm_names))
    }

    pub async fn login(&self, username: &str, password: &str) -> Result<LoginResult> {
        self.ensure_password_login_allowed()?;
        let username = username.trim();
        self.rate_limiter.check_and_record_failure(username).await?;

        let user = self.authenticate_user(username, password).await?;
        let user_id = user.id.to_string();
        let (roles, perm_names) = self.fetch_user_roles_and_perms(&user_id).await?;

        let token = self.jwt.issue_with_options(
            &user_id,
            &user.username,
            roles.clone(),
            perm_names,
            None,
        )?;

        Ok(LoginResult {
            token,
            user_id,
            username: user.username.clone(),
            display_name: user.display_name.clone(),
            roles,
            session_id: None,
        })
    }

    pub async fn verify_token(
        &self,
        token: &str,
    ) -> Result<crate::auth::credential::basic::Claims> {
        self.jwt.verify_with_revocation(token).await
    }

    #[must_use]
    pub async fn check_permission(&self, user_id: &str, permission: &P) -> bool {
        let subject = StringSubject::new(user_id);
        self.engine.check(&subject, permission).await
    }

    #[cfg(feature = "rbac-dynamic")]
    #[must_use]
    pub async fn check_static_and_dynamic(
        &self,
        user_id: &str,
        permission: &P,
        action_request: &crate::rbac::dynamic::metrics::ActionRequest,
    ) -> bool {
        let subject = StringSubject::new(user_id);
        if !self.engine.check(&subject, permission).await {
            return false;
        }
        if let Some(ref arbiter) = self.arbiter {
            let verdict = arbiter.authorize(action_request).await;
            return verdict.allowed;
        }
        true
    }

    pub async fn change_password(
        &self,
        user_id: &str,
        old_password: &str,
        new_password: &str,
    ) -> Result<()> {
        let uid = Uuid::parse_str(user_id)
            .map_err(|_| KirinoError::Validation("invalid user_id".to_string()))?;

        let user = self
            .db
            .find_by_id(&uid)
            .await?
            .ok_or_else(|| KirinoError::NotFound("user not found".to_string()))?;

        if !verify_password(old_password, &user.password_hash)? {
            return Err(KirinoError::AuthenticationFailed.into());
        }

        validate_password(new_password)?;

        let new_hash = hash_password(new_password)?;
        self.jwt.revoke_all_for_user(user_id).await;
        self.db.update_password(&uid, &new_hash).await
    }

    pub async fn list_users(&self) -> Result<Vec<UserInfo>> {
        let users = self.db.list_users().await?;
        Ok(users.iter().map(UserRecord::to_public).collect())
    }

    pub async fn delete_user(&self, user_id: &str) -> Result<bool> {
        let uid = Uuid::parse_str(user_id)
            .map_err(|_| KirinoError::Validation("invalid user_id".to_string()))?;
        self.jwt.revoke_all_for_user(user_id).await;
        self.db.delete_user(&uid).await
    }

    pub async fn login_with_session<SM>(
        &self,
        username: &str,
        password: &str,
        session_mgr: &SM,
        session_ttl: chrono::Duration,
    ) -> Result<(LoginResult, crate::rbac::session::Session<StringSubject>)>
    where
        SM: crate::rbac::session::SessionManager<StringSubject>,
    {
        self.ensure_password_login_allowed()?;
        let username_trimmed = username.trim();
        self.rate_limiter
            .check_and_record_failure(username_trimmed)
            .await?;

        let user = self.authenticate_user(username_trimmed, password).await?;

        let user_id = user.id.to_string();
        let (roles, perm_names) = self.fetch_user_roles_and_perms(&user_id).await?;

        let active_roles: HashSet<String> = roles.iter().cloned().collect();
        let subject = StringSubject::new(&user_id);
        let session = session_mgr
            .create_session(&subject, active_roles, session_ttl)
            .await?;

        let token = self.jwt.issue_with_options(
            &user_id,
            &user.username,
            roles.clone(),
            perm_names,
            Some(session.id.to_string()),
        )?;

        Ok((
            LoginResult {
                token,
                user_id,
                username: user.username.clone(),
                display_name: user.display_name.clone(),
                roles,
                session_id: Some(session.id),
            },
            session,
        ))
    }

    pub async fn logout<SM>(&self, _user_id: &str, session_id: Uuid, session_mgr: &SM) -> Result<()>
    where
        SM: crate::rbac::session::SessionManager<StringSubject>,
    {
        self.jwt.revoke_session(&session_id.to_string()).await;
        session_mgr.destroy_session(session_id).await
    }
}

/// Build an RBAC engine using the hierarchical `Permission` enum.
#[must_use]
pub fn build_default_engine() -> Shared<
    RbacEngine<
        StringSubject,
        crate::rbac::permission::Permission,
        InMemoryAssignmentStore<StringSubject, crate::rbac::permission::Permission>,
    >,
> {
    use crate::rbac::permission::Permission;

    let mut role_reg = StaticRoleRegistry::new();
    role_reg.register(SimpleRole::new(
        "admin",
        Permission::all().into_iter().collect(),
    ));
    role_reg.register(SimpleRole::new(
        "operator",
        Permission::all()
            .into_iter()
            .filter(|p: &Permission| p.domain() != "system" && p.domain() != "rbac")
            .collect(),
    ));
    role_reg.register(SimpleRole::new(
        "member",
        Permission::all()
            .into_iter()
            .filter(|p: &Permission| {
                matches!(
                    p.name(),
                    "provider.list"
                        | "provider.use"
                        | "mcp.list"
                        | "mcp.use"
                        | "agent.list"
                        | "agent.use"
                        | "channel.list"
                        | "channel.use"
                        | "workspace.list"
                        | "workspace.create"
                        | "device.list"
                        | "device.connect"
                )
            })
            .collect(),
    ));
    role_reg.register(SimpleRole::new(
        "viewer",
        Permission::all()
            .into_iter()
            .filter(|p| p.name().ends_with(".list") || p.name() == "deploy.read")
            .collect(),
    ));

    let perm_reg = StaticPermissionRegistry::new(Permission::all().into_iter().collect());
    let store = InMemoryAssignmentStore::new();

    Shared::new(RbacEngine::new(role_reg, perm_reg, store))
}

#[async_trait::async_trait]
pub trait UserDatabase: Send + Sync + Clone + 'static {
    async fn create_user(&self, user: &UserRecord) -> Result<()>;
    async fn find_by_username(&self, username: &str) -> Result<Option<UserRecord>>;
    async fn find_by_id(&self, id: &Uuid) -> Result<Option<UserRecord>>;
    async fn update_password(&self, id: &Uuid, new_hash: &str) -> Result<()>;
    async fn delete_user(&self, id: &Uuid) -> Result<bool>;
    async fn list_users(&self) -> Result<Vec<UserRecord>>;
    async fn count_users(&self) -> Result<u64>;
}

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

    #[test]
    fn test_validate_username_valid() {
        assert_eq!(validate_username("alice").unwrap(), "alice");
        assert_eq!(validate_username("bob_123").unwrap(), "bob_123");
        assert_eq!(validate_username("user.name").unwrap(), "user.name");
        assert_eq!(validate_username("a-b").unwrap(), "a-b");
    }

    #[test]
    fn test_validate_username_too_short() {
        assert!(validate_username("a").is_err());
        assert!(validate_username("").is_err());
    }

    #[test]
    fn test_validate_username_too_long() {
        let long = "a".repeat(65);
        assert!(validate_username(&long).is_err());
    }

    #[test]
    fn test_validate_username_exactly_max_length() {
        let max = "a".repeat(64);
        assert!(validate_username(&max).is_ok());
    }

    #[test]
    fn test_validate_username_invalid_chars() {
        assert!(validate_username("alice bob").is_err());
        assert!(validate_username("alice@domain").is_err());
        assert!(validate_username("用户").is_err());
        assert!(validate_username("user!name").is_err());
    }

    #[test]
    fn test_validate_username_whitespace_only() {
        assert!(validate_username("  ").is_err());
    }

    #[test]
    fn test_validate_username_trimmed() {
        assert_eq!(validate_username("  ab  ").unwrap(), "ab");
    }

    #[test]
    fn test_validate_password_valid() {
        assert!(validate_password("Password1!").is_ok());
        assert!(validate_password("Abcdefg1").is_ok());
        assert!(validate_password("HELLOworld123!").is_ok());
    }

    #[test]
    fn test_validate_password_too_short() {
        assert!(validate_password("Ab1!").is_err());
    }

    #[test]
    fn test_validate_password_exactly_8() {
        assert!(validate_password("Abcd123!").is_ok());
    }

    #[test]
    fn test_validate_password_too_long() {
        let long = "Aa1!".repeat(33);
        assert!(validate_password(&long).is_err());
    }

    #[test]
    fn test_validate_password_exactly_max() {
        let max = "A".repeat(96) + "a1!";
        assert!(validate_password(&max).is_ok());
    }

    #[test]
    fn test_validate_password_only_two_categories() {
        assert!(validate_password("abcdefgh").is_err());
        assert!(validate_password("ABCDEFGH").is_err());
        assert!(validate_password("12345678").is_err());
        assert!(validate_password("abcdABCD").is_err());
        assert!(validate_password("abcd1234").is_err());
        assert!(validate_password("ABCD1234").is_err());
    }

    #[test]
    fn test_validate_password_exactly_three_categories() {
        assert!(validate_password("ABCDefgh1").is_ok());
        assert!(validate_password("Abcd1234").is_ok());
        assert!(validate_password("abcd123!").is_ok());
    }

    #[test]
    fn test_validate_password_unicode_uppercase_lowercase() {
        assert!(
            validate_password("Élève1!").is_ok(),
            "French accented chars should work"
        );
        assert!(
            validate_password("ÜberCafé1!").is_ok(),
            "German umlauts should work"
        );
        assert!(
            validate_password("Niño123!").is_ok(),
            "Spanish tilde should work"
        );
        assert!(
            validate_password("中文密码A1!").is_ok(),
            "CJK + ascii uppercase + digit + special"
        );
    }

    #[test]
    fn test_validate_password_unicode_all_one_category() {
        assert!(
            validate_password("abcdefgh").is_err(),
            "only lowercase fails"
        );
        assert!(
            validate_password("ÉÉÉÉÉÉÉÉ").is_err(),
            "only unicode uppercase fails"
        );
        assert!(
            validate_password("汉字汉字汉字汉字").is_err(),
            "only CJK fails"
        );
    }

    #[test]
    fn test_validate_password_unicode_with_special() {
        assert!(
            validate_password("Passエンド1!").is_ok(),
            "mixed ascii + CJK + special"
        );
    }

    #[tokio::test]
    async fn test_rate_limiter_allows_under_max() {
        let limiter = LoginRateLimiter::new(3, 300, 900);
        assert!(limiter.check_and_record_failure("user").await.is_ok());
        assert!(limiter.check_and_record_failure("user").await.is_ok());
        assert!(limiter.check_and_record_failure("user").await.is_ok());
    }

    /// Audit kirino-R1-A1: the rate-limit KEY is case-normalized, so
    /// `Admin` and `admin` share one bucket — a consumer store that
    /// matches usernames case-insensitively cannot be turned into N
    /// per-variant lockout bypasses. (The account lookup itself stays
    /// exact-match; only the limiter bucket collapses.)
    #[tokio::test]
    async fn test_rate_limiter_keys_share_one_bucket_across_case() {
        let limiter = LoginRateLimiter::new(3, 300, 900);
        limiter.check_and_record_failure("Admin").await.unwrap();
        limiter.check_and_record_failure("ADMIN").await.unwrap();
        limiter.check_and_record_failure("admin").await.unwrap();
        assert!(
            limiter.check_and_record_failure("aDmin").await.is_err(),
            "case variants must share one lockout bucket"
        );
        assert!(
            limiter.check_and_record_failure(" admin ").await.is_err(),
            "whitespace-trimmed case variants share the bucket too"
        );
        // Audit R1 suggestion: the RESET path normalizes too — three
        // failures under one case, a success under another must still
        // clear the shared bucket.
        limiter.reset("ADMIN").await;
        assert!(
            limiter.check_and_record_failure("admin").await.is_ok(),
            "reset must clear the bucket regardless of key case"
        );
    }

    #[tokio::test]
    async fn test_rate_limiter_blocks_at_max() {
        let limiter = LoginRateLimiter::new(3, 300, 900);
        limiter.check_and_record_failure("user").await.unwrap();
        limiter.check_and_record_failure("user").await.unwrap();
        limiter.check_and_record_failure("user").await.unwrap();
        assert!(limiter.check_and_record_failure("user").await.is_err());
    }

    #[tokio::test]
    async fn test_rate_limiter_independent_keys() {
        let limiter = LoginRateLimiter::new(2, 300, 900);
        limiter.check_and_record_failure("user-a").await.unwrap();
        limiter.check_and_record_failure("user-a").await.unwrap();
        assert!(limiter.check_and_record_failure("user-a").await.is_err());
        assert!(limiter.check_and_record_failure("user-b").await.is_ok());
    }

    #[tokio::test]
    async fn test_rate_limiter_reset() {
        let limiter = LoginRateLimiter::new(2, 300, 900);
        limiter.check_and_record_failure("user").await.unwrap();
        limiter.check_and_record_failure("user").await.unwrap();
        limiter.reset("user").await;
        assert!(limiter.check_and_record_failure("user").await.is_ok());
        assert!(limiter.check_and_record_failure("user").await.is_ok());
        assert!(limiter.check_and_record_failure("user").await.is_err());
    }

    #[tokio::test]
    async fn test_rate_limiter_reset_nonexistent_key() {
        let limiter = LoginRateLimiter::new(2, 300, 900);
        limiter.reset("nonexistent").await;
        assert!(limiter
            .check_and_record_failure("nonexistent")
            .await
            .is_ok());
    }

    #[tokio::test]
    async fn test_rate_limiter_window_reset_below_max() {
        let limiter = LoginRateLimiter::new(5, 1, 60);
        limiter.check_and_record_failure("user").await.unwrap();
        limiter.check_and_record_failure("user").await.unwrap();
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
        assert!(limiter.check_and_record_failure("user").await.is_ok());
    }

    #[tokio::test]
    async fn test_rate_limiter_lockout_persists_during_window() {
        let limiter = LoginRateLimiter::new(2, 60, 60);
        limiter.check_and_record_failure("user").await.unwrap();
        limiter.check_and_record_failure("user").await.unwrap();
        assert!(limiter.check_and_record_failure("user").await.is_err());
    }

    #[test]
    fn test_rate_limiter_default_policy_is_enabled() {
        // Default-keep: a limiter built without an explicit policy keeps
        // counting, exactly as before the policy existed.
        let limiter = LoginRateLimiter::new(3, 300, 900);
        assert_eq!(limiter.policy(), PasswordLoginPolicy::Enabled);
    }

    #[tokio::test]
    async fn test_rate_limiter_with_policy_disabled_records_nothing() {
        let limiter = LoginRateLimiter::new(2, 300, 900).with_policy(PasswordLoginPolicy::Disabled);
        assert_eq!(limiter.policy(), PasswordLoginPolicy::Disabled);

        // Far past max_attempts, yet every call succeeds: the Disabled path
        // neither blocks nor counts.
        for _ in 0..10 {
            assert!(limiter.check_and_record_failure("user").await.is_ok());
        }
        limiter.reset("user").await;

        // No bucket was ever created: Disabled means no bookkeeping at all.
        assert!(limiter.entries.read().await.is_empty());
    }

    #[cfg(all(feature = "auth-password", feature = "auth-jwt"))]
    mod password_login_policy {
        use super::*;
        use crate::{
            database::memory::InMemoryUserDatabase,
            rbac::{
                permission::Permission, session::InMemorySessionManager,
                store::memory::InMemoryAssignmentStore, subject::StringSubject,
            },
        };

        type Service = AuthService<
            InMemoryUserDatabase,
            Permission,
            InMemoryAssignmentStore<StringSubject, Permission>,
        >;

        fn make_auth() -> Service {
            AuthService::new(
                InMemoryUserDatabase::new(),
                "test-secret-that-is-at-least-32-bytes-long",
                24,
                build_default_engine(),
                "admin",
                "viewer",
            )
            .unwrap()
        }

        fn make_session_mgr() -> InMemorySessionManager<StringSubject, Permission> {
            InMemorySessionManager::new(InMemoryAssignmentStore::new())
        }

        #[tokio::test]
        async fn test_default_policy_keeps_password_login_enabled() {
            let auth = make_auth();
            assert_eq!(auth.password_login_policy(), PasswordLoginPolicy::Enabled);

            auth.register("alice", "Password123!", None).await.unwrap();
            let result = auth.login("alice", "Password123!").await.unwrap();
            assert_eq!(result.username, "alice");
        }

        #[test]
        fn test_builder_order_limiter_inherits_service_policy() {
            // R1 finding: with_rate_limiter AFTER with_password_login_policy
            // must not resurrect Enabled bookkeeping on the fresh limiter.
            let svc = make_auth()
                .with_password_login_policy(PasswordLoginPolicy::Disabled)
                .with_rate_limiter(LoginRateLimiter::new(5, 300, 900));
            assert_eq!(svc.rate_limiter.policy(), PasswordLoginPolicy::Disabled);
            // Reverse order: the policy setter stays authoritative.
            let svc2 = make_auth()
                .with_rate_limiter(LoginRateLimiter::new(5, 300, 900))
                .with_password_login_policy(PasswordLoginPolicy::Disabled);
            assert_eq!(svc2.rate_limiter.policy(), PasswordLoginPolicy::Disabled);
        }

        #[tokio::test]
        async fn test_disabled_policy_rejects_login_before_credentials() {
            let auth = make_auth().with_password_login_policy(PasswordLoginPolicy::Disabled);
            assert_eq!(auth.password_login_policy(), PasswordLoginPolicy::Disabled);

            auth.register("alice", "Password123!", None).await.unwrap();

            // Even the correct password is refused: the gate precedes any
            // credential lookup, hash or comparison.
            let err = auth.login("alice", "Password123!").await.unwrap_err();
            assert!(
                err.to_string().contains("password login is disabled"),
                "expected the policy refusal, got: {err}"
            );
        }

        #[tokio::test]
        async fn test_disabled_policy_performs_no_rate_limit_bookkeeping() {
            let auth = make_auth()
                .with_rate_limiter(LoginRateLimiter::new(2, 300, 900))
                .with_password_login_policy(PasswordLoginPolicy::Disabled);
            auth.register("alice", "Password123!", None).await.unwrap();

            // Way past the limiter's max_attempts, yet every attempt yields
            // the policy refusal, never "too many login attempts": the
            // password-attempt bookkeeping never runs.
            for _ in 0..6 {
                let err = auth.login("alice", "wrong").await.unwrap_err();
                assert!(
                    err.to_string().contains("password login is disabled"),
                    "expected the policy refusal, got: {err}"
                );
            }
        }

        #[tokio::test]
        async fn test_disabled_policy_rejects_login_with_session() {
            let auth = make_auth().with_password_login_policy(PasswordLoginPolicy::Disabled);
            auth.register("alice", "Password123!", None).await.unwrap();

            let mgr = make_session_mgr();
            let err = auth
                .login_with_session("alice", "Password123!", &mgr, chrono::Duration::hours(1))
                .await
                .unwrap_err();
            assert!(
                err.to_string().contains("password login is disabled"),
                "expected the policy refusal, got: {err}"
            );
        }

        #[tokio::test]
        async fn test_disabled_policy_keeps_registration_and_change_password() {
            let auth = make_auth().with_password_login_policy(PasswordLoginPolicy::Disabled);

            // The policy governs the login method, not the credential data:
            // registration still works...
            let user = auth.register("alice", "Password123!", None).await.unwrap();

            // ...and an account that holds a credential can still rotate it.
            auth.change_password(&user.id.to_string(), "Password123!", "NewPassword456!")
                .await
                .unwrap();
        }
    }

    #[test]
    fn test_build_default_engine_roles() {
        let engine = build_default_engine();
        let reg = engine.role_registry();
        assert!(reg.get_role_permissions("admin").is_some());
        assert!(reg.get_role_permissions("operator").is_some());
        assert!(reg.get_role_permissions("viewer").is_some());
        assert!(reg.get_role_permissions("member").is_some());
        assert!(reg.get_role_permissions("nonexistent").is_none());
    }

    #[test]
    fn test_build_default_engine_admin_has_all_perms() {
        let engine = build_default_engine();
        let admin = engine
            .role_registry()
            .get_role_permissions("admin")
            .unwrap();
        assert_eq!(
            admin.len(),
            crate::rbac::permission::Permission::all().len()
        );
    }

    #[test]
    fn test_build_default_engine_viewer_is_list_read_only() {
        let engine = build_default_engine();
        let viewer = engine
            .role_registry()
            .get_role_permissions("viewer")
            .unwrap();
        for perm in &viewer {
            let n = perm.name();
            assert!(
                n.ends_with(".list") || n == "deploy.read",
                "viewer should only have .list or deploy.read, got {}",
                n
            );
        }
    }

    #[test]
    fn test_permission_all_count() {
        // 37 points through kirino 0.7.7; +4 plugin.* fabric points (A2).
        assert_eq!(crate::rbac::permission::Permission::all().len(), 41);
    }

    #[test]
    fn test_permission_domains() {
        use crate::rbac::permission::Permission;
        let p = Permission::from_path("agent.read").unwrap();
        assert_eq!(p.domain(), "agent");
        let p = Permission::from_path("config.write").unwrap();
        assert_eq!(p.domain(), "config");
        let p = Permission::from_path("system.read").unwrap();
        assert_eq!(p.domain(), "system");
        let p = Permission::from_path("deploy.execute").unwrap();
        assert_eq!(p.domain(), "deploy");
    }

    #[test]
    fn test_user_record_to_public() {
        let id = Uuid::now_v7();
        let now = Utc::now();
        let record = UserRecord {
            id,
            username: "alice".to_string(),
            password_hash: "hash".to_string(),
            display_name: Some("Alice".to_string()),
            is_active: true,
            identity: Identity::Basic {
                id,
                created_at: now,
            },
            created_at: now,
            updated_at: now,
        };
        let info = record.to_public();
        assert_eq!(info.id, id);
        assert_eq!(info.username, "alice");
        assert_eq!(info.display_name, Some("Alice".to_string()));
        assert!(info.is_active);
    }
}