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
//! Unified authentication result types.
//!
//! Provides [`AuthProviderKind`] to identify which authentication method
//! was used, [`AuthIdentity`] for the authenticated user, [`AuthResult`]
//! as the successful outcome of authentication, and [`AuthError`] as the
//! top-level error type.
//!
//! # Security
//!
//! [`AuthError::is_invalid_credentials`] deliberately does not distinguish
//! between "user not found" and "wrong password" — the error *value* reveals
//! no reason, to prevent user enumeration. This closes the *semantic* channel
//! only; to also close the *timing* channel (an absent user otherwise skips
//! the expensive password hash and answers far faster), perform the
//! verification step with
//! [`verify_credential`](crate::verify_credential), which spends one Argon2id
//! verification even when the user does not exist. All error messages are safe
//! for logging and never contain secret material.

use std::fmt;

use crate::session::Session;
use crate::util::timestamp::Timestamp;

// ---------------------------------------------------------------------------
// AuthProviderKind
// ---------------------------------------------------------------------------

/// Identifies which authentication provider was used.
///
/// This is a simple tag — it carries no configuration or state. Use it
/// to branch on provider type in middleware, audit logs, and metrics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[doc(alias = "provider")]
pub enum AuthProviderKind {
    /// Local username/password credentials.
    Local,
    /// OAuth 2.0 delegated authorization.
    OAuth,
    /// `OpenID` Connect identity layer.
    Oidc,
    /// SAML 2.0 federated identity.
    Saml,
    /// Pre-shared API key.
    ApiKey,
    /// HMAC-signed request.
    Hmac,
    /// Opaque bearer token.
    Bearer,
}

impl fmt::Display for AuthProviderKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::Local => "local",
            Self::OAuth => "oauth",
            Self::Oidc => "oidc",
            Self::Saml => "saml",
            Self::ApiKey => "api_key",
            Self::Hmac => "hmac",
            Self::Bearer => "bearer",
        };
        f.write_str(name)
    }
}

// ---------------------------------------------------------------------------
// AuthIdentity
// ---------------------------------------------------------------------------

/// The authenticated user's identity, as asserted by the provider.
///
/// Carries the mandatory `subject` (unique user identifier) plus optional
/// profile fields and arbitrary key-value claims from the token or
/// assertion.
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc(alias = "identity")]
pub struct AuthIdentity {
    subject: String,
    email: Option<String>,
    display_name: Option<String>,
    claims: Vec<(String, String)>,
}

impl AuthIdentity {
    /// Creates a new identity with the given subject and no optional fields.
    ///
    /// Use the `with_*` builder methods to attach optional profile data.
    ///
    /// # Examples
    ///
    /// ```
    /// use entropy_auth::AuthIdentity;
    ///
    /// let identity = AuthIdentity::new("user-123")
    ///     .with_email("user@example.com")
    ///     .with_claim("role", "admin");
    ///
    /// assert_eq!(identity.subject(), "user-123");
    /// assert_eq!(identity.email(), Some("user@example.com"));
    /// assert_eq!(identity.get_claim("role"), Some("admin"));
    /// ```
    #[must_use]
    pub fn new(subject: impl Into<String>) -> Self {
        Self {
            subject: subject.into(),
            email: None,
            display_name: None,
            claims: Vec::new(),
        }
    }

    /// Sets the email address.
    #[must_use]
    pub fn with_email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// Sets the human-readable display name.
    #[must_use]
    pub fn with_display_name(mut self, name: impl Into<String>) -> Self {
        self.display_name = Some(name.into());
        self
    }

    /// Appends an arbitrary key-value claim.
    #[must_use]
    pub fn with_claim(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.claims.push((key.into(), value.into()));
        self
    }

    /// Returns the subject (unique user identifier).
    #[must_use]
    #[inline]
    pub fn subject(&self) -> &str {
        &self.subject
    }

    /// Returns the email address, if set.
    #[must_use]
    #[inline]
    pub fn email(&self) -> Option<&str> {
        self.email.as_deref()
    }

    /// Returns the display name, if set.
    #[must_use]
    #[inline]
    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    /// Returns the list of additional claims.
    #[must_use]
    #[inline]
    pub fn claims(&self) -> &[(String, String)] {
        &self.claims
    }

    /// Returns the value of the claim with the given key, if present.
    ///
    /// Performs a linear scan of the claims list. This is efficient for
    /// the small number of claims typical of authentication tokens.
    #[must_use]
    #[inline]
    pub fn get_claim(&self, key: &str) -> Option<&str> {
        self.claims
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.as_str())
    }
}

// ---------------------------------------------------------------------------
// AuthResult
// ---------------------------------------------------------------------------

/// Successful outcome of an authentication operation.
///
/// Bundles the verified [`AuthIdentity`], the [`AuthProviderKind`] that
/// produced it, the wall-clock time of authentication, and an optional
/// [`Session`] for stateful flows.
#[derive(Debug, Clone)]
#[doc(alias = "auth_result")]
pub struct AuthResult {
    identity: AuthIdentity,
    provider: AuthProviderKind,
    authenticated_at: Timestamp,
    session: Option<Session>,
}

impl AuthResult {
    /// Creates a new result without a session.
    #[must_use]
    pub fn new(
        identity: AuthIdentity,
        provider: AuthProviderKind,
        authenticated_at: Timestamp,
    ) -> Self {
        Self {
            identity,
            provider,
            authenticated_at,
            session: None,
        }
    }

    /// Attaches a session to this result.
    #[must_use]
    pub fn with_session(mut self, session: Session) -> Self {
        self.session = Some(session);
        self
    }

    /// Returns the authenticated identity.
    #[must_use]
    #[inline]
    pub fn identity(&self) -> &AuthIdentity {
        &self.identity
    }

    /// Returns which provider performed the authentication.
    #[must_use]
    #[inline]
    pub fn provider(&self) -> AuthProviderKind {
        self.provider
    }

    /// Returns the wall-clock time of authentication.
    #[must_use]
    #[inline]
    pub fn authenticated_at(&self) -> &Timestamp {
        &self.authenticated_at
    }

    /// Returns the session, if one was attached.
    #[must_use]
    #[inline]
    pub fn session(&self) -> Option<&Session> {
        self.session.as_ref()
    }
}

// ---------------------------------------------------------------------------
// AuthError
// ---------------------------------------------------------------------------

// NOTE: `AuthError` was previously a `#[non_exhaustive] pub enum`. It has
// been converted to the private `ErrorKind` + public struct wrapper pattern
// used by every other error type in this crate (e.g., `HmacAuthError`).
// This gives callers a stable API surface (query methods, `Display`) while
// keeping variant details private, allowing us to add or restructure
// variants without breaking downstream code.

/// The kind of authentication error that occurred.
///
/// Private — callers inspect errors through the query methods on
/// [`AuthError`].
// NOTE: All variants and constructors are exercised by tests and form
// the intended internal API for downstream modules. Dead-code analysis
// cannot see cross-crate test usage, so we suppress the warning on
// the enum and its constructors with a single module-level attribute.
#[derive(Debug, Clone, PartialEq, Eq)]
enum AuthErrorKind {
    // SECURITY: This variant deliberately does not distinguish between
    // "user not found" and "wrong password" to prevent user enumeration.
    InvalidCredentials,
    TokenExpired,
    InvalidToken(String),
    InvalidConfiguration(String),
    Crypto(String),
    SessionExpired,
    Provider(String),
}

/// Top-level authentication error.
///
/// Error messages are safe for logging and never contain secret material
/// (passwords, tokens, keys). Inspect the error category using the
/// `is_*()` query methods, and retrieve the detail string (if any) with
/// [`detail()`](AuthError::detail).
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc(alias = "auth_error")]
pub struct AuthError {
    kind: AuthErrorKind,
}

// -- Constructors (crate-internal) ----------------------------------------
//
// NOTE: Suppress dead_code for the constructor block — all constructors
// form the intended internal API and are exercised by tests. They will
// be called by downstream modules as the crate's integration layer grows.
#[allow(dead_code)]
impl AuthError {
    /// Creates a new `AuthError` from the given kind.
    const fn new(kind: AuthErrorKind) -> Self {
        Self { kind }
    }

    /// Authentication failed (deliberately vague).
    ///
    /// # Security
    ///
    /// Does not distinguish between "user not found" and "wrong password"
    /// to prevent user-enumeration attacks.
    pub(crate) fn invalid_credentials() -> Self {
        Self::new(AuthErrorKind::InvalidCredentials)
    }

    /// The provided token has expired.
    pub(crate) fn token_expired() -> Self {
        Self::new(AuthErrorKind::TokenExpired)
    }

    /// The provided token is invalid (malformed, bad signature, etc.).
    pub(crate) fn invalid_token(detail: impl Into<String>) -> Self {
        Self::new(AuthErrorKind::InvalidToken(detail.into()))
    }

    /// The authentication provider is misconfigured.
    pub(crate) fn invalid_configuration(detail: impl Into<String>) -> Self {
        Self::new(AuthErrorKind::InvalidConfiguration(detail.into()))
    }

    /// A cryptographic operation failed.
    pub(crate) fn crypto(detail: impl Into<String>) -> Self {
        Self::new(AuthErrorKind::Crypto(detail.into()))
    }

    /// The session has expired or is invalid.
    pub(crate) fn session_expired() -> Self {
        Self::new(AuthErrorKind::SessionExpired)
    }

    /// The provider returned an error.
    pub(crate) fn provider(detail: impl Into<String>) -> Self {
        Self::new(AuthErrorKind::Provider(detail.into()))
    }
}

// -- Query methods --------------------------------------------------------

impl AuthError {
    /// Returns `true` if authentication failed due to invalid credentials.
    ///
    /// # Security
    ///
    /// This deliberately does not distinguish between "user not found"
    /// and "wrong password" to prevent user-enumeration attacks.
    #[must_use]
    #[inline]
    pub fn is_invalid_credentials(&self) -> bool {
        self.kind == AuthErrorKind::InvalidCredentials
    }

    /// Returns `true` if the token has expired.
    #[must_use]
    #[inline]
    pub fn is_token_expired(&self) -> bool {
        self.kind == AuthErrorKind::TokenExpired
    }

    /// Returns `true` if the token was invalid (malformed, bad signature, etc.).
    #[must_use]
    #[inline]
    pub fn is_invalid_token(&self) -> bool {
        matches!(self.kind, AuthErrorKind::InvalidToken(_))
    }

    /// Returns `true` if the authentication provider is misconfigured.
    #[must_use]
    #[inline]
    pub fn is_invalid_configuration(&self) -> bool {
        matches!(self.kind, AuthErrorKind::InvalidConfiguration(_))
    }

    /// Returns `true` if a cryptographic operation failed.
    #[must_use]
    #[inline]
    pub fn is_crypto(&self) -> bool {
        matches!(self.kind, AuthErrorKind::Crypto(_))
    }

    /// Returns `true` if the session has expired or is invalid.
    #[must_use]
    #[inline]
    pub fn is_session_expired(&self) -> bool {
        self.kind == AuthErrorKind::SessionExpired
    }

    /// Returns `true` if the provider returned an error.
    #[must_use]
    #[inline]
    pub fn is_provider(&self) -> bool {
        matches!(self.kind, AuthErrorKind::Provider(_))
    }

    /// Returns the detail string for variants that carry one, or `None`
    /// for unit variants (`InvalidCredentials`, `TokenExpired`,
    /// `SessionExpired`).
    #[must_use]
    #[inline]
    pub fn detail(&self) -> Option<&str> {
        match &self.kind {
            AuthErrorKind::InvalidToken(d)
            | AuthErrorKind::InvalidConfiguration(d)
            | AuthErrorKind::Crypto(d)
            | AuthErrorKind::Provider(d) => Some(d),
            AuthErrorKind::InvalidCredentials
            | AuthErrorKind::TokenExpired
            | AuthErrorKind::SessionExpired => None,
        }
    }
}

impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            // SECURITY: Deliberately vague to prevent user enumeration.
            AuthErrorKind::InvalidCredentials => f.write_str("authentication failed"),
            AuthErrorKind::TokenExpired => f.write_str("token expired"),
            AuthErrorKind::InvalidToken(detail) => {
                f.write_str("invalid token: ")?;
                f.write_str(detail)
            }
            AuthErrorKind::InvalidConfiguration(detail) => {
                f.write_str("invalid configuration: ")?;
                f.write_str(detail)
            }
            AuthErrorKind::Crypto(detail) => {
                f.write_str("crypto error: ")?;
                f.write_str(detail)
            }
            AuthErrorKind::SessionExpired => f.write_str("session expired"),
            AuthErrorKind::Provider(detail) => {
                f.write_str("provider error: ")?;
                f.write_str(detail)
            }
        }
    }
}

impl std::error::Error for AuthError {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- AuthProviderKind ---

    #[test]
    fn provider_kind_display_local() {
        assert_eq!(AuthProviderKind::Local.to_string(), "local");
    }

    #[test]
    fn provider_kind_display_oauth() {
        assert_eq!(AuthProviderKind::OAuth.to_string(), "oauth");
    }

    #[test]
    fn provider_kind_display_oidc() {
        assert_eq!(AuthProviderKind::Oidc.to_string(), "oidc");
    }

    #[test]
    fn provider_kind_display_saml() {
        assert_eq!(AuthProviderKind::Saml.to_string(), "saml");
    }

    #[test]
    fn provider_kind_display_api_key() {
        assert_eq!(AuthProviderKind::ApiKey.to_string(), "api_key");
    }

    #[test]
    fn provider_kind_display_hmac() {
        assert_eq!(AuthProviderKind::Hmac.to_string(), "hmac");
    }

    #[test]
    fn provider_kind_display_bearer() {
        assert_eq!(AuthProviderKind::Bearer.to_string(), "bearer");
    }

    #[test]
    fn provider_kind_clone() {
        let original = AuthProviderKind::OAuth;
        let cloned = original;
        assert_eq!(original, cloned);
    }

    #[test]
    fn provider_kind_copy() {
        let a = AuthProviderKind::Oidc;
        let b = a;
        // Both `a` and `b` remain usable — Copy semantics.
        assert_eq!(a, b);
    }

    #[test]
    fn provider_kind_partial_eq_different_variants() {
        assert_ne!(AuthProviderKind::Local, AuthProviderKind::OAuth);
        assert_ne!(AuthProviderKind::Hmac, AuthProviderKind::Bearer);
    }

    // --- AuthIdentity ---

    #[test]
    fn identity_new_creates_with_subject_only() {
        let id = AuthIdentity::new("user-42");
        assert_eq!(id.subject(), "user-42");
        assert_eq!(id.email(), None);
        assert_eq!(id.display_name(), None);
        assert!(id.claims().is_empty());
    }

    #[test]
    fn identity_builder_methods_chain() {
        let id = AuthIdentity::new("sub-1")
            .with_email("alice@example.com")
            .with_display_name("Alice")
            .with_claim("role", "admin")
            .with_claim("org", "entropy");

        assert_eq!(id.subject(), "sub-1");
        assert_eq!(id.email(), Some("alice@example.com"));
        assert_eq!(id.display_name(), Some("Alice"));
        assert_eq!(id.claims().len(), 2);
    }

    #[test]
    fn identity_accessors_return_correct_values() {
        let id = AuthIdentity::new("sub-99")
            .with_email("bob@test.io")
            .with_display_name("Bob")
            .with_claim("tier", "free");

        assert_eq!(id.subject(), "sub-99");
        assert_eq!(id.email(), Some("bob@test.io"));
        assert_eq!(id.display_name(), Some("Bob"));
        assert_eq!(id.claims(), &[("tier".to_owned(), "free".to_owned())]);
    }

    #[test]
    fn identity_empty_claims_vec() {
        let id = AuthIdentity::new("x");
        let empty: &[(String, String)] = &[];
        assert_eq!(id.claims(), empty);
    }

    #[test]
    fn identity_get_claim_returns_matching_value() {
        let id = AuthIdentity::new("sub-1")
            .with_claim("role", "admin")
            .with_claim("org", "entropy");
        assert_eq!(id.get_claim("role"), Some("admin"));
        assert_eq!(id.get_claim("org"), Some("entropy"));
    }

    #[test]
    fn identity_get_claim_returns_none_for_missing_key() {
        let id = AuthIdentity::new("sub-1").with_claim("role", "admin");
        assert_eq!(id.get_claim("missing"), None);
    }

    #[test]
    fn identity_get_claim_returns_none_when_no_claims() {
        let id = AuthIdentity::new("sub-1");
        assert_eq!(id.get_claim("anything"), None);
    }

    // --- AuthResult ---

    #[test]
    fn result_new_without_session() {
        let identity = AuthIdentity::new("user-1");
        let ts = Timestamp::from_unix_secs(1_700_000_000);
        let result = AuthResult::new(identity, AuthProviderKind::Local, ts);

        assert_eq!(result.identity().subject(), "user-1");
        assert_eq!(result.provider(), AuthProviderKind::Local);
        assert_eq!(result.authenticated_at().unix_epoch_secs(), 1_700_000_000);
        assert!(result.session().is_none());
    }

    #[test]
    fn result_with_session() {
        let identity = AuthIdentity::new("user-2");
        let ts = Timestamp::from_unix_secs(1_700_000_000);
        let config = crate::session::SessionConfig::default();
        let (_, session) = Session::create(&config).unwrap();

        let result = AuthResult::new(identity, AuthProviderKind::Bearer, ts).with_session(session);

        assert!(result.session().is_some());
    }

    #[test]
    fn result_accessors() {
        let identity = AuthIdentity::new("sub-abc").with_email("c@d.com");
        let ts = Timestamp::from_unix_secs(1_234_567_890);
        let result = AuthResult::new(identity, AuthProviderKind::Hmac, ts);

        assert_eq!(result.identity().email(), Some("c@d.com"));
        assert_eq!(result.provider(), AuthProviderKind::Hmac);
        assert_eq!(result.authenticated_at().unix_epoch_secs(), 1_234_567_890);
        assert!(result.session().is_none());
    }

    // --- AuthError ---

    #[test]
    fn error_display_invalid_credentials_is_vague() {
        // SECURITY: Must say "authentication failed" — never reveal whether
        // the user exists or the password was wrong.
        let err = AuthError::invalid_credentials();
        assert_eq!(err.to_string(), "authentication failed");
        assert!(err.is_invalid_credentials());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn error_display_token_expired() {
        let err = AuthError::token_expired();
        assert_eq!(err.to_string(), "token expired");
        assert!(err.is_token_expired());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn error_display_invalid_token() {
        let err = AuthError::invalid_token("bad signature");
        assert_eq!(err.to_string(), "invalid token: bad signature");
        assert!(err.is_invalid_token());
        assert_eq!(err.detail(), Some("bad signature"));
    }

    #[test]
    fn error_display_invalid_configuration() {
        let err = AuthError::invalid_configuration("missing issuer");
        assert_eq!(err.to_string(), "invalid configuration: missing issuer");
        assert!(err.is_invalid_configuration());
        assert_eq!(err.detail(), Some("missing issuer"));
    }

    #[test]
    fn error_display_crypto() {
        let err = AuthError::crypto("hash mismatch");
        assert_eq!(err.to_string(), "crypto error: hash mismatch");
        assert!(err.is_crypto());
        assert_eq!(err.detail(), Some("hash mismatch"));
    }

    #[test]
    fn error_display_session_expired() {
        let err = AuthError::session_expired();
        assert_eq!(err.to_string(), "session expired");
        assert!(err.is_session_expired());
        assert_eq!(err.detail(), None);
    }

    #[test]
    fn error_display_provider() {
        let err = AuthError::provider("upstream timeout");
        assert_eq!(err.to_string(), "provider error: upstream timeout");
        assert!(err.is_provider());
        assert_eq!(err.detail(), Some("upstream timeout"));
    }

    #[test]
    fn error_debug_does_not_leak_secrets() {
        // Verify Debug output for variants with payloads does not contain
        // anything beyond the variant name and the developer-supplied detail
        // string. The detail strings themselves must never contain secrets —
        // that is the caller's responsibility — but we verify the Debug
        // format is a straightforward struct/enum representation.
        let err = AuthError::invalid_token("test detail");
        let debug = format!("{err:?}");
        assert!(
            debug.contains("InvalidToken"),
            "Debug should contain variant name: {debug}",
        );
        assert!(
            debug.contains("test detail"),
            "Debug should contain the detail string: {debug}",
        );
        // The Debug output should not contain anything resembling a secret.
        assert!(
            !debug.contains("password"),
            "Debug must not mention passwords: {debug}",
        );
    }

    #[test]
    fn error_implements_std_error() {
        // Verify all variants can be used as `dyn Error`.
        let errors: Vec<Box<dyn std::error::Error>> = vec![
            Box::new(AuthError::invalid_credentials()),
            Box::new(AuthError::token_expired()),
            Box::new(AuthError::invalid_token("x")),
            Box::new(AuthError::invalid_configuration("y")),
            Box::new(AuthError::crypto("z")),
            Box::new(AuthError::session_expired()),
            Box::new(AuthError::provider("w")),
        ];
        for err in &errors {
            // source() should return None for all variants (no wrapped cause).
            assert!(err.source().is_none(), "source() should be None for: {err}");
        }
    }

    #[test]
    fn error_partial_eq() {
        assert_eq!(
            AuthError::invalid_credentials(),
            AuthError::invalid_credentials()
        );
        assert_eq!(AuthError::token_expired(), AuthError::token_expired());
        assert_eq!(AuthError::session_expired(), AuthError::session_expired());
        assert_eq!(AuthError::invalid_token("x"), AuthError::invalid_token("x"));
        assert_ne!(AuthError::invalid_token("x"), AuthError::invalid_token("y"));
        assert_ne!(AuthError::invalid_credentials(), AuthError::token_expired());
    }

    #[test]
    fn error_query_methods_are_exclusive() {
        // Each error should return `true` for exactly one query method.
        let cases: Vec<(AuthError, &str)> = vec![
            (AuthError::invalid_credentials(), "invalid_credentials"),
            (AuthError::token_expired(), "token_expired"),
            (AuthError::invalid_token("t"), "invalid_token"),
            (
                AuthError::invalid_configuration("c"),
                "invalid_configuration",
            ),
            (AuthError::crypto("c"), "crypto"),
            (AuthError::session_expired(), "session_expired"),
            (AuthError::provider("p"), "provider"),
        ];
        for (err, expected_name) in &cases {
            let hits: Vec<&str> = [
                err.is_invalid_credentials()
                    .then_some("invalid_credentials"),
                err.is_token_expired().then_some("token_expired"),
                err.is_invalid_token().then_some("invalid_token"),
                err.is_invalid_configuration()
                    .then_some("invalid_configuration"),
                err.is_crypto().then_some("crypto"),
                err.is_session_expired().then_some("session_expired"),
                err.is_provider().then_some("provider"),
            ]
            .into_iter()
            .flatten()
            .collect();
            assert_eq!(
                hits,
                vec![*expected_name],
                "expected exactly one query match for {expected_name}, got {hits:?}",
            );
        }
    }
}