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
//! UTC timestamp with epoch-seconds tracking for auth token operations.
//!
//! Provides a [`Timestamp`] type that captures the current UTC time and
//! formats it as `YYYY-MM-DD HH:MM:SS` without heap allocation. Uses the
//! Hinnant civil-date algorithm to convert Unix epoch days to calendar
//! dates, avoiding a dependency on a datetime library.
//!
//! This module is adapted from `entropy-logging`'s `timestamp.rs` and
//! extended for auth use cases: the struct stores raw epoch seconds for
//! O(1) token-expiry comparisons, implements `Ord` over that value, and
//! exposes [`Timestamp::from_unix_secs`] for reconstructing timestamps
//! from serialised token claims.
//!
//! # Examples
//!
//! ```
//! use entropy_auth::Timestamp;
//!
//! // Reconstruct an expiry from a token claim and check it.
//! let exp = Timestamp::from_unix_secs(1_700_000_000);
//! let now = Timestamp::from_unix_secs(1_700_000_500);
//! assert!(exp.is_expired(&now));
//! assert_eq!(exp.to_iso8601(), "2023-11-14T22:13:20Z");
//! ```

use std::cmp::Ordering;
use std::fmt;
use std::time::SystemTime;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// UTC timestamp that renders as `YYYY-MM-DD HH:MM:SS` without heap
/// allocation. Implements [`fmt::Display`] so it can be embedded directly
/// in `format_args!` / `write!` calls.
///
/// Stores the raw epoch seconds alongside calendar fields so that
/// [`unix_epoch_secs`](Timestamp::unix_epoch_secs) is O(1) and ordering
/// comparisons avoid re-deriving the scalar value.
///
/// Uses `u32` for calendar fields — sufficient for calendar values and
/// reduces struct size compared to `u64`. Year will not overflow `u32`
/// for any post-epoch `SystemTime` value.
#[doc(alias = "time")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timestamp {
    total_secs: u64,
    year: u32,
    month: u32,
    day: u32,
    hours: u32,
    minutes: u32,
    seconds: u32,
}

impl PartialOrd for Timestamp {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Timestamp {
    fn cmp(&self, other: &Self) -> Ordering {
        self.total_secs.cmp(&other.total_secs)
    }
}

impl Timestamp {
    /// Constructs a `Timestamp` with explicit field values.
    ///
    /// Only available in test builds. Allows tests to verify `Display`
    /// formatting with known values without depending on the wall clock.
    #[cfg(test)]
    fn new(year: u32, month: u32, day: u32, hours: u32, minutes: u32, seconds: u32) -> Self {
        // `total_secs` is computed from the calendar fields so that `Ord`
        // (which compares `total_secs`) stays consistent with the derived
        // `PartialEq`/`Eq` (which compare every field). The fields are then
        // recovered via `from_unix_secs` to guarantee an exact round-trip.
        let days = days_from_civil(u64::from(year), u64::from(month), u64::from(day));
        let total_secs =
            days * 86_400 + u64::from(hours) * 3600 + u64::from(minutes) * 60 + u64::from(seconds);
        let ts = Self::from_unix_secs(total_secs);
        debug_assert_eq!(
            (ts.year, ts.month, ts.day, ts.hours, ts.minutes, ts.seconds),
            (year, month, day, hours, minutes, seconds),
            "Timestamp::new called with fields that do not round-trip through epoch seconds"
        );
        ts
    }

    /// Captures the current UTC time.
    ///
    /// If the system clock is before the Unix epoch (theoretically possible
    /// on misconfigured systems or certain embedded platforms), the duration
    /// falls back to zero, producing `1970-01-01 00:00:00`. This is
    /// intentional — timestamps are best-effort diagnostics and must never
    /// panic or propagate errors.
    #[must_use]
    #[inline]
    pub fn now() -> Self {
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default();
        Self::from_unix_secs(now.as_secs())
    }

    /// Constructs a `Timestamp` from raw Unix epoch seconds.
    ///
    /// Needed for parsing token expiry claims where the timestamp is stored
    /// as a `u64` seconds-since-epoch value.
    ///
    /// # Examples
    ///
    /// ```
    /// use entropy_auth::Timestamp;
    ///
    /// let ts = Timestamp::from_unix_secs(0);
    /// assert_eq!(ts.to_iso8601(), "1970-01-01T00:00:00Z");
    /// assert_eq!(ts.unix_epoch_secs(), 0);
    /// ```
    #[must_use]
    #[inline]
    pub fn from_unix_secs(secs: u64) -> Self {
        let days = secs / 86_400;
        let day_secs = secs % 86_400;
        let (year, month, day) = civil_from_days(days);

        // Time-of-day truncations are safe: hours <= 23, minutes/seconds <= 59.
        #[allow(clippy::cast_possible_truncation)]
        Self {
            total_secs: secs,
            year,
            month,
            day,
            hours: (day_secs / 3600) as u32,
            minutes: ((day_secs % 3600) / 60) as u32,
            seconds: (day_secs % 60) as u32,
        }
    }

    /// Returns the raw Unix epoch seconds stored at construction time.
    ///
    /// This is O(1) — the value is stored directly in the struct rather
    /// than recomputed from calendar fields.
    #[must_use]
    #[inline]
    pub fn unix_epoch_secs(&self) -> u64 {
        self.total_secs
    }

    /// Returns `true` if `self` represents an earlier moment than `other`.
    #[must_use]
    #[inline]
    pub fn is_before(&self, other: &Timestamp) -> bool {
        self.total_secs < other.total_secs
    }
    // NOTE: serde is implemented manually below as a single epoch-seconds
    // scalar (not the seven calendar fields), so persisted timestamps are
    // compact and reconstruct identically via `from_unix_secs`.

    /// Returns `true` if this timestamp is in the past relative to `now`.
    ///
    /// Convenience wrapper for `self < now`, intended for token-expiry
    /// checks where `self` is the expiry time and `now` is the current
    /// wall-clock time.
    // NOTE: A timestamp exactly equal to `now` is considered expired.
    // This matches the convention that a token valid "until T" is no
    // longer valid at T itself.
    #[must_use]
    #[inline]
    pub fn is_expired(&self, now: &Timestamp) -> bool {
        self.total_secs <= now.total_secs
    }

    /// Returns the calendar year (e.g. `2026`).
    #[must_use]
    #[inline]
    pub fn year(&self) -> u32 {
        self.year
    }

    /// Returns the calendar month (`1..=12`).
    #[must_use]
    #[inline]
    pub fn month(&self) -> u32 {
        self.month
    }

    /// Returns the calendar day of the month (`1..=31`).
    #[must_use]
    #[inline]
    pub fn day(&self) -> u32 {
        self.day
    }

    /// Returns the hour of the day (`0..=23`).
    #[must_use]
    #[inline]
    pub fn hour(&self) -> u32 {
        self.hours
    }

    /// Returns the minute of the hour (`0..=59`).
    #[must_use]
    #[inline]
    pub fn minute(&self) -> u32 {
        self.minutes
    }

    /// Returns the second of the minute (`0..=59`).
    #[must_use]
    #[inline]
    pub fn second(&self) -> u32 {
        self.seconds
    }

    /// Returns the hour of the day (`0..=23`).
    #[deprecated(note = "renamed to `hour()` for consistency with `year()`/`month()`/`day()`")]
    #[must_use]
    #[inline]
    pub fn hours(&self) -> u32 {
        self.hours
    }

    /// Returns the minute of the hour (`0..=59`).
    #[deprecated(note = "renamed to `minute()` for consistency")]
    #[must_use]
    #[inline]
    pub fn minutes(&self) -> u32 {
        self.minutes
    }

    /// Returns the second of the minute (`0..=59`).
    #[deprecated(note = "renamed to `second()` for consistency")]
    #[must_use]
    #[inline]
    pub fn seconds(&self) -> u32 {
        self.seconds
    }

    /// Parses an ISO 8601 UTC timestamp (`YYYY-MM-DDTHH:MM:SSZ`) into a
    /// `Timestamp`.
    ///
    /// Returns `None` if the string is not in the expected format. The `Z`
    /// (UTC) designator and numeric offsets (`+HH:MM` / `-HH:MM`) are both
    /// accepted; an offset is normalized to UTC. An optional fractional-second
    /// part (`.fff…`) is accepted and truncated to whole seconds, since SAML
    /// `xsd:dateTime` attributes commonly carry sub-second precision.
    ///
    /// # Examples
    ///
    /// ```
    /// use entropy_auth::Timestamp;
    ///
    /// let ts = Timestamp::parse_iso8601("2023-11-14T22:13:20Z").unwrap();
    /// assert_eq!(ts.unix_epoch_secs(), 1_700_000_000);
    ///
    /// // Fractional seconds are accepted and truncated.
    /// let ts = Timestamp::parse_iso8601("2023-11-14T22:13:20.123456Z").unwrap();
    /// assert_eq!(ts.unix_epoch_secs(), 1_700_000_000);
    ///
    /// // Numeric offsets are normalized to UTC (23:13:20+01:00 == 22:13:20Z).
    /// let ts = Timestamp::parse_iso8601("2023-11-14T23:13:20+01:00").unwrap();
    /// assert_eq!(ts.unix_epoch_secs(), 1_700_000_000);
    ///
    /// // Pre-1970 instants (after offset normalization) are rejected.
    /// assert!(Timestamp::parse_iso8601("1969-01-01T00:00:00Z").is_none());
    /// ```
    #[must_use]
    pub fn parse_iso8601(s: &str) -> Option<Self> {
        // Expected: "YYYY-MM-DDTHH:MM:SS" (19 chars) optionally followed by
        // a fractional-second part (".fff…") and a mandatory trailing "Z".
        // Fractional seconds are accepted but truncated to whole seconds:
        // SAML `xsd:dateTime` attributes from real identity providers
        // (ADFS, Azure AD, Shibboleth) routinely carry them, and rejecting
        // them would fail otherwise-valid assertions. Timezone offsets
        // other than `Z` are still rejected (the value must be UTC).
        if !s.is_ascii() {
            return None;
        }
        // SECURITY: bound the input before scanning. A well-formed timestamp is
        // at most ~32 chars (date + time + fractional seconds + offset); the
        // value can come from an attacker-controlled SAML attribute bounded
        // only by `MAX_XML_SIZE`, so cap it to avoid scanning a multi-megabyte
        // "fractional" string per call.
        if s.len() > 64 {
            return None;
        }
        // Timezone designator: either `Z` (UTC) or a numeric offset
        // `+HH:MM` / `-HH:MM` (xsd:dateTime). The offset is applied to
        // normalize to UTC. SAML recommends `Z`, but real IdPs (e.g. ADFS)
        // emit offsets, so accepting and converting them avoids rejecting
        // otherwise-valid assertions.
        let (core, offset_secs): (&str, i64) = if let Some(c) = s.strip_suffix('Z') {
            (c, 0)
        } else if s.len() >= 6 {
            let (head, tz) = s.split_at(s.len() - 6);
            let tz = tz.as_bytes();
            let sign: i64 = match tz[0] {
                b'+' => 1,
                b'-' => -1,
                _ => return None,
            };
            if tz[3] != b':' {
                return None;
            }
            let oh: i64 = core::str::from_utf8(&tz[1..3]).ok()?.parse().ok()?;
            let om: i64 = core::str::from_utf8(&tz[4..6]).ok()?.parse().ok()?;
            if oh > 23 || om > 59 {
                return None;
            }
            (head, sign * (oh * 3600 + om * 60))
        } else {
            return None;
        };
        if core.len() < 19 {
            return None;
        }
        let (datetime, frac) = core.split_at(19);
        // A fractional part, when present, must be `.` followed by at least
        // one digit and nothing else. The value itself is discarded.
        if !frac.is_empty() {
            let digits = frac.strip_prefix('.')?;
            if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
                return None;
            }
        }
        let b = datetime.as_bytes();
        if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
            return None;
        }
        // `str::parse::<u64>` accepts a leading `+`, so non-canonical
        // spellings like `2025-+1-01T00:00:00Z` parsed to a real instant. An
        // xsd:dateTime field is fixed-width digits; require that before parsing
        // so two different strings cannot denote the same timestamp.
        if !b[..19]
            .iter()
            .enumerate()
            .all(|(i, c)| matches!(i, 4 | 7 | 10 | 13 | 16) || c.is_ascii_digit())
        {
            return None;
        }
        let year: u64 = datetime[0..4].parse().ok()?;
        let month: u64 = datetime[5..7].parse().ok()?;
        let day: u64 = datetime[8..10].parse().ok()?;
        let hour: u64 = datetime[11..13].parse().ok()?;
        let minute: u64 = datetime[14..16].parse().ok()?;
        let second: u64 = datetime[17..19].parse().ok()?;

        // Basic validation. The epoch-seconds representation is `u64`, so
        // pre-1970 dates are not representable; reject them rather than
        // underflowing the `days_from_civil` conversion below.
        if year < 1970
            || !(1..=12).contains(&month)
            || !(1..=31).contains(&day)
            || hour > 23
            || minute > 59
            || second > 59
        {
            return None;
        }

        // Validate day-of-month against the specific month.
        let max_day = match month {
            2 => {
                // Leap year: divisible by 4, except centuries unless divisible by 400.
                let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
                if leap { 29 } else { 28 }
            }
            4 | 6 | 9 | 11 => 30,
            _ => 31,
        };
        if day > max_day {
            return None;
        }

        let days = days_from_civil(year, month, day);
        let local_secs = days * 86_400 + hour * 3600 + minute * 60 + second;
        // Normalize the wall-clock value to UTC by subtracting the offset
        // (an instant `10:00+01:00` is `09:00Z`). A result before the Unix
        // epoch is not representable and is rejected.
        let utc_secs = i64::try_from(local_secs).ok()? - offset_secs;
        if utc_secs < 0 {
            return None;
        }
        Some(Self::from_unix_secs(utc_secs.unsigned_abs()))
    }

    /// Formats the timestamp as an ISO 8601 UTC string (`YYYY-MM-DDTHH:MM:SSZ`).
    ///
    /// This format is used by SAML assertions and other XML-based protocols.
    /// The returned string sorts lexicographically for any pair of UTC
    /// timestamps, enabling direct string comparison.
    ///
    /// # Examples
    ///
    /// ```
    /// use entropy_auth::Timestamp;
    ///
    /// let ts = Timestamp::from_unix_secs(1_700_000_000);
    /// assert_eq!(ts.to_iso8601(), "2023-11-14T22:13:20Z");
    /// ```
    #[must_use]
    pub fn to_iso8601(&self) -> String {
        format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
            self.year, self.month, self.day, self.hours, self.minutes, self.seconds,
        )
    }
}

impl Serialize for Timestamp {
    /// Serialized as a single Unix epoch-seconds scalar.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u64(self.total_secs)
    }
}

impl<'de> Deserialize<'de> for Timestamp {
    /// Reconstructed from the epoch-seconds scalar via [`Timestamp::from_unix_secs`].
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let secs = u64::deserialize(deserializer)?;
        Ok(Self::from_unix_secs(secs))
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
            self.year, self.month, self.day, self.hours, self.minutes, self.seconds,
        )
    }
}

/// Converts a day count since Unix epoch to a `(year, month, day)` triple.
///
/// Returns `u32` values directly — sufficient for any realistic calendar
/// date. Year will not overflow `u32` for any post-epoch `SystemTime`.
///
/// Algorithm by Howard Hinnant, public domain. The original algorithm uses
/// signed arithmetic; we convert to `i64` internally and truncate to `u32`
/// for the return value. Only post-epoch timestamps (1970-01-01 and later)
/// are supported — the `u64` input enforces this at the type level, and
/// debug assertions guard against any future misuse.
///
/// This function is `const` — it performs only integer arithmetic with no
/// heap allocation, I/O, or floating-point operations. The `const`
/// qualifier signals purity to both the compiler and human readers,
/// though in practice the function is always called with runtime values
/// from `SystemTime::now()`.
///
/// # Cast safety
///
/// The input `days` is derived from `SystemTime::now()` via
/// `duration.as_secs() / 86_400`. The maximum `u64` seconds value divided
/// by 86,400 yields approximately 213 billion days, which fits comfortably
/// within `i64::MAX` (approximately 9.2 quintillion). The `u64 → i64` cast
/// is therefore safe for any value produced by `SystemTime`.
///
/// <http://howardhinnant.github.io/date_algorithms.html#civil_from_days>
const fn civil_from_days(days: u64) -> (u32, u32, u32) {
    // The Hinnant algorithm is defined over signed integers.
    #[allow(clippy::cast_possible_wrap)]
    let z = days as i64 + 719_468;
    let era = z / 146_097;
    let doe = z - era * 146_097; // day of era
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // day of year
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    // `debug_assert!` compiles away in release builds, avoiding four
    // comparisons on every log call. Plain `assert!` would remain as
    // runtime checks even in release. The conditions here are only
    // violated for inputs outside the supported post-epoch range, which
    // the `u64` parameter type prevents.
    debug_assert!(
        y >= 0,
        "civil_from_days: negative year from post-epoch input"
    );
    debug_assert!(y <= u32::MAX as i64, "civil_from_days: year overflows u32");
    debug_assert!(m >= 1 && m <= 12, "civil_from_days: month out of range");
    debug_assert!(d >= 1 && d <= 31, "civil_from_days: day out of range");

    // Truncations are safe: year, month (1–12), and day (1–31) all fit
    // in u32 for any post-epoch timestamp.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    (y as u32, m as u32, d as u32)
}

/// Converts a proleptic-Gregorian civil date to days since the Unix epoch
/// (the inverse of [`civil_from_days`], per the Hinnant algorithm).
///
/// Caller MUST pass a post-epoch date (`year >= 1970`) with `month` in
/// `1..=12` and `day` valid for that month; otherwise the `- 719_468`
/// term underflows. Both call sites enforce this before calling.
const fn days_from_civil(year: u64, month: u64, day: u64) -> u64 {
    // Shift March-based month so that the leap day falls at the end of the
    // adjusted year.
    let y = if month <= 2 { year - 1 } else { year };
    let era = y / 400;
    let yoe = y - era * 400;
    let m_adj = if month > 2 { month - 3 } else { month + 9 };
    let doy = (153 * m_adj + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

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

    // --- Civil Date Algorithm ---
    //
    // Validates the Hinnant civil date algorithm against well-known
    // calendar dates spanning decades and edge cases (leap years,
    // century boundaries, year transitions).

    #[test]
    fn civil_from_days_unix_epoch() {
        // Day 0 = 1970-01-01
        assert_eq!(civil_from_days(0), (1970, 1, 1));
    }

    #[test]
    fn civil_from_days_day_one() {
        assert_eq!(civil_from_days(1), (1970, 1, 2));
    }

    #[test]
    fn civil_from_days_end_of_1970() {
        // 1970-12-31 is day 364
        assert_eq!(civil_from_days(364), (1970, 12, 31));
    }

    #[test]
    fn civil_from_days_start_of_1971() {
        assert_eq!(civil_from_days(365), (1971, 1, 1));
    }

    #[test]
    fn civil_from_days_leap_day_2000() {
        // 2000-02-29: days from epoch = 11016
        assert_eq!(civil_from_days(11016), (2000, 2, 29));
    }

    #[test]
    fn civil_from_days_y2k() {
        // 2000-01-01: days from epoch = 10957
        assert_eq!(civil_from_days(10957), (2000, 1, 1));
    }

    #[test]
    fn civil_from_days_2024_leap_day() {
        // 2024-02-29: days from epoch = 19782
        assert_eq!(civil_from_days(19782), (2024, 2, 29));
    }

    #[test]
    fn civil_from_days_2025_01_01() {
        // 2025-01-01: days from epoch = 20089
        assert_eq!(civil_from_days(20089), (2025, 1, 1));
    }

    #[test]
    fn civil_from_days_2026_02_21() {
        // 2026-02-21: days from epoch = 20505
        assert_eq!(civil_from_days(20505), (2026, 2, 21));
    }

    #[test]
    fn civil_from_days_non_leap_century_1900_feb() {
        // 1900 was NOT a leap year (century rule).
        // 1900-03-01 = day -25508 from epoch, but we only handle
        // post-epoch. Verify 2100-03-01 instead (2100 is not a leap year).
        // 2100-03-01: days from epoch = 47541
        assert_eq!(civil_from_days(47541), (2100, 3, 1));
    }

    #[test]
    fn civil_from_days_millennium_boundary() {
        // 1999-12-31: days from epoch = 10956
        assert_eq!(civil_from_days(10956), (1999, 12, 31));
    }

    #[test]
    fn civil_from_days_round_trip_consistency() {
        // Verify a range of dates produce monotonically increasing
        // (year, month, day) values and day-of-month stays in [1, 31].
        let mut prev = civil_from_days(0);
        for day in 1..=25_000_u64 {
            let (y, m, d) = civil_from_days(day);
            assert!((1..=12).contains(&m), "month out of range at day {day}");
            assert!((1..=31).contains(&d), "day out of range at day {day}");
            assert!(
                (y, m, d) >= prev,
                "dates should be monotonically non-decreasing: \
                 day {day} produced ({y}, {m}, {d}), prev was {prev:?}",
            );
            prev = (y, m, d);
        }
    }

    // --- Timestamp Construction ---

    #[test]
    fn from_unix_secs_epoch() {
        let ts = Timestamp::from_unix_secs(0);
        assert_eq!(ts.year(), 1970);
        assert_eq!(ts.month(), 1);
        assert_eq!(ts.day(), 1);
        assert_eq!(ts.hour(), 0);
        assert_eq!(ts.minute(), 0);
        assert_eq!(ts.second(), 0);
        assert_eq!(ts.unix_epoch_secs(), 0);
    }

    #[test]
    fn from_unix_secs_known_date() {
        // 2025-01-01 00:00:00 UTC = 1_735_689_600 seconds since epoch
        let ts = Timestamp::from_unix_secs(1_735_689_600);
        assert_eq!(ts.year(), 2025);
        assert_eq!(ts.month(), 1);
        assert_eq!(ts.day(), 1);
        assert_eq!(ts.hour(), 0);
        assert_eq!(ts.minute(), 0);
        assert_eq!(ts.second(), 0);
    }

    #[test]
    fn from_unix_secs_with_time_of_day() {
        // 2026-02-21 14:30:45 UTC
        // 2026-02-21 = day 20505, 14:30:45 = 52245 seconds into day
        // total = 20505 * 86400 + 52245 = 1_771_684_245
        let ts = Timestamp::from_unix_secs(1_771_684_245);
        assert_eq!(ts.year(), 2026);
        assert_eq!(ts.month(), 2);
        assert_eq!(ts.day(), 21);
        assert_eq!(ts.hour(), 14);
        assert_eq!(ts.minute(), 30);
        assert_eq!(ts.second(), 45);
    }

    #[test]
    fn from_unix_secs_round_trips_with_unix_epoch_secs() {
        // NOTE: Values must stay within the post-epoch range supported by
        // civil_from_days (year fits in u32). The largest value here
        // corresponds to a date far in the future but well within range.
        let values = [0, 1, 86_400, 1_000_000, 1_735_689_600, 4_102_444_800];
        for secs in values {
            let ts = Timestamp::from_unix_secs(secs);
            assert_eq!(ts.unix_epoch_secs(), secs, "round-trip failed for {secs}");
        }
    }

    #[test]
    fn now_returns_plausible_date() {
        let ts = Timestamp::now();
        // Should be at least 2020 and at most a few decades from now.
        assert!(ts.year() >= 2020, "year {}", ts.year());
        assert!(ts.year() <= 2100, "year {}", ts.year());
        assert!((1..=12).contains(&ts.month()), "month {}", ts.month());
        assert!((1..=31).contains(&ts.day()), "day {}", ts.day());
        assert!(ts.hour() < 24, "hour {}", ts.hour());
        assert!(ts.minute() < 60, "minute {}", ts.minute());
        assert!(ts.second() < 60, "second {}", ts.second());
        // total_secs should also be plausible (after 2020-01-01)
        assert!(ts.unix_epoch_secs() > 1_577_836_800);
    }

    // --- Comparison ---

    #[test]
    fn ordering_earlier_is_less() {
        let earlier = Timestamp::from_unix_secs(1_000_000);
        let later = Timestamp::from_unix_secs(2_000_000);
        assert!(earlier < later);
        assert!(later > earlier);
        assert_ne!(earlier, later);
    }

    #[test]
    fn ordering_equal() {
        let a = Timestamp::from_unix_secs(1_735_689_600);
        let b = Timestamp::from_unix_secs(1_735_689_600);
        assert_eq!(a, b);
        assert!(a <= b);
        assert!(a >= b);
    }

    #[test]
    fn ordering_adjacent_seconds() {
        let a = Timestamp::from_unix_secs(1_735_689_600);
        let b = Timestamp::from_unix_secs(1_735_689_601);
        assert!(a < b);
    }

    #[test]
    fn is_before_correctness() {
        let earlier = Timestamp::from_unix_secs(100);
        let later = Timestamp::from_unix_secs(200);
        assert!(earlier.is_before(&later));
        assert!(!later.is_before(&earlier));
        // NOTE: A timestamp is not before itself.
        assert!(!earlier.is_before(&earlier));
    }

    // --- Expiry ---

    #[test]
    fn is_expired_token_in_the_past() {
        let expiry = Timestamp::from_unix_secs(1_000_000);
        let now = Timestamp::from_unix_secs(2_000_000);
        assert!(expiry.is_expired(&now));
    }

    #[test]
    fn is_expired_token_in_the_future() {
        let expiry = Timestamp::from_unix_secs(3_000_000);
        let now = Timestamp::from_unix_secs(2_000_000);
        assert!(!expiry.is_expired(&now));
    }

    #[test]
    fn is_expired_exact_boundary() {
        // NOTE: A token whose expiry equals `now` is considered expired.
        let expiry = Timestamp::from_unix_secs(1_000_000);
        let now = Timestamp::from_unix_secs(1_000_000);
        assert!(expiry.is_expired(&now));
    }

    // --- Display ---

    #[test]
    fn display_format_is_fixed_width() {
        // Construct a known timestamp by going through now() — we cannot
        // construct Timestamp directly (fields are private), so we verify
        // the output format structurally.
        let ts = Timestamp::now();
        let formatted = format!("{ts}");
        // Expected: "YYYY-MM-DD HH:MM:SS" = exactly 19 characters.
        assert_eq!(
            formatted.len(),
            19,
            "Expected 19-char timestamp, got '{formatted}' (len {})",
            formatted.len(),
        );
        // Verify the delimiter positions.
        assert_eq!(&formatted[4..5], "-", "Expected '-' at position 4");
        assert_eq!(&formatted[7..8], "-", "Expected '-' at position 7");
        assert_eq!(&formatted[10..11], " ", "Expected ' ' at position 10");
        assert_eq!(&formatted[13..14], ":", "Expected ':' at position 13");
        assert_eq!(&formatted[16..17], ":", "Expected ':' at position 16");
    }

    #[test]
    fn display_epoch_timestamp() {
        let ts = Timestamp::new(1970, 1, 1, 0, 0, 0);
        assert_eq!(format!("{ts}"), "1970-01-01 00:00:00");
    }

    #[test]
    fn display_zero_pads_single_digit_fields() {
        let ts = Timestamp::new(2026, 3, 5, 8, 4, 9);
        assert_eq!(format!("{ts}"), "2026-03-05 08:04:09");
    }

    #[test]
    fn display_double_digit_fields() {
        let ts = Timestamp::new(2026, 12, 31, 23, 59, 59);
        assert_eq!(format!("{ts}"), "2026-12-31 23:59:59");
    }

    #[test]
    fn display_from_unix_secs() {
        let ts = Timestamp::from_unix_secs(0);
        assert_eq!(format!("{ts}"), "1970-01-01 00:00:00");
    }

    // --- ISO 8601 ---

    #[test]
    fn to_iso8601_epoch() {
        let ts = Timestamp::from_unix_secs(0);
        assert_eq!(ts.to_iso8601(), "1970-01-01T00:00:00Z");
    }

    #[test]
    fn to_iso8601_known_date() {
        let ts = Timestamp::from_unix_secs(1_735_689_600);
        assert_eq!(ts.to_iso8601(), "2025-01-01T00:00:00Z");
    }

    #[test]
    fn to_iso8601_with_time() {
        let ts = Timestamp::from_unix_secs(1_771_684_245);
        assert_eq!(ts.to_iso8601(), "2026-02-21T14:30:45Z");
    }

    #[test]
    fn to_iso8601_sorts_lexicographically() {
        let a = Timestamp::from_unix_secs(1_000_000);
        let b = Timestamp::from_unix_secs(2_000_000);
        assert!(a.to_iso8601() < b.to_iso8601());
    }

    // --- parse_iso8601 ---

    #[test]
    fn parse_iso8601_epoch() {
        let ts = Timestamp::parse_iso8601("1970-01-01T00:00:00Z").unwrap();
        assert_eq!(ts.unix_epoch_secs(), 0);
    }

    #[test]
    fn parse_iso8601_known_date() {
        let ts = Timestamp::parse_iso8601("2025-01-01T00:00:00Z").unwrap();
        assert_eq!(ts.unix_epoch_secs(), 1_735_689_600);
        assert_eq!(ts.year(), 2025);
        assert_eq!(ts.month(), 1);
        assert_eq!(ts.day(), 1);
    }

    #[test]
    fn parse_iso8601_with_time() {
        let ts = Timestamp::parse_iso8601("2026-02-21T14:30:45Z").unwrap();
        assert_eq!(ts.unix_epoch_secs(), 1_771_684_245);
        assert_eq!(ts.year(), 2026);
        assert_eq!(ts.month(), 2);
        assert_eq!(ts.day(), 21);
        assert_eq!(ts.hour(), 14);
        assert_eq!(ts.minute(), 30);
        assert_eq!(ts.second(), 45);
    }

    #[test]
    fn parse_iso8601_round_trips_with_to_iso8601() {
        let values = [0_u64, 1, 86_400, 1_000_000, 1_735_689_600, 1_771_684_245];
        for secs in values {
            let original = Timestamp::from_unix_secs(secs);
            let iso = original.to_iso8601();
            let parsed = Timestamp::parse_iso8601(&iso).unwrap();
            assert_eq!(
                parsed.unix_epoch_secs(),
                original.unix_epoch_secs(),
                "round-trip failed for {secs} (iso={iso})",
            );
        }
    }

    #[test]
    fn parse_iso8601_leap_day() {
        let ts = Timestamp::parse_iso8601("2024-02-29T00:00:00Z").unwrap();
        assert_eq!(ts.year(), 2024);
        assert_eq!(ts.month(), 2);
        assert_eq!(ts.day(), 29);
    }

    #[test]
    fn parse_iso8601_end_of_day() {
        let ts = Timestamp::parse_iso8601("2026-12-31T23:59:59Z").unwrap();
        assert_eq!(ts.hour(), 23);
        assert_eq!(ts.minute(), 59);
        assert_eq!(ts.second(), 59);
    }

    #[test]
    fn parse_iso8601_rejects_empty() {
        assert!(Timestamp::parse_iso8601("").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_wrong_length() {
        assert!(Timestamp::parse_iso8601("2025-01-01T00:00:00").is_none());
        assert!(Timestamp::parse_iso8601("2025-01-01T00:00:00ZZ").is_none());
    }

    #[test]
    fn parse_iso8601_normalizes_numeric_offsets() {
        // +00:00 is exactly UTC.
        let z = Timestamp::parse_iso8601("2023-11-14T22:13:20Z").unwrap();
        assert_eq!(
            Timestamp::parse_iso8601("2023-11-14T22:13:20+00:00").unwrap(),
            z
        );
        // +01:00 means local is one hour ahead of UTC → subtract an hour.
        assert_eq!(
            Timestamp::parse_iso8601("2023-11-14T23:13:20+01:00").unwrap(),
            z
        );
        // -05:30 means local is behind UTC → add 5h30m.
        assert_eq!(
            Timestamp::parse_iso8601("2023-11-14T16:43:20-05:30").unwrap(),
            z
        );
        // Offset with fractional seconds.
        assert_eq!(
            Timestamp::parse_iso8601("2023-11-14T23:13:20.5+01:00").unwrap(),
            z
        );
    }

    #[test]
    fn parse_iso8601_rejects_malformed_offsets() {
        assert!(Timestamp::parse_iso8601("2025-01-01T00:00:00+0100").is_none()); // no colon
        assert!(Timestamp::parse_iso8601("2025-01-01T00:00:00+24:00").is_none()); // hour > 23
        assert!(Timestamp::parse_iso8601("2025-01-01T00:00:00+01:60").is_none()); // min > 59
        // An offset that pushes the instant before the Unix epoch is rejected.
        assert!(Timestamp::parse_iso8601("1970-01-01T00:00:00+01:00").is_none());
    }

    #[test]
    fn parse_iso8601_accepts_fractional_seconds() {
        // SAML IdPs (ADFS, Azure AD, Shibboleth) routinely emit sub-second
        // precision; it must parse and truncate to whole seconds.
        let base = Timestamp::parse_iso8601("2026-02-21T14:30:45Z").unwrap();
        for s in [
            "2026-02-21T14:30:45.1Z",
            "2026-02-21T14:30:45.123Z",
            "2026-02-21T14:30:45.123456789Z",
        ] {
            let ts = Timestamp::parse_iso8601(s).unwrap();
            assert_eq!(ts.unix_epoch_secs(), base.unix_epoch_secs(), "for {s}");
        }
    }

    #[test]
    fn parse_iso8601_rejects_malformed_fractional_seconds() {
        // A '.' with no digits, or non-digit fractional content, is invalid.
        assert!(Timestamp::parse_iso8601("2026-02-21T14:30:45.Z").is_none());
        assert!(Timestamp::parse_iso8601("2026-02-21T14:30:45.12aZ").is_none());
        // A non-'.' separator before the fraction is rejected.
        assert!(Timestamp::parse_iso8601("2026-02-21T14:30:45,5Z").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_bad_delimiters() {
        // Missing 'T' separator
        assert!(Timestamp::parse_iso8601("2025-01-01 00:00:00Z").is_none());
        // Slash instead of dash
        assert!(Timestamp::parse_iso8601("2025/01/01T00:00:00Z").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_invalid_month() {
        assert!(Timestamp::parse_iso8601("2025-00-01T00:00:00Z").is_none());
        assert!(Timestamp::parse_iso8601("2025-13-01T00:00:00Z").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_invalid_day() {
        assert!(Timestamp::parse_iso8601("2025-01-00T00:00:00Z").is_none());
        assert!(Timestamp::parse_iso8601("2025-01-32T00:00:00Z").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_invalid_time() {
        assert!(Timestamp::parse_iso8601("2025-01-01T24:00:00Z").is_none());
        assert!(Timestamp::parse_iso8601("2025-01-01T00:60:00Z").is_none());
        assert!(Timestamp::parse_iso8601("2025-01-01T00:00:60Z").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_non_numeric() {
        assert!(Timestamp::parse_iso8601("abcd-ef-ghTij:kl:mnZ").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_pre_epoch_years() {
        // Pre-1970 dates are not representable as u64 epoch seconds and
        // would underflow the days_from_civil conversion; reject them.
        assert!(Timestamp::parse_iso8601("1969-12-31T23:59:59Z").is_none());
        assert!(Timestamp::parse_iso8601("0001-01-01T00:00:00Z").is_none());
    }

    #[test]
    fn parse_iso8601_accepts_epoch_boundary() {
        let ts = Timestamp::parse_iso8601("1970-01-01T00:00:00Z").unwrap();
        assert_eq!(ts.unix_epoch_secs(), 0);
    }

    #[test]
    fn new_total_secs_consistent_with_ordering() {
        // `Ord` compares total_secs; ensure the test constructor computes it
        // so ordering stays consistent with the derived `Eq`.
        let earlier = Timestamp::new(1970, 1, 1, 0, 0, 0);
        let later = Timestamp::new(2026, 6, 19, 12, 0, 0);
        assert!(earlier < later);
        assert_ne!(earlier, later);
        // Round-trips through epoch seconds.
        assert_eq!(Timestamp::from_unix_secs(later.unix_epoch_secs()), later);
    }

    // --- Singular accessor aliases ---

    #[test]
    fn accessor_hour_minute_second() {
        let ts = Timestamp::from_unix_secs(1_771_684_245);
        assert_eq!(ts.hour(), 14);
        assert_eq!(ts.minute(), 30);
        assert_eq!(ts.second(), 45);
    }

    #[test]
    #[allow(deprecated)]
    fn deprecated_hours_minutes_seconds_still_work() {
        let ts = Timestamp::from_unix_secs(1_771_684_245);
        assert_eq!(ts.hours(), 14);
        assert_eq!(ts.minutes(), 30);
        assert_eq!(ts.seconds(), 45);
    }
}