entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
//! Shared input validation for names, usernames, OAuth parameters, and other
//! external identifiers used throughout the auth crate.
//!
//! Centralises character allowlists and safety rules so that every untrusted
//! string passes through one code path before it reaches storage, logging, or
//! downstream services.
//!
//! # Name validation
//!
//! [`is_valid_name`] reuses the exact rules from `entropy-logging` so that
//! names accepted here are also safe for log file paths and command identifiers.
//!
//! # Auth-specific validators
//!
//! Additional validators enforce constraints appropriate for OAuth 2.0 /
//! `OpenID` Connect parameters:
//!
//! | Validator                   | Governed by          |
//! |-----------------------------|----------------------|
//! | [`is_valid_username`]       | Application policy   |
//! | [`is_valid_redirect_uri`]   | RFC 6749 §3.1.2     |
//! | [`is_valid_scope`]          | RFC 6749 §3.3       |
//! | [`is_valid_client_id`]      | RFC 6749 §2.2       |

// ---------------------------------------------------------------------------
// Name validation (mirrored from entropy-logging)
// ---------------------------------------------------------------------------

/// Maximum byte length for a validated name.
///
/// Names longer than this are rejected by [`is_valid_name`]. The limit
/// is deliberately generous — most names are under 30 bytes — but
/// bounded to prevent unbounded allocation in error messages and
/// log file paths.
pub const MAX_NAME_LEN: usize = 200;

/// Human-readable description of the validation rules enforced by
/// [`is_valid_name`]. Used by error types to avoid duplicating the
/// constraint list in multiple `Display` implementations.
///
/// The numeric limit is embedded directly in the string (rather than
/// referencing `MAX_NAME_LEN` by name) so that user-facing error
/// messages are self-contained and readable without consulting the docs.
pub const NAME_RULES: &str = "must be non-empty, not exceed 200 bytes, \
     start with an ASCII alphanumeric character, contain only [a-zA-Z0-9._-], \
     must not contain consecutive periods ('..') or end with a period, \
     and must not match a Windows reserved device name";

// Compile-time guard: the "200 bytes" literal in `NAME_RULES` must
// match `MAX_NAME_LEN`. If `MAX_NAME_LEN` changes, update the string
// above and this assertion will enforce the correspondence.
const _: () = assert!(
    MAX_NAME_LEN == 200,
    "MAX_NAME_LEN changed — update NAME_RULES string to match"
);

/// Returns `true` if `name` is safe to use as a filename or command
/// identifier.
///
/// The name must:
/// - Not be empty
/// - Not exceed 200 bytes
/// - Start with an ASCII alphanumeric character
/// - Contain only ASCII alphanumeric characters, hyphens (`-`), underscores
///   (`_`), or periods (`.`)
/// - Not contain consecutive periods (`..`)
/// - Not end with a period
/// - Not match a Windows reserved device name (`CON`, `PRN`, etc.)
///
/// # Security
///
/// This rejects path separators, null bytes, control characters, whitespace,
/// hidden-file prefixes, and shell metacharacters — preventing path traversal,
/// command injection, and filename collision attacks.
#[must_use]
#[inline]
#[doc(alias = "validate_name")]
pub fn is_valid_name(name: &str) -> bool {
    if name.is_empty() || name.len() > MAX_NAME_LEN {
        return false;
    }

    // Must start with alphanumeric.
    if !name.as_bytes()[0].is_ascii_alphanumeric() {
        return false;
    }

    // Only allow [a-zA-Z0-9._-].
    if !name
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.')
    {
        return false;
    }

    // Reject consecutive periods (path traversal component) and trailing
    // periods (Windows silently strips them from filenames, which could
    // cause unexpected collisions).
    if name.contains("..") || name.ends_with('.') {
        return false;
    }

    // Reject Windows reserved device names (case-insensitive).
    // Check the stem (part before the first period) against reserved names.
    // Uses `eq_ignore_ascii_case` to avoid heap-allocating an uppercase copy.
    //
    // `split('.')` always yields at least one element (even for an empty
    // string), so the `unwrap_or` fallback is unreachable. We use
    // `unwrap_or(name)` instead of `unwrap()` to avoid a clippy
    // `missing_panics_doc` warning on this public function — adding a
    // `# Panics` section for an unreachable code path would be misleading.
    let stem = name.split('.').next().unwrap_or(name);
    if is_windows_reserved_name(stem) {
        return false;
    }

    true
}

/// Windows reserved device names used by [`is_windows_reserved_name`].
///
/// `CONIN$` and `CONOUT$` are also reserved on Windows but are not
/// listed here because the `$` character is already rejected by the
/// character allowlist in [`is_valid_name`].
const WINDOWS_RESERVED: &[&str] = &[
    // Standard device names.
    "CON", "PRN", "AUX", "NUL", // Serial ports.
    "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
    // Parallel ports.
    "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];

/// Returns `true` if `stem` matches a Windows reserved device name
/// (case-insensitive). Uses [`str::eq_ignore_ascii_case`] to avoid
/// heap allocation.
fn is_windows_reserved_name(stem: &str) -> bool {
    // Short-circuit on length: all reserved names are 3-4 characters.
    if stem.len() < 3 || stem.len() > 4 {
        return false;
    }

    WINDOWS_RESERVED
        .iter()
        .any(|reserved| stem.eq_ignore_ascii_case(reserved))
}

// ---------------------------------------------------------------------------
// Username validation
// ---------------------------------------------------------------------------

/// Maximum byte length for a validated username.
///
/// 256 bytes accommodates email-style usernames (`user@example.com`) and
/// federated identity providers that use long opaque identifiers, while
/// still bounding storage and display costs.
pub const MAX_USERNAME_LEN: usize = 256;

/// Human-readable description of the validation rules enforced by
/// [`is_valid_username`].
pub const USERNAME_RULES: &str = "must be non-empty, not exceed 256 bytes, \
     start with an ASCII alphanumeric character, contain only [a-zA-Z0-9._@-], \
     must not contain consecutive special characters, and must not contain null bytes";

// Compile-time guard: keep the embedded "256" in sync with the constant.
const _: () = assert!(
    MAX_USERNAME_LEN == 256,
    "MAX_USERNAME_LEN changed — update USERNAME_RULES string to match"
);

/// Returns `true` if `s` is a valid username.
///
/// The username must:
/// - Not be empty
/// - Not exceed 256 bytes
/// - Start with an ASCII alphanumeric character (`[a-zA-Z0-9]`)
/// - Contain only ASCII alphanumeric characters, periods (`.`), underscores
///   (`_`), hyphens (`-`), or at-signs (`@`)
/// - Not contain consecutive special (non-alphanumeric) characters
/// - Not contain null bytes
///
/// # Security
///
/// * Rejecting null bytes prevents truncation attacks in C-backed storage.
/// * Requiring an alphanumeric start prevents hidden-file or option-injection
///   attacks (`-flag`, `.hidden`).
/// * Forbidding consecutive special characters mitigates visual spoofing
///   (e.g. `user..name` vs `user.name`) and simplifies display rendering.
#[must_use]
#[inline]
#[doc(alias = "validate_username")]
pub fn is_valid_username(s: &str) -> bool {
    if s.is_empty() || s.len() > MAX_USERNAME_LEN {
        return false;
    }

    // Must start with alphanumeric.
    if !s.as_bytes()[0].is_ascii_alphanumeric() {
        return false;
    }

    // Track whether the previous character was a special (non-alphanumeric)
    // character so we can reject consecutive specials.
    let mut prev_special = false;

    for &b in s.as_bytes() {
        if b == 0 {
            // Null byte — reject unconditionally.
            return false;
        }

        let is_alnum = b.is_ascii_alphanumeric();
        let is_special = b == b'.' || b == b'_' || b == b'-' || b == b'@';

        if !is_alnum && !is_special {
            // Character outside the allowlist.
            return false;
        }

        if is_special {
            if prev_special {
                // Consecutive special characters.
                return false;
            }
            prev_special = true;
        } else {
            prev_special = false;
        }
    }

    true
}

// ---------------------------------------------------------------------------
// Redirect URI validation
// ---------------------------------------------------------------------------

/// Maximum byte length for a validated redirect URI.
///
/// 2048 bytes matches the de-facto limit in most browsers and reverse
/// proxies (e.g. Nginx `large_client_header_buffers`). Longer URIs
/// are almost certainly malformed or adversarial.
pub const MAX_REDIRECT_URI_LEN: usize = 2048;

/// Human-readable description of the validation rules enforced by
/// [`is_valid_redirect_uri`].
pub const REDIRECT_URI_RULES: &str = "must not be empty, not exceed 2048 bytes, \
     start with \"https://\" (or \"http://localhost\" / \"http://127.0.0.1\" for local \
     development), must not contain a fragment (#), and must not contain null bytes";

// Compile-time guard: keep the embedded "2048" in sync with the constant.
const _: () = assert!(
    MAX_REDIRECT_URI_LEN == 2048,
    "MAX_REDIRECT_URI_LEN changed — update REDIRECT_URI_RULES string to match"
);

/// Returns `true` if `s` is a valid OAuth 2.0 redirect URI.
///
/// Per RFC 6749 §3.1.2 the redirect URI must be an absolute URI. This
/// validator enforces:
///
/// - Non-empty
/// - At most 2048 bytes
/// - Scheme is `https://`, **or** `http://localhost` / `http://127.0.0.1`
///   (for local development per RFC 8252 §8.3)
/// - No fragment component (`#`) — RFC 6749 §3.1.2 explicitly forbids it
/// - No null bytes
///
/// # Security
///
/// * Requiring HTTPS (except for loopback) prevents token interception
///   via unencrypted transport.
/// * Rejecting fragments prevents client-side token leakage through
///   the URL hash, which is never sent to the server.
/// * Null byte rejection prevents truncation attacks in C-backed HTTP
///   stacks.
/// * Length bounding mitigates denial-of-service through oversized URIs.
#[must_use]
#[inline]
#[doc(alias = "validate_redirect_uri")]
pub fn is_valid_redirect_uri(s: &str) -> bool {
    if s.is_empty() || s.len() > MAX_REDIRECT_URI_LEN {
        return false;
    }

    // Null bytes could cause truncation in C-backed HTTP stacks.
    if s.bytes().any(|b| b == 0) {
        return false;
    }

    // Fragments are forbidden by RFC 6749 §3.1.2.
    if s.contains('#') {
        return false;
    }

    // Scheme check: HTTPS required, with loopback exceptions for local dev.
    let has_valid_scheme = s.starts_with("https://") || is_http_loopback(s);

    if !has_valid_scheme {
        return false;
    }

    true
}

/// Returns `true` if `s` is an `http://` URI targeting a loopback address.
///
/// RFC 8252 §8.3 permits `http` for loopback redirect URIs during local
/// development. We accept `http://localhost`, `http://127.0.0.1`, and
/// `http://[::1]` (with optional port and path).
fn is_http_loopback(s: &str) -> bool {
    if !s.starts_with("http://") {
        return false;
    }

    let after_scheme = &s["http://".len()..];

    // SECURITY: isolate the AUTHORITY and reject userinfo first. Matching the
    // loopback literal anywhere in `after_scheme` accepted
    // `http://127.0.0.1:8080@attacker.example/cb`, where the real host is
    // `attacker.example` and the loopback text is merely the userinfo — so a
    // plain-HTTP off-host redirect URI passed as a "loopback" exception.
    let authority = after_scheme
        .split(['/', '?', '#'])
        .next()
        .unwrap_or(after_scheme);
    if authority.contains('@') {
        return false;
    }

    // Match "localhost" or "127.0.0.1", optionally followed by `:port`,
    // `/path`, or `?query`. The host portion ends at the first `/`, `?`,
    // or `:` (port separator).
    for host in &["localhost", "127.0.0.1", "[::1]"] {
        if after_scheme.eq_ignore_ascii_case(host) {
            // Exact match with no trailing path/port.
            return true;
        }
        if let Some(rest) = after_scheme
            .get(..host.len())
            .filter(|prefix| prefix.eq_ignore_ascii_case(host))
            .and_then(|_| after_scheme.get(host.len()..))
        {
            // The character immediately after the host must be a delimiter.
            let next = rest.as_bytes().first().copied();
            if matches!(next, Some(b':' | b'/' | b'?')) {
                return true;
            }
        }
    }

    false
}

// ---------------------------------------------------------------------------
// HTTPS URL validation
// ---------------------------------------------------------------------------

/// Returns `true` if `url` starts with `"https://"`.
///
/// This is a simple scheme check used by OIDC discovery and SAML
/// configuration to enforce transport-layer security on endpoint URLs.
/// It does **not** validate the URL structure beyond the scheme prefix.
#[must_use]
#[inline]
pub fn is_https_url(url: &str) -> bool {
    url.starts_with("https://")
}

// ---------------------------------------------------------------------------
// Scope validation
// ---------------------------------------------------------------------------

/// Maximum byte length for a validated scope string.
///
/// 1024 bytes is generous for space-delimited scope tokens. The bound
/// prevents abuse via extremely long scope lists that could bloat tokens
/// or logs.
pub const MAX_SCOPE_LEN: usize = 1024;

/// Human-readable description of the validation rules enforced by
/// [`is_valid_scope`].
pub const SCOPE_RULES: &str = "must be non-empty, not exceed 1024 bytes, \
     consist of space-delimited tokens where each token contains only NQCHAR \
     characters (0x21, 0x23-0x5B, 0x5D-0x7E) per RFC 6749 §3.3";

// Compile-time guard: keep the embedded "1024" in sync with the constant.
const _: () = assert!(
    MAX_SCOPE_LEN == 1024,
    "MAX_SCOPE_LEN changed — update SCOPE_RULES string to match"
);

/// Returns `true` if `s` is a valid OAuth 2.0 scope string.
///
/// Per RFC 6749 §3.3 the scope is a space-delimited list of scope tokens.
/// Each token consists of one or more NQCHAR characters, defined in
/// RFC 6749 Appendix A as:
///
/// ```text
/// NQCHAR = %x21 / %x23-5B / %x5D-7E
/// ```
///
/// This excludes space (`0x20`), double-quote (`0x22`, `"`), and backslash
/// (`0x5C`, `\`), as well as all control characters and non-ASCII bytes.
///
/// The full scope string must:
/// - Not be empty
/// - Not exceed 1024 bytes
/// - Consist of one or more tokens separated by single spaces (`0x20`)
///
/// # Security
///
/// * Strict NQCHAR enforcement prevents injection of control characters
///   or shell metacharacters into scope values that may appear in logs,
///   tokens, or HTTP headers.
/// * Length bounding prevents denial-of-service through oversized scope
///   parameters.
#[must_use]
#[inline]
#[doc(alias = "validate_scope")]
pub fn is_valid_scope(s: &str) -> bool {
    if s.is_empty() || s.len() > MAX_SCOPE_LEN {
        return false;
    }

    // Split on spaces; each segment must be a non-empty NQCHAR token.
    // This also implicitly rejects leading/trailing spaces and consecutive
    // spaces (they would produce empty segments).
    for token in s.split(' ') {
        if token.is_empty() {
            // Empty token means leading/trailing/consecutive spaces.
            return false;
        }
        if !token.bytes().all(is_nqchar) {
            return false;
        }
    }

    true
}

/// Returns `true` if `b` is an NQCHAR as defined by RFC 6749 Appendix A.
///
/// ```text
/// NQCHAR = %x21 / %x23-5B / %x5D-7E
/// ```
///
/// Excludes: space (0x20), double-quote (0x22), backslash (0x5C), control
/// characters (0x00-0x1F, 0x7F), and non-ASCII bytes (0x80-0xFF).
#[inline]
const fn is_nqchar(b: u8) -> bool {
    matches!(b, 0x21 | 0x23..=0x5B | 0x5D..=0x7E)
}

// ---------------------------------------------------------------------------
// Client ID validation
// ---------------------------------------------------------------------------

/// Maximum byte length for a validated client identifier.
///
/// 256 bytes accommodates UUIDs, URIs, and other provider-issued
/// identifiers while bounding storage costs.
pub const MAX_CLIENT_ID_LEN: usize = 256;

/// Human-readable description of the validation rules enforced by
/// [`is_valid_client_id`].
pub const CLIENT_ID_RULES: &str = "must be non-empty, not exceed 256 bytes, \
     contain only printable ASCII characters (0x20-0x7E), and must not contain \
     null bytes";

// Compile-time guard: keep the embedded "256" in sync with the constant.
const _: () = assert!(
    MAX_CLIENT_ID_LEN == 256,
    "MAX_CLIENT_ID_LEN changed — update CLIENT_ID_RULES string to match"
);

/// Returns `true` if `s` is a valid OAuth 2.0 client identifier.
///
/// Per RFC 6749 §2.2 the client identifier is issued by the authorization
/// server and is not a secret. This validator enforces:
///
/// - Non-empty
/// - At most 256 bytes
/// - All bytes are printable ASCII (`0x20`–`0x7E`)
/// - No null bytes (implied by printable ASCII, but checked explicitly for
///   clarity)
///
/// # Security
///
/// * Printable-ASCII enforcement prevents control-character injection into
///   HTTP headers, logs, and database queries.
/// * Null byte rejection prevents C-string truncation attacks.
/// * Length bounding prevents denial-of-service through oversized identifiers.
#[must_use]
#[inline]
#[doc(alias = "validate_client_id")]
pub fn is_valid_client_id(s: &str) -> bool {
    if s.is_empty() || s.len() > MAX_CLIENT_ID_LEN {
        return false;
    }

    // Printable ASCII: 0x20 (space) through 0x7E (~). This range excludes
    // null (0x00), control characters (0x01-0x1F), and DEL (0x7F).
    s.bytes().all(|b| (0x20..=0x7E).contains(&b))
}

// ---------------------------------------------------------------------------
// Email validation
// ---------------------------------------------------------------------------

/// Maximum byte length for a validated email address.
///
/// RFC 5321 §4.5.3.1 limits the total length of a mailbox to 254 octets
/// (256 minus the angle brackets used in SMTP).
pub const MAX_EMAIL_LEN: usize = 254;

/// Human-readable description of the validation rules enforced by
/// [`is_valid_email`].
pub const EMAIL_RULES: &str = "must be non-empty, not exceed 254 bytes, \
     contain exactly one '@', have a non-empty local part (max 64 bytes) and \
     a non-empty domain with at least one '.', using only printable ASCII";

// Compile-time guard: keep the embedded "254" in sync with the constant.
const _: () = assert!(
    MAX_EMAIL_LEN == 254,
    "MAX_EMAIL_LEN changed — update EMAIL_RULES string to match"
);

/// Returns `true` if `email` is a structurally valid email address.
///
/// This is a practical validation suitable for registration forms, not a
/// full RFC 5322 parser. The address must:
///
/// - Not be empty
/// - Not exceed 254 bytes (RFC 5321 §4.5.3.1)
/// - Contain exactly one `@` character
/// - Have a non-empty local part (max 64 bytes, RFC 5321 §4.5.3.1.1)
/// - Have a non-empty domain containing at least one `.`
/// - Contain only printable ASCII characters (0x21–0x7E), excluding
///   control characters and spaces
/// - Not have consecutive dots in either local or domain part
/// - Not start or end with a dot in either local or domain part
///
/// # Security
///
/// * Printable-ASCII enforcement prevents control-character injection.
/// * Length bounding prevents denial-of-service through oversized values.
/// * Null bytes and spaces are rejected to prevent truncation attacks
///   and display spoofing.
#[must_use]
#[inline]
#[doc(alias = "validate_email")]
pub fn is_valid_email(email: &str) -> bool {
    if email.is_empty() || email.len() > MAX_EMAIL_LEN {
        return false;
    }

    // Must contain only printable ASCII (0x21-0x7E), no spaces.
    if !email.bytes().all(|b| (0x21..=0x7E).contains(&b)) {
        return false;
    }

    // Must contain exactly one '@'.
    let at_count = email.bytes().filter(|&b| b == b'@').count();
    if at_count != 1 {
        return false;
    }

    // `at_count == 1` above guarantees this is `Some`; the else is unreachable.
    let Some(at_pos) = email.find('@') else {
        return false;
    };
    let local = &email[..at_pos];
    let domain = &email[at_pos + 1..];

    // Local part: non-empty, max 64 bytes.
    if local.is_empty() || local.len() > 64 {
        return false;
    }

    // Local part must be an unquoted dot-atom (RFC 5321 §4.1.2): restrict to
    // the `atext` set plus '.'. This rejects specials that are illegal
    // outside a quoted string — `< > , ; : ( ) [ ] \ "` — which the
    // printable-ASCII gate above would otherwise admit. Quoted local parts
    // (`"foo bar"@example.com`) are deliberately unsupported.
    if !local.bytes().all(|b| {
        b.is_ascii_alphanumeric()
            || matches!(
                b,
                b'!' | b'#'
                    | b'$'
                    | b'%'
                    | b'&'
                    | b'\''
                    | b'*'
                    | b'+'
                    | b'-'
                    | b'/'
                    | b'='
                    | b'?'
                    | b'^'
                    | b'_'
                    | b'`'
                    | b'{'
                    | b'|'
                    | b'}'
                    | b'~'
                    | b'.'
            )
    }) {
        return false;
    }

    // Domain: non-empty, must contain at least one dot.
    if domain.is_empty() || !domain.contains('.') {
        return false;
    }

    // No consecutive dots, no leading/trailing dots in either part.
    for part in [local, domain] {
        if part.starts_with('.') || part.ends_with('.') || part.contains("..") {
            return false;
        }
    }

    // Domain labels: split on dots, each must be non-empty and alphanumeric
    // with hyphens allowed (but not at start/end).
    for label in domain.split('.') {
        if label.is_empty() {
            return false;
        }
        if label.starts_with('-') || label.ends_with('-') {
            return false;
        }
        if !label
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-')
        {
            return false;
        }
    }

    true
}

// ---------------------------------------------------------------------------
// Password strength validation
// ---------------------------------------------------------------------------

/// Default set of special characters accepted for password complexity.
pub const DEFAULT_SPECIAL_CHARS: &str = "!@#$%^&*()_+-=[]{}|;:,.<>?";

/// Human-readable description of the default password rules.
pub const PASSWORD_RULES: &str = "must be at least 8 bytes, contain at least one \
     uppercase letter, one lowercase letter, one digit, and one special character";

/// Configuration for password strength validation rules.
///
/// Uses builder pattern with sensible defaults matching common security
/// policies.
// Each bool is an independent, user-facing policy toggle; collapsing them into
// a bitflag would hurt the builder API's readability.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PasswordRules {
    /// Minimum password length. Default: 8.
    min_length: usize,
    /// Require at least one uppercase ASCII letter. Default: true.
    require_uppercase: bool,
    /// Require at least one lowercase ASCII letter. Default: true.
    require_lowercase: bool,
    /// Require at least one ASCII digit. Default: true.
    require_digit: bool,
    /// Require at least one special character. Default: true.
    require_special: bool,
    /// The set of characters considered "special". Default: [`DEFAULT_SPECIAL_CHARS`].
    special_chars: &'static str,
}

impl Default for PasswordRules {
    fn default() -> Self {
        Self {
            min_length: 8,
            require_uppercase: true,
            require_lowercase: true,
            require_digit: true,
            require_special: true,
            special_chars: DEFAULT_SPECIAL_CHARS,
        }
    }
}

impl PasswordRules {
    /// Creates a new `PasswordRules` with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the minimum password length in bytes (not characters).
    ///
    /// Because the check uses `str::len()`, multi-byte UTF-8 characters
    /// count as more than one toward the minimum. For ASCII-only passwords
    /// the byte length equals the character count.
    #[must_use]
    pub fn with_min_length(mut self, min_length: usize) -> Self {
        self.min_length = min_length;
        self
    }

    /// Sets whether an uppercase letter is required.
    #[must_use]
    pub fn with_require_uppercase(mut self, required: bool) -> Self {
        self.require_uppercase = required;
        self
    }

    /// Sets whether a lowercase letter is required.
    #[must_use]
    pub fn with_require_lowercase(mut self, required: bool) -> Self {
        self.require_lowercase = required;
        self
    }

    /// Sets whether a digit is required.
    #[must_use]
    pub fn with_require_digit(mut self, required: bool) -> Self {
        self.require_digit = required;
        self
    }

    /// Sets whether a special character is required.
    #[must_use]
    pub fn with_require_special(mut self, required: bool) -> Self {
        self.require_special = required;
        self
    }

    /// Sets the special character set.
    #[must_use]
    pub fn with_special_chars(mut self, chars: &'static str) -> Self {
        self.special_chars = chars;
        self
    }

    /// Returns the minimum password length in bytes (not characters).
    #[must_use]
    #[inline]
    pub fn min_length(&self) -> usize {
        self.min_length
    }
}

/// Validates a password against the given rules.
///
/// Returns `Ok(())` if the password satisfies all rules.
///
/// # Errors
///
/// Returns `Err` with a list of human-readable descriptions of the unmet
/// rules when the password fails one or more checks.
///
/// # Security
///
/// This function never logs or includes the password in error output.
/// The returned error strings describe which *rules* are unmet, not
/// what the password contains.
pub fn validate_password_strength(
    password: &str,
    rules: &PasswordRules,
) -> Result<(), Vec<&'static str>> {
    let mut errors = Vec::new();

    if password.len() < rules.min_length {
        errors.push("must meet the minimum length requirement");
    }
    if rules.require_uppercase && !password.chars().any(|c| c.is_ascii_uppercase()) {
        errors.push("must contain at least one uppercase letter");
    }
    if rules.require_lowercase && !password.chars().any(|c| c.is_ascii_lowercase()) {
        errors.push("must contain at least one lowercase letter");
    }
    if rules.require_digit && !password.chars().any(|c| c.is_ascii_digit()) {
        errors.push("must contain at least one digit");
    }
    if rules.require_special && !password.chars().any(|c| rules.special_chars.contains(c)) {
        errors.push("must contain at least one special character");
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

// ===========================================================================
// Tests
// ===========================================================================

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

    // --- Name Validation ---

    #[test]
    fn name_empty() {
        assert!(!is_valid_name(""));
    }

    #[test]
    fn name_exceeds_max_length() {
        let long = "a".repeat(MAX_NAME_LEN + 1);
        assert!(!is_valid_name(&long));
    }

    #[test]
    fn name_max_length_accepted() {
        let name = "a".repeat(MAX_NAME_LEN);
        assert!(is_valid_name(&name));
    }

    #[test]
    fn name_starts_with_hyphen() {
        assert!(!is_valid_name("-myapp"));
    }

    #[test]
    fn name_starts_with_underscore() {
        assert!(!is_valid_name("_myapp"));
    }

    #[test]
    fn name_starts_with_period() {
        assert!(!is_valid_name(".hidden"));
    }

    #[test]
    fn name_contains_slash() {
        assert!(!is_valid_name("foo/bar"));
    }

    #[test]
    fn name_contains_backslash() {
        assert!(!is_valid_name("foo\\bar"));
    }

    #[test]
    fn name_contains_space() {
        assert!(!is_valid_name("foo bar"));
    }

    #[test]
    fn name_contains_null() {
        assert!(!is_valid_name("foo\0bar"));
    }

    #[test]
    fn name_contains_newline() {
        assert!(!is_valid_name("foo\nbar"));
    }

    #[test]
    fn name_contains_tab() {
        assert!(!is_valid_name("foo\tbar"));
    }

    #[test]
    fn name_consecutive_periods() {
        assert!(!is_valid_name("foo..bar"));
    }

    #[test]
    fn name_dot_dot() {
        assert!(!is_valid_name(".."));
    }

    #[test]
    fn name_single_dot() {
        assert!(!is_valid_name("."));
    }

    #[test]
    fn name_trailing_period() {
        assert!(!is_valid_name("app."));
    }

    #[test]
    fn name_shell_metacharacters() {
        assert!(!is_valid_name("git;echo"));
        assert!(!is_valid_name("git|cat"));
        assert!(!is_valid_name("$(cmd)"));
    }

    #[test]
    fn name_windows_reserved() {
        for name in ["CON", "con", "PRN", "AUX", "NUL", "COM1", "LPT1"] {
            assert!(!is_valid_name(name), "{name} should be rejected");
        }
    }

    #[test]
    fn name_windows_reserved_with_extension() {
        // "CON.txt" should still be rejected — the stem is "CON".
        assert!(!is_valid_name("CON.txt"));
        assert!(!is_valid_name("nul.log"));
    }

    #[test]
    fn name_simple() {
        assert!(is_valid_name("my_app"));
    }

    #[test]
    fn name_with_hyphens() {
        assert!(is_valid_name("cargo-deny"));
    }

    #[test]
    fn name_with_periods() {
        assert!(is_valid_name("app.v2.1"));
    }

    #[test]
    fn name_with_mixed_characters() {
        assert!(is_valid_name("my-app_v2.1"));
    }

    #[test]
    fn name_single_character() {
        assert!(is_valid_name("a"));
    }

    #[test]
    fn name_numeric_start() {
        assert!(is_valid_name("7zip"));
    }

    // --- Username Validation ---

    #[test]
    fn username_empty() {
        assert!(!is_valid_username(""));
    }

    #[test]
    fn username_exceeds_max_length() {
        let long = "a".repeat(MAX_USERNAME_LEN + 1);
        assert!(!is_valid_username(&long));
    }

    #[test]
    fn username_max_length_accepted() {
        let name = "a".repeat(MAX_USERNAME_LEN);
        assert!(is_valid_username(&name));
    }

    #[test]
    fn username_simple() {
        assert!(is_valid_username("alice"));
    }

    #[test]
    fn username_with_at_sign() {
        assert!(is_valid_username("alice@example.com"));
    }

    #[test]
    fn username_with_all_special_chars() {
        assert!(is_valid_username("a.b-c_d@e"));
    }

    #[test]
    fn username_numeric_start() {
        assert!(is_valid_username("42user"));
    }

    #[test]
    fn username_single_character() {
        assert!(is_valid_username("a"));
    }

    #[test]
    fn username_starts_with_hyphen() {
        assert!(!is_valid_username("-alice"));
    }

    #[test]
    fn username_starts_with_period() {
        assert!(!is_valid_username(".alice"));
    }

    #[test]
    fn username_starts_with_underscore() {
        assert!(!is_valid_username("_alice"));
    }

    #[test]
    fn username_starts_with_at() {
        assert!(!is_valid_username("@alice"));
    }

    #[test]
    fn username_consecutive_specials() {
        assert!(!is_valid_username("alice..bob"));
        assert!(!is_valid_username("alice.-bob"));
        assert!(!is_valid_username("alice._bob"));
        assert!(!is_valid_username("alice@-bob"));
        assert!(!is_valid_username("alice-.bob"));
    }

    #[test]
    fn username_contains_space() {
        assert!(!is_valid_username("alice bob"));
    }

    #[test]
    fn username_contains_null() {
        assert!(!is_valid_username("alice\0bob"));
    }

    #[test]
    fn username_contains_slash() {
        assert!(!is_valid_username("alice/bob"));
    }

    #[test]
    fn username_contains_hash() {
        assert!(!is_valid_username("alice#1"));
    }

    #[test]
    fn username_trailing_special_allowed() {
        // Trailing special is allowed (only consecutive specials are rejected).
        // e.g. an email ending in a domain is fine.
        assert!(is_valid_username("alice@example.com"));
    }

    // --- Redirect URI Validation ---

    #[test]
    fn redirect_uri_empty() {
        assert!(!is_valid_redirect_uri(""));
    }

    #[test]
    fn redirect_uri_exceeds_max_length() {
        let long = format!("https://example.com/{}", "a".repeat(MAX_REDIRECT_URI_LEN));
        assert!(!is_valid_redirect_uri(&long));
    }

    #[test]
    fn redirect_uri_max_length_accepted() {
        let padding = "a".repeat(MAX_REDIRECT_URI_LEN - "https://x.co/".len());
        let uri = format!("https://x.co/{padding}");
        assert_eq!(uri.len(), MAX_REDIRECT_URI_LEN);
        assert!(is_valid_redirect_uri(&uri));
    }

    #[test]
    fn redirect_uri_https() {
        assert!(is_valid_redirect_uri("https://example.com/callback"));
    }

    #[test]
    fn redirect_uri_https_with_port() {
        assert!(is_valid_redirect_uri("https://example.com:8443/callback"));
    }

    #[test]
    fn redirect_uri_https_with_query() {
        assert!(is_valid_redirect_uri("https://example.com/cb?state=abc"));
    }

    #[test]
    fn redirect_uri_http_localhost() {
        assert!(is_valid_redirect_uri("http://localhost/callback"));
    }

    #[test]
    fn redirect_uri_http_localhost_with_port() {
        assert!(is_valid_redirect_uri("http://localhost:8080/callback"));
    }

    #[test]
    fn redirect_uri_http_localhost_bare() {
        assert!(is_valid_redirect_uri("http://localhost"));
    }

    #[test]
    fn redirect_uri_http_127_0_0_1() {
        assert!(is_valid_redirect_uri("http://127.0.0.1/callback"));
    }

    #[test]
    fn redirect_uri_http_127_0_0_1_with_port() {
        assert!(is_valid_redirect_uri("http://127.0.0.1:3000"));
    }

    #[test]
    fn redirect_uri_http_non_loopback_rejected() {
        assert!(!is_valid_redirect_uri("http://example.com/callback"));
    }

    #[test]
    fn redirect_uri_http_localhost_like_rejected() {
        // "localhostevil.com" should not match the loopback exception.
        assert!(!is_valid_redirect_uri("http://localhostevil.com/callback"));
    }

    #[test]
    fn redirect_uri_http_127_0_0_1_like_rejected() {
        // "127.0.0.1evil.com" should not match the loopback exception.
        assert!(!is_valid_redirect_uri("http://127.0.0.1evil.com"));
    }

    #[test]
    fn redirect_uri_http_ipv6_loopback() {
        assert!(is_valid_redirect_uri("http://[::1]/callback"));
    }

    #[test]
    fn redirect_uri_http_ipv6_loopback_with_port() {
        assert!(is_valid_redirect_uri("http://[::1]:8080/callback"));
    }

    #[test]
    fn redirect_uri_fragment_rejected() {
        assert!(!is_valid_redirect_uri("https://example.com/cb#frag"));
    }

    #[test]
    fn redirect_uri_null_byte_rejected() {
        assert!(!is_valid_redirect_uri("https://example.com/\0"));
    }

    #[test]
    fn redirect_uri_plain_http_rejected() {
        assert!(!is_valid_redirect_uri("http://remote-host.com/callback"));
    }

    #[test]
    fn redirect_uri_ftp_rejected() {
        assert!(!is_valid_redirect_uri("ftp://example.com/callback"));
    }

    #[test]
    fn redirect_uri_no_scheme() {
        assert!(!is_valid_redirect_uri("example.com/callback"));
    }

    #[test]
    fn redirect_uri_localhost_with_query() {
        assert!(is_valid_redirect_uri("http://localhost?code=abc"));
    }

    // --- Scope Validation ---

    #[test]
    fn scope_empty() {
        assert!(!is_valid_scope(""));
    }

    #[test]
    fn scope_exceeds_max_length() {
        let long = "a".repeat(MAX_SCOPE_LEN + 1);
        assert!(!is_valid_scope(&long));
    }

    #[test]
    fn scope_max_length_accepted() {
        let s = "a".repeat(MAX_SCOPE_LEN);
        assert!(is_valid_scope(&s));
    }

    #[test]
    fn scope_single_token() {
        assert!(is_valid_scope("openid"));
    }

    #[test]
    fn scope_multiple_tokens() {
        assert!(is_valid_scope("openid profile email"));
    }

    #[test]
    fn scope_with_special_nqchar() {
        // 0x21 is '!', 0x23 is '#', 0x7E is '~'
        assert!(is_valid_scope("read!write"));
        assert!(is_valid_scope("scope#1"));
        assert!(is_valid_scope("a~b"));
    }

    #[test]
    fn scope_leading_space_rejected() {
        assert!(!is_valid_scope(" openid"));
    }

    #[test]
    fn scope_trailing_space_rejected() {
        assert!(!is_valid_scope("openid "));
    }

    #[test]
    fn scope_consecutive_spaces_rejected() {
        assert!(!is_valid_scope("openid  profile"));
    }

    #[test]
    fn scope_double_quote_rejected() {
        // 0x22 is `"` — excluded from NQCHAR.
        assert!(!is_valid_scope("open\"id"));
    }

    #[test]
    fn scope_backslash_rejected() {
        // 0x5C is `\` — excluded from NQCHAR.
        assert!(!is_valid_scope("open\\id"));
    }

    #[test]
    fn scope_control_char_rejected() {
        assert!(!is_valid_scope("open\x01id"));
    }

    #[test]
    fn scope_null_byte_rejected() {
        assert!(!is_valid_scope("open\x00id"));
    }

    #[test]
    fn scope_non_ascii_rejected() {
        assert!(!is_valid_scope("öpenid"));
    }

    #[test]
    fn scope_space_only_rejected() {
        assert!(!is_valid_scope(" "));
    }

    #[test]
    fn scope_nqchar_boundary_0x21() {
        // 0x21 ('!') is the lowest valid NQCHAR.
        assert!(is_valid_scope("!"));
    }

    #[test]
    fn scope_nqchar_boundary_0x20_rejected() {
        // 0x20 is space — only valid as a token delimiter, not within a token.
        // A single space produces two empty tokens, which fails.
        assert!(!is_valid_scope(" "));
    }

    #[test]
    fn scope_nqchar_boundary_0x7e() {
        // 0x7E ('~') is the highest valid NQCHAR.
        assert!(is_valid_scope("~"));
    }

    #[test]
    fn scope_nqchar_boundary_0x7f_rejected() {
        // 0x7F is DEL — not valid NQCHAR.
        assert!(!is_valid_scope("\x7F"));
    }

    // --- Client ID Validation ---

    #[test]
    fn client_id_empty() {
        assert!(!is_valid_client_id(""));
    }

    #[test]
    fn client_id_exceeds_max_length() {
        let long = "a".repeat(MAX_CLIENT_ID_LEN + 1);
        assert!(!is_valid_client_id(&long));
    }

    #[test]
    fn client_id_max_length_accepted() {
        let id = "a".repeat(MAX_CLIENT_ID_LEN);
        assert!(is_valid_client_id(&id));
    }

    #[test]
    fn client_id_simple() {
        assert!(is_valid_client_id("my-client-123"));
    }

    #[test]
    fn client_id_uuid() {
        assert!(is_valid_client_id("550e8400-e29b-41d4-a716-446655440000"));
    }

    #[test]
    fn client_id_with_spaces() {
        // Spaces (0x20) are printable ASCII and allowed.
        assert!(is_valid_client_id("my client"));
    }

    #[test]
    fn client_id_all_printable_ascii() {
        // Every printable ASCII character from 0x20 to 0x7E.
        let all_printable: String = (0x20u8..=0x7Eu8).map(|b| b as char).collect();
        assert!(is_valid_client_id(&all_printable));
    }

    #[test]
    fn client_id_null_byte_rejected() {
        assert!(!is_valid_client_id("client\0id"));
    }

    #[test]
    fn client_id_control_char_rejected() {
        assert!(!is_valid_client_id("client\x01id"));
        assert!(!is_valid_client_id("client\nid"));
        assert!(!is_valid_client_id("client\tid"));
    }

    #[test]
    fn client_id_del_rejected() {
        // 0x7F (DEL) is not printable ASCII.
        assert!(!is_valid_client_id("client\x7Fid"));
    }

    #[test]
    fn client_id_non_ascii_rejected() {
        assert!(!is_valid_client_id("clïent"));
    }

    #[test]
    fn client_id_single_char() {
        assert!(is_valid_client_id("x"));
    }

    #[test]
    fn client_id_single_space() {
        assert!(is_valid_client_id(" "));
    }

    // --- HTTPS URL Validation ---

    #[test]
    fn https_url_valid() {
        assert!(is_https_url("https://example.com"));
        assert!(is_https_url("https://example.com/path?query=1"));
    }

    #[test]
    fn https_url_rejects_http() {
        assert!(!is_https_url("http://example.com"));
    }

    #[test]
    fn https_url_rejects_empty() {
        assert!(!is_https_url(""));
    }

    #[test]
    fn https_url_rejects_no_scheme() {
        assert!(!is_https_url("example.com"));
    }

    // --- Email Validation ---

    #[test]
    fn email_valid_simple() {
        assert!(is_valid_email("user@example.com"));
    }

    #[test]
    fn email_valid_with_subdomain() {
        assert!(is_valid_email("user@mail.example.com"));
    }

    #[test]
    fn email_valid_with_plus() {
        assert!(is_valid_email("user+tag@example.com"));
    }

    #[test]
    fn email_valid_with_dots_in_local() {
        assert!(is_valid_email("first.last@example.com"));
    }

    #[test]
    fn email_empty() {
        assert!(!is_valid_email(""));
    }

    #[test]
    fn email_no_at() {
        assert!(!is_valid_email("userexample.com"));
    }

    #[test]
    fn email_double_at() {
        assert!(!is_valid_email("user@@example.com"));
    }

    #[test]
    fn email_no_domain() {
        assert!(!is_valid_email("user@"));
    }

    #[test]
    fn email_no_local() {
        assert!(!is_valid_email("@example.com"));
    }

    #[test]
    fn email_no_tld_dot() {
        assert!(!is_valid_email("user@localhost"));
    }

    #[test]
    fn email_consecutive_dots_local() {
        assert!(!is_valid_email("user..name@example.com"));
    }

    #[test]
    fn email_consecutive_dots_domain() {
        assert!(!is_valid_email("user@example..com"));
    }

    #[test]
    fn email_leading_dot_local() {
        assert!(!is_valid_email(".user@example.com"));
    }

    #[test]
    fn email_trailing_dot_local() {
        assert!(!is_valid_email("user.@example.com"));
    }

    #[test]
    fn email_leading_dot_domain() {
        assert!(!is_valid_email("user@.example.com"));
    }

    #[test]
    fn email_domain_label_leading_hyphen() {
        assert!(!is_valid_email("user@-example.com"));
    }

    #[test]
    fn email_domain_label_trailing_hyphen() {
        assert!(!is_valid_email("user@example-.com"));
    }

    #[test]
    fn email_with_space() {
        assert!(!is_valid_email("user @example.com"));
    }

    #[test]
    fn email_with_null() {
        assert!(!is_valid_email("user\0@example.com"));
    }

    #[test]
    fn email_exceeds_max_length() {
        let local = "a".repeat(64);
        let domain = format!("{}.com", "b".repeat(MAX_EMAIL_LEN));
        let email = format!("{local}@{domain}");
        assert!(!is_valid_email(&email));
    }

    #[test]
    fn email_local_exceeds_64_bytes() {
        let local = "a".repeat(65);
        let email = format!("{local}@example.com");
        assert!(!is_valid_email(&email));
    }

    #[test]
    fn email_non_ascii_rejected() {
        assert!(!is_valid_email("üser@example.com"));
    }

    // --- Password Strength Validation ---

    #[test]
    fn password_strength_valid() {
        let rules = PasswordRules::default();
        assert!(validate_password_strength("MyP@ssw0rd", &rules).is_ok());
    }

    #[test]
    fn password_strength_too_short() {
        let rules = PasswordRules::default();
        let errors = validate_password_strength("Ab1!", &rules).unwrap_err();
        assert!(errors.iter().any(|e| e.contains("minimum length")));
    }

    #[test]
    fn password_strength_no_uppercase() {
        let rules = PasswordRules::default();
        let errors = validate_password_strength("myp@ssw0rd", &rules).unwrap_err();
        assert!(errors.iter().any(|e| e.contains("uppercase")));
    }

    #[test]
    fn password_strength_no_lowercase() {
        let rules = PasswordRules::default();
        let errors = validate_password_strength("MYP@SSW0RD", &rules).unwrap_err();
        assert!(errors.iter().any(|e| e.contains("lowercase")));
    }

    #[test]
    fn password_strength_no_digit() {
        let rules = PasswordRules::default();
        let errors = validate_password_strength("MyP@ssword", &rules).unwrap_err();
        assert!(errors.iter().any(|e| e.contains("digit")));
    }

    #[test]
    fn password_strength_no_special() {
        let rules = PasswordRules::default();
        let errors = validate_password_strength("MyPassw0rd", &rules).unwrap_err();
        assert!(errors.iter().any(|e| e.contains("special")));
    }

    #[test]
    fn password_strength_multiple_failures() {
        let rules = PasswordRules::default();
        let errors = validate_password_strength("short", &rules).unwrap_err();
        assert!(errors.len() >= 3);
    }

    #[test]
    fn password_strength_custom_min_length() {
        let rules = PasswordRules::new().with_min_length(12);
        let errors = validate_password_strength("MyP@ssw0rd", &rules).unwrap_err();
        assert!(errors.iter().any(|e| e.contains("minimum length")));
    }

    #[test]
    fn password_strength_relaxed_rules() {
        let rules = PasswordRules::new()
            .with_require_uppercase(false)
            .with_require_special(false);
        assert!(validate_password_strength("password1", &rules).is_ok());
    }

    #[test]
    fn password_rules_builder() {
        let rules = PasswordRules::new().with_min_length(16);
        assert_eq!(rules.min_length(), 16);
    }
}