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
//! REST auth flow: `login`/`verify_mfa`/`refresh`/`logout` (CONTRACT.md §1).
//!
//! Mirrors `crates/axiam-api-rest/src/handlers/auth.rs` request/response
//! shapes exactly (mirror only, no server crate dependency). Tokens are
//! delivered exclusively via `Set-Cookie` — `LoginResult` deliberately has
//! **no** `access_token` field (D-05).

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

use crate::AxiamError;
use crate::Sensitive;
use crate::client::{AxiamClient, OrgIdentifier, TenantIdentifier};
use crate::token::jwks::Claims;
use crate::token::refresh_guard::RefreshedTokens;

const LOGIN_PATH: &str = "/api/v1/auth/login";
const MFA_VERIFY_PATH: &str = "/api/v1/auth/mfa/verify";
const REFRESH_PATH: &str = "/api/v1/auth/refresh";
const LOGOUT_PATH: &str = "/api/v1/auth/logout";
const DEVICE_PATH: &str = "/api/v1/auth/device";

// ---------------------------------------------------------------------------
// Request bodies (mirror crates/axiam-api-rest/src/handlers/auth.rs)
// ---------------------------------------------------------------------------

// X-4/SDK-13: `Debug` is NOT derived on the two request bodies that carry
// plaintext credentials (`password`, `totp_code`) / a bearer challenge token —
// a derived `Debug` would print those secrets verbatim into any log or panic
// message. Manual `Debug` impls below redact the secret fields.
#[derive(Serialize)]
struct LoginRequestBody {
    #[serde(skip_serializing_if = "Option::is_none")]
    tenant_id: Option<Uuid>,
    #[serde(skip_serializing_if = "Option::is_none")]
    org_id: Option<Uuid>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tenant_slug: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    org_slug: Option<String>,
    username_or_email: String,
    password: String,
}

impl std::fmt::Debug for LoginRequestBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LoginRequestBody")
            .field("tenant_id", &self.tenant_id)
            .field("org_id", &self.org_id)
            .field("tenant_slug", &self.tenant_slug)
            .field("org_slug", &self.org_slug)
            .field("username_or_email", &self.username_or_email)
            .field("password", &"[REDACTED]")
            .finish()
    }
}

#[derive(Serialize)]
struct MfaVerifyRequestBody {
    challenge_token: String,
    totp_code: String,
}

impl std::fmt::Debug for MfaVerifyRequestBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Both fields are sensitive: `totp_code` is a live second factor and
        // `challenge_token` is a short-lived "logging in as this user" bearer.
        f.debug_struct("MfaVerifyRequestBody")
            .field("challenge_token", &"[REDACTED]")
            .field("totp_code", &"[REDACTED]")
            .finish()
    }
}

/// The `403` body of `POST /api/v1/auth/login` when the tenant requires MFA
/// and the account has none (CONTRACT.md §25.2).
#[derive(Deserialize)]
struct MfaSetupRequiredResponseWire {
    #[serde(default)]
    mfa_setup_required: bool,
    setup_token: String,
}

#[derive(Debug, Serialize)]
struct RefreshRequestBody {
    tenant_id: Uuid,
    org_id: Uuid,
}

#[derive(Debug, Serialize)]
struct LogoutRequestBody {
    session_id: Uuid,
}

// ---------------------------------------------------------------------------
// Response bodies (mirror server shapes; Deserialize only, no server dep)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
pub(crate) struct LoginUserInfoWire {
    #[allow(dead_code)]
    id: Uuid,
    #[allow(dead_code)]
    username: String,
    #[allow(dead_code)]
    email: String,
    /// CONTRACT.md §5.2. Absent on a server older than contract 1.31, and
    /// `false` is the safe reading of absent: the client then offers no
    /// cross-tenant action rather than offering one that would 403.
    #[serde(default)]
    organization_level: bool,
    /// CONTRACT.md §5.2.2 — the tenant being **acted on**.
    #[serde(default)]
    tenant_id: Option<Uuid>,
    /// CONTRACT.md §5.2.2 — the tenant this principal's record **lives in**.
    ///
    /// Equal to `tenant_id` for every ordinary principal; they diverge only
    /// once an organization-level principal selects another acting tenant.
    /// Absent on a server older than contract 1.34, where the two cannot
    /// diverge at all, so [`LoginResult::principal_tenant_id`] falls back to
    /// `tenant_id` rather than to `None`.
    #[serde(default)]
    principal_tenant_id: Option<Uuid>,
    /// CONTRACT.md §5.2.2 — slug of `principal_tenant_id` (`"organization"`
    /// for an organization-level principal).
    #[serde(default)]
    principal_tenant_slug: Option<String>,
    /// CONTRACT.md §5.2.2 — the caller's organization as a UUID, so a client
    /// holding only the slug does not have to reach `GET
    /// /api/v1/organizations` (`super-admin`-only) to address the
    /// `/organizations/{org_id}/…` routes.
    #[serde(default)]
    org_id: Option<Uuid>,
    /// CONTRACT.md §5.2.3 — the tenants this caller's roles reach, when they
    /// are restricted to particular ones. Absent means unrestricted.
    #[serde(default)]
    reachable_tenant_ids: Option<Vec<Uuid>>,
}

impl LoginUserInfoWire {
    /// What this user object says about the principal's reach — the input to
    /// the §5.2 rule 1 gate on [`AxiamClient::acting_tenant`].
    pub(crate) fn principal_scope(&self) -> crate::client::PrincipalScope {
        crate::client::PrincipalScope {
            organization_level: self.organization_level,
            reachable_tenant_ids: self.reachable_tenant_ids.clone(),
        }
    }
}

/// `200 OK` body from `/api/v1/auth/login`, `/api/v1/auth/mfa/verify`, and
/// (fields overlap) `/api/v1/auth/refresh`.
#[derive(Debug, Deserialize)]
struct LoginSuccessResponseWire {
    user: LoginUserInfoWire,
    session_id: Uuid,
    expires_in: u64,
}

/// `202 Accepted` body from `/api/v1/auth/login` when MFA is required.
///
/// Not `Debug`: it holds the challenge token until it is wrapped (§7 rule 1).
#[derive(Deserialize)]
struct MfaRequiredResponseWire {
    challenge_token: String,
    available_methods: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct RefreshSuccessResponseWire {
    expires_in: u64,
}

/// `200 OK` body from `/api/v1/auth/device` (server `DeviceAuthResponse`).
///
/// No `Debug`: it holds the raw token until [`DeviceToken`] wraps it.
#[derive(Deserialize)]
struct DeviceAuthResponseWire {
    access_token: String,
    token_type: String,
    expires_in: u64,
}

/// The result of [`AxiamClient::authenticate_device`] — CONTRACT.md §6.1
/// rule 6.
///
/// The one place in this SDK a token is handed back in a value rather than
/// kept only in the cookie jar, because the device login delivers it in the
/// response body and sets no cookie. It is also adopted as the client's own
/// credential, so most callers never need to read it.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DeviceToken {
    /// The access token. [`Sensitive`] (§7): redacted in every rendering.
    ///
    /// **Certificate-bound** when AXIAM itself terminated the TLS handshake
    /// (§6.1 rule 9): it carries `cnf: {"x5t#S256": …}` naming the certificate
    /// that obtained it, and is refused on any connection that does not present
    /// that certificate. Keep using it through *this* client, which presents
    /// the certificate on REST and gRPC alike; handing it to a second client
    /// without the certificate is the theft scenario the binding exists to
    /// close, and fails with `401`.
    pub access_token: Sensitive<String>,
    /// Always `"Bearer"`, bound or not — `token_type` does not say whether a
    /// token is bound (§1.1.1 rule 5). The `cnf` claim does.
    pub token_type: String,
    /// The access-token lifetime in seconds (the server's default is 900).
    ///
    /// There is **no refresh token** (§6.1 rule 6). Call
    /// [`AxiamClient::authenticate_device`] again before this runs out; it
    /// costs one TLS handshake.
    pub expires_in: u64,
}

// ---------------------------------------------------------------------------
// Public result type — CONTRACT.md §1, D-05 (no access_token field)
// ---------------------------------------------------------------------------

/// The outcome of [`AxiamClient::login`]/[`AxiamClient::verify_mfa`].
///
/// **No `access_token` field exists here or anywhere else in this SDK's
/// public API** — AXIAM delivers tokens exclusively via `Set-Cookie`
/// (D-05). After a successful (non-MFA) call, the access token is already
/// present in the client's cookie jar and its claims have been decoded into
/// the internal [`crate::token::TokenManager`].
#[derive(Debug)]
pub struct LoginResult {
    /// `true` if the server responded with an MFA challenge instead of a
    /// completed session; call [`AxiamClient::verify_mfa`] next.
    pub mfa_required: bool,
    /// Set when `mfa_required` is `true` — the opaque challenge token to
    /// pass to [`AxiamClient::verify_mfa`]. Treated as sensitive (short-lived
    /// bearer of "logging in as this user") even though it is not a full
    /// session token.
    pub challenge_token: Option<Sensitive<String>>,
    /// Authentication methods available to satisfy the MFA challenge (only
    /// populated when `mfa_required` is `true`).
    pub available_methods: Vec<String>,
    /// The server-issued session id (only populated on a completed,
    /// non-MFA-pending login/verify_mfa).
    pub session_id: Option<Uuid>,
    /// Access token lifetime in seconds, as reported by the server (only
    /// populated on a completed login/verify_mfa).
    pub expires_in: Option<u64>,
    /// `true` when the tenant requires MFA and this account has none —
    /// CONTRACT.md §25.2 rule 1.
    ///
    /// An **outcome**, not an error. The server answers `403` here with the
    /// token to finish, and mapping that through §2 to
    /// [`AxiamError::Authz`] told the caller they lacked permission to log in,
    /// when what the server said was recoverable and came with the means to
    /// recover. Pass `setup_token` to [`AxiamClient::mfa_setup_enroll`], show
    /// the user the URI, then [`AxiamClient::mfa_setup_confirm`], which
    /// completes this login.
    ///
    /// Additive here rather than a new type, because this result has always
    /// been one struct with flags rather than a discriminated union — so
    /// nothing that reads `mfa_required` today has to change.
    pub mfa_setup_required: bool,
    /// Authorizes the `mfa_setup_enroll`/`mfa_setup_confirm` pair; populated
    /// only when `mfa_setup_required` is `true`.
    pub setup_token: Option<Sensitive<String>>,
    /// Whether the account that just signed in is an **organization-level**
    /// principal — CONTRACT.md §5.2.
    ///
    /// Such a principal's record lives in its organization's reserved tenant,
    /// so its global grants apply in every tenant of that organization, and it
    /// can act on a different one by sending a different `X-Axiam-Tenant` on
    /// the next request — no re-login, because it already is a principal of
    /// every tenant there.
    ///
    /// Since contract 1.35 that reach can be narrowed per assignment, so this
    /// flag alone no longer decides what to offer: consult
    /// [`Self::reachable_tenant_ids`] as well (§5.2.3 rule 3).
    ///
    /// An ordinary tenant principal is a principal of exactly one tenant.
    /// Changing the header for one of those produces a `403`, so this flag is
    /// what an application checks *before* offering a tenant switch, rather
    /// than discovering the answer from a failed request.
    ///
    /// `false` on a completed login against a server older than contract 1.31,
    /// and `false` on the two pending outcomes, where no principal has been
    /// established yet.
    pub organization_level: bool,
    /// The tenant this login is **acting on** — CONTRACT.md §5.2.2.
    ///
    /// `None` on the two pending outcomes and against a server older than
    /// contract 1.34.
    pub tenant_id: Option<Uuid>,
    /// The tenant this principal's record **lives in** — CONTRACT.md §5.2.2.
    ///
    /// This is the tenant the account's own credentials belong to, and it is
    /// what a §23 registration record for *this* account must be sealed
    /// against — see [`AxiamClient::opaque_enrollment_for_self`].
    ///
    /// Defaults to [`Self::tenant_id`] when the server does not send it, which
    /// is exactly right there: a server older than contract 1.34 cannot switch
    /// the acting tenant, so the two cannot differ.
    ///
    /// [`AxiamClient::opaque_enrollment_for_self`]: crate::client::AxiamClient::opaque_enrollment_for_self
    pub principal_tenant_id: Option<Uuid>,
    /// Slug of [`Self::principal_tenant_id`] — `"organization"` for an
    /// organization-level principal. `None` when the server omits it.
    pub principal_tenant_slug: Option<String>,
    /// The caller's organization as a UUID — CONTRACT.md §5.2.2 rule 3.
    ///
    /// Read this rather than resolving a slug through `GET
    /// /api/v1/organizations`, which is `super-admin`-only and returns only
    /// the caller's own organization.
    pub org_id: Option<Uuid>,
    /// The tenants this caller's roles reach, when restricted — CONTRACT.md
    /// §5.2.3.
    ///
    /// `None` means **unrestricted**, which is both the common case and the
    /// only thing a server older than contract 1.35 can mean. `Some(list)` is
    /// a deliberately narrowed organization-level account: an application
    /// offering a tenant switch MUST confine its choices to `list`, because
    /// naming anything outside it is refused at the header (§5.2.3 rule 4).
    ///
    /// Note the pairing with [`Self::organization_level`]: a narrowed account
    /// still reports `organization_level: true`, so gating on that flag alone
    /// offers tenants the server will refuse.
    pub reachable_tenant_ids: Option<Vec<Uuid>>,
}

impl LoginResult {
    pub(crate) fn mfa_required(challenge_token: String, available_methods: Vec<String>) -> Self {
        Self {
            mfa_required: true,
            challenge_token: Some(Sensitive::new(challenge_token)),
            available_methods,
            session_id: None,
            expires_in: None,
            mfa_setup_required: false,
            setup_token: None,
            // No principal is established until the login completes, so there
            // is nothing yet for this to be true of, nor any principal whose
            // tenant, organization or reach these could describe.
            organization_level: false,
            tenant_id: None,
            principal_tenant_id: None,
            principal_tenant_slug: None,
            org_id: None,
            reachable_tenant_ids: None,
        }
    }

    /// CONTRACT.md §25.2 rule 1 — the tenant requires MFA and this account has
    /// none.
    pub(crate) fn mfa_setup_required(setup_token: String) -> Self {
        Self {
            mfa_required: false,
            challenge_token: None,
            available_methods: Vec::new(),
            session_id: None,
            expires_in: None,
            mfa_setup_required: true,
            setup_token: Some(Sensitive::new(setup_token)),
            organization_level: false,
            tenant_id: None,
            principal_tenant_id: None,
            principal_tenant_slug: None,
            org_id: None,
            reachable_tenant_ids: None,
        }
    }

    /// A completed login for an ordinary tenant principal.
    ///
    /// Kept alongside [`Self::success_with_user`] so the call sites that
    /// complete a login without reading a user object — OPAQUE and the forced
    /// MFA setup path — do not have to assert a scope they were not told.
    pub(crate) fn success(session_id: Uuid, expires_in: u64) -> Self {
        Self {
            mfa_required: false,
            challenge_token: None,
            available_methods: Vec::new(),
            session_id: Some(session_id),
            expires_in: Some(expires_in),
            mfa_setup_required: false,
            setup_token: None,
            organization_level: false,
            tenant_id: None,
            principal_tenant_id: None,
            principal_tenant_slug: None,
            org_id: None,
            reachable_tenant_ids: None,
        }
    }

    /// A completed login, carrying the §5.2/§5.2.2/§5.2.3 scope the server
    /// reported about the principal.
    ///
    /// Takes the whole user object rather than the fields one at a time
    /// because they are read together and a server that omits one usually
    /// omits its neighbours: passing them individually invites a call site
    /// that forwards three of five and silently defaults the rest.
    pub(crate) fn success_with_user(
        session_id: Uuid,
        expires_in: u64,
        user: &LoginUserInfoWire,
    ) -> Self {
        Self {
            mfa_required: false,
            challenge_token: None,
            available_methods: Vec::new(),
            session_id: Some(session_id),
            expires_in: Some(expires_in),
            mfa_setup_required: false,
            setup_token: None,
            organization_level: user.organization_level,
            tenant_id: user.tenant_id,
            // §5.2.2 rule 1: absent means equal. A server older than contract
            // 1.34 omits this and cannot switch the acting tenant either, so
            // falling back to `tenant_id` is not a guess -- it is the only
            // value the field could have had there.
            principal_tenant_id: user.principal_tenant_id.or(user.tenant_id),
            principal_tenant_slug: user.principal_tenant_slug.clone(),
            org_id: user.org_id,
            reachable_tenant_ids: user.reachable_tenant_ids.clone(),
        }
    }
}

// ---------------------------------------------------------------------------
// Shared post-success handling: extract cookies, verify, cache state
// ---------------------------------------------------------------------------

/// After any 200 response that sets `axiam_access`/`axiam_refresh`/
/// `axiam_csrf`, read them out of the jar (RESEARCH.md Pattern 1), decode
/// the access token's claims via the JWKS verifier to populate `exp` and
/// resolve `tenant_id`/`org_id`, and cache the CSRF token for §3 forwarding.
///
/// `pub(crate)` because CONTRACT.md §12.1's `sso_complete` establishes a
/// session the same way (addendum judgment call 16) and must run the identical
/// sync rather than a partial copy of it — see
/// [`AxiamClient::sso_complete`](crate::client::AxiamClient::sso_complete).
pub(crate) async fn absorb_session_cookies(client: &AxiamClient) -> Result<Claims, AxiamError> {
    let access = client
        .inner
        .jar
        .access_token(&client.inner.base_url)
        .ok_or_else(|| AxiamError::Auth {
            message: "server response did not set the axiam_access cookie".into(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        })?;
    // H8 fix (SDK bench harness validation): `axiam_refresh` is
    // `Path=/api/v1/auth/refresh`-scoped (crates/axiam-api-rest/src/
    // middleware/csrf.rs `refresh_cookie()`), so a jar lookup keyed on
    // `base_url` (path "/") never matches it per RFC 6265 path-matching (a
    // cookie's Path must be a prefix of the *request* path, not the other
    // way around) — every login()/verify_mfa()/sso_complete() therefore
    // absorbed a `refresh: None`, and the very first refresh() call failed
    // with "no refresh token available; re-authentication required"
    // (token/refresh_guard.rs) despite the server having issued one. Look it
    // up at the REFRESH_PATH-scoped URL instead, matching the URL the cookie
    // was actually set against.
    let refresh = client.inner.jar.refresh_token(&client.url(REFRESH_PATH));

    let claims = client
        .jwks_verifier()
        .verify_session_token(access.expose())
        .await?;

    let tenant_id = Uuid::parse_str(&claims.tenant_id).ok();
    let org_id = claims
        .org_id
        .as_deref()
        .and_then(|s| Uuid::parse_str(s).ok());

    client
        .token_manager()
        .set_tokens(access, refresh, Some(claims.exp), tenant_id)
        .await;

    if let Some(org_id) = org_id {
        client.set_resolved_org_id(org_id);
    }

    client.capture_csrf_from_jar();

    // A new session is a new principal until its login says otherwise. The two
    // callers that read a user object (`login`, `verify_mfa`) record its reach
    // straight after this; every other path that lands here (OPAQUE, SSO, the
    // forced MFA setup, WebAuthn) completes a session without one, and must
    // not inherit the previous principal's reach as a gate on
    // `acting_tenant` (CONTRACT.md §5.2 rule 1).
    client.set_principal_scope(None);
    // A cookie session again: requests carry the jar, not a bearer header.
    client.set_bearer_credential(false);

    Ok(claims)
}

// ---------------------------------------------------------------------------
// Public REST auth methods
// ---------------------------------------------------------------------------

impl AxiamClient {
    /// `POST /api/v1/auth/login` (CONTRACT.md §1).
    ///
    /// On success (no MFA), the access token is read from the cookie jar,
    /// verified, and cached — `LoginResult` itself never carries it (D-05).
    /// When the server signals MFA is required, returns
    /// `LoginResult { mfa_required: true, .. }` carrying the challenge
    /// token; call [`Self::verify_mfa`] next.
    pub async fn login(&self, email: &str, password: &str) -> Result<LoginResult, AxiamError> {
        // §18.1 rule 4: use-after-close is an error, not a reconnect.
        self.ensure_open()?;
        // §17.1 rule 9: entries are keyed by subject, not session, so any
        // credential change must drop them — otherwise a re-authentication as
        // a different principal inherits the previous one's decisions.
        self.decision_memo().clear();
        let body = self.build_login_body(email, password);

        let response = self
            .http()
            .post(self.url(LOGIN_PATH))
            // CONTRACT 1.52 N-§5-rule-2 (C-12): unconditional on every
            // outgoing request, including this pre-session call — the server
            // reads no acting tenant here, so §5.2 rule 1's header is
            // optional and harmless, but `tenant_headers_of` sends both
            // together and matches every other request builder in the crate.
            .tenant_headers_of(self)
            .json(&body)
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("login request failed: {e}"),
                source: Some(Box::new(e)),
            })?;

        match response.status().as_u16() {
            200 => {
                let wire: LoginSuccessResponseWire = response.json().await.map_err(deser_err)?;
                absorb_session_cookies(self).await?;
                // §5.2.2: cache the principal tenant before building the
                // result, so a later `opaque_enrollment_for_self` seals
                // against the account's own tenant without a second round
                // trip.
                if let Some(pt) = wire.user.principal_tenant_id.or(wire.user.tenant_id) {
                    self.set_resolved_principal_tenant_id(pt);
                }
                // §5.2 rule 1: this client now holds a login result, so the
                // acting-tenant helper gates on what it reported.
                self.set_principal_scope(Some(wire.user.principal_scope()));
                Ok(LoginResult::success_with_user(
                    wire.session_id,
                    wire.expires_in,
                    &wire.user,
                ))
            }
            202 => {
                let wire: MfaRequiredResponseWire = response.json().await.map_err(deser_err)?;
                self.set_pending_mfa_challenge(Sensitive::new(wire.challenge_token.clone()));
                Ok(LoginResult::mfa_required(
                    wire.challenge_token,
                    wire.available_methods,
                ))
            }
            403 => {
                // CONTRACT.md §25.2 rule 1: a `403` carrying
                // `mfa_setup_required` is an OUTCOME, not a refusal.
                //
                // Matched on the body's own discriminant rather than the
                // status alone: a genuine authorization refusal is also a
                // `403`, and only one of the two carries a `setup_token`. The
                // body is read as text first so a non-matching `403` still
                // reaches the taxonomy mapper with its message intact.
                let body = response.text().await.unwrap_or_default();
                if let Ok(wire) = serde_json::from_str::<MfaSetupRequiredResponseWire>(&body)
                    && wire.mfa_setup_required
                    && !wire.setup_token.is_empty()
                {
                    return Ok(LoginResult::mfa_setup_required(wire.setup_token));
                }
                Err(AxiamError::from_http_status(403, body))
            }
            status => Err(map_error_response(status, response).await),
        }
    }

    /// `POST /api/v1/auth/mfa/verify` (CONTRACT.md §1).
    ///
    /// Completes the two-phase flow started by [`Self::login`] when
    /// `mfa_required` was `true`, using the challenge token captured
    /// internally from that prior `login()` call.
    pub async fn verify_mfa(&self, code: &str) -> Result<LoginResult, AxiamError> {
        // §18.1 rule 4: use-after-close is an error, not a reconnect.
        self.ensure_open()?;
        // §17.1 rule 9: entries are keyed by subject, not session, so any
        // credential change must drop them — otherwise a re-authentication as
        // a different principal inherits the previous one's decisions.
        self.decision_memo().clear();
        let challenge = self
            .take_pending_mfa_challenge()
            .ok_or_else(|| AxiamError::Auth {
                message: "verify_mfa called with no pending MFA challenge — call login() first"
                    .into(),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            })?;

        let body = MfaVerifyRequestBody {
            challenge_token: challenge.expose().clone(),
            totp_code: code.to_string(),
        };

        let response = self
            .http()
            .post(self.url(MFA_VERIFY_PATH))
            // CONTRACT 1.52 N-§5-rule-2 (C-12): see `login()`.
            .tenant_headers_of(self)
            .json(&body)
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("verify_mfa request failed: {e}"),
                source: Some(Box::new(e)),
            })?;

        match response.status().as_u16() {
            200 => {
                let wire: LoginSuccessResponseWire = response.json().await.map_err(deser_err)?;
                absorb_session_cookies(self).await?;
                // §5.2.2: cache the principal tenant before building the
                // result, so a later `opaque_enrollment_for_self` seals
                // against the account's own tenant without a second round
                // trip.
                if let Some(pt) = wire.user.principal_tenant_id.or(wire.user.tenant_id) {
                    self.set_resolved_principal_tenant_id(pt);
                }
                // §5.2 rule 1: this client now holds a login result, so the
                // acting-tenant helper gates on what it reported.
                self.set_principal_scope(Some(wire.user.principal_scope()));
                Ok(LoginResult::success_with_user(
                    wire.session_id,
                    wire.expires_in,
                    &wire.user,
                ))
            }
            status => Err(map_error_response(status, response).await),
        }
    }

    /// `POST /api/v1/auth/refresh` (CONTRACT.md §1).
    ///
    /// Delegates to the single-flight guard
    /// ([`crate::token::TokenManager::refresh_if_needed`]) — this method
    /// contains no refresh HTTP logic of its own beyond driving that guard
    /// with the actual `reqwest` call as its closure.
    pub async fn refresh(&self) -> Result<(), AxiamError> {
        // §18.1 rule 4: use-after-close is an error, not a reconnect.
        self.ensure_open()?;
        // §17.1 rule 9: entries are keyed by subject, not session, so any
        // credential change must drop them — otherwise a re-authentication as
        // a different principal inherits the previous one's decisions.
        self.decision_memo().clear();
        let observed =
            self.token_manager()
                .cached_access_token()
                .ok_or_else(|| AxiamError::Auth {
                    message: "no access token to refresh — call login() first".into(),
                    oauth: None,
                    reason: None,
                    set_reason: None,
                    retry_after: None,
                })?;
        let observed_value = observed.expose().clone();

        let tenant_id = self
            .resolved_tenant_id()
            .await
            .ok_or_else(|| AxiamError::Auth {
                message: "tenant_id could not be resolved; login() must succeed before refresh()"
                    .into(),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            })?;
        let org_id = self.resolved_org_id().ok_or_else(|| AxiamError::Auth {
            message: "org_id could not be resolved; login() must succeed before refresh()".into(),
            oauth: None,
            reason: None,
            set_reason: None,
            retry_after: None,
        })?;

        let client = self.clone();
        self.token_manager()
            .refresh_if_needed(&observed_value, move |_refresh_token_unused| {
                // The refresh token itself travels via the httpOnly
                // `axiam_refresh` cookie (already in the shared jar), not
                // the request body — mirroring
                // crates/axiam-api-rest/src/handlers/auth.rs::refresh.
                let client = client.clone();
                async move {
                    let body = RefreshRequestBody { tenant_id, org_id };
                    let response = client
                        .http()
                        .post(client.url(REFRESH_PATH))
                        .tenant_headers_of(&client)
                        .maybe_csrf_header(&client)
                        .json(&body)
                        .send()
                        .await
                        .map_err(|e| AxiamError::Network {
                            message: format!("refresh request failed: {e}"),
                            source: Some(Box::new(e)),
                        })?;

                    match response.status().as_u16() {
                        200 => {
                            let wire: RefreshSuccessResponseWire =
                                response.json().await.map_err(deser_err)?;
                            // §9.3 requires the refresh call to not retry on
                            // failure, but on SUCCESS we still must read the
                            // rotated cookies before reporting the new token.
                            let access = client
                                .inner
                                .jar
                                .access_token(&client.inner.base_url)
                                .ok_or_else(|| AxiamError::Auth {
                                    message: "refresh response did not set axiam_access".into(),
                                    oauth: None,
                                    reason: None,
                                    set_reason: None,
                                    retry_after: None,
                                })?;
                            // Same REFRESH_PATH-scoped lookup as
                            // absorb_session_cookies above, and just as
                            // load-bearing here: on a `base_url` lookup this
                            // always returned None, so `RefreshedTokens.
                            // refresh` was always None and `refresh_if_needed`
                            // kept the OLD, already-consumed (single-use)
                            // refresh token in its state forever — meaning
                            // even a fixed first refresh() call would still
                            // make every subsequent refresh() fail.
                            let refresh_token =
                                client.inner.jar.refresh_token(&client.url(REFRESH_PATH));
                            let claims = client
                                .jwks_verifier()
                                .verify_session_token(access.expose())
                                .await?;
                            client.capture_csrf_from_jar();
                            let _ = wire.expires_in; // exp is authoritative from claims, not this field
                            Ok(RefreshedTokens {
                                access,
                                refresh: refresh_token,
                                exp: Some(claims.exp),
                                tenant_id: Uuid::parse_str(&claims.tenant_id).ok(),
                            })
                        }
                        // §9.3: 401 on the refresh call itself is AuthError,
                        // no retry loop.
                        status => Err(map_error_response(status, response).await),
                    }
                }
            })
            .await?;

        Ok(())
    }

    /// `POST /api/v1/auth/logout` (CONTRACT.md §1).
    ///
    /// Clears in-memory token state and the jar's session cookies.
    pub async fn logout(&self) -> Result<(), AxiamError> {
        // §18.1 rule 4: use-after-close is an error, not a reconnect.
        self.ensure_open()?;
        // §17.1 rule 9: entries are keyed by subject, not session, so any
        // credential change must drop them — otherwise a re-authentication as
        // a different principal inherits the previous one's decisions.
        self.decision_memo().clear();
        let session_id = {
            // The server keys logout off the session id embedded in the
            // caller's own JWT (`jti`), cross-validated server-side against
            // the authenticated user — the SDK must supply the same id it
            // received at login.
            let manager = self.token_manager();
            let access = manager.cached_access_token();
            match access {
                Some(token) => {
                    let claims = self
                        .jwks_verifier()
                        .verify_session_token(token.expose())
                        .await?;
                    claims
                        .jti
                        .as_deref()
                        .and_then(|s| Uuid::parse_str(s).ok())
                        .ok_or_else(|| AxiamError::Auth {
                            message: "access token has no session id (jti) to log out".into(),
                            oauth: None,
                            reason: None,
                            set_reason: None,
                            retry_after: None,
                        })?
                }
                None => {
                    return Err(AxiamError::Auth {
                        message: "no active session to log out".into(),
                        oauth: None,
                        reason: None,
                        set_reason: None,
                        retry_after: None,
                    });
                }
            }
        };

        let body = LogoutRequestBody { session_id };
        let response = self
            .http()
            .post(self.url(LOGOUT_PATH))
            .tenant_headers_of(self)
            // CONTRACT 1.52 N4.3 (C-12): present the held device credential
            // and withhold a stale cookie — logout must identify the session
            // it is closing by the credential actually held, not by whatever
            // cookie happens to still be in the jar.
            .session_credential_of(self)
            .maybe_csrf_header(self)
            .json(&body)
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("logout request failed: {e}"),
                source: Some(Box::new(e)),
            })?;

        if !response.status().is_success() {
            return Err(map_error_response(response.status().as_u16(), response).await);
        }

        self.token_manager().clear().await;
        self.set_principal_scope(None);
        self.set_bearer_credential(false);
        Ok(())
    }

    /// `POST /api/v1/auth/device` — log in as the service account bound to
    /// this client's certificate (CONTRACT.md §6.1 rules 6–10, contract 1.51).
    ///
    /// The certificate is the credential: the request has no body, and the
    /// server identifies the caller from the client certificate it verified
    /// during the TLS handshake. Configure it with
    /// [`AxiamClientBuilder::with_client_cert`].
    ///
    /// On success the token is **adopted** as this client's credential, as a
    /// `login` result is: management calls and `check_access` that follow send
    /// it as `Authorization: Bearer`. It is also returned, as a
    /// [`DeviceToken`].
    ///
    /// ```no_run
    /// # use axiam_sdk::client::AxiamClient;
    /// # async fn demo(cert_pem: &[u8], key_pem: &[u8]) -> Result<(), axiam_sdk::AxiamError> {
    /// let device = AxiamClient::builder()
    ///     .base_url("https://iam.example.com")?
    ///     .tenant_id(uuid::Uuid::nil())
    ///     .with_client_cert(cert_pem, key_pem)?
    ///     .build()?;
    /// let token = device.authenticate_device().await?;
    /// println!("valid for {} s", token.expires_in);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # What the token is, and is not
    ///
    /// * A **service-account** token (`aud` = `axiam:m2m`, §6.1 rule 10). It is
    ///   accepted by `check_access` / `batch_check` and by the §27 operations
    ///   the account's roles authorize (§27.13 S-9); any other route answers
    ///   `401` for an audience mismatch.
    /// * **Certificate-bound** when AXIAM terminated TLS (§6.1 rule 9), so it
    ///   works only on connections that present the same certificate. This
    ///   client presents it on every REST request and on any gRPC channel built
    ///   from [`AxiamClient::grpc_channel_config`]. A gRPC listener that does
    ///   not request client certificates — the server's default,
    ///   `AXIAM__GRPC_TLS_CLIENT_AUTH=off` — refuses a bound token on every call.
    /// * **Not refreshable** (§6.1 rule 6). A later `401` on it is returned as
    ///   [`AxiamError::Auth`] without any refresh attempt; recover by calling
    ///   this method again.
    ///
    /// # Errors
    ///
    /// * [`AxiamError::Auth`], **with no wire call**, when this client was built
    ///   without [`AxiamClientBuilder::with_client_cert`] (§6.1 rule 7). Without
    ///   a certificate the server can only answer `401`, so going to the wire
    ///   would turn a configuration mistake into an authentication failure.
    /// * [`AxiamError::Auth`] on the server's `401`, with its message verbatim:
    ///   an unknown, untrusted, expired, revoked or unbound certificate, and a
    ///   `Server`-type certificate, are all refused that way (§6.1 rule 8). This
    ///   *is* the login, so it never enters the §9 refresh guard.
    /// * [`AxiamError::Network`] on a `429` — the route is rate-limited per
    ///   client IP (default 60 per minute), and that is not an authentication
    ///   failure — and on any other non-2xx or transport failure. Like every
    ///   login, it is made **exactly once** (§16).
    ///
    /// [`AxiamClientBuilder::with_client_cert`]: crate::client::AxiamClientBuilder::with_client_cert
    pub async fn authenticate_device(&self) -> Result<DeviceToken, AxiamError> {
        self.ensure_open()?;
        // §6.1 rule 7: unreachable without a certificate, and refused before
        // the network rather than by it.
        if !self.has_client_certificate() {
            return Err(AxiamError::auth(
                "authenticate_device: this client has no client certificate — configure one \
                 with AxiamClientBuilder::with_client_cert (CONTRACT.md §6.1 rule 7)",
            ));
        }
        // §17.1 rule 9: a credential change drops every memoised decision.
        self.decision_memo().clear();

        let response = self
            .http()
            .post(self.url(DEVICE_PATH))
            .header("X-Tenant-ID", self.tenant_header_value())
            // The certificate is the credential. Withhold the jar so a cookie
            // session this client may still hold does not ride along with it.
            .header(reqwest::header::COOKIE, "")
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("authenticate_device request failed: {e}"),
                source: Some(Box::new(e)),
            })?;

        let status = response.status().as_u16();
        if status != 200 {
            // §6.1 rule 8: `401` → `Auth`, verbatim; `429` and the rest follow
            // the ordinary §2 mapping. Neither reaches the refresh guard.
            return Err(map_error_response(status, response).await);
        }
        let wire: DeviceAuthResponseWire = response.json().await.map_err(deser_err)?;
        let access = Sensitive::new(wire.access_token);

        // Adopt it (§6.1 rule 6), as `absorb_session_cookies` adopts a login:
        // decode the claims for `exp` and the tenant, then replace whatever
        // credential this client held. `clear` first, because `set_tokens`
        // keeps an existing refresh token when handed none, and a previous
        // cookie session's refresh token must not survive into a device
        // credential that has no refresh at all.
        let claims = self
            .jwks_verifier()
            .verify_session_token(access.expose())
            .await?;
        let tenant_id = Uuid::parse_str(&claims.tenant_id).ok();
        if let Some(org_id) = claims
            .org_id
            .as_deref()
            .and_then(|s| Uuid::parse_str(s).ok())
        {
            self.set_resolved_org_id(org_id);
        }
        let manager = self.token_manager();
        manager.clear().await;
        manager
            .set_tokens(access.clone_inner(), None, Some(claims.exp), tenant_id)
            .await;
        self.set_bearer_credential(true);
        // A device holds no login result: nothing gates `acting_tenant` now,
        // and the server's answer decides (§5.2 rule 1).
        self.set_principal_scope(None);

        Ok(DeviceToken {
            access_token: access,
            token_type: wire.token_type,
            expires_in: wire.expires_in,
        })
    }

    fn build_login_body(&self, email: &str, password: &str) -> LoginRequestBody {
        let (tenant_id, tenant_slug) = match &self.inner.tenant {
            TenantIdentifier::Id(id) => (Some(*id), None),
            TenantIdentifier::Slug(slug) => (None, Some(slug.clone())),
        };
        let (org_id, org_slug) = match self.org_identifier() {
            Some(OrgIdentifier::Id(id)) => (Some(*id), None),
            Some(OrgIdentifier::Slug(slug)) => (None, Some(slug.clone())),
            None => (None, None),
        };
        LoginRequestBody {
            tenant_id,
            org_id,
            tenant_slug,
            org_slug,
            username_or_email: email.to_string(),
            password: password.to_string(),
        }
    }

    pub(crate) fn url(&self, path: &str) -> url::Url {
        self.inner
            .base_url
            .join(path)
            .expect("path is a well-formed relative URL literal")
    }
}

/// Map a non-2xx REST response to an [`AxiamError`] per CONTRACT.md §2,
/// pulling a human-readable message out of the body if present (never a
/// raw token — these responses never carry one).
pub(crate) async fn map_error_response(status: u16, response: reqwest::Response) -> AxiamError {
    let message = response
        .text()
        .await
        .unwrap_or_else(|_| "no response body".to_string());
    AxiamError::from_http_status(status, message)
}

pub(crate) fn deser_err(e: reqwest::Error) -> AxiamError {
    AxiamError::Network {
        message: format!("failed to parse response body: {e}"),
        source: Some(Box::new(e)),
    }
}

/// Small extension trait so state-changing request builders can forward the
/// captured `X-CSRF-Token` (§3) in one line without repeating the
/// `if-let`/`header` boilerplate everywhere. `pub(crate)` so sibling REST
/// modules (e.g. `rest::authz`) reuse the exact same forwarding logic instead
/// of duplicating it (SDK-Q04).
/// Extension so a request builder chain can take the §5 / §5.2 tenant headers
/// in one call, in the same fluent position as [`CsrfHeaderExt`].
pub(crate) trait TenantHeadersExt {
    /// `X-Tenant-ID`, plus `X-Axiam-Tenant` when the handle acts on a tenant —
    /// see [`AxiamClient::tenant_headers`].
    fn tenant_headers_of(self, client: &AxiamClient) -> Self;
    /// The held credential when it is a bearer token — see
    /// [`AxiamClient::session_credential`].
    fn session_credential_of(self, client: &AxiamClient) -> Self;
}

impl TenantHeadersExt for reqwest::RequestBuilder {
    fn tenant_headers_of(self, client: &AxiamClient) -> Self {
        client.tenant_headers(self)
    }

    fn session_credential_of(self, client: &AxiamClient) -> Self {
        client.session_credential(self)
    }
}

pub(crate) trait CsrfHeaderExt {
    fn maybe_csrf_header(self, client: &AxiamClient) -> Self;
}

impl CsrfHeaderExt for reqwest::RequestBuilder {
    fn maybe_csrf_header(self, client: &AxiamClient) -> Self {
        match client.csrf_token() {
            Some(token) => self.header("X-CSRF-Token", token),
            None => self,
        }
    }
}

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

    // X-4/SDK-13: the plaintext credential must never appear in a Debug render.
    #[test]
    fn login_body_debug_redacts_password() {
        let body = LoginRequestBody {
            tenant_id: None,
            org_id: None,
            tenant_slug: Some("acme".into()),
            org_slug: None,
            username_or_email: "user@example.com".into(),
            password: "hunter2-super-secret".into(),
        };
        let rendered = format!("{body:?}");
        assert!(
            !rendered.contains("hunter2-super-secret"),
            "password must never appear in Debug output: {rendered}"
        );
        assert!(rendered.contains("[REDACTED]"));
        // Non-secret fields remain visible for diagnostics.
        assert!(rendered.contains("user@example.com"));
        assert!(rendered.contains("acme"));
    }

    #[test]
    fn mfa_verify_body_debug_redacts_totp_and_challenge() {
        let body = MfaVerifyRequestBody {
            challenge_token: "challenge-abc-123".into(),
            totp_code: "654321".into(),
        };
        let rendered = format!("{body:?}");
        assert!(
            !rendered.contains("654321"),
            "totp_code must never appear in Debug output: {rendered}"
        );
        assert!(
            !rendered.contains("challenge-abc-123"),
            "challenge_token must never appear in Debug output: {rendered}"
        );
        assert!(rendered.contains("[REDACTED]"));
    }
}

/// 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::MfaRequiredResponseWire),
            "MfaRequiredResponseWire is Debug"
        );
    }
}