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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
//! `oidc_exchange`, `oidc_refresh`, `login_client_credentials`,
//! `introspect`, `revoke`, `sso_start`, `sso_complete` (CONTRACT.md §12.1).
//!
//! The token endpoint is form-encoded (RFC 6749 §4.1.3, note 1); the
//! federation `sso_*` pair is JSON. `tenant_id` travels as a required
//! **query** parameter on `/oauth2/*` (note 2) — never in the form body —
//! alongside the unconditional §5 `X-Tenant-ID` header.

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::AxiamError;
use crate::Sensitive;
use crate::client::{AxiamClient, OrgIdentifier, TenantIdentifier};
use crate::rest::auth::CsrfHeaderExt;

use super::discovery::{MtlsEndpointAliases, OidcConfiguration};
use super::id_token::{IdTokenClaims, IdTokenExpectations, check_id_token_claims};

/// Path of the federation SSO step-1 endpoint.
pub const SSO_START_PATH: &str = "/api/v1/auth/federation/oidc/start";
/// Path of the federation SSO step-2 (callback) endpoint.
pub const SSO_CALLBACK_PATH: &str = "/api/v1/auth/federation/oidc/callback";

// ---------------------------------------------------------------------------
// Wire types (snake_case, mirror the server schemas verbatim)
// ---------------------------------------------------------------------------

#[derive(Serialize)]
struct TokenRequestForm<'a> {
    grant_type: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    code: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    code_verifier: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    redirect_uri: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    refresh_token: Option<&'a str>,
    client_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_secret: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    scope: Option<&'a str>,
}

#[derive(Serialize)]
struct IntrospectOrRevokeForm<'a> {
    token: &'a str,
    client_id: &'a str,
    client_secret: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    token_type_hint: Option<&'a str>,
}

/// 200 body of `POST /oauth2/token` (wire schema `TokenResponse`).
/// Not `Debug`: it holds the tokens until they are wrapped (§7 rule 1).
#[derive(Deserialize)]
pub(crate) struct TokenResponseWire {
    pub(crate) access_token: String,
    pub(crate) token_type: String,
    pub(crate) expires_in: u64,
    #[serde(default)]
    pub(crate) scope: Option<String>,
    #[serde(default)]
    pub(crate) refresh_token: Option<String>,
    #[serde(default)]
    pub(crate) id_token: Option<String>,
}

/// 200 body of `POST /oauth2/introspect` (wire schema
/// `IntrospectionResponse`).
#[derive(Debug, Deserialize)]
struct IntrospectionResponseWire {
    active: bool,
    #[serde(default)]
    sub: Option<String>,
    #[serde(default)]
    client_id: Option<String>,
    #[serde(default)]
    scope: Option<String>,
    #[serde(default)]
    token_type: Option<String>,
    #[serde(default)]
    exp: Option<i64>,
    #[serde(default)]
    iat: Option<i64>,
}

/// The RFC 6749 error body shape (`OAuth2ErrorResponse`) returned by
/// AXIAM's `/oauth2/*` endpoints. Both fields are required by the schema.
///
/// `error_description` is read leniently: §2's `/oauth2/*` row (and §28.12.3)
/// dispatch on "an error object with a non-empty `error` member", and an
/// RFC 6749 §5.2 / RFC 7591 §3.2.2 server may omit the description.
#[derive(Debug, Deserialize)]
struct OAuth2ErrorResponseWire {
    error: String,
    #[serde(default)]
    error_description: String,
}

#[derive(Serialize)]
struct OidcStartRequestWire {
    federation_config_id: String,
    redirect_uri: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    tenant_id: Option<Uuid>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tenant_slug: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    org_id: Option<Uuid>,
    #[serde(skip_serializing_if = "Option::is_none")]
    org_slug: Option<String>,
}

#[derive(Debug, Deserialize)]
struct OidcStartResponseWire {
    authorize_url: String,
    state: String,
    expires_in_secs: u64,
}

#[derive(Serialize)]
struct OidcPublicCallbackRequestWire<'a> {
    state: &'a str,
    code: &'a str,
}

#[derive(Debug, Deserialize)]
struct SsoLoginSuccessResponseWire {
    user_id: Uuid,
    session_id: Uuid,
    expires_in: u64,
    redirect_uri: String,
}

// ---------------------------------------------------------------------------
// Public SDK types
// ---------------------------------------------------------------------------

/// A token set returned by the OAuth2 token endpoint (wire schema
/// `TokenResponse`), returned by `oidc_exchange`, `oidc_refresh` and
/// `login_client_credentials`.
///
/// `access_token`, `refresh_token` and `id_token` are [`Sensitive`] (§12.5).
/// `id_claims` is present exactly when `id_token` is, and holds the
/// **already-validated** claim set (§12.4) — validation happens before this
/// struct is ever constructed, so an `OidcTokenSet` in your hands is never
/// partially trusted (§12.4 rule 7).
///
/// `Clone` is implemented so the single in-flight `oidc_refresh` can hand the
/// *same* token set to every concurrent waiter (CONTRACT.md §9 rule 2). It
/// clones the [`Sensitive`] wrappers, never unwraps them: a clone redacts
/// exactly as the original does.
#[derive(Debug, Clone)]
pub struct OidcTokenSet {
    /// The OAuth2 access token (§12.5 secret).
    pub access_token: Sensitive<String>,
    /// The token type the server issued (`Bearer`).
    pub token_type: String,
    /// Access-token lifetime in seconds from the time of the response.
    pub expires_in: u64,
    /// The granted scope, as this response states it. After `oidc_refresh`
    /// it is the token's scope, which may be narrower than the original
    /// grant's when the client's registration was narrowed since (§12.1,
    /// contract 1.60): never assume the two are equal. `None` when the
    /// response carried none.
    pub scope: Option<String>,
    /// The refresh token, when the grant issued one (§12.5 secret).
    pub refresh_token: Option<Sensitive<String>>,
    /// The raw ID token, when the grant issued one (§12.5 secret).
    pub id_token: Option<Sensitive<String>>,
    /// The validated ID-token claims — present exactly when [`Self::id_token`]
    /// is.
    pub id_claims: Option<IdTokenClaims>,
}

/// Arguments to `oidc_exchange` (`grant_type=authorization_code`).
pub struct OidcExchangeParams {
    /// The authorization code the IdP redirected back with.
    pub code: String,
    /// The verifier from the matching [`super::AuthorizationRequest`].
    pub code_verifier: Sensitive<String>,
    /// The same `redirect_uri` that was sent on the authorization request.
    pub redirect_uri: String,
    /// The `nonce` from the matching [`super::AuthorizationRequest`].
    /// MANDATORY — §12.4 rule 6 is not optional for this grant.
    pub nonce: String,
    /// Tenant UUID for the token endpoint's required `tenant_id` query
    /// parameter. Defaults to the client's configured tenant when it was
    /// built in UUID form (§12.3 rule 4).
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document, to avoid re-reading the (cached)
    /// one. Fetched via `oidc_discover` when `None`.
    pub configuration: Option<OidcConfiguration>,
}

/// Arguments to `oidc_refresh` (`grant_type=refresh_token`).
pub struct OidcRefreshParams {
    /// The refresh token to redeem.
    pub refresh_token: Sensitive<String>,
    /// Optional narrowed scope to request. Omitted from the form body when
    /// absent.
    pub scope: Option<String>,
    /// Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4).
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document. Fetched via `oidc_discover` when
    /// `None`.
    pub configuration: Option<OidcConfiguration>,
}

/// Arguments to `login_client_credentials` (`grant_type=client_credentials`).
#[derive(Default)]
pub struct LoginClientCredentialsParams {
    /// Optional scope to request. This grant requests no `openid` scope and
    /// the response carries no `id_token` (§12.1).
    pub scope: Option<String>,
    /// Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4).
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document. Fetched via `oidc_discover` when
    /// `None`.
    pub configuration: Option<OidcConfiguration>,
}

/// Arguments to `introspect` (RFC 7662). Requires confidential-client
/// credentials (§12.1 note 4).
pub struct IntrospectParams {
    /// The token to introspect.
    pub token: Sensitive<String>,
    /// Optional RFC 7662 `token_type_hint` (`access_token`/`refresh_token`).
    pub token_type_hint: Option<String>,
    /// Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4).
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document. Fetched via `oidc_discover` when
    /// `None`.
    pub configuration: Option<OidcConfiguration>,
}

/// Arguments to `revoke` (RFC 7009). Requires confidential-client
/// credentials (§12.1 note 4).
pub struct RevokeParams {
    /// The token to revoke.
    pub token: Sensitive<String>,
    /// Optional RFC 7009 `token_type_hint`.
    pub token_type_hint: Option<String>,
    /// Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4).
    pub tenant_id: Option<Uuid>,
    /// A pre-fetched discovery document. Fetched via `oidc_discover` when
    /// `None`.
    pub configuration: Option<OidcConfiguration>,
}

/// The RFC 7662 introspection result (wire schema
/// `IntrospectionResponse`). Only `active` is guaranteed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IntrospectionResult {
    /// Whether the token is currently active.
    pub active: bool,
    /// Subject the token was issued to.
    pub sub: Option<String>,
    /// Client the token was issued to.
    pub client_id: Option<String>,
    /// Scope granted to the token.
    pub scope: Option<String>,
    /// Token type (`Bearer`).
    pub token_type: Option<String>,
    /// Expiry time, epoch seconds.
    pub exp: Option<i64>,
    /// Issued-at time, epoch seconds.
    pub iat: Option<i64>,
}

/// Arguments to `sso_start` (`POST /api/v1/auth/federation/oidc/start`).
#[derive(Default)]
pub struct SsoStartParams {
    /// UUID of the server-side federation configuration identifying the
    /// upstream IdP.
    pub federation_config_id: String,
    /// Post-login destination, stored server-side and echoed back by
    /// `sso_complete`.
    pub redirect_uri: String,
    /// Tenant UUID. One tenant form (`tenant_id` or `tenant_slug`) is
    /// required; defaults to the client's configuration (§5.1).
    pub tenant_id: Option<Uuid>,
    /// Tenant slug. Alternative to [`Self::tenant_id`].
    pub tenant_slug: Option<String>,
    /// Organization UUID. One org form (`org_id` or `org_slug`) is
    /// required; defaults to the client's configuration (§5.1).
    pub org_id: Option<Uuid>,
    /// Organization slug. Alternative to [`Self::org_id`].
    pub org_slug: Option<String>,
}

/// The result of `sso_start` (wire schema `OidcStartResponse`).
///
/// There is deliberately **no nonce**: on the federation path the nonce
/// never leaves the server (§12.1 note 7). Round-trip [`Self::state`] into
/// `sso_complete` unmodified.
#[derive(Debug, Clone)]
pub struct SsoStartResult {
    /// The upstream IdP authorization URL to redirect the user agent to.
    pub authorize_url: String,
    /// Single-use CSRF state to round-trip back into `sso_complete`
    /// unmodified.
    pub state: String,
    /// Remaining TTL of the server-side state row, in seconds (600 = 10
    /// min).
    pub expires_in_secs: u64,
}

/// Arguments to `sso_complete`
/// (`POST /api/v1/auth/federation/oidc/callback`).
pub struct SsoCompleteParams {
    /// The `state` value the IdP redirected back with — must be the one
    /// `sso_start` returned.
    pub state: String,
    /// The authorization code the IdP redirected back with.
    pub code: String,
}

/// The result of `sso_complete` (wire schema `SsoLoginSuccessResponse`).
///
/// Carries **no token material** — the session arrives as `Set-Cookie`
/// (§12.1 note 6), captured automatically by this client's existing §4
/// cookie jar (the same `reqwest::cookie::Jar` every other REST call uses).
#[derive(Debug, Clone)]
pub struct SsoCompleteResult {
    /// The provisioned/linked user's UUID.
    pub user_id: Uuid,
    /// The established session's UUID.
    pub session_id: Uuid,
    /// Session/access-token lifetime in seconds.
    pub expires_in: u64,
    /// The post-login destination that was stored during `sso_start`.
    pub redirect_uri: String,
}

// ---------------------------------------------------------------------------
// Internals shared across the nine operations
// ---------------------------------------------------------------------------

/// Map a non-2xx `/oauth2/*` response onto the §2 taxonomy: an
/// `OAuth2ErrorResponse`-shaped body becomes [`AxiamError::oauth_protocol_error`]
/// (CONTRACT.md §12.3 rule 3); anything else falls back to the generic
/// [`AxiamError::from_http_status`] mapping.
pub(crate) async fn oauth2_error_or_fallback(response: reqwest::Response) -> AxiamError {
    let status = response.status().as_u16();
    // CONTRACT.md §12.1 rule 3: a `3xx` answer to an `/oauth2/*` POST is a
    // `NetworkError`, whatever its body says. The status is checked *before*
    // the body so an intermediary's `{"error":…}` cannot turn a redirect into
    // an `OAuthProtocolError`. The body is neither read nor echoed.
    if (300..400).contains(&status) {
        return AxiamError::Network {
            message: format!(
                "unexpected redirect (HTTP {status}) from an OAuth2 endpoint; not followed"
            ),
            source: None,
        };
    }
    let retry_after = response
        .headers()
        .get(reqwest::header::RETRY_AFTER)
        .and_then(|v| v.to_str().ok())
        .and_then(crate::retry::parse_retry_after);
    let text = response
        .text()
        .await
        .unwrap_or_else(|_| "no response body".to_string());
    if let Ok(body) = serde_json::from_str::<OAuth2ErrorResponseWire>(&text)
        && !body.error.is_empty()
    {
        let mut err = AxiamError::oauth_protocol_error(body.error, body.error_description);
        // §37.3: surfaced on the 429 only (a stray header elsewhere is noise).
        if status == 429
            && let AxiamError::Auth {
                retry_after: slot, ..
            } = &mut err
        {
            *slot = retry_after;
        }
        return err;
    }
    AxiamError::from_http_status(status, text)
}

pub(crate) fn network_err(context: &str, e: reqwest::Error) -> AxiamError {
    AxiamError::Network {
        message: format!("{context}: {e}"),
        source: Some(Box::new(e)),
    }
}

/// Refuse an `mtls_endpoint_aliases` entry that cannot carry a client
/// certificate (CONTRACT.md §21.3.1 vector C).
///
/// Two defects, and each is a refusal on its own:
///
/// * **Not absolute.** A relative alias resolves against nothing a client
///   holds. There is no sensible base — the issuer's host is precisely the host
///   the alias exists to name a different one from.
/// * **A scheme weaker than the endpoint it replaces.** An alias substitutes
///   for exactly one top-level endpoint, so that is what it is compared
///   against: an `http` alias for an `https` `token_endpoint` is a downgrade,
///   and mutual TLS over cleartext is a contradiction rather than a weaker
///   option.
///
/// Comparing like with like is the only test that is true in every topology,
/// and the two obvious alternatives both fail. "The alias must be `https`"
/// refuses the dev and test stacks AXIAM ships — `build_mtls_aliases` accepts
/// `http` for local development, and this crate's own suite runs against a
/// mock server that speaks plain HTTP. "Weaker than the `issuer`" refuses them
/// too, because a fixture pairs a realistic issuer string with loopback
/// endpoints, exactly as a deployment behind a TLS-terminating proxy may.
///
/// Called only from [`AxiamClient::mtls_alias`], and therefore only when this
/// call actually presents a certificate: a client configured without one must
/// not be broken by a member it never reads.
fn validate_mtls_alias(alias: &str, replaces: &str) -> Result<(), AxiamError> {
    let url = url::Url::parse(alias).map_err(|e| AxiamError::Network {
        message: format!(
            "mtls_endpoint_aliases publishes {alias:?}, which is not an absolute URL ({e}). \
             Refusing rather than falling back to the top-level endpoint: this call presents a \
             client certificate, and sending it to the front-channel host would authenticate \
             nothing while appearing to work."
        ),
        source: None,
    })?;
    let replaced_is_tls = url::Url::parse(replaces).is_ok_and(|e| e.scheme() == "https");
    if replaced_is_tls && url.scheme() != "https" {
        return Err(AxiamError::Network {
            message: format!(
                "mtls_endpoint_aliases publishes {alias:?}, whose scheme is {:?}, in place of \
                 an https endpoint. That is a downgrade, and mutual TLS over cleartext is a \
                 contradiction; refusing rather than falling back to the top-level endpoint.",
                url.scheme()
            ),
            source: None,
        });
    }
    Ok(())
}

impl AxiamClient {
    /// The configured §12 `client_id`, or a client-side [`AxiamError::Auth`]
    /// (no wire call) when none was configured.
    pub(crate) fn oidc_client_id_or_err(&self) -> Result<&str, AxiamError> {
        self.oidc_client_id().ok_or_else(|| AxiamError::Auth {
            message:
                "this OIDC operation requires a client_id: build the client with .oidc_client_id(...) (CONTRACT.md §12.1)"
                    .into(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        })
    }

    /// The configured §12 `client_secret`, or a client-side
    /// [`AxiamError::Auth`] (no wire call) for an operation that cannot be
    /// performed by a public client (§12.1 note 4).
    pub(crate) fn oidc_client_secret_or_err(&self, operation: &str) -> Result<String, AxiamError> {
        self.oidc_client_secret()
            .map(|s| s.expose().clone())
            .ok_or_else(|| AxiamError::Auth {
                message: format!(
                    "{operation} requires confidential-client credentials: build the client with .oidc_client_secret(...) (CONTRACT.md §12.1 note 4)"
                ),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            })
    }

    /// Resolve the tenant UUID for the `/oauth2/*` `tenant_id` query
    /// parameter (§12.3 rule 4): the explicit argument, else the client's
    /// resolved tenant, else a client-side [`AxiamError::Auth`] (no wire
    /// call) — a slug-only, not-yet-logged-in client cannot fill this.
    pub(crate) async fn resolve_oidc_tenant_id(
        &self,
        explicit: Option<Uuid>,
    ) -> Result<Uuid, AxiamError> {
        if let Some(id) = explicit {
            return Ok(id);
        }
        self.resolved_tenant_id().await.ok_or_else(|| AxiamError::Auth {
            message:
                "this operation requires a tenant_id UUID for the /oauth2 query parameter: pass tenant_id explicitly, or construct the client with the tenant_id (UUID) form (CONTRACT.md §12.3 rule 4)"
                    .into(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        })
    }

    /// Whether this client presents a §6.1 mTLS client certificate, and so
    /// whether CONTRACT.md §21.3 rule 2 applies to the calls it makes.
    ///
    /// The identity is configured once on the builder and presented on every
    /// request the client issues, so "is this call going over mutual TLS" has
    /// a whole-client answer here rather than a per-call one.
    pub(crate) fn presents_client_certificate(&self) -> bool {
        self.inner.client_cert_pem.is_some()
    }

    /// The RFC 8705 §5 alias for an always-advertised endpoint, falling back
    /// to the top-level entry (CONTRACT.md §21.3 rule 2).
    ///
    /// Three things this deliberately does NOT do, each of them a documented
    /// way to get rule 2 wrong:
    ///
    /// * An absent `mtls_endpoint_aliases` is never an error. It means "no
    ///   separate mTLS host", not "mTLS unsupported" — a deployment running
    ///   `client_auth = optional` on one listener serves both populations at
    ///   the conventional endpoints and correctly publishes nothing.
    /// * The `select` closure can only reach [`MtlsEndpointAliases`], so
    ///   `authorization_endpoint`, `end_session_endpoint` and `jwks_uri` are
    ///   unreachable rather than merely unused: they are front-channel or
    ///   public, and an mTLS host would raise a certificate-chooser dialog in
    ///   the user's browser.
    /// * `issuer` is untouched. It is an identifier, not an endpoint, and
    ///   §12.4 rule 3 still compares a token's `iss` against
    ///   `configuration.issuer` by exact string — including for a token
    ///   minted at an alias endpoint.
    pub(crate) fn mtls_preferred<'a>(
        &self,
        configuration: &'a OidcConfiguration,
        select: impl Fn(&'a MtlsEndpointAliases) -> Option<&'a str>,
        top_level: &'a str,
    ) -> Result<&'a str, AxiamError> {
        Ok(self
            .mtls_alias(configuration, select, Some(top_level))?
            .unwrap_or(top_level))
    }

    /// The alias itself, or `None` when this call is not going over mTLS, the
    /// document publishes no aliases, or it publishes none for this endpoint.
    ///
    /// An alias that is present and **unusable** is an error, never a fallback
    /// (CONTRACT.md §21.3.1 vector C, contract 1.43). Falling back is the
    /// dangerous answer and not the safe one: the caller asked to authenticate
    /// with a certificate, the operator published something that cannot carry
    /// one, and quietly presenting the certificate to the front-channel host
    /// authenticates nothing while appearing to work.
    fn mtls_alias<'a>(
        &self,
        configuration: &'a OidcConfiguration,
        select: impl Fn(&'a MtlsEndpointAliases) -> Option<&'a str>,
        replaces: Option<&str>,
    ) -> Result<Option<&'a str>, AxiamError> {
        if !self.presents_client_certificate() {
            // A client with no certificate does not read the member at all —
            // not even to validate it. A deployment whose aliases are
            // malformed must not break the clients that never use them.
            return Ok(None);
        }
        let Some(alias) = configuration
            .mtls_endpoint_aliases
            .as_ref()
            .and_then(select)
        else {
            return Ok(None);
        };
        validate_mtls_alias(alias, replaces.unwrap_or(""))?;
        Ok(Some(alias))
    }

    /// The same preference for a conditionally-advertised endpoint. `None`
    /// still means "this server does not support the feature" — the caller
    /// raises that, and never concatenates a URL onto the issuer.
    pub(crate) fn mtls_preferred_opt<'a>(
        &self,
        configuration: &'a OidcConfiguration,
        select: impl Fn(&'a MtlsEndpointAliases) -> Option<&'a str>,
        top_level: Option<&'a str>,
    ) -> Result<Option<&'a str>, AxiamError> {
        Ok(self
            .mtls_alias(configuration, select, top_level)?
            .or(top_level))
    }

    /// Build the token/introspection/revocation endpoint URL with the
    /// mandatory `?tenant_id=<uuid>` query parameter (§12.1 note 2).
    ///
    /// **Replaces rather than appends.** Since contract 1.42 the discovery
    /// document publishes the tenant *inside* the endpoint URLs it
    /// advertises — every endpoint that authenticates a client gets
    /// `?tenant_id=<uuid>` server-side, whenever the discovery request named
    /// a tenant or the deployment configures a default one. Appending a
    /// second `tenant_id` to such a URL produces
    /// `?tenant_id=A&tenant_id=B`, which is not a parameter the server can
    /// deserialise into one `Uuid`.
    ///
    /// Every *other* query parameter the endpoint carries is preserved:
    /// RFC 6749 §3.1 and §3.2 both require a client adding parameters of its
    /// own to retain the endpoint's existing query component, and that is the
    /// mechanism this whole arrangement relies on.
    ///
    /// The resolved tenant wins when the two disagree. It is the one the
    /// caller or the current session actually authenticated against, and a
    /// deterministic answer is worth more here than a silent mismatch
    /// between the tenant in the URL and the tenant in the `X-Tenant-ID`
    /// header that accompanies it.
    pub(crate) fn oidc_endpoint_url(
        &self,
        endpoint: &str,
        tenant_id: Uuid,
    ) -> Result<url::Url, AxiamError> {
        let mut url = url::Url::parse(endpoint).map_err(|e| AxiamError::Network {
            message: format!("invalid endpoint URL in discovery document: {e}"),
            source: None,
        })?;

        // Rebuild the query only when there is a `tenant_id` to displace.
        // Appending to an untouched query keeps it byte-for-byte as the
        // server wrote it; round-tripping every pair through
        // `append_pair` would re-encode it, and an endpoint's own query is
        // not this SDK's to normalise.
        let has_tenant = url.query_pairs().any(|(k, _)| k == "tenant_id");
        if has_tenant {
            // Collected first: `query_pairs_mut` borrows the URL mutably
            // and cannot run while `query_pairs` is still reading it.
            let retained: Vec<(String, String)> = url
                .query_pairs()
                .filter(|(k, _)| k != "tenant_id")
                .map(|(k, v)| (k.into_owned(), v.into_owned()))
                .collect();
            url.set_query(None);
            let mut pairs = url.query_pairs_mut();
            for (k, v) in &retained {
                pairs.append_pair(k, v);
            }
            pairs.append_pair("tenant_id", &tenant_id.to_string());
        } else {
            url.query_pairs_mut()
                .append_pair("tenant_id", &tenant_id.to_string());
        }
        Ok(url)
    }

    pub(crate) async fn post_token<F: Serialize + ?Sized>(
        &self,
        configuration: &OidcConfiguration,
        form: &F,
        tenant_id: Uuid,
    ) -> Result<TokenResponseWire, AxiamError> {
        let endpoint = self.mtls_preferred(
            configuration,
            |a| a.token_endpoint.as_deref(),
            &configuration.token_endpoint,
        )?;
        let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
        let response = self
            .idp_form_post(url)
            .form(form)
            .send()
            .await
            .map_err(|e| network_err("token request failed", e))?;

        if !response.status().is_success() {
            return Err(oauth2_error_or_fallback(response).await);
        }
        response
            .json::<TokenResponseWire>()
            .await
            .map_err(|e| network_err("failed to parse token response", e))
    }

    /// Convert a `TokenResponse` into an [`OidcTokenSet`], validating any
    /// `id_token` first (§12.4). Validation precedes construction, so a
    /// failure discards the whole set (§12.4 rule 7).
    pub(crate) async fn to_token_set(
        &self,
        wire: TokenResponseWire,
        configuration: &OidcConfiguration,
        nonce: Option<&str>,
    ) -> Result<OidcTokenSet, AxiamError> {
        let id_claims = match &wire.id_token {
            Some(id_token) => {
                let verifier = self.oidc_verifier_for(&configuration.jwks_uri)?;
                let claims: IdTokenClaims = verifier.verify_id_token_signature(id_token).await?;
                let expectations = IdTokenExpectations {
                    issuer: &configuration.issuer,
                    client_id: self.oidc_client_id_or_err()?,
                    nonce,
                    clock_skew_sec: self.oidc_clock_skew_sec(),
                };
                let now_sec = crate::time::SystemTime::now()
                    .duration_since(crate::time::UNIX_EPOCH)
                    .map(|d| d.as_secs() as i64)
                    .unwrap_or(0);
                Some(check_id_token_claims(claims, &expectations, now_sec)?)
            }
            None => None,
        };

        Ok(OidcTokenSet {
            access_token: Sensitive::new(wire.access_token),
            token_type: wire.token_type,
            expires_in: wire.expires_in,
            scope: wire.scope,
            refresh_token: wire.refresh_token.map(Sensitive::new),
            id_token: wire.id_token.map(Sensitive::new),
            id_claims,
        })
    }
}

// ---------------------------------------------------------------------------
// The seven remaining canonical operations (`oidc_discover`/`oidc_begin`
// live in `discovery.rs`/`authorize.rs`)
// ---------------------------------------------------------------------------

impl AxiamClient {
    /// `POST /oauth2/token` with `grant_type=authorization_code`
    /// (CONTRACT.md §12.1) — exchange an authorization code for a token
    /// set, validating the returned ID token in full before returning.
    ///
    /// If **any** §12.4 rule fails, the whole token set is discarded and
    /// the matching `AxiamError` reason code is raised — the access and
    /// refresh tokens from the same response are never returned (rule 7).
    pub async fn oidc_exchange(
        &self,
        params: OidcExchangeParams,
    ) -> Result<OidcTokenSet, AxiamError> {
        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
        let client_id = self.oidc_client_id_or_err()?.to_string();
        let client_secret = self.oidc_client_secret().map(|s| s.expose().clone());

        let form = TokenRequestForm {
            grant_type: "authorization_code",
            code: Some(&params.code),
            code_verifier: Some(params.code_verifier.expose().as_str()),
            redirect_uri: Some(&params.redirect_uri),
            refresh_token: None,
            client_id: &client_id,
            client_secret: client_secret.as_deref(),
            scope: None,
        };

        let wire = self.post_token(&configuration, &form, tenant_id).await?;
        self.to_token_set(wire, &configuration, Some(&params.nonce))
            .await
    }

    /// `POST /oauth2/token` with `grant_type=refresh_token` (CONTRACT.md
    /// §12.1) — refresh an [`OidcTokenSet`], under the §9 single-flight
    /// refresh guard.
    ///
    /// A **distinct operation** from [`AxiamClient::refresh`], which drives
    /// the cookie/opaque-token session path at `POST /api/v1/auth/refresh`.
    /// The two are never merged or aliased.
    ///
    /// An `id_token` in the response is validated against rules 1–5 and 7;
    /// rule 6 (nonce) is skipped (OIDC Core §12.2 does not require a nonce
    /// in a refresh-issued ID token).
    ///
    /// # Concurrency (CONTRACT.md §9)
    ///
    /// A burst of N concurrent calls produces **exactly one**
    /// `POST /oauth2/token` and every one of the N callers receives that one
    /// call's outcome — the same [`OidcTokenSet`] on success, an equivalent
    /// error (same variant, same `oauth` payload, same `reason`) on failure.
    /// This is §9 rule 2's observable requirement, and it is not optional:
    /// AXIAM refresh tokens are single-use with rotation, so N independent
    /// wire calls would mean N−1 replays of a consumed token, each failing
    /// `invalid_grant`. The coalescer lives in `src/oidc/single_flight.rs` — a
    /// dedicated instance, as §9 rule 5 permits. There is no retry loop
    /// anywhere on this path (§9 rule 3).
    pub async fn oidc_refresh(
        &self,
        params: OidcRefreshParams,
    ) -> Result<OidcTokenSet, AxiamError> {
        use super::single_flight::{OidcRefreshCancelled, OidcRefreshElection};

        // §9 rules 1 + 2: elect one leader per burst; everyone else waits for
        // the leader's outcome and issues no wire call of its own.
        let leader = match self.oidc_refresh_election() {
            OidcRefreshElection::Waiter(waiter) => {
                return match waiter.wait().await {
                    Ok(Ok(tokens)) => Ok(tokens),
                    Ok(Err(shared)) => Err(shared.clone_for_waiter()),
                    // The leader's future was cancelled before it published
                    // (see `single_flight`'s Drop impl). §9 rule 3 forbids a
                    // retry loop, so this surfaces as an auth failure and the
                    // caller decides what to do next.
                    Err(OidcRefreshCancelled) => Err(AxiamError::auth(
                        "the in-flight oidc_refresh was cancelled before completing; retry or re-authenticate (CONTRACT.md §9)",
                    )),
                };
            }
            OidcRefreshElection::Leader(leader) => leader,
        };

        let result = self.oidc_refresh_wire_call(params).await;
        leader.publish(&result);
        result
    }

    /// The actual single `POST /oauth2/token?grant_type=refresh_token` wire
    /// call, performed by the elected leader only.
    async fn oidc_refresh_wire_call(
        &self,
        params: OidcRefreshParams,
    ) -> Result<OidcTokenSet, AxiamError> {
        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
        let client_id = self.oidc_client_id_or_err()?.to_string();
        let client_secret = self.oidc_client_secret().map(|s| s.expose().clone());

        let form = TokenRequestForm {
            grant_type: "refresh_token",
            code: None,
            code_verifier: None,
            redirect_uri: None,
            refresh_token: Some(params.refresh_token.expose().as_str()),
            client_id: &client_id,
            client_secret: client_secret.as_deref(),
            scope: params.scope.as_deref(),
        };

        let wire = self.post_token(&configuration, &form, tenant_id).await?;
        self.to_token_set(wire, &configuration, None).await
    }

    /// `POST /oauth2/token` with `grant_type=client_credentials`
    /// (CONTRACT.md §12.1) — service-account machine-to-machine login.
    ///
    /// Requests no `openid` scope, so the response carries no `id_token`.
    ///
    /// # Errors
    /// A client-side [`AxiamError::Auth`] when no `client_secret` is
    /// configured — this grant cannot be performed by a public client.
    pub async fn login_client_credentials(
        &self,
        params: LoginClientCredentialsParams,
    ) -> Result<OidcTokenSet, AxiamError> {
        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
        let client_id = self.oidc_client_id_or_err()?.to_string();
        let client_secret = self.oidc_client_secret_or_err("login_client_credentials")?;

        let form = TokenRequestForm {
            grant_type: "client_credentials",
            code: None,
            code_verifier: None,
            redirect_uri: None,
            refresh_token: None,
            client_id: &client_id,
            client_secret: Some(&client_secret),
            scope: params.scope.as_deref(),
        };

        let wire = self.post_token(&configuration, &form, tenant_id).await?;
        // No nonce: rule 6 does not apply to this grant.
        self.to_token_set(wire, &configuration, None).await
    }

    /// `POST /oauth2/introspect` (RFC 7662, CONTRACT.md §12.1) — ask the
    /// server whether a token is active and, if so, for its metadata.
    ///
    /// Requires confidential-client credentials (§12.1 note 4). A `401`
    /// here is a *client-credential* failure surfaced as
    /// [`AxiamError::oauth_protocol_error`]; it never enters the §9
    /// single-flight refresh guard (§12.3 rule 3) — this method does not
    /// touch that guard at all.
    pub async fn introspect(
        &self,
        params: IntrospectParams,
    ) -> Result<IntrospectionResult, AxiamError> {
        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
        let client_id = self.oidc_client_id_or_err()?.to_string();
        let client_secret = self.oidc_client_secret_or_err("introspect")?;

        let endpoint = self.mtls_preferred(
            &configuration,
            |a| a.introspection_endpoint.as_deref(),
            &configuration.introspection_endpoint,
        )?;
        let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
        let form = IntrospectOrRevokeForm {
            token: params.token.expose().as_str(),
            client_id: &client_id,
            client_secret: &client_secret,
            token_type_hint: params.token_type_hint.as_deref(),
        };

        let response = self
            .idp_form_post(url)
            .form(&form)
            .send()
            .await
            .map_err(|e| network_err("introspect request failed", e))?;

        if !response.status().is_success() {
            return Err(oauth2_error_or_fallback(response).await);
        }

        let wire: IntrospectionResponseWire = response
            .json()
            .await
            .map_err(|e| network_err("failed to parse introspect response", e))?;

        Ok(IntrospectionResult {
            active: wire.active,
            sub: wire.sub,
            client_id: wire.client_id,
            scope: wire.scope,
            token_type: wire.token_type,
            exp: wire.exp,
            iat: wire.iat,
        })
    }

    /// `POST /oauth2/revoke` (RFC 7009, CONTRACT.md §12.1) — revoke an
    /// access or refresh token.
    ///
    /// Per RFC 7009 the server answers `200` for unknown, expired and
    /// already-revoked tokens alike, so revocation is **idempotent**: any
    /// `200` is success. Only a `401` (client authentication failed) is an
    /// error, surfaced as [`AxiamError::oauth_protocol_error`].
    ///
    /// # Errors
    /// A client-side [`AxiamError::Auth`] when no `client_secret` is
    /// configured.
    pub async fn revoke(&self, params: RevokeParams) -> Result<(), AxiamError> {
        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
        let client_id = self.oidc_client_id_or_err()?.to_string();
        let client_secret = self.oidc_client_secret_or_err("revoke")?;

        let endpoint = self.mtls_preferred(
            &configuration,
            |a| a.revocation_endpoint.as_deref(),
            &configuration.revocation_endpoint,
        )?;
        let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
        let form = IntrospectOrRevokeForm {
            token: params.token.expose().as_str(),
            client_id: &client_id,
            client_secret: &client_secret,
            token_type_hint: params.token_type_hint.as_deref(),
        };

        let response = self
            .idp_form_post(url)
            .form(&form)
            .send()
            .await
            .map_err(|e| network_err("revoke request failed", e))?;

        if !response.status().is_success() {
            return Err(oauth2_error_or_fallback(response).await);
        }
        Ok(())
    }

    /// `POST /api/v1/auth/federation/oidc/start` (CONTRACT.md §12.1) — step
    /// 1 of first-time SSO against an **upstream** IdP. No JWT required.
    ///
    /// One tenant form (`tenant_id`/`tenant_slug`) and one org form
    /// (`org_id`/`org_slug`) must be resolvable, from the arguments or from
    /// the client's construction-time configuration (§5.1). Redirect to the
    /// returned `authorize_url` and round-trip `state` back into
    /// [`Self::sso_complete`] unmodified.
    ///
    /// # Errors
    /// A client-side [`AxiamError::Auth`] (no wire call) when tenant or org
    /// context cannot be resolved.
    pub async fn sso_start(&self, params: SsoStartParams) -> Result<SsoStartResult, AxiamError> {
        // Tenant context always resolves: `TenantIdentifier` is a two-variant
        // enum and §5 guarantees the builder set one of them, so unlike the
        // organization pair below there is no unresolvable case to guard
        // against here.
        let (tenant_id, tenant_slug) = match (params.tenant_id, params.tenant_slug) {
            (Some(id), _) => (Some(id), None),
            (None, Some(slug)) => (None, Some(slug)),
            (None, None) => match &self.inner.tenant {
                TenantIdentifier::Id(id) => (Some(*id), None),
                TenantIdentifier::Slug(slug) => (None, Some(slug.clone())),
            },
        };

        let (org_id, org_slug) = match (params.org_id, params.org_slug) {
            (Some(id), _) => (Some(id), None),
            (None, Some(slug)) => (None, Some(slug)),
            (None, None) => match self.org_identifier() {
                Some(OrgIdentifier::Id(id)) => (Some(*id), None),
                Some(OrgIdentifier::Slug(slug)) => (None, Some(slug.clone())),
                None => (self.resolved_org_id(), None),
            },
        };
        if org_id.is_none() && org_slug.is_none() {
            return Err(AxiamError::Auth {
                message:
                    "sso_start requires organization context: pass org_id or org_slug, or construct the client with one (CONTRACT.md §5.1)"
                        .into(),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            });
        }

        let body = OidcStartRequestWire {
            federation_config_id: params.federation_config_id,
            redirect_uri: params.redirect_uri,
            tenant_id,
            tenant_slug,
            org_id,
            org_slug,
        };

        let url = self
            .base_url()
            .join(SSO_START_PATH)
            .expect("sso_start path is a well-formed relative URL literal");
        let response = self
            .http()
            .post(url)
            .header("X-Tenant-ID", self.tenant_header_value())
            .maybe_csrf_header(self)
            .json(&body)
            .send()
            .await
            .map_err(|e| network_err("sso_start request failed", e))?;

        if !response.status().is_success() {
            // Addendum item 12: the federation start endpoint documents no
            // response schema for its errors, so it is NOT parsed as an
            // OAuth2ErrorResponse — plain §2 status mapping only.
            let status = response.status().as_u16();
            let message = response
                .text()
                .await
                .unwrap_or_else(|_| "no response body".to_string());
            return Err(AxiamError::from_http_status(status, message));
        }

        let wire: OidcStartResponseWire = response
            .json()
            .await
            .map_err(|e| network_err("failed to parse sso_start response", e))?;

        Ok(SsoStartResult {
            authorize_url: wire.authorize_url,
            state: wire.state,
            expires_in_secs: wire.expires_in_secs,
        })
    }

    /// `POST /api/v1/auth/federation/oidc/callback` (CONTRACT.md §12.1) —
    /// step 2 of upstream SSO: consumes the single-use `state`, provisions
    /// or links the user, and establishes the session.
    ///
    /// The session arrives as **`Set-Cookie`** (§12.1 note 6), captured
    /// automatically by this client's own cookie jar (§4) — the same
    /// `reqwest::Client` every other REST call on this `AxiamClient` uses.
    /// §12.4 does not apply here: no ID token ever reaches the SDK on the
    /// federation path.
    ///
    /// On success this runs the **same post-login session sync** as
    /// [`AxiamClient::login`] / [`AxiamClient::verify_mfa`] (§4, §3): the
    /// `axiam_access`/`axiam_refresh` cookies are read out of the jar, the
    /// access token is verified through the JWKS verifier to resolve
    /// `tenant_id`/`org_id` and its expiry, the token manager is seeded, and
    /// the `axiam_csrf` value is cached for §3 forwarding. A `sso_complete`
    /// therefore leaves the client in exactly the state a `login()` would —
    /// [`AxiamClient::refresh`] and [`AxiamClient::logout`] work afterwards.
    ///
    /// # Errors
    /// Besides the §2 status mapping, an [`AxiamError::Auth`] when the
    /// response set no usable `axiam_access` cookie or that cookie does not
    /// verify — identical to `login()`'s behaviour, since a session that
    /// cannot be absorbed is not a successful login.
    pub async fn sso_complete(
        &self,
        params: SsoCompleteParams,
    ) -> Result<SsoCompleteResult, AxiamError> {
        let body = OidcPublicCallbackRequestWire {
            state: &params.state,
            code: &params.code,
        };

        let url = self
            .base_url()
            .join(SSO_CALLBACK_PATH)
            .expect("sso_complete path is a well-formed relative URL literal");
        let response = self
            .http()
            .post(url)
            .header("X-Tenant-ID", self.tenant_header_value())
            .maybe_csrf_header(self)
            .json(&body)
            .send()
            .await
            .map_err(|e| network_err("sso_complete request failed", e))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let message = response
                .text()
                .await
                .unwrap_or_else(|_| "no response body".to_string());
            return Err(AxiamError::from_http_status(status, message));
        }

        let wire: SsoLoginSuccessResponseWire = response
            .json()
            .await
            .map_err(|e| network_err("failed to parse sso_complete response", e))?;

        // Addendum judgment call 16 / §4 + §3: mark the session authenticated
        // by running the *same* post-login sync login()/verify_mfa() run —
        // seed the token manager from the jar, resolve tenant_id/org_id from
        // the verified access token, and cache the CSRF token. Without this a
        // caller holds a live server-side session the client knows nothing
        // about, and a subsequent refresh() fails with "no access token to
        // refresh".
        crate::rest::auth::absorb_session_cookies(self).await?;

        Ok(SsoCompleteResult {
            user_id: wire.user_id,
            session_id: wire.session_id,
            expires_in: wire.expires_in,
            redirect_uri: wire.redirect_uri,
        })
    }
}

/// CONTRACT.md §7 rule 1: these wire structs hold the plaintext of a value
/// the public type wraps in `Sensitive`, so none of them may be `Debug`.
#[cfg(test)]
mod wire_redaction_tests {
    #[test]
    fn no_wire_struct_holding_a_secret_is_debug() {
        assert!(
            !crate::sensitive::implements_debug!(super::TokenResponseWire),
            "TokenResponseWire is Debug"
        );
    }
}