polyc-web-session 2026.9.0

Browser session establishment (ADR 0007): one-time login challenges, the shared session cookie, and both the persona-passkey and wallet-passkey ceremonies that mint a polyc_crypto::session token. Consumed by polyc-control-plane; carries no ceremony-consumer naming of its own.
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
//! The persona-rooted passkey login ceremony (ADR 0007).
//!
//! A discoverable `WebAuthn` assertion, verified against a persona's
//! already-enrolled [`polyc_persona::PersonaCredential`], resolved into a
//! [`polyc_crypto::session`] token.
//!
//! [`PasskeyLoginSessions`] mints one-time challenges
//! ([`PasskeyLoginSessions::challenge`], built on
//! [`crate::LoginChallengeRegistry`]) and redeems a posted assertion
//! ([`PasskeyLoginSessions::login`]) into a minted session token. The login
//! challenge is single-use, while the credential is reusable. Nothing is
//! written to the persona store here, only read and verified.
//!
//! # `credential_id` -> `persona_id` resolution
//!
//! A login assertion's `userHandle` carries no persona id to read (the
//! retired browser enrollment ceremony minted a fresh random `user.id`,
//! deliberately never the persona id, so it can never collide with the
//! wallet-passkey credential's own `user.id`). This module instead uses
//! [`polyc_persona::PersonaHost::resolve_persona_credential`], a reverse-
//! index read backed by a directory row written once at enrollment
//! (`credential_id -> persona_id`, keyed independently of the forward
//! `persona_id -> PersonaCredential` row). That resolution is explicitly a
//! directory pointer only — [`PasskeyLoginSessions::login`] always re-reads
//! the authoritative forward record via
//! [`polyc_persona::PersonaHost::get_persona_credential`] before trusting a
//! public key or a `revoked` flag.

use polyc_passkey::{Assertion, verify_assertion};
use std::sync::Arc;

use crate::{
    LoginChallenge, LoginChallengeRegistry, MintedSession, ScopeRoot, WebAuthnLoginConfig,
};
use polyc_ceremony::{CeremonyAuthority, CeremonyError};
use polyc_session_family::authority::BrowserSessionAuthority;

/// What the browser posts back to [`PasskeyLoginSessions::login`]: the
/// `WebAuthn` login assertion plus the credential id it was signed by.
///
/// The superset of [`Assertion`] (the same three signed outputs) plus the
/// opaque `credential_id` a browser's `navigator.credentials.get()` always
/// returns. Owned rather than borrowed, since a POST body decodes into owned
/// `Vec<u8>` fields; [`Assertion`] is borrowed and is what the verifier
/// takes, so this type lends its slices at the call site.
#[derive(Debug, Clone)]
pub struct PostedLoginAssertion {
    /// Opaque `WebAuthn` credential id the authenticator returned.
    pub credential_id: Vec<u8>,
    /// Raw authenticator data from the assertion.
    pub authenticator_data: Vec<u8>,
    /// Raw `clientDataJSON` bytes from the assertion.
    pub client_data_json: Vec<u8>,
    /// DER-encoded ECDSA (P-256) signature from the assertion.
    pub signature: Vec<u8>,
}

/// A login failed; every variant is a hard rejection (fail-closed, no
/// partial acceptance).
///
/// The message is neutral server-internal text — this module mounts no
/// route, so nothing here is reader-facing copy; the caller's HTTP handler
/// decides what (if anything) to surface.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum LoginError {
    /// The login challenge was missing, already redeemed, or older than the
    /// shared one-time-token TTL.
    #[error("login challenge was missing, already used, or expired")]
    ChallengeExpired,
    /// No enrolled credential resolves to this `credential_id` (directory
    /// miss), OR the resolved persona has no forward
    /// [`polyc_persona::PersonaCredential`] record to load (should not
    /// happen absent store corruption, since the directory row is written
    /// alongside the forward record — treated the same, fail-closed).
    #[error("no enrolled passkey credential matches this login assertion")]
    UnknownCredential,
    /// The resolved credential exists but has been revoked.
    #[error("this passkey credential has been revoked")]
    CredentialRevoked,
    /// [`verify_assertion`] rejected the assertion (wrong challenge, origin,
    /// rp id, signature, or malformed authenticator data — the specific
    /// [`polyc_passkey::WebAuthnError`] is not preserved).
    #[error("the passkey assertion did not verify")]
    AssertionRejected,
    /// The resolved persona exists but is not [`polyc_persona::STATUS_LINKED`]
    /// (e.g. still provisional).
    #[error("this persona is not a linked, registered user")]
    NotLinked,
    /// A persona-store read failed (host closed or a database error) — no
    /// verification verdict was reached either way.
    #[error("a persona-store read failed during login")]
    Storage,
    /// The session-family store failed while creating this session's
    /// rotation family.
    #[error("a session-store write failed during login")]
    FamilyStore(#[from] polyc_session_family::authority::SessionAuthorityError),
    /// Durable one-time authority could not establish a safe verdict.
    #[error("the one-time ceremony authority is unavailable")]
    CeremonyStore,
}

/// The registry of pending persona-credential login challenges plus the
/// deployment's `WebAuthn` login-page config.
///
/// A thin persona-credential-specific wrapper around
/// [`LoginChallengeRegistry`]: challenge mint/redeem, the `WebAuthn`
/// login-page config, and the logout denylist are the credential-agnostic
/// half every `WebAuthn`-rooted login ceremony needs, so they live in the
/// shared registry [`crate::wallet_login`] (a sibling ceremony feeding the
/// SAME session shape, not a replacement for this one) can build its own
/// wrapper around too. [`Self::login`] is the persona-credential-specific
/// half that stays here — resolving a `credential_id` to a persona and
/// verifying against its enrolled key is meaningless for a wallet login,
/// which instead resolves a wallet address to an onchain-derived public
/// key. [`Self::login`] never writes to the persona store, and a successful
/// login can be repeated indefinitely (until the credential is revoked)
/// rather than being spent.
pub struct PasskeyLoginSessions {
    /// The shared challenge/config registry this wrapper delegates
    /// to for everything except the credential-specific verification step.
    registry: LoginChallengeRegistry,
}

impl PasskeyLoginSessions {
    /// Build the registry from the login page's public `base_url` and an
    /// optional `rp_id_override`, or `None` when the URL yields no
    /// `WebAuthn` origin OR the override is set but is not a registrable
    /// suffix of the URL's host (fail closed — see
    /// [`WebAuthnLoginConfig::from_base_url`]).
    #[must_use]
    pub fn from_base_url(
        base_url: &str,
        rp_id_override: Option<&str>,
        ceremonies: Arc<dyn CeremonyAuthority>,
    ) -> Option<Self> {
        Some(Self {
            registry: LoginChallengeRegistry::from_base_url(base_url, rp_id_override, ceremonies)?,
        })
    }

    /// The `WebAuthn` config this registry verifies login assertions
    /// against. Also the source of the session cookie's `Domain` attribute
    /// — the login page's registrable host and the cookie's scope are the
    /// SAME field deliberately (design doc, "Resolved" #3).
    #[must_use]
    pub const fn config(&self) -> &WebAuthnLoginConfig {
        self.registry.config()
    }

    /// Mint a one-time login challenge. Delegates to
    /// [`LoginChallengeRegistry::challenge`].
    ///
    /// # Errors
    ///
    /// Returns the durable authority failure when no token was safely minted.
    pub async fn challenge(&self, now_ms: u64) -> Result<LoginChallenge, CeremonyError> {
        self.registry.challenge(now_ms).await
    }

    /// Redeem a login challenge against a posted assertion and, on success,
    /// mint a session token bound to the resolved persona.
    ///
    /// Steps:
    ///
    /// 1. Redeem `challenge_token` through the durable authority as the first
    ///    operation, so a replayed token fails whether the later verification
    ///    succeeds or rejects.
    /// 2. Resolve `proof.credential_id` to a persona id via
    ///    [`polyc_persona::PersonaHost::resolve_persona_credential`] (directory pointer
    ///    only).
    /// 3. Load that persona's authoritative
    ///    [`polyc_persona::PersonaCredential`]; reject if absent or revoked.
    /// 4. Verify the assertion ([`verify_assertion`]) against THIS
    ///    registry's `rp_id`/`origin` (the login page's) and the
    ///    credential's stored public key.
    /// 5. Confirm the persona is [`polyc_persona::STATUS_LINKED`] — the
    ///    precondition for establishing a session here at all.
    /// 6. Resolve the session's scopes via [`crate::resolve_subject_and_scopes`]
    ///    (the ONE shared scope-policy helper: scopes are recomputed fresh
    ///    here, never replayed from a stored value), then durably create the
    ///    rotation family and bearer through [`BrowserSessionAuthority`].
    ///
    /// # Cancellation safety
    ///
    /// The durable redemption is the first awaited operation. If the caller
    /// cancels while its outcome is ambiguous, retrying may observe the token
    /// as spent; it can never restore or double-spend it. The caller therefore
    /// starts a fresh ceremony after cancellation. Every step from 2 onward is
    /// read-only against the persona store until step 6's family creation.
    ///
    /// # Errors
    ///
    /// See [`LoginError`]'s variants.
    pub async fn login(
        &self,
        challenge_token: &str,
        proof: &PostedLoginAssertion,
        persona: &(impl crate::PersonaSessionReader + ?Sized),
        sessions: &dyn BrowserSessionAuthority,
        now_ms: u64,
    ) -> Result<MintedSession, LoginError> {
        // 1. Redeem single-use as the first durable operation. An unknown,
        // expired, spent, or concurrently changed challenge stays one neutral
        // rejection; an unavailable or malformed authority answer is an
        // operational failure, never an authentication oracle.
        match self.registry.redeem(challenge_token, now_ms).await {
            Ok(()) => {}
            Err(
                CeremonyError::NotRecognized
                | CeremonyError::Expired
                | CeremonyError::Spent
                | CeremonyError::Conflict,
            ) => return Err(LoginError::ChallengeExpired),
            Err(CeremonyError::Invalid | CeremonyError::Unavailable) => {
                return Err(LoginError::CeremonyStore);
            }
        }
        let expected_challenge = polyc_passkey::challenge_b64(challenge_token.as_bytes());

        // 2. credential_id -> persona_id (directory pointer only; see module docs).
        let persona_id = persona
            .session_credential_persona(&proof.credential_id)
            .await
            .map_err(|()| LoginError::Storage)?
            .ok_or(LoginError::UnknownCredential)?;

        // 3. Load the authoritative record; reject absent/revoked.
        let credential = persona
            .session_credential(&persona_id)
            .await
            .map_err(|()| LoginError::Storage)?
            .ok_or(LoginError::UnknownCredential)?;
        if credential.revoked {
            return Err(LoginError::CredentialRevoked);
        }

        // 4. Verify against the LOGIN PAGE's rp_id/origin (`self.registry`'s
        // config, never the credential's stored enrollment rp_id/origin) and
        // the credential's registered public key.
        let config = self.registry.config();
        let assertion = Assertion {
            authenticator_data: &proof.authenticator_data,
            client_data_json: &proof.client_data_json,
            signature: &proof.signature,
        };
        verify_assertion(
            &credential.p256_public_key_sec1,
            &assertion,
            &expected_challenge,
            &config.rp_id,
            &config.origin,
        )
        .map_err(|_| LoginError::AssertionRejected)?;

        // 5. Confirm the persona is a linked, registered user — this
        // ceremony's own precondition for minting a session at all (a
        // REFRESH, unlike login, tolerates an unlinked persona and simply
        // withholds the linked-only scopes; see `crate::resolve_subject_and_scopes`'s
        // doc for that split).
        let profile = persona
            .session_profile(persona_id.clone())
            .await
            .map_err(|()| LoginError::Storage)?
            .ok_or(LoginError::UnknownCredential)?;
        if profile.status != polyc_persona::STATUS_LINKED {
            return Err(LoginError::NotLinked);
        }

        // 6. Scopes via the ONE shared policy helper. A persona-credential
        // login carries `explorer-read` plus `agent-turn`; `wallet-manage` is
        // minted only by a wallet-rooted
        // login (`crate::wallet_login`). The two are minted together by
        // POLICY, not because either implies the other (ADR 0007): this
        // ceremony has just verified a passkey assertion for a
        // `STATUS_LINKED` persona (step 5, just above), which is the same
        // standard of proof a turn needs, and separating them into a second
        // cookie-authorized upgrade step would add a gesture without
        // reducing any threat — whoever can present this cookie could take
        // that step too. Every gate still names the exact scope it requires,
        // so tightening this is a change in the shared helper alone.
        let (subject, scopes) = crate::resolve_subject_and_scopes(
            persona,
            ScopeRoot::PersonaCredential {
                persona_id: persona_id.clone(),
            },
        )
        .await
        .map_err(|_| LoginError::Storage)?;

        let (family, grant) = sessions
            .create_family(ScopeRoot::PersonaCredential { persona_id }, now_ms)
            .await
            .map_err(LoginError::FamilyStore)?;

        let session_token = sessions
            .mint_bearer(&subject, &scopes, now_ms, crate::SESSION_TTL_MS)
            .await
            .map_err(LoginError::FamilyStore)?;
        Ok(MintedSession {
            session_token,
            grant,
            family_expires_ms: family.absolute_expires_ms,
        })
    }

    /// Legacy fixture logout. Production logout is a durable State command.
    #[cfg(any(test, feature = "test-util"))]
    pub fn logout(&self, session_token: &str) {
        self.registry.logout(session_token);
    }

    /// Legacy fixture denylist.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub const fn revoked(&self) -> &std::sync::Arc<polyc_crypto::session::RevokedTokens> {
        self.registry.revoked()
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use polyc_ceremony::test_util::MemoryCeremonies;
    use polyc_crypto::session::{
        SessionScope, SessionSubject, mint_session, verify_authorized_session, verify_session,
    };
    use polyc_crypto::signing_role::WebSessionGrantSigner;
    use polyc_passkey::softkey::SoftPasskey;
    use polyc_persona::PersonaHost;

    use super::*;
    use polyc_session_family::family_host::test_util::spawn_families;

    const BASE_URL: &str = "https://explore.polychrome.test";
    const NOW: u64 = 1_700_000_000_000;

    fn test_signer() -> WebSessionGrantSigner {
        WebSessionGrantSigner::from_key_bytes(&[7u8; 32])
            .expect("valid 32-byte ed25519 key material")
    }

    fn test_sessions() -> PasskeyLoginSessions {
        PasskeyLoginSessions::from_base_url(BASE_URL, None, Arc::new(MemoryCeremonies::new()))
            .expect("a well-formed https URL configures")
    }

    /// A spawned `PersonaHost` on a temp dir, cleaned up on drop.
    struct TestPersona {
        host: PersonaHost,
        shutdown: tokio_util::sync::CancellationToken,
        dir: std::path::PathBuf,
    }
    impl std::ops::Deref for TestPersona {
        type Target = PersonaHost;
        fn deref(&self) -> &Self::Target {
            &self.host
        }
    }
    impl Drop for TestPersona {
        fn drop(&mut self) {
            self.shutdown.cancel();
            let _ = std::fs::remove_dir_all(&self.dir);
        }
    }
    fn spawn_persona() -> TestPersona {
        let dir = std::env::temp_dir().join(format!(
            "polychrome-passkey-login-{}-{}",
            std::process::id(),
            uuid::Uuid::new_v4()
        ));
        let shutdown = tokio_util::sync::CancellationToken::new();
        let host = PersonaHost::spawn(dir.clone(), shutdown.clone()).expect("spawn persona host");
        TestPersona {
            host,
            shutdown,
            dir,
        }
    }

    /// A `SoftPasskey`'s credential id is a fixed constant regardless of
    /// seed — extracted from a throwaway signed assertion since
    /// [`SoftPasskey`] exposes it only on
    /// [`polyc_passkey::softkey::SignedAssertion`], never as a bare getter.
    fn credential_id_of(soft: &SoftPasskey) -> Vec<u8> {
        soft.sign_assertion("unused", "unused.example", "https://unused.example")
            .credential_id
    }

    /// Provision a fresh, `STATUS_LINKED` persona bound to `soft`'s passkey
    /// credential and return its persona id, so a login assertion for it has
    /// something to verify against.
    async fn enroll_and_link(persona: &PersonaHost, soft: &SoftPasskey) -> String {
        let actor = polyc_proto::proto::polychrome::persona::v1::ExternalIdentity {
            provider: "test".to_owned(),
            external_id: "actor".to_owned(),
            ..Default::default()
        };
        persona
            .attribute(
                actor.clone(),
                "conv-bootstrap".to_owned(),
                polyc_persona::ROLE_INITIATOR.to_owned(),
                NOW,
            )
            .await
            .expect("bootstrap actor persona");

        let target = polyc_proto::proto::polychrome::persona::v1::ExternalIdentity {
            provider: "test".to_owned(),
            external_id: uuid::Uuid::new_v4().to_string(),
            ..Default::default()
        };
        let code = uuid::Uuid::new_v4().to_string();
        persona
            .start_link(actor, code.clone(), 3_600_000, NOW)
            .await
            .expect("start_link");
        let persona_id = match persona
            .complete_link(code, target, NOW)
            .await
            .expect("complete_link")
        {
            polyc_persona::CompleteLinkOutcome::Linked { persona_id } => persona_id,
            other => panic!("a fresh target must link cleanly: {other:?}"),
        };

        persona
            .seed_persona_credential_for_tests(
                &persona_id,
                credential_id_of(soft),
                soft.public_key_sec1(),
                vec![9u8; 32],
                "unused.enrollment.rp".to_owned(),
                "https://unused.enrollment.origin".to_owned(),
                NOW,
            )
            .await
            .expect("seed_persona_credential_for_tests");

        persona_id
    }

    fn build_proof(
        soft: &SoftPasskey,
        challenge_b64: &str,
        rp_id: &str,
        origin: &str,
    ) -> PostedLoginAssertion {
        let signed = soft.sign_assertion(challenge_b64, rp_id, origin);
        PostedLoginAssertion {
            credential_id: signed.credential_id,
            authenticator_data: signed.authenticator_data,
            client_data_json: signed.client_data_json,
            signature: signed.signature,
        }
    }

    // ---- round-trip -------------------------------------------------------

    #[tokio::test]
    async fn valid_login_mints_a_session_verify_session_accepts() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let signer = test_signer();
        let soft = SoftPasskey::from_seed(1);
        let persona_id = enroll_and_link(&persona, &soft).await;

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            &sessions.config().rp_id,
            &sessions.config().origin,
        );

        let minted = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect("a valid assertion for a linked, enrolled persona logs in");

        let resolved =
            verify_authorized_session(&signer.public_key_bytes(), &minted.session_token, NOW)
                .expect("a freshly minted session verifies");
        assert_eq!(resolved.subject.persona_id(), Some(persona_id.as_str()));
        assert!(resolved.has_scope(polyc_crypto::session::SessionScope::ExplorerRead));
        assert!(
            resolved.has_scope(polyc_crypto::session::SessionScope::AgentTurn),
            "a verified assertion for a STATUS_LINKED persona is the same standard of proof a turn \
             needs, so this ceremony mints AgentTurn alongside ExplorerRead (ADR 0007)"
        );
        assert!(
            !resolved.has_scope(polyc_crypto::session::SessionScope::WalletManage),
            "minting two scopes together is a policy choice, not a slide into minting every scope \
             — wallet-manage still belongs to the wallet-rooted ceremony alone"
        );

        // The family this login created verifies against the SAME grant returned.
        let claims =
            polyc_crypto::session_grant::verify_grant(&signer.public_key_bytes(), &minted.grant)
                .expect("a freshly minted grant verifies");
        assert_eq!(claims.generation, 1);
        let family = families
            .get(claims.family_id.clone())
            .await
            .expect("get")
            .expect("the family login created is present");
        assert_eq!(family.persona_id, persona_id);
        assert_eq!(minted.family_expires_ms, family.absolute_expires_ms);
    }

    // ---- assertion rejection: wrong challenge / origin / rp_id ------------

    #[tokio::test]
    async fn wrong_challenge_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(2);
        enroll_and_link(&persona, &soft).await;

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            "some-other-challenge",
            &sessions.config().rp_id,
            &sessions.config().origin,
        );

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a mismatched challenge must be rejected");
        assert_eq!(err, LoginError::AssertionRejected);
    }

    #[tokio::test]
    async fn wrong_origin_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(3);
        enroll_and_link(&persona, &soft).await;

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            &sessions.config().rp_id,
            "https://evil.example",
        );

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a mismatched origin must be rejected");
        assert_eq!(err, LoginError::AssertionRejected);
    }

    #[tokio::test]
    async fn wrong_rp_id_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(4);
        enroll_and_link(&persona, &soft).await;

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            "other.rp.id",
            &sessions.config().origin,
        );

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a mismatched rp id must be rejected");
        assert_eq!(err, LoginError::AssertionRejected);
    }

    // ---- challenge expiry / replay -----------------------------------------

    #[tokio::test]
    async fn expired_challenge_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(5);
        enroll_and_link(&persona, &soft).await;

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            &sessions.config().rp_id,
            &sessions.config().origin,
        );

        let err = sessions
            .login(
                &challenge.token,
                &proof,
                &*persona,
                &*families,
                NOW + polyc_ceremony::MAX_TTL_MS + 1,
            )
            .await
            .expect_err("a challenge older than the shared TTL must be rejected");
        assert_eq!(err, LoginError::ChallengeExpired);
    }

    #[tokio::test]
    async fn replayed_challenge_token_is_rejected_proving_single_use() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(6);
        enroll_and_link(&persona, &soft).await;

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            &sessions.config().rp_id,
            &sessions.config().origin,
        );

        sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect("first redemption succeeds");

        let replay = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await;
        assert_eq!(
            replay.unwrap_err(),
            LoginError::ChallengeExpired,
            "a spent challenge token must never redeem twice"
        );
    }

    // ---- unlinked persona ---------------------------------------------------

    #[tokio::test]
    async fn unlinked_provisional_persona_with_a_valid_assertion_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(7);
        let outcome = persona
            .attribute(
                polyc_proto::proto::polychrome::persona::v1::ExternalIdentity {
                    provider: "test".to_owned(),
                    external_id: "unlinked-persona".to_owned(),
                    ..Default::default()
                },
                "conv-1".to_owned(),
                polyc_persona::ROLE_INITIATOR.to_owned(),
                NOW,
            )
            .await
            .expect("attribute provisions a persona");
        persona
            .seed_persona_credential_for_tests(
                &outcome.persona_id,
                credential_id_of(&soft),
                soft.public_key_sec1(),
                vec![9u8; 32],
                "unused.enrollment.rp".to_owned(),
                "https://unused.enrollment.origin".to_owned(),
                NOW,
            )
            .await
            .expect("seed_persona_credential_for_tests");

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            &sessions.config().rp_id,
            &sessions.config().origin,
        );

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a provisional persona must not log in");
        assert_eq!(err, LoginError::NotLinked);
    }

    // ---- unknown / revoked credential ---------------------------------------

    #[tokio::test]
    async fn unknown_credential_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(8);

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            &sessions.config().rp_id,
            &sessions.config().origin,
        );

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("an unenrolled credential id must not resolve");
        assert_eq!(err, LoginError::UnknownCredential);
    }

    #[tokio::test]
    async fn revoked_credential_is_rejected() {
        let sessions = test_sessions();
        let persona = spawn_persona();
        let families = spawn_families(test_signer());
        let _signer = test_signer();
        let soft = SoftPasskey::from_seed(9);
        let persona_id = enroll_and_link(&persona, &soft).await;
        persona
            .revoke_persona_credential(&persona_id, NOW)
            .await
            .expect("revoke")
            .expect("a credential was enrolled to revoke");

        let challenge = sessions.challenge(NOW).await.expect("mint challenge");
        let proof = build_proof(
            &soft,
            &challenge.challenge_b64,
            &sessions.config().rp_id,
            &sessions.config().origin,
        );

        let err = sessions
            .login(&challenge.token, &proof, &*persona, &*families, NOW)
            .await
            .expect_err("a revoked credential must not log in even with a valid assertion");
        assert_eq!(err, LoginError::CredentialRevoked);
    }

    // ---- logout ---------------------------------------------------------------

    #[test]
    fn logout_revokes_a_previously_accepted_session() {
        let sessions = test_sessions();
        let signer = test_signer();
        let session_signer = signer.relabel_for_test();
        let token = mint_session(
            &session_signer,
            &SessionSubject::Persona {
                persona_id: "persona-1".to_owned(),
            },
            &[SessionScope::ExplorerRead],
            NOW,
            crate::SESSION_TTL_MS,
        );

        assert!(
            verify_session(
                &session_signer.public_key_bytes(),
                &token,
                NOW,
                sessions.revoked()
            )
            .is_some(),
            "a freshly minted session verifies before logout"
        );

        sessions.logout(&token);

        assert!(
            verify_session(
                &session_signer.public_key_bytes(),
                &token,
                NOW,
                sessions.revoked()
            )
            .is_none(),
            "the same session must be rejected once revoked"
        );
    }

    // ---- config -------------------------------------------------------------

    #[test]
    fn config_from_base_url_derives_rp_id_and_origin() {
        let sessions = test_sessions();
        assert_eq!(sessions.config().rp_id, "explore.polychrome.test");
        assert_eq!(sessions.config().origin, "https://explore.polychrome.test");
    }

    #[test]
    fn from_base_url_fails_closed_on_an_opaque_or_unparseable_url() {
        let invalid = |url| {
            PasskeyLoginSessions::from_base_url(url, None, Arc::new(MemoryCeremonies::new()))
                .is_none()
        };
        assert!(invalid("not a url"));
        assert!(invalid("data:text/plain,hi"));
        assert!(invalid(""));
    }
}