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
//! WebAuthn and passkeys — CONTRACT.md §24.
//!
//! A passkey ceremony is **two exchanges stacked**: one with an
//! *authenticator*, which needs a platform API, and one with *AXIAM*, which is
//! ordinary JSON round trips. The native Rust build has no authenticator, so
//! this module is the second half.
//!
//! Eight wire operations as of contract 1.45: the original six, plus
//! `webauthn_setup_register_start` / `webauthn_setup_register_finish` — the
//! WebAuthn twin of [`AxiamClient::mfa_setup_enroll`] /
//! [`AxiamClient::mfa_setup_confirm`] (CONTRACT.md §24.1, §25.2). Those two
//! are the only pair in this module that take **no session at all**: a setup
//! token from a forced first-login enrolment is the sole credential, and
//! §24.1 forbids attaching this client's own session credential to them even
//! when one happens to be configured.
//!
//! That is not a consolation prize. A Rust service completing a ceremony that
//! ran on an Android or iOS handset is the relying party exactly as a browser
//! is, and §24.6b rule 2 forbids the alternative outright: an SDK MUST NOT
//! emulate an authenticator in software, because a "credential" held in process
//! memory is not a second factor.
//!
//! `axiam-sdk-wasm` is the one build of this SDK that *does* reach an
//! authenticator, through `web-sys`; it drives the six session-based operations.
//!
//! The rule everything below obeys is §24.0: the server chooses every option
//! and verifies every response, so this carries both through untouched. It does
//! not default a field, normalize one, or re-encode a buffer — the challenge is
//! held as [`serde_json::Value`] precisely so there is nothing to normalize
//! through.

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

use crate::AxiamError;
use crate::Sensitive;
use crate::client::{AxiamClient, OrgIdentifier, TenantIdentifier};
use crate::rest::LoginResult;
use crate::rest::auth::{
    CsrfHeaderExt, LoginUserInfoWire, TenantHeadersExt, absorb_session_cookies, deser_err,
    map_error_response,
};

const REGISTER_START_PATH: &str = "/api/v1/auth/webauthn/register/start";
const REGISTER_FINISH_PATH: &str = "/api/v1/auth/webauthn/register/finish";
const AUTH_START_PATH: &str = "/api/v1/auth/webauthn/authenticate/start";
const AUTH_FINISH_PATH: &str = "/api/v1/auth/webauthn/authenticate/finish";
const DISCOVERABLE_START_PATH: &str = "/api/v1/auth/webauthn/authenticate/discoverable/start";
const DISCOVERABLE_FINISH_PATH: &str = "/api/v1/auth/webauthn/authenticate/discoverable/finish";
const SETUP_REGISTER_START_PATH: &str = "/api/v1/auth/webauthn/setup/register/start";
const SETUP_REGISTER_FINISH_PATH: &str = "/api/v1/auth/webauthn/setup/register/finish";

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

/// A started ceremony: the server's options plus the token binding a response
/// to them.
#[derive(Debug, Clone)]
pub struct WebauthnChallenge {
    /// The server's options, exactly as they arrived.
    ///
    /// A `{"publicKey": {…}}` object carrying base64url buffers. Hand it to the
    /// authenticator **unchanged** (§24.0), or call
    /// [`Self::request_json`] for the string a platform API takes.
    pub challenge: Value,
    /// Binds the authenticator's answer to this challenge.
    ///
    /// A bearer credential for the length of the ceremony — one that leaks
    /// inside that window is a ceremony an attacker can try to complete — so it
    /// is [`Sensitive`] (§24.5). It is **opaque**: this SDK never decodes it,
    /// and neither should a caller.
    pub state_token: Sensitive<String>,
}

impl WebauthnChallenge {
    /// The challenge in the JSON form every platform authenticator API takes
    /// (§24.6a rule 1).
    ///
    /// This is the string an Android app passes to
    /// `CreatePublicKeyCredentialRequest` or `GetPublicKeyCredentialOption`,
    /// and the value a browser passes to
    /// `PublicKeyCredential.parseCreationOptionsFromJSON()`. It is the inner
    /// options object: the `publicKey` wrapper belongs to the DOM's
    /// `CredentialCreationOptions`, and the platform JSON APIs do not want it.
    ///
    /// Pure local computation, no I/O. Nothing is defaulted, dropped or
    /// reordered on the way through (§24.0).
    pub fn request_json(&self) -> String {
        let options = self.challenge.get("publicKey").unwrap_or(&self.challenge);
        options.to_string()
    }
}

/// A credential the user just enrolled — the `201` body of `register/finish`.
#[derive(Debug, Clone, Deserialize)]
pub struct WebauthnCredential {
    /// The AXIAM record id.
    pub id: Uuid,
    /// base64url credential id, as the authenticator reported it.
    pub credential_id: String,
    /// The caller-supplied label.
    pub name: String,
    /// `"passkey"` or `"security_key"`, as the server classified it.
    pub credential_type: String,
    /// RFC 3339 timestamp of enrolment.
    pub created_at: String,
    /// RFC 3339 timestamp of the last successful assertion, if there has been
    /// one.
    #[serde(default)]
    pub last_used_at: Option<String>,
}

/// The outcome of a completed passkey sign-in.
///
/// The client is **already authenticated** when this is returned (§24.3
/// rule 1) — the tokens come back as well because a caller may want to hand
/// them onward, not because adoption was optional.
#[derive(Debug, Clone)]
pub struct WebauthnLoginResult {
    /// The new access token.
    pub access_token: Sensitive<String>,
    /// A **session** refresh token, refreshed through
    /// [`AxiamClient::refresh`] and not `oidc_refresh` (§24.3 rule 5).
    pub refresh_token: Sensitive<String>,
    /// Identifies the session just created.
    pub session_id: Uuid,
    /// Access-token lifetime in seconds.
    pub expires_in: u64,
}

/// The workspace a usernameless ceremony runs inside.
///
/// Unlike the five tenant-scoped `/oauth2/*` operations of §12.1 rule 2, this
/// endpoint **accepts slugs**, so a slug-only client can run a discoverable
/// sign-in. The SDK fills these from its own configured identity when the
/// caller passes `None`.
#[derive(Debug, Clone, Default)]
pub struct WebauthnWorkspace {
    /// Organization UUID.
    pub org_id: Option<Uuid>,
    /// Organization slug — accepted here, unlike on the `/oauth2/*` operations.
    pub org_slug: Option<String>,
    /// Tenant UUID.
    pub tenant_id: Option<Uuid>,
    /// Tenant slug.
    pub tenant_slug: Option<String>,
}

// ---------------------------------------------------------------------------
// Wire shapes
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
struct ChallengeWire {
    challenge: Value,
    state_token: String,
}

#[derive(Deserialize)]
struct LoginWire {
    access_token: String,
    refresh_token: String,
    session_id: Uuid,
    expires_in: u64,
}

/// The `setup/register/finish` success body — `LoginSuccessResponse`, the
/// same shape `mfa_setup_confirm` decodes (CONTRACT.md §25.1). Unlike
/// [`LoginWire`] above, tokens are **not** in this body — they arrive only as
/// the `axiam_access`/`axiam_refresh`/`axiam_csrf` cookie triple (§24.3),
/// which is why this struct carries neither `access_token` nor
/// `refresh_token`.
#[derive(Deserialize)]
struct SetupLoginSuccessWire {
    session_id: Uuid,
    expires_in: u64,
    /// CONTRACT 1.52 N5.5 (C-12): present on this completion exactly as on a
    /// password `login()`. Decoded leniently — absent means unknown, never
    /// an error (N5.5 rule 5).
    #[serde(default)]
    user: Option<LoginUserInfoWire>,
}

#[derive(Serialize)]
struct RegisterFinishBody {
    state_token: String,
    credential_name: String,
    response: Value,
}

impl std::fmt::Debug for RegisterFinishBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RegisterFinishBody")
            .field("state_token", &"[REDACTED]")
            .field("credential_name", &self.credential_name)
            .field("response", &self.response)
            .finish()
    }
}

#[derive(Serialize)]
struct FinishBody {
    state_token: String,
    response: Value,
}

impl std::fmt::Debug for FinishBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FinishBody")
            .field("state_token", &"[REDACTED]")
            .field("response", &self.response)
            .finish()
    }
}

#[derive(Debug, Serialize)]
struct AuthStartBody {
    challenge_token: String,
}

#[derive(Serialize)]
struct SetupRegisterStartBody {
    setup_token: String,
}

impl std::fmt::Debug for SetupRegisterStartBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SetupRegisterStartBody")
            .field("setup_token", &"[REDACTED]")
            .finish()
    }
}

#[derive(Serialize)]
struct SetupRegisterFinishBody {
    setup_token: String,
    state_token: String,
    credential_name: String,
    response: Value,
}

impl std::fmt::Debug for SetupRegisterFinishBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SetupRegisterFinishBody")
            .field("setup_token", &"[REDACTED]")
            .field("state_token", &"[REDACTED]")
            .field("credential_name", &self.credential_name)
            .field("response", &self.response)
            .finish()
    }
}

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

// ---------------------------------------------------------------------------
// The eight operations
// ---------------------------------------------------------------------------

impl AxiamClient {
    /// `POST /api/v1/auth/webauthn/register/start` (CONTRACT.md §24.1).
    ///
    /// Enrolling a passkey is something a signed-in user does to their own
    /// account, so this requires a session and fails **client-side with no wire
    /// call** when there is none.
    ///
    /// A `503` means the tenant's attestation policy requires attestation and
    /// the FIDO metadata service has no usable snapshot. That is a server
    /// configuration state, not a transient failure, so §24.4 rule 2
    /// deliberately does not retry it.
    pub async fn webauthn_register_start(&self) -> Result<WebauthnChallenge, AxiamError> {
        self.ensure_open()?;
        self.require_webauthn_session("webauthn_register_start")?;
        self.webauthn_start(REGISTER_START_PATH, &serde_json::json!({}))
            .await
    }

    /// `POST /api/v1/auth/webauthn/register/finish` (CONTRACT.md §24.1).
    ///
    /// `response` is the authenticator's answer, as
    /// [`serde_json::Value`] — build it from a platform's own JSON string with
    /// [`webauthn_response_from_json`] (§24.6a rule 2). It reaches the server
    /// unchanged: it is the input to a signature check over bytes this SDK did
    /// not produce.
    ///
    /// A `403` is the tenant's attestation policy refusing **this
    /// authenticator** — an AAGUID that is not allow-listed, a missing FIDO
    /// certification, a revoked status — not a permission problem with the
    /// user. The server's message is surfaced verbatim (§24.4 rule 1), because
    /// it is the only way the person holding the key learns a different one
    /// would work.
    pub async fn webauthn_register_finish(
        &self,
        state_token: &Sensitive<String>,
        credential_name: &str,
        response: Value,
    ) -> Result<WebauthnCredential, AxiamError> {
        self.ensure_open()?;
        self.require_webauthn_session("webauthn_register_finish")?;

        let body = RegisterFinishBody {
            state_token: state_token.expose().clone(),
            credential_name: credential_name.to_string(),
            response,
        };
        let http_response = self.webauthn_post(REGISTER_FINISH_PATH, &body).await?;

        match http_response.status().as_u16() {
            200 | 201 => http_response
                .json::<WebauthnCredential>()
                .await
                .map_err(deser_err),
            status => Err(map_error_response(status, http_response).await),
        }
    }

    /// `POST /api/v1/auth/webauthn/authenticate/start` (CONTRACT.md §24.1).
    ///
    /// The **second-factor** ceremony: it continues a
    /// [`login`](AxiamClient::login) that answered `mfa_required` with
    /// `"webauthn"` among its methods, and `challenge_token` is that result's
    /// token.
    ///
    /// A different flow from [`Self::webauthn_discoverable_start`], not the
    /// same one with an optional argument — see §24.2 for why they cannot be
    /// merged.
    pub async fn webauthn_authenticate_start(
        &self,
        challenge_token: &Sensitive<String>,
    ) -> Result<WebauthnChallenge, AxiamError> {
        self.ensure_open()?;
        let body = AuthStartBody {
            challenge_token: challenge_token.expose().clone(),
        };
        self.webauthn_start(AUTH_START_PATH, &body).await
    }

    /// `POST /api/v1/auth/webauthn/authenticate/finish` (CONTRACT.md §24.1).
    ///
    /// Leaves this client authenticated (§24.3 rule 1). That is not §14.3's
    /// "MAY adopt" posture: `device_login` mints tokens a caller may want to
    /// route elsewhere, and this is the SDK's own primary authentication —
    /// returning a token set without adopting it would make a passkey sign-in
    /// the one way to log in that does not log you in.
    pub async fn webauthn_authenticate_finish(
        &self,
        state_token: &Sensitive<String>,
        response: Value,
    ) -> Result<WebauthnLoginResult, AxiamError> {
        self.webauthn_finish(AUTH_FINISH_PATH, state_token, response)
            .await
    }

    /// `POST /api/v1/auth/webauthn/authenticate/discoverable/start`
    /// (CONTRACT.md §24.1).
    ///
    /// The **primary-factor** ceremony: nothing precedes it, the server sends
    /// an empty `allowCredentials`, and the assertion itself identifies the
    /// user.
    ///
    /// The workspace still has to be named — a discoverable credential is
    /// resolved inside one tenant's isolation boundary — but it comes from this
    /// client's own configuration unless overridden, and slugs are accepted.
    pub async fn webauthn_discoverable_start(
        &self,
        workspace: Option<&WebauthnWorkspace>,
    ) -> Result<WebauthnChallenge, AxiamError> {
        self.ensure_open()?;
        let body = self.webauthn_workspace_body(workspace)?;
        self.webauthn_start(DISCOVERABLE_START_PATH, &body).await
    }

    /// `POST /api/v1/auth/webauthn/authenticate/discoverable/finish`
    /// (CONTRACT.md §24.1).
    ///
    /// Leaves this client authenticated (§24.3). Unlike its username-bound
    /// twin, this fires the server's `login.post_auth` reactor hook (§22.5):
    /// there was no password step for the event to have been fired at.
    pub async fn webauthn_discoverable_finish(
        &self,
        state_token: &Sensitive<String>,
        response: Value,
    ) -> Result<WebauthnLoginResult, AxiamError> {
        self.webauthn_finish(DISCOVERABLE_FINISH_PATH, state_token, response)
            .await
    }

    /// `POST /api/v1/auth/webauthn/setup/register/start` (CONTRACT.md §24.1,
    /// §25.1 — contract 1.45).
    ///
    /// The WebAuthn twin of [`AxiamClient::mfa_setup_enroll`]: reached when
    /// [`AxiamClient::login`] answers `mfa_setup_required` and the caller
    /// chooses a passkey or security key over TOTP as their first factor.
    ///
    /// **Takes no session at all.** The setup token is the only credential —
    /// there is no session yet, because this is the account's *first* factor
    /// — and this call MUST NOT and does not attach this client's own session
    /// credential, even when one happens to be configured (§24.1). See
    /// [`Self::webauthn_setup_register_finish`] for why that matters and how
    /// it is enforced.
    ///
    /// `400` means the account already has a factor — the same answer
    /// [`AxiamClient::mfa_setup_enroll`] gives for the same reason: a setup
    /// token adds a first factor, never a second.
    pub async fn webauthn_setup_register_start(
        &self,
        setup_token: &Sensitive<String>,
    ) -> Result<WebauthnChallenge, AxiamError> {
        self.ensure_open()?;
        let body = SetupRegisterStartBody {
            setup_token: setup_token.expose().clone(),
        };
        let response = self
            .webauthn_post_no_session(SETUP_REGISTER_START_PATH, &body)
            .await?;
        match response.status().as_u16() {
            200 => {
                let wire: ChallengeWire = response.json().await.map_err(deser_err)?;
                Ok(WebauthnChallenge {
                    challenge: wire.challenge,
                    state_token: Sensitive::new(wire.state_token),
                })
            }
            status => Err(map_error_response(status, response).await),
        }
    }

    /// `POST /api/v1/auth/webauthn/setup/register/finish` (CONTRACT.md §24.1,
    /// §25.1, §25.2 rule 2 — contract 1.45).
    ///
    /// **Adopts credentials exactly as [`AxiamClient::mfa_setup_confirm`]
    /// does** (§25.2 rule 2): both are completions of the same interrupted
    /// login and both answer `LoginSuccessResponse`, so this mirrors that
    /// function's tail rather than `webauthn_finish`'s — the
    /// response carries no `access_token`/`refresh_token` in the body (they
    /// arrive only via the cookie triple, §24.3 rule 2), and there is no
    /// `WebauthnLoginResult` to build. §24.3's five adoption rules apply
    /// verbatim, including clearing the §17 decision memo: an SDK that
    /// adopted on one completion and not the other would leave a caller
    /// authenticated or not depending on which factor the user happened to
    /// choose.
    ///
    /// Like [`Self::webauthn_setup_register_start`], this takes no session:
    /// the setup token is the only credential, and neither call sends this
    /// client's own session cookie or CSRF header even when a session is
    /// configured — `webauthn_post_no_session` is what enforces that, by
    /// skipping `CsrfHeaderExt::maybe_csrf_header` and by pre-empting
    /// `reqwest`'s cookie jar with an explicit empty `Cookie` header (the jar
    /// only auto-populates one when the request does not already carry it).
    pub async fn webauthn_setup_register_finish(
        &self,
        setup_token: &Sensitive<String>,
        state_token: &Sensitive<String>,
        credential_name: &str,
        response: Value,
    ) -> Result<LoginResult, AxiamError> {
        self.ensure_open()?;
        // §17.1 rule 9 / §24.3 rule 4 / §25.2 rule 2: this completes a login,
        // and the subject is about to change.
        self.decision_memo().clear();

        let body = SetupRegisterFinishBody {
            setup_token: setup_token.expose().clone(),
            state_token: state_token.expose().clone(),
            credential_name: credential_name.to_string(),
            response,
        };
        let http_response = self
            .webauthn_post_no_session(SETUP_REGISTER_FINISH_PATH, &body)
            .await?;

        match http_response.status().as_u16() {
            200 => {
                let wire: SetupLoginSuccessWire = http_response.json().await.map_err(deser_err)?;
                // Same triple, same call as `mfa_setup_confirm` and every
                // other login completion (§24.3 rule 2).
                absorb_session_cookies(self).await?;
                // CONTRACT 1.52 N5.5 (C-12): record the gate from the
                // response's user object rather than leaving
                // `absorb_session_cookies`'s blanket reset to unknown.
                if let Some(user) = &wire.user {
                    self.set_principal_scope(Some(user.principal_scope()));
                }
                Ok(LoginResult::success(wire.session_id, wire.expires_in))
            }
            status => Err(map_error_response(status, http_response).await),
        }
    }

    // -----------------------------------------------------------------------
    // Internals
    // -----------------------------------------------------------------------

    /// Run either `*_start` call and return the options untouched.
    async fn webauthn_start<B: Serialize>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<WebauthnChallenge, AxiamError> {
        let response = self.webauthn_post(path, body).await?;
        match response.status().as_u16() {
            200 => {
                let wire: ChallengeWire = response.json().await.map_err(deser_err)?;
                Ok(WebauthnChallenge {
                    challenge: wire.challenge,
                    state_token: Sensitive::new(wire.state_token),
                })
            }
            status => Err(map_error_response(status, response).await),
        }
    }

    /// The shared tail of both authentication ceremonies.
    async fn webauthn_finish(
        &self,
        path: &str,
        state_token: &Sensitive<String>,
        response: Value,
    ) -> Result<WebauthnLoginResult, AxiamError> {
        self.ensure_open()?;
        // §17.1 rule 9 / §24.3 rule 4: memo entries are keyed by subject, and
        // this call changes the subject.
        self.decision_memo().clear();

        let body = FinishBody {
            state_token: state_token.expose().clone(),
            response,
        };
        let http_response = self.webauthn_post(path, &body).await?;

        match http_response.status().as_u16() {
            200 => {
                let wire: LoginWire = http_response.json().await.map_err(deser_err)?;
                // The server sets the same axiam_access/axiam_refresh/axiam_csrf
                // triple here as it does on a password login, so adoption is
                // the same call.
                absorb_session_cookies(self).await?;
                Ok(WebauthnLoginResult {
                    access_token: Sensitive::new(wire.access_token),
                    refresh_token: Sensitive::new(wire.refresh_token),
                    session_id: wire.session_id,
                    expires_in: wire.expires_in,
                })
            }
            status => Err(map_error_response(status, http_response).await),
        }
    }

    /// POST a JSON body.
    ///
    /// Deliberately not routed through §16's retry helper, and that is true for
    /// the whole section: most of these operations are ceremony steps that
    /// consume server-side state, and `register/start` carries the `503`
    /// §24.4 rule 2 forbids retrying. There is nothing here a bounded retry
    /// could help.
    async fn webauthn_post<B: Serialize>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<reqwest::Response, AxiamError> {
        self.http()
            .post(self.url(path))
            .maybe_csrf_header(self)
            // CONTRACT 1.52 N4.3 (C-12): present the held device credential
            // and withhold a stale cookie, exactly as management/authz do
            // (`client.rs::session_credential`).
            .session_credential_of(self)
            // CONTRACT 1.52 N-§5-rule-2 (C-12): `X-Tenant-ID` is
            // unconditional on every request — this builder predated the
            // rule and only ever sent §5.2 rule 1's `X-Axiam-Tenant` ("as
            // normal", §5.2.2 rule 4).
            .tenant_headers_of(self)
            .json(body)
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("webauthn request failed: {e}"),
                source: Some(Box::new(e)),
            })
    }

    /// POST a JSON body for the two `setup/register/*` operations, which take
    /// **no session** (§24.1, contract 1.45) — deliberately not shared with
    /// [`Self::webauthn_post`] above, because that function attaches this
    /// client's stored CSRF token, and the whole point here is to attach
    /// nothing this client has from a prior session:
    ///
    /// * No [`CsrfHeaderExt::maybe_csrf_header`] call — the setup token is the
    ///   only credential; a CSRF token echoed alongside it would be a second,
    ///   unasked-for one.
    /// * An explicit, empty `Cookie` header. `reqwest`'s cookie jar only
    ///   auto-populates the `Cookie` header when the outgoing request does
    ///   not already carry one — setting it here (even to nothing) pre-empts
    ///   that, so a session cookie held by this client's jar from an
    ///   unrelated prior login never rides along. The **response's**
    ///   `Set-Cookie` headers are unaffected by this and still populate the
    ///   jar normally, which is what lets `webauthn_setup_register_finish`
    ///   adopt the new session afterwards exactly as `mfa_setup_confirm` does.
    ///
    /// §24.8 requires a test asserting both, on the transport, with a session
    /// configured.
    async fn webauthn_post_no_session<B: Serialize>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<reqwest::Response, AxiamError> {
        self.http()
            .post(self.url(path))
            // CONTRACT 1.52 N-§5-rule-2 (C-12): unconditional on every
            // outgoing request, even this sessionless pair — distinct from
            // the CSRF/cookie omission just above, which is deliberate.
            .header("X-Tenant-ID", self.tenant_header_value())
            .header(reqwest::header::COOKIE, "")
            .json(body)
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("webauthn request failed: {e}"),
                source: Some(Box::new(e)),
            })
    }

    /// §24.1: `register/*` needs a session, and the refusal is raised
    /// client-side with **no wire call** — the shape §1.1 rule 3 requires of
    /// `get_user_info`.
    ///
    /// The signal is the access cookie rather than a separate flag: this SDK
    /// has never kept one, and a second source of truth for "am I signed in" is
    /// a second thing to get out of step with the jar.
    fn require_webauthn_session(&self, operation: &str) -> Result<(), AxiamError> {
        if self.inner.jar.access_token(&self.inner.base_url).is_none() {
            return Err(AxiamError::Auth {
                message: format!(
                    "{operation} requires an authenticated session: enrol a passkey while \
                     signed in (CONTRACT.md §24.1)"
                ),
                oauth: None,
                reason: None,
                set_reason: None,
                retry_after: None,
            });
        }
        Ok(())
    }

    /// Fill the discoverable ceremony's workspace from this client's own
    /// configuration when the caller passed none.
    ///
    /// Only fields that actually have a value are emitted: the server takes
    /// either form at either level, and sending `null` for the ones it does not
    /// have is indistinguishable from asking it to resolve nothing.
    fn webauthn_workspace_body(
        &self,
        workspace: Option<&WebauthnWorkspace>,
    ) -> Result<DiscoverableStartBody, AxiamError> {
        let mut body = DiscoverableStartBody {
            org_id: workspace.and_then(|w| w.org_id),
            org_slug: workspace.and_then(|w| w.org_slug.clone()),
            tenant_id: workspace.and_then(|w| w.tenant_id),
            tenant_slug: workspace.and_then(|w| w.tenant_slug.clone()),
        };

        if body.org_id.is_none() && body.org_slug.is_none() {
            match self.org_identifier() {
                Some(OrgIdentifier::Id(id)) => body.org_id = Some(*id),
                Some(OrgIdentifier::Slug(slug)) => body.org_slug = Some(slug.clone()),
                None => {
                    // This SDK's §2 taxonomy has three variants and no
                    // Validation; a missing client configuration is a
                    // deployment mistake, which §12.1 already routes through
                    // `Auth` for the same reason.
                    return Err(AxiamError::auth(
                        "webauthn_discoverable_start needs an organization: construct the \
                         client with one, or pass it in the workspace argument \
                         (CONTRACT.md §24.1)",
                    ));
                }
            }
        }
        if body.tenant_id.is_none() && body.tenant_slug.is_none() {
            match &self.inner.tenant {
                TenantIdentifier::Id(id) => body.tenant_id = Some(*id),
                TenantIdentifier::Slug(slug) => body.tenant_slug = Some(slug.clone()),
            }
        }
        Ok(body)
    }
}

/// Parse a platform's authenticator response JSON into the value the
/// `*_finish` operations take (§24.6a rule 2).
///
/// Android's Credential Manager hands back `registrationResponseJson` /
/// `authenticationResponseJson`, and a browser hands back
/// `credential.toJSON()`. Making a caller model one of those as a Rust struct
/// this SDK immediately re-serializes is three chances to corrupt a signed
/// buffer in service of nothing — so the string is taken directly.
///
/// Parsing is value-preserving: every field in these messages is a string or a
/// plain object, so what reaches the server is what the authenticator produced.
pub fn webauthn_response_from_json(response: &str) -> Result<Value, AxiamError> {
    let value: Value = serde_json::from_str(response).map_err(|e| {
        AxiamError::auth(format!(
            "the authenticator response string is not valid JSON ({e}). Pass the platform's \
             response JSON verbatim (CONTRACT.md §24.6a)"
        ))
    })?;
    if !value.is_object() {
        return Err(AxiamError::auth(
            "the authenticator response must be a JSON object (CONTRACT.md §24.6a)",
        ));
    }
    Ok(value)
}

// ---------------------------------------------------------------------------
// §24.6b rule 5 — ceremony failure classification
// ---------------------------------------------------------------------------

/// A ceremony failure a caller can say something useful about (§24.6b rule 5).
///
/// Five outcomes, and the first two are the ones that matter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebauthnFailure {
    /// Covers **both** an explicit refusal and a silent timeout.
    ///
    /// The WebAuthn spec deliberately refuses to distinguish them, because
    /// telling a website which one happened leaks whether an authenticator was
    /// present. It must not be recovered by timing the call.
    Cancelled,
    /// The authenticator already holds a credential for this account and
    /// refused to silently mint a second — the exclusion list working, not a
    /// failure. The only classification whose remedy is "use a different
    /// device".
    AlreadyRegistered,
    /// An explicitly aborted ceremony.
    Timeout,
    /// This device or browser cannot run the ceremony.
    Unsupported,
    /// Everything else.
    Unknown,
}

impl WebauthnFailure {
    /// Map a platform ceremony error name to its canonical classification.
    ///
    /// Every platform reports a ceremony failure as one opaque type whose only
    /// machine-readable part is a name, so a handset can relay just that name
    /// and a Rust service can turn it into the same five outcomes a browser
    /// would see. Anything unrecognized is [`Self::Unknown`] rather than an
    /// error — a classifier that can fail is one more thing for an error
    /// handler to handle.
    pub fn classify(name: &str) -> Self {
        match name.trim().to_ascii_lowercase().as_str() {
            "notallowederror" | "canceled" | "cancelled" => Self::Cancelled,
            "invalidstateerror" => Self::AlreadyRegistered,
            "aborterror" | "timeout" => Self::Timeout,
            "notsupportederror" | "securityerror" => Self::Unsupported,
            _ => Self::Unknown,
        }
    }

    /// Copy for this failure, safe to show a user.
    ///
    /// The [`Self::Cancelled`] string deliberately does not accuse anyone of
    /// cancelling: the same classification covers a silent timeout, and the
    /// spec will not say which happened.
    pub fn message(self) -> &'static str {
        match self {
            Self::Cancelled => "The request was cancelled or timed out. You can try again.",
            Self::AlreadyRegistered => {
                "This device is already registered on your account. Try a different device, \
                 or remove the existing one first."
            }
            Self::Timeout => "The request timed out before it completed. Please try again.",
            Self::Unsupported => {
                "This browser or device cannot be used for passkeys. Try a different browser, \
                 or use another sign-in method."
            }
            Self::Unknown => "Something went wrong. Please try again.",
        }
    }
}

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

    // §24.2: `state_token` is the ceremony's bearer handle — whoever holds it
    // can finish the ceremony — so §7 rule 3 applies to it exactly as it does
    // to a password, and these bodies hand-write `Debug` to say so.

    #[test]
    fn register_finish_body_debug_redacts_the_state_token() {
        let rendered = format!(
            "{:?}",
            RegisterFinishBody {
                state_token: "state-token-abc".into(),
                credential_name: "Alice's laptop".into(),
                response: serde_json::json!({ "id": "credential-id" }),
            }
        );
        assert!(!rendered.contains("state-token-abc"), "{rendered}");
        assert!(rendered.contains("[REDACTED]"), "{rendered}");
        // The name and the authenticator response are not secrets: §24.0 hands
        // the response through untouched, and a redaction here would hide the
        // one field an integrator debugging a rejected attestation needs.
        assert!(rendered.contains("Alice's laptop"), "{rendered}");
        assert!(rendered.contains("credential-id"), "{rendered}");
    }

    #[test]
    fn finish_body_debug_redacts_the_state_token() {
        let rendered = format!(
            "{:?}",
            FinishBody {
                state_token: "state-token-abc".into(),
                response: serde_json::json!({ "id": "credential-id" }),
            }
        );
        assert!(!rendered.contains("state-token-abc"), "{rendered}");
        assert!(rendered.contains("[REDACTED]"), "{rendered}");
        assert!(rendered.contains("credential-id"), "{rendered}");
    }
}