axiam-sdk 1.2.2

Official Rust client SDK for AXIAM IAM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! `AxiamError` — the single, `?`-friendly error type for this SDK
//! (CONTRACT.md §2, D-06).
//!
//! Three top-level *kinds* exist: `Auth`, `Authz`, `Network`, matching the
//! CONTRACT.md §2 error taxonomy exactly. §2 additionally permits
//! language-idiomatic **sub-types** of those three (they never replace them):
//! [`OAuthProtocolError`] is one such sub-type, carried by the `Auth` variant
//! itself via its `oauth` field (CONTRACT.md §12.3 rule 3, addendum item 17)
//! — `AxiamError::Auth { .. }` still matches an OAuth2-protocol failure, so
//! existing `match`/`?` handling that only cares about the outer variant
//! keeps compiling and behaving correctly; code that wants the structured
//! `error`/`error_description` pair reads the `oauth` field or calls
//! [`AxiamError::oauth_protocol_error`]. Mapping helpers translate HTTP
//! status codes and gRPC status codes into the correct variant per the
//! CONTRACT.md §2 tables.
//!
//! **Security note:** none of these variants may ever carry a raw token
//! value. The mapping helpers below accept a caller-controlled `message`;
//! callers MUST NOT pass token values into it.

use std::error::Error as StdError;
use std::fmt;

/// Why an [`AxiamError::Authz`] was raised (CONTRACT.md §27.4 rule 7).
///
/// §2 permits "language-idiomatic sub-types" of its three error types, and in
/// a language with exceptions that is a subclass. Rust has no subtyping, so
/// the idiomatic form is a discriminant on the variant that already carries
/// the failure: `matches!(e, AxiamError::Authz { .. })` keeps working
/// unchanged, and a caller who needs the distinction reads `kind`.
///
/// The distinction is worth having because these three mean different things
/// to whoever is on the other end. `Denied` says *you may not*; `NotFound`
/// says *there is no such thing — or it is not yours*, which in a multi-tenant
/// IAM is deliberately the same answer; `Conflict` says *something already
/// exists*, and is the one of the three a caller can usually fix.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthzKind {
    /// HTTP 403 — the caller is authenticated and lacks permission. The
    /// default, and what every pre-§27 `Authz` error means.
    #[default]
    Denied,
    /// HTTP 404 — the resource does not exist, **or** belongs to another
    /// tenant. The server answers identically in both cases on purpose: a
    /// distinguishable "exists but not yours" lets a caller enumerate another
    /// tenant's ids.
    NotFound,
    /// HTTP 409 — a uniqueness or state conflict, such as creating a role
    /// whose name is taken. Never retried (§27.4 rule 8): a 409 is the server
    /// telling the truth, not a transient fault.
    Conflict,
}

/// The unified error type returned by all fallible operations in this SDK.
///
/// # Stability of the variant *fields*
///
/// All three variants are `#[non_exhaustive]`. The enum itself is not: §2
/// fixes the taxonomy at exactly three error types, so no fourth variant can
/// ever be added and `match`ing all three exhaustively stays sound. What §2
/// does *not* freeze is each variant's field set — contract 1.4 added
/// `oauth`/`reason` to [`AxiamError::Auth`], and a future contract revision
/// may add more.
///
/// `#[non_exhaustive]` on the variants makes such an addition additive
/// instead of source-breaking:
///
/// * **Matching** — always use `..`: `AxiamError::Auth { message, .. }`,
///   `matches!(e, AxiamError::Network { .. })`. This already compiles today
///   and keeps compiling when fields are added.
/// * **Constructing** — outside this crate, use the constructors
///   ([`AxiamError::auth`], [`AxiamError::authz`], [`AxiamError::network`],
///   [`AxiamError::network_with_source`], [`AxiamError::oauth_protocol_error`],
///   [`AxiamError::id_token_invalid`], [`AxiamError::from_http_status`],
///   [`AxiamError::from_grpc_code`]) rather than struct-variant literals.
#[derive(thiserror::Error, Debug)]
pub enum AxiamError {
    /// Authentication failure: wrong credentials, expired session, MFA
    /// failure, a 401 on refresh, an RFC 6749 OAuth2 protocol error
    /// (CONTRACT.md §12.3 rule 3), or a §12.4 ID-token validation failure
    /// (CONTRACT.md §2).
    ///
    /// Construct with [`AxiamError::auth`] (or one of the more specific
    /// builders); destructure with a trailing `..`.
    #[error("authentication failed: {message}")]
    #[non_exhaustive]
    Auth {
        /// Human-readable description of the failure. MUST NOT contain a
        /// raw token value.
        message: String,
        /// Populated when this failure is specifically an RFC 6749
        /// `OAuth2ErrorResponse` from an `/oauth2/*` endpoint
        /// (CONTRACT.md §12.3 rule 3) — `None` for every other `Auth`
        /// failure. See [`OAuthProtocolError`].
        oauth: Option<OAuthProtocolError>,
        /// A stable, machine-readable reason code, populated by the
        /// CONTRACT.md §12.4 ID-token validation checklist with one of the
        /// seven codes [`IdTokenFailureReason`] enumerates; `None` for every
        /// other `Auth` failure. A *code*, never free text, so callers can
        /// branch on it without parsing `message`.
        reason: Option<IdTokenFailureReason>,
        /// A stable reason code for a refused Security Event Token, populated
        /// by the CONTRACT.md §32.7 receiver helper
        /// ([`crate::ssf::SsfReceiver::verify_set`]); `None` for every other
        /// `Auth` failure. See [`SetFailureReason`].
        set_reason: Option<SetFailureReason>,
        /// The server's `Retry-After` delay, in whole seconds, on a
        /// rate-limited (`429`) `/oauth2/*` response (CONTRACT.md §37.3);
        /// `None` when the response carried none or was not rate limited. A
        /// floor, not a ceiling: wait at least this long before retrying.
        /// Added in the 1.2 line; additive because the variant is
        /// `#[non_exhaustive]`. See [`AxiamError::retry_after`].
        retry_after: Option<std::time::Duration>,
    },

    /// Authorization failure: the caller is authenticated but lacks
    /// permission for the requested operation (CONTRACT.md §2).
    ///
    /// Construct with [`AxiamError::authz`]; destructure with a trailing `..`.
    #[error("authorization denied: {message}")]
    #[non_exhaustive]
    Authz {
        /// Which refusal this is (CONTRACT.md §27.4 rule 7). `Denied` for
        /// every failure that predates §27.
        kind: AuthzKind,
        /// Human-readable description of the failure. MUST NOT contain a
        /// raw token value.
        message: String,
        /// The denied action, if known from the response body.
        action: Option<String>,
        /// The resource the action was denied against, if known.
        resource_id: Option<String>,
        /// The server's machine-readable sub-code of a `409`, read from the
        /// body's `reason_code` member (CONTRACT.md §36.3 rule 2, §36.4;
        /// contract 1.62): `stale_version`, `strands_profile`,
        /// `duplicate_vlan` and so on. A string, because the vocabulary is
        /// **open** (§27.13) — a value this SDK has never seen is surfaced
        /// verbatim. `None` for every refusal that is not a `409`, and for a
        /// `409` whose server predates the member. Read it with
        /// [`AxiamError::reason_code`]; branch on it, never on `message`.
        reason_code: Option<Box<str>>,
    },

    /// Transport-level failure: connection refused, timeout, TLS error, DNS
    /// failure, or a server-side 5xx (CONTRACT.md §2).
    ///
    /// Construct with [`AxiamError::network`] /
    /// [`AxiamError::network_with_source`]; destructure with a trailing `..`.
    #[error("network error: {message}")]
    #[non_exhaustive]
    Network {
        /// Human-readable description of the failure. MUST NOT contain a
        /// raw token value.
        message: String,
        /// The underlying transport error, if any. Boxed as a trait object
        /// so this variant compiles without any transport feature enabled;
        /// later plans may wrap concrete `reqwest`/`tonic`/`lapin` errors
        /// here via `From` impls.
        #[source]
        source: Option<Box<dyn StdError + Send + Sync>>,
    },
}

impl AxiamError {
    /// Build an [`AxiamError::Auth`] carrying just a message — the public
    /// constructor to use instead of a struct-variant literal, so that adding
    /// a field to the variant stays additive (see the type-level docs).
    ///
    /// `message` MUST NOT contain a raw token value.
    pub fn auth(message: impl Into<String>) -> AxiamError {
        AxiamError::Auth {
            message: message.into(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        }
    }

    /// Build an [`AxiamError::Authz`], optionally with the denied `action`
    /// and `resource_id` CONTRACT.md §2 says to carry when the response body
    /// provides them.
    pub fn authz(
        message: impl Into<String>,
        action: Option<String>,
        resource_id: Option<String>,
    ) -> AxiamError {
        AxiamError::authz_kind(AuthzKind::Denied, message, action, resource_id)
    }

    /// Build an [`AxiamError::Authz`] with an explicit [`AuthzKind`].
    ///
    /// [`AxiamError::authz`] is this with `Denied`, which is what every
    /// refusal outside the §27 management surface is.
    pub fn authz_kind(
        kind: AuthzKind,
        message: impl Into<String>,
        action: Option<String>,
        resource_id: Option<String>,
    ) -> AxiamError {
        AxiamError::Authz {
            kind,
            message: message.into(),
            action,
            resource_id,
            reason_code: None,
        }
    }

    /// Build an [`AxiamError::Network`] with no chained transport cause.
    pub fn network(message: impl Into<String>) -> AxiamError {
        AxiamError::Network {
            message: message.into(),
            source: None,
        }
    }

    /// Build an [`AxiamError::Network`] chaining the underlying transport
    /// error as its [`std::error::Error::source`], as CONTRACT.md §2's
    /// construction rules require.
    pub fn network_with_source(
        message: impl Into<String>,
        source: Box<dyn StdError + Send + Sync>,
    ) -> AxiamError {
        AxiamError::Network {
            message: message.into(),
            source: Some(source),
        }
    }

    /// Map an HTTP status code to an [`AxiamError`] variant per CONTRACT.md
    /// §2's HTTP status table.
    ///
    /// | Status       | Variant  |
    /// |--------------|----------|
    /// | 400          | Network  |
    /// | 401          | Auth     |
    /// | 403          | Authz    |
    /// | 408, 429     | Network  |
    /// | 409          | Authz    |
    /// | 5xx          | Network  |
    /// | other        | Network  |
    ///
    /// `message` is caller-controlled and MUST NOT contain a raw token
    /// value.
    ///
    /// For 403/409 (mapped to `Authz`), `message` is also speculatively
    /// parsed as the server's structured error body
    /// (`{"error":"authorization_denied","message":"...","action":"...",
    /// "resource_id":"..."}`) to populate `action`/`resource_id` when the
    /// server included them. `message` itself is left exactly as passed in
    /// (raw body text) — only `action`/`resource_id` are pulled out of the
    /// same body.
    pub fn from_http_status(status: u16, message: impl Into<String>) -> AxiamError {
        let message = message.into();
        match status {
            401 => AxiamError::Auth {
                message,
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            },
            403 | 409 => {
                let (action, resource_id, reason_code) = parse_authz_body_fields(&message);
                AxiamError::Authz {
                    // §2 maps 403 and 409 to the same type; §27.4 rule 7
                    // keeps that mapping and splits only the discriminant.
                    kind: if status == 409 {
                        AuthzKind::Conflict
                    } else {
                        AuthzKind::Denied
                    },
                    message,
                    action,
                    resource_id,
                    // §36.4: only a 409 carries the sub-code.
                    reason_code: if status == 409 {
                        reason_code.map(String::into_boxed_str)
                    } else {
                        None
                    },
                }
            }
            _ => AxiamError::Network {
                message,
                source: None,
            },
        }
    }

    /// Map a gRPC status code (as its numeric `tonic::Code` value) to an
    /// [`AxiamError`] variant per CONTRACT.md §2's gRPC status table.
    ///
    /// | Code                      | Variant  |
    /// |---------------------------|----------|
    /// | 16 UNAUTHENTICATED        | Auth     |
    /// | 7 PERMISSION_DENIED       | Authz    |
    /// | 14 UNAVAILABLE            | Network  |
    /// | 4 DEADLINE_EXCEEDED       | Network  |
    /// | 13 INTERNAL               | Network  |
    /// | 8 RESOURCE_EXHAUSTED      | Network  |
    /// | other                     | Network  |
    ///
    /// `message` is caller-controlled and MUST NOT contain a raw token
    /// value.
    pub fn from_grpc_code(code: i32, message: impl Into<String>) -> AxiamError {
        let message = message.into();
        match code {
            16 => AxiamError::Auth {
                message,
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            },
            // gRPC `PERMISSION_DENIED` carries no structured error body (no
            // JSON payload analogous to the REST 403's
            // `{"action":...,"resource_id":...}`) — `action`/`resource_id`
            // stay `None` here.
            7 => AxiamError::Authz {
                kind: AuthzKind::Denied,
                message,
                action: None,
                resource_id: None,
                reason_code: None,
            },
            _ => AxiamError::Network {
                message,
                source: None,
            },
        }
    }
}

impl AxiamError {
    /// The RFC 6749 `error` code, when this failure carries an
    /// `OAuth2ErrorResponse` body (CONTRACT.md §12.3 rule 3) — `None` for
    /// every other error, including transport failures.
    ///
    /// Added for the CONTRACT.md §14.2 rule 5 dispatch order: the five
    /// device-polling answers all arrive as `400`, which the §2 taxonomy
    /// would map to one indistinguishable error, so the poll loop must
    /// branch on the `error` field **before** the status code. Callers
    /// driving their own poll loop over [`crate::client::AxiamClient::device_poll`]
    /// need the same accessor, which is why it is public rather than
    /// crate-internal.
    ///
    /// ```
    /// # use axiam_sdk::AxiamError;
    /// let e = AxiamError::oauth_protocol_error("slow_down", "polling too fast");
    /// assert_eq!(e.oauth_error_code(), Some("slow_down"));
    /// assert_eq!(AxiamError::network("connection reset").oauth_error_code(), None);
    /// ```
    pub fn oauth_error_code(&self) -> Option<&str> {
        match self {
            AxiamError::Auth { oauth, .. } => oauth.as_ref().map(|o| o.error.as_str()),
            _ => None,
        }
    }

    /// The server's `Retry-After` delay on a rate-limited `/oauth2/*`
    /// response (CONTRACT.md §37.3), when it sent one.
    ///
    /// `None` for every other error. A floor: do not retry sooner.
    pub fn retry_after(&self) -> Option<std::time::Duration> {
        match self {
            AxiamError::Auth { retry_after, .. } => *retry_after,
            _ => None,
        }
    }

    /// Whether this is a transport-level failure that a bounded retry may
    /// resolve — a connection reset, timeout, TLS or DNS failure, or a 5xx.
    ///
    /// CONTRACT.md §14.2 rule 6 makes exactly these non-terminal during
    /// device polling: a server restart mid-flow must not discard a grant
    /// the user has already approved. Distinct from
    /// [`Self::oauth_error_code`], which identifies the *protocol* answers
    /// that terminate a poll.
    pub fn is_retryable_transport(&self) -> bool {
        matches!(self, AxiamError::Network { .. })
    }

    /// Build the `Auth` sub-type for an RFC 6749 `OAuth2ErrorResponse` body
    /// returned by an `/oauth2/*` endpoint (CONTRACT.md §12.3 rule 3,
    /// addendum item 17): a `400` from `POST /oauth2/token` or a `401` from
    /// `POST /oauth2/introspect` / `POST /oauth2/revoke`.
    ///
    /// The result is still `AxiamError::Auth { .. }` — `matches!(err,
    /// AxiamError::Auth { .. })` is `true` for it, so it participates in
    /// every existing "this is an authentication failure" code path — but
    /// its `oauth` field is populated so callers can branch on the RFC 6749
    /// `error` code without parsing `message`. `message` is always exactly
    /// `"<error>: <error_description>"` (CONTRACT.md §2 construction rules).
    pub fn oauth_protocol_error(
        error: impl Into<String>,
        error_description: impl Into<String>,
    ) -> AxiamError {
        let error = error.into();
        let error_description = error_description.into();
        let message = format!("{error}: {error_description}");
        AxiamError::Auth {
            message,
            oauth: Some(OAuthProtocolError {
                error,
                error_description,
            }),
            reason: None,
            set_reason: None,
            retry_after: None,
        }
    }

    /// Build the `Auth` sub-type for a CONTRACT.md §12.4 ID-token validation
    /// failure, carrying the matching stable `reason` code. `detail` is a
    /// short, human-readable explanation; per §2's construction rules it
    /// MUST NOT embed a token, client secret, code verifier, or expected
    /// nonce value.
    pub fn id_token_invalid(reason: IdTokenFailureReason, detail: impl fmt::Display) -> AxiamError {
        AxiamError::Auth {
            message: format!("id_token validation failed ({reason}): {detail}"),
            oauth: None,
            reason: Some(reason),
            set_reason: None,
            retry_after: None,
        }
    }

    /// The structured RFC 6749 `error`/`error_description` pair, when this
    /// is an OAuth2-protocol `Auth` failure (CONTRACT.md §12.3 rule 3).
    /// `None` for every other error, including every other `Auth` failure.
    pub fn as_oauth_protocol_error(&self) -> Option<&OAuthProtocolError> {
        match self {
            AxiamError::Auth {
                oauth: Some(oauth), ..
            } => Some(oauth),
            _ => None,
        }
    }

    /// The stable CONTRACT.md §12.4 ID-token validation reason code, when
    /// this `Auth` failure came from the ID-token validation checklist.
    /// `None` for every other error.
    pub fn id_token_failure_reason(&self) -> Option<IdTokenFailureReason> {
        match self {
            AxiamError::Auth { reason, .. } => *reason,
            _ => None,
        }
    }

    /// Reconstruct this error for a CONTRACT.md §9 rule 2 *waiter*.
    ///
    /// `AxiamError` is not `Clone`, and cannot cheaply become so: the
    /// `Network` variant chains a `Box<dyn std::error::Error + Send + Sync>`
    /// that has no `Clone` bound. §9 rule 2 nonetheless requires the single
    /// in-flight refresh to hand *its* failure to every concurrent waiter, and
    /// a waiter needs **an** error, not a byte-identical one. This therefore
    /// preserves everything a caller can branch on —
    ///
    /// * the taxonomy variant (`Auth` stays `Auth`, never widens to `Network`),
    /// * the `oauth` [`OAuthProtocolError`] payload (`error` +
    ///   `error_description`, so `invalid_grant` is still `invalid_grant`),
    /// * the `reason` [`IdTokenFailureReason`] code,
    /// * the `message` string, and for `Authz` the `action`/`resource_id`
    ///
    /// — and drops only the un-clonable `Network::source` chain, which is a
    /// diagnostic detail rather than something a caller matches on. `Display`
    /// output is byte-identical in every case, because every variant's
    /// `#[error(...)]` format string reads only `message`.
    #[cfg_attr(not(feature = "rest"), allow(dead_code))]
    pub(crate) fn clone_for_waiter(&self) -> AxiamError {
        match self {
            AxiamError::Auth {
                message,
                oauth,
                reason,
                set_reason,
                retry_after,
            } => AxiamError::Auth {
                message: message.clone(),
                oauth: oauth.clone(),
                reason: *reason,
                set_reason: *set_reason,
                retry_after: *retry_after,
            },
            AxiamError::Authz {
                kind,
                message,
                action,
                resource_id,
                reason_code,
            } => AxiamError::Authz {
                kind: *kind,
                message: message.clone(),
                action: action.clone(),
                resource_id: resource_id.clone(),
                reason_code: reason_code.clone(),
            },
            AxiamError::Network { message, .. } => AxiamError::Network {
                message: message.clone(),
                source: None,
            },
        }
    }
}

/// An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an
/// `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).
///
/// A **sub-type of [`AxiamError::Auth`]**, not a replacement for it: it is
/// always carried *inside* an `Auth` value (see
/// [`AxiamError::oauth_protocol_error`]), never a separate top-level
/// variant, so existing `match err { AxiamError::Auth { .. } => .. }` code
/// keeps matching it — that backward compatibility is what makes contract
/// 1.4 additive rather than breaking.
///
/// `error`/`error_description` are the two `OAuth2ErrorResponse` wire
/// fields, exposed individually; [`AxiamError::Auth`]'s `message` field is
/// always exactly `"<error>: <error_description>"`, built from them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthProtocolError {
    /// The RFC 6749 `error` code (e.g. `"invalid_grant"`, `"invalid_client"`,
    /// `"unsupported_grant_type"`).
    pub error: String,
    /// The server's human-readable `error_description`. Never contains
    /// token material.
    pub error_description: String,
}

impl fmt::Display for OAuthProtocolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.error, self.error_description)
    }
}

impl StdError for OAuthProtocolError {}

/// The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for
/// ID-token validation failures ([§12.4](crate) checklist), one per rule.
/// Surfaced via [`AxiamError::id_token_failure_reason`]. `Display` renders
/// the exact wire spelling the contract fixes (e.g. `invalid_alg`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IdTokenFailureReason {
    /// The JOSE header `alg` was not exactly `EdDSA` (§12.4 rule 1).
    InvalidAlg,
    /// The `kid` was absent, or still unknown after one JWKS re-fetch
    /// (§12.4 rule 2).
    UnknownKid,
    /// The Ed25519 signature did not verify against the resolved key
    /// (§12.4 rule 2).
    InvalidSignature,
    /// The `iss` claim did not exactly equal the discovery document's
    /// `issuer` (§12.4 rule 3).
    InvalidIssuer,
    /// The `aud` claim did not contain this client's `client_id`, or
    /// multiple audiences were present with no matching `azp` (§12.4
    /// rule 4).
    InvalidAudience,
    /// `exp`, `iat`, or `nbf` failed the §12.4 rule 5 time checks (beyond
    /// the permitted clock skew, or missing/non-numeric).
    TokenExpired,
    /// The `nonce` claim was absent, non-string, or did not match the
    /// request nonce (§12.4 rule 6).
    NonceMismatch,
}

impl IdTokenFailureReason {
    /// The exact machine-readable wire spelling CONTRACT.md §12.3 rule 3
    /// fixes for this reason code (e.g. `"invalid_alg"`).
    pub fn as_str(self) -> &'static str {
        match self {
            IdTokenFailureReason::InvalidAlg => "invalid_alg",
            IdTokenFailureReason::UnknownKid => "unknown_kid",
            IdTokenFailureReason::InvalidSignature => "invalid_signature",
            IdTokenFailureReason::InvalidIssuer => "invalid_issuer",
            IdTokenFailureReason::InvalidAudience => "invalid_audience",
            IdTokenFailureReason::TokenExpired => "token_expired",
            IdTokenFailureReason::NonceMismatch => "nonce_mismatch",
        }
    }
}

impl fmt::Display for IdTokenFailureReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Best-effort extraction of `action`/`resource_id` out of a REST error
/// body for the `Authz` variant (CONTRACT.md §2: "SHOULD carry the denied
/// `action` and `resource_id` if available from the response body"). The
/// server's structured 403 body looks like:
/// `{"error":"authorization_denied","message":"...","action":"users:get","resource_id":"<uuid>"}`
/// — `action` is present when known, `resource_id` only for a
/// resource-scoped denial. Any parse failure (non-JSON body, missing keys,
/// or a 409 body with a different shape) silently yields all `None`
/// rather than surfacing a secondary error — `action`/`resource_id` are
/// best-effort extras, never load-bearing for the `Authz` variant itself.
///
/// The third member is the `reason_code` of a `409` (CONTRACT.md §36.4,
/// contract 1.62); the caller keeps it only for that status.
fn parse_authz_body_fields(body: &str) -> (Option<String>, Option<String>, Option<String>) {
    #[derive(serde::Deserialize)]
    struct AuthzErrorBody {
        #[serde(default)]
        action: Option<String>,
        #[serde(default)]
        resource_id: Option<String>,
        // Read leniently: a member that is not a string is "absent", and must
        // not cost the `action` and `resource_id` beside it.
        #[serde(default)]
        reason_code: Option<serde_json::Value>,
    }

    match serde_json::from_str::<AuthzErrorBody>(body) {
        Ok(parsed) => (
            parsed.action,
            parsed.resource_id,
            parsed
                .reason_code
                .and_then(|v| v.as_str().map(str::to_string)),
        ),
        Err(_) => (None, None, None),
    }
}

// Manual Display impls are provided by `#[error(...)]` above via thiserror;
// this explicit re-statement documents the redaction invariant for readers
// browsing the source without expanding the derive macro.
#[allow(dead_code)]
fn _assert_no_token_in_display<T: fmt::Display>(_: &T) {}

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

    // Exercises the otherwise-uncalled `_assert_no_token_in_display` helper
    // itself (it exists purely to document the redaction invariant at the
    // type level — no other code path ever calls it).
    #[test]
    fn assert_no_token_in_display_accepts_any_display_error_variant() {
        let auth = AxiamError::auth("msg");
        _assert_no_token_in_display(&auth);
    }

    #[test]
    fn public_constructors_build_the_documented_variants() {
        assert!(matches!(AxiamError::auth("a"), AxiamError::Auth { .. }));
        assert!(matches!(
            AxiamError::authz("b", Some("users:get".into()), None),
            AxiamError::Authz {
                action: Some(_),
                resource_id: None,
                ..
            }
        ));
        assert!(matches!(
            AxiamError::network("c"),
            AxiamError::Network { source: None, .. }
        ));
        let chained = AxiamError::network_with_source("d", Box::new(std::fmt::Error));
        assert!(StdError::source(&chained).is_some());
    }

    /// CONTRACT.md §9 rule 2: waiters receive the leader's outcome. The
    /// taxonomy variant, the `oauth` payload, the `reason` code and the
    /// rendered `Display` must all survive the trip.
    #[test]
    fn clone_for_waiter_preserves_variant_oauth_payload_and_reason() {
        let oauth = AxiamError::oauth_protocol_error("invalid_grant", "refresh token revoked");
        let cloned = oauth.clone_for_waiter();
        assert!(matches!(cloned, AxiamError::Auth { .. }));
        assert_eq!(
            cloned.as_oauth_protocol_error().map(|o| o.error.as_str()),
            Some("invalid_grant")
        );
        assert_eq!(
            cloned
                .as_oauth_protocol_error()
                .map(|o| o.error_description.as_str()),
            Some("refresh token revoked")
        );
        assert_eq!(cloned.to_string(), oauth.to_string());

        let id_token = AxiamError::id_token_invalid(IdTokenFailureReason::NonceMismatch, "nope");
        let cloned = id_token.clone_for_waiter();
        assert_eq!(
            cloned.id_token_failure_reason(),
            Some(IdTokenFailureReason::NonceMismatch)
        );
        assert_eq!(cloned.to_string(), id_token.to_string());
    }

    #[test]
    fn clone_for_waiter_keeps_authz_fields_and_drops_only_the_network_source() {
        let authz = AxiamError::from_http_status(
            403,
            r#"{"action":"users:get","resource_id":"r-1"}"#.to_string(),
        );
        let cloned = authz.clone_for_waiter();
        match cloned {
            AxiamError::Authz {
                ref action,
                ref resource_id,
                ..
            } => {
                assert_eq!(action.as_deref(), Some("users:get"));
                assert_eq!(resource_id.as_deref(), Some("r-1"));
            }
            other => panic!("expected Authz, got {other:?}"),
        }

        let network = AxiamError::network_with_source("boom", Box::new(std::fmt::Error));
        let cloned = network.clone_for_waiter();
        assert!(matches!(cloned, AxiamError::Network { source: None, .. }));
        // Display is unchanged: the format string reads only `message`.
        assert_eq!(cloned.to_string(), network.to_string());
    }
}

/// Why the CONTRACT.md §32.7 receiver helper refused a Security Event Token,
/// one code per step of its verification order. Surfaced via
/// [`AxiamError::set_failure_reason`].
///
/// Four of the seven are RFC 8935 §2.4 `err` values; `malformed`,
/// `invalid_type` and `replayed` are not, so a push endpoint answers
/// `400 {"err": <code>}` with [`Self::push_error_code`], which sends
/// `invalid_request` for those three.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SetFailureReason {
    /// Not three base64url parts decoding to a JSON header and payload (step 1).
    Malformed,
    /// The header `typ` is not `secevent+jwt` / `application/secevent+jwt` (step 2).
    InvalidType,
    /// `alg` not `EdDSA`, no key for `kid` after one refetch, or a bad
    /// signature (steps 3–5).
    InvalidKey,
    /// `iss` is not the configured issuer (step 6).
    InvalidIssuer,
    /// `aud` does not name the configured audience (step 7).
    InvalidAudience,
    /// `exp` or `sub` present, `jti` / `iat` / `sub_id` absent, or `events`
    /// not exactly one member (step 8).
    InvalidRequest,
    /// The `jti` was already seen inside the replay window (step 9).
    Replayed,
}

impl SetFailureReason {
    /// The code as the contract spells it (`"replayed"` included).
    pub fn as_str(self) -> &'static str {
        match self {
            SetFailureReason::Malformed => "malformed",
            SetFailureReason::InvalidType => "invalid_type",
            SetFailureReason::InvalidKey => "invalid_key",
            SetFailureReason::InvalidIssuer => "invalid_issuer",
            SetFailureReason::InvalidAudience => "invalid_audience",
            SetFailureReason::InvalidRequest => "invalid_request",
            SetFailureReason::Replayed => "replayed",
        }
    }

    /// The RFC 8935 §2.4 `err` value to answer a push with, or to send in a
    /// poll's `setErrs`: [`Self::as_str`] where RFC 8935 defines the code, and
    /// `invalid_request` for `replayed`, `malformed` and `invalid_type`, which
    /// it does not (RFC 8935 §2.4 has `invalid_request`, `invalid_key`,
    /// `invalid_issuer`, `invalid_audience`, `authentication_failed` and
    /// `access_denied` only).
    pub fn push_error_code(self) -> &'static str {
        match self {
            SetFailureReason::Replayed
            | SetFailureReason::Malformed
            | SetFailureReason::InvalidType => "invalid_request",
            other => other.as_str(),
        }
    }
}

impl fmt::Display for SetFailureReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl AxiamError {
    /// Build the `Auth` error the §32.7 receiver helper raises for a refused
    /// SET. `detail` MUST NOT contain the SET or any claim value.
    pub fn set_refused(reason: SetFailureReason, detail: impl fmt::Display) -> AxiamError {
        AxiamError::Auth {
            message: format!("security event token refused ({reason}): {detail}"),
            oauth: None,
            reason: None,
            set_reason: Some(reason),
            retry_after: None,
        }
    }

    /// The §32.7 reason code, when this `Auth` failure is a refused SET.
    pub fn set_failure_reason(&self) -> Option<SetFailureReason> {
        match self {
            AxiamError::Auth { set_reason, .. } => *set_reason,
            _ => None,
        }
    }
}