Skip to main content

hyprstream_core/services/oauth/
federate_exchange.rs

1//! Fixed Federate challenge and token-exchange wire contract. The routes deny
2//! while the authenticated Policy adapter and composite signer are absent.
3
4use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64, Engine as _};
5use hyprstream_rpc::auth::Scope;
6#[cfg(feature = "postgres")]
7use hyprstream_rpc::auth::{signer_suite::signer_suite_thumbprint, Claims, Cnf, CnfJwk};
8#[cfg(feature = "postgres")]
9use hyprstream_session_store::Session;
10use serde::Deserialize;
11#[cfg(feature = "postgres")]
12use serde::Serialize;
13
14use super::federate_source::{self, ClientClass, Commitment, Source, Verifier};
15
16const PROFILE: &str = "federate-session-v1";
17const ID_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:id_token";
18const MAX_BODY: usize = 24 * 1024;
19const MAX_SOURCE_TOKEN: usize = 16 * 1024;
20const MAX_CODE: usize = 2048;
21
22/// Resolve a wire `client_id` against the classes this route accepts: the
23/// hardcoded staging www pin plus the optional configured TUI class
24/// (`None` = staging-only, exactly the previous behavior). Anything else
25/// fails closed before any signature or claim work. Callers that hold a
26/// [`Verifier`] must prefer `Verifier::resolve_client_class`, which applies
27/// the same rule against the verifier's own configured class.
28pub(crate) fn resolve_wire_class(
29    client_id: &str,
30    tui_client: Option<&ClientClass>,
31) -> Result<ClientClass, federate_source::Error> {
32    if client_id == federate_source::CLIENT {
33        return Ok(ClientClass::staging());
34    }
35    match tui_client {
36        Some(class) if class.client_id() == client_id => Ok(class.clone()),
37        _ => Err(federate_source::Error::Invalid),
38    }
39}
40
41#[cfg(all(test, feature = "postgres"))]
42pub(crate) fn committed_claims(
43    session: &Session,
44    now: i64,
45    issuer: &str,
46    subject: &str,
47) -> Result<Claims, federate_source::Error> {
48    committed_claims_for_host(
49        session,
50        now,
51        issuer,
52        subject,
53        &federate_source::FederateHost::new(federate_source::HOST)
54            .map_err(|_| federate_source::Error::Invalid)?,
55    )
56}
57
58/// The exact A0 challenge envelope. `deny_unknown_fields` and serde's
59/// duplicate-field rejection prevent browser-chosen authority from being
60/// silently ignored or ambiguously interpreted.
61#[derive(Deserialize)]
62#[serde(deny_unknown_fields)]
63pub(crate) struct ChallengeRequest {
64    profile: String,
65    client_id: String,
66    subject_token: String,
67    subject_token_type: String,
68    authorization_code: String,
69    resource: String,
70    scope: String,
71    login_random: String,
72    state: String,
73    pkce_challenge: String,
74    ed25519_public: String,
75    ml_dsa65_public: String,
76}
77
78impl ChallengeRequest {
79    #[cfg(test)]
80    pub(crate) fn parse(body: &[u8]) -> Result<Self, federate_source::Error> {
81        Self::parse_for_host(
82            body,
83            &federate_source::FederateHost::new(federate_source::HOST)
84                .map_err(|_| federate_source::Error::Invalid)?,
85            None,
86        )
87    }
88    pub(crate) fn parse_for_host(
89        body: &[u8],
90        host: &federate_source::FederateHost,
91        tui_client: Option<&ClientClass>,
92    ) -> Result<Self, federate_source::Error> {
93        if body.is_empty() || body.len() > MAX_BODY {
94            return Err(federate_source::Error::Invalid);
95        }
96        let request: Self =
97            serde_json::from_slice(body).map_err(|_| federate_source::Error::Invalid)?;
98        // The wire client_id selects the accepted class, and the profile
99        // string must be exactly that class's profile (`federate-session-v1`
100        // for www, `federate-tui-v1` for the configured TUI class). An
101        // unconfigured/unknown client fails closed here.
102        let class = resolve_wire_class(&request.client_id, tui_client)?;
103        if request.profile != class.profile()
104            || request.subject_token_type != ID_TOKEN_TYPE
105            || request.resource != host.as_str()
106            || request.subject_token.is_empty()
107            || request.subject_token.len() > MAX_SOURCE_TOKEN
108            || request.authorization_code.is_empty()
109            || request.authorization_code.len() > MAX_CODE
110            || !request.authorization_code.is_ascii()
111        {
112            return Err(federate_source::Error::Invalid);
113        }
114        federate_source::scopes(&request.scope)?;
115        let requested: Vec<_> = request.scope.split(' ').collect();
116        if requested.len() > 64
117            || requested.iter().any(|text| {
118                text.len() > 256
119                    || Scope::parse(text).is_err()
120                    || text
121                        .split(':')
122                        .any(|part| part.is_empty() || part.contains('*'))
123            })
124        {
125            return Err(federate_source::Error::Invalid);
126        }
127        Ok(request)
128    }
129
130    /// Still only upstream identity evidence. The resulting Source must be
131    /// mapped through Policy and paired with a challenge and both signatures.
132    pub(crate) async fn verify_source(
133        &self,
134        verifier: &Verifier,
135        now: u64,
136    ) -> Result<Source, federate_source::Error> {
137        if self.resource != verifier.host()?.as_str() {
138            return Err(federate_source::Error::Invalid);
139        }
140        // Build the class from the verifier's own canonical resolution —
141        // never from raw request fields. `Verifier::source` re-resolves the
142        // class from the commitment and rejects anything the verifier did
143        // not configure (W1.1 acceptance check).
144        let class = verifier.resolve_client_class(&self.client_id)?;
145        let commitment = Commitment::for_class(
146            verifier.host()?.clone(),
147            &class,
148            &self.login_random,
149            &self.state,
150            &self.pkce_challenge,
151            &self.ed25519_public,
152            &self.ml_dsa65_public,
153        )?;
154        verifier
155            .source(
156                &self.subject_token,
157                &self.authorization_code,
158                commitment,
159                now,
160                None,
161            )
162            .await
163    }
164
165    pub(crate) fn requested_scope(&self) -> &str {
166        &self.scope
167    }
168
169    pub(crate) fn subject_token(&self) -> &str {
170        &self.subject_token
171    }
172
173    /// The class-resolved wire client id (validated against the accepted
174    /// classes at parse time).
175    pub(crate) fn client_id(&self) -> &str {
176        &self.client_id
177    }
178}
179
180/// The exact W1b device challenge envelope. Mirrors [`ChallengeRequest`]
181/// but binds the RFC 8628 `device_code` instead of the authorization-code
182/// `state`/`pkce_challenge` pair; the source token is pinned through the
183/// issuer-signed `binding_key` claim (W5f/D1), not `nonce`/`c_hash`.
184/// `deny_unknown_fields` keeps browser-chosen authority from being silently
185/// ignored, exactly as in the code-flow envelope.
186#[derive(Deserialize)]
187#[serde(deny_unknown_fields)]
188pub(crate) struct DeviceChallengeRequest {
189    profile: String,
190    client_id: String,
191    subject_token: String,
192    subject_token_type: String,
193    device_code: String,
194    resource: String,
195    scope: String,
196    login_random: String,
197    ed25519_public: String,
198    ml_dsa65_public: String,
199}
200
201impl DeviceChallengeRequest {
202    #[cfg(test)]
203    pub(crate) fn parse(body: &[u8]) -> Result<Self, federate_source::Error> {
204        Self::parse_for_host(
205            body,
206            &federate_source::FederateHost::new(federate_source::HOST)
207                .map_err(|_| federate_source::Error::Invalid)?,
208            None,
209        )
210    }
211    pub(crate) fn parse_for_host(
212        body: &[u8],
213        host: &federate_source::FederateHost,
214        tui_client: Option<&ClientClass>,
215    ) -> Result<Self, federate_source::Error> {
216        if body.is_empty() || body.len() > MAX_BODY {
217            return Err(federate_source::Error::Invalid);
218        }
219        let request: Self =
220            serde_json::from_slice(body).map_err(|_| federate_source::Error::Invalid)?;
221        // The wire client_id selects the accepted class and the profile
222        // string must be exactly the device profile. The device variant is
223        // the native second-class flow: the hardcoded www staging class
224        // keeps the authorization-code challenge only, so a device-profile
225        // request naming the staging client fails closed here.
226        let class = resolve_wire_class(&request.client_id, tui_client)?;
227        if class == ClientClass::staging()
228            || request.profile != federate_source::TUI_DEVICE_PROFILE
229            || request.subject_token_type != ID_TOKEN_TYPE
230            || request.resource != host.as_str()
231            || request.subject_token.is_empty()
232            || request.subject_token.len() > MAX_SOURCE_TOKEN
233            || request.device_code.is_empty()
234            || request.device_code.len() > MAX_CODE
235            || !request.device_code.is_ascii()
236        {
237            return Err(federate_source::Error::Invalid);
238        }
239        validate_requested_scope(&request.scope)?;
240        Ok(request)
241    }
242
243    /// Still only upstream identity evidence. The resulting Source must be
244    /// mapped through Policy and paired with a challenge and both signatures.
245    pub(crate) async fn verify_source(
246        &self,
247        verifier: &Verifier,
248        now: u64,
249    ) -> Result<Source, federate_source::Error> {
250        if self.resource != verifier.host()?.as_str() {
251            return Err(federate_source::Error::Invalid);
252        }
253        // Build the class from the verifier's own canonical resolution —
254        // never from raw request fields. `Verifier::source` re-resolves the
255        // class from the commitment and rejects anything the verifier did
256        // not configure (W1.1 acceptance check).
257        let class = verifier.resolve_client_class(&self.client_id)?;
258        let commitment = Commitment::for_class_device(
259            verifier.host()?.clone(),
260            &class,
261            &self.login_random,
262            &self.device_code,
263            &self.ed25519_public,
264            &self.ml_dsa65_public,
265        )?;
266        verifier
267            .source(
268                &self.subject_token,
269                &self.device_code,
270                commitment,
271                now,
272                None,
273            )
274            .await
275    }
276
277    pub(crate) fn requested_scope(&self) -> &str {
278        &self.scope
279    }
280
281    pub(crate) fn subject_token(&self) -> &str {
282        &self.subject_token
283    }
284
285    /// The class-resolved wire client id (validated against the accepted
286    /// classes at parse time).
287    pub(crate) fn client_id(&self) -> &str {
288        &self.client_id
289    }
290}
291
292/// Either challenge envelope, dispatched on the exact wire profile string
293/// so a device-profile request can never be interpreted as a code-flow one
294/// (and vice versa: the code-flow parser rejects the device profile).
295pub(crate) enum AnyChallengeRequest {
296    Code(ChallengeRequest),
297    Device(DeviceChallengeRequest),
298}
299
300impl AnyChallengeRequest {
301    pub(crate) fn parse_for_host(
302        body: &[u8],
303        host: &federate_source::FederateHost,
304        tui_client: Option<&ClientClass>,
305    ) -> Result<Self, federate_source::Error> {
306        if body.is_empty() || body.len() > MAX_BODY {
307            return Err(federate_source::Error::Invalid);
308        }
309        #[derive(Deserialize)]
310        struct Probe {
311            profile: String,
312        }
313        let probe: Probe =
314            serde_json::from_slice(body).map_err(|_| federate_source::Error::Invalid)?;
315        if probe.profile == federate_source::TUI_DEVICE_PROFILE {
316            DeviceChallengeRequest::parse_for_host(body, host, tui_client).map(Self::Device)
317        } else {
318            ChallengeRequest::parse_for_host(body, host, tui_client).map(Self::Code)
319        }
320    }
321
322    pub(crate) async fn verify_source(
323        &self,
324        verifier: &Verifier,
325        now: u64,
326    ) -> Result<Source, federate_source::Error> {
327        match self {
328            Self::Code(request) => request.verify_source(verifier, now).await,
329            Self::Device(request) => request.verify_source(verifier, now).await,
330        }
331    }
332
333    /// The exact profile string the challenge leg was validated under; the
334    /// exchange leg must repeat it, pinning both legs to one flow.
335    pub(crate) fn profile(&self) -> &str {
336        match self {
337            Self::Code(request) => &request.profile,
338            Self::Device(request) => &request.profile,
339        }
340    }
341
342    pub(crate) fn requested_scope(&self) -> &str {
343        match self {
344            Self::Code(request) => request.requested_scope(),
345            Self::Device(request) => request.requested_scope(),
346        }
347    }
348
349    pub(crate) fn subject_token(&self) -> &str {
350        match self {
351            Self::Code(request) => request.subject_token(),
352            Self::Device(request) => request.subject_token(),
353        }
354    }
355
356    pub(crate) fn client_id(&self) -> &str {
357        match self {
358            Self::Code(request) => request.client_id(),
359            Self::Device(request) => request.client_id(),
360        }
361    }
362}
363
364/// The shared scope grammar/limit check of both challenge envelopes.
365fn validate_requested_scope(scope: &str) -> Result<(), federate_source::Error> {
366    federate_source::scopes(scope)?;
367    let requested: Vec<_> = scope.split(' ').collect();
368    if requested.len() > 64
369        || requested.iter().any(|text| {
370            text.len() > 256
371                || Scope::parse(text).is_err()
372                || text
373                    .split(':')
374                    .any(|part| part.is_empty() || part.contains('*'))
375        })
376    {
377        return Err(federate_source::Error::Invalid);
378    }
379    Ok(())
380}
381
382const EXCHANGE_GRANT: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
383const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
384
385/// Exact public-client RFC 8693 form for this one staging profile. A generic
386/// token-exchange request must never be reinterpreted as Federate authority.
387#[derive(Deserialize)]
388#[serde(deny_unknown_fields)]
389pub(crate) struct ExchangeRequest {
390    grant_type: String,
391    hs_profile: String,
392    client_id: String,
393    subject_token_type: String,
394    subject_token: String,
395    requested_token_type: String,
396    resource: String,
397    scope: String,
398    challenge_id: String,
399    ed25519_signature: String,
400    ml_dsa65_signature: String,
401}
402
403impl ExchangeRequest {
404    #[cfg(test)]
405    pub(crate) fn parse(body: &[u8]) -> Result<Self, federate_source::Error> {
406        Self::parse_for_host(
407            body,
408            &federate_source::FederateHost::new(federate_source::HOST)
409                .map_err(|_| federate_source::Error::Invalid)?,
410            None,
411        )
412    }
413    pub(crate) fn parse_for_host(
414        body: &[u8],
415        host: &federate_source::FederateHost,
416        tui_client: Option<&ClientClass>,
417    ) -> Result<Self, federate_source::Error> {
418        if body.is_empty() || body.len() > MAX_BODY {
419            return Err(federate_source::Error::Invalid);
420        }
421        // serde_urlencoded does not reject duplicate form members for every
422        // destination type. Count names before deserialization, including any
423        // unknown field, so first/last-value ambiguity cannot enter this grant.
424        let mut keys = std::collections::BTreeSet::new();
425        for (key, _) in url::form_urlencoded::parse(body) {
426            if !keys.insert(key.into_owned()) {
427                return Err(federate_source::Error::Invalid);
428            }
429        }
430        let request: Self =
431            serde_urlencoded::from_bytes(body).map_err(|_| federate_source::Error::Invalid)?;
432        // Per-class profile pin: the wire client_id selects the accepted
433        // class and hs_profile must be exactly that class's profile string.
434        // A non-staging class additionally accepts the W1b device challenge
435        // profile; the exact flow is pinned against the pending challenge
436        // in the exchange handler, so accepting both here cannot mix flows.
437        let class = resolve_wire_class(&request.client_id, tui_client)?;
438        let profile_ok = request.hs_profile == class.profile()
439            || (class != ClientClass::staging()
440                && request.hs_profile == federate_source::TUI_DEVICE_PROFILE);
441        if request.grant_type != EXCHANGE_GRANT
442            || !profile_ok
443            || request.subject_token_type != ID_TOKEN_TYPE
444            || request.requested_token_type != ACCESS_TOKEN_TYPE
445            || request.resource != host.as_str()
446            || request.subject_token.is_empty()
447            || request.subject_token.len() > MAX_SOURCE_TOKEN
448        {
449            return Err(federate_source::Error::Invalid);
450        }
451        federate_source::scopes(&request.scope)?;
452        let requested: Vec<_> = request.scope.split(' ').collect();
453        if requested.len() > 64
454            || requested.iter().any(|text| {
455                text.len() > 256
456                    || Scope::parse(text).is_err()
457                    || text
458                        .split(':')
459                        .any(|part| part.is_empty() || part.contains('*'))
460            })
461        {
462            return Err(federate_source::Error::Invalid);
463        }
464        request.challenge_id()?;
465        request.signatures()?;
466        Ok(request)
467    }
468
469    pub(crate) fn challenge_id(&self) -> Result<[u8; 32], federate_source::Error> {
470        let bytes = B64
471            .decode(&self.challenge_id)
472            .map_err(|_| federate_source::Error::Invalid)?;
473        let id: [u8; 32] = bytes
474            .try_into()
475            .map_err(|_| federate_source::Error::Invalid)?;
476        if B64.encode(id) != self.challenge_id {
477            return Err(federate_source::Error::Invalid);
478        }
479        Ok(id)
480    }
481
482    pub(crate) fn signatures(&self) -> Result<(Vec<u8>, Vec<u8>), federate_source::Error> {
483        let ed = B64
484            .decode(&self.ed25519_signature)
485            .map_err(|_| federate_source::Error::Invalid)?;
486        let pq = B64
487            .decode(&self.ml_dsa65_signature)
488            .map_err(|_| federate_source::Error::Invalid)?;
489        if ed.len() != 64
490            || pq.len() != 3309
491            || B64.encode(&ed) != self.ed25519_signature
492            || B64.encode(&pq) != self.ml_dsa65_signature
493        {
494            return Err(federate_source::Error::Invalid);
495        }
496        Ok((ed, pq))
497    }
498
499    pub(crate) fn subject_token(&self) -> &str {
500        &self.subject_token
501    }
502
503    pub(crate) fn requested_scope(&self) -> &str {
504        &self.scope
505    }
506
507    /// The submitted profile string (validated at parse time against the
508    /// accepted class; the exchange handler additionally pins it to the
509    /// pending challenge's exact flow profile).
510    pub(crate) fn hs_profile(&self) -> &str {
511        &self.hs_profile
512    }
513
514    /// The class-resolved wire client id (validated against the accepted
515    /// classes at parse time).
516    pub(crate) fn client_id(&self) -> &str {
517        &self.client_id
518    }
519}
520
521/// Shared durable-record shape validation for both client classes. The
522/// per-class mint (`committed_claims_for_host` / `committed_tui_claims_for_host`)
523/// additionally pins the exact client and its marker set.
524#[cfg(feature = "postgres")]
525fn committed_session_shape(
526    session: &Session,
527    now: i64,
528    source_issuer: &str,
529    source_subject: &str,
530    host: &federate_source::FederateHost,
531) -> Result<(), federate_source::Error> {
532    if session.host != host.as_str()
533        || session.resource != host.as_str()
534        || session.sid.is_empty()
535        || !crate::auth::valid_tenant_component(&session.tenant)
536        || session.scopes.is_empty()
537        || session.ed_public.iter().all(|byte| *byte == 0)
538        || session.pq_public.len() != 1952
539        || session.proof_epoch <= 0
540        || session.generation != session.collision_inventory_id
541        || session.expires_at <= now
542        || session.expires_at > now.saturating_add(300)
543        || source_issuer != federate_source::ISSUER
544        || source_subject.is_empty()
545        || source_subject.len() > 256
546    {
547        return Err(federate_source::Error::Invalid);
548    }
549    let scope = session.scopes.join(" ");
550    federate_source::scopes(&scope)?;
551    if session.scopes.len() > 64
552        || session.scopes.iter().any(|text| {
553            text.len() > 256
554                || Scope::parse(text).is_err()
555                || text
556                    .split(':')
557                    .any(|part| part.is_empty() || part.contains('*'))
558        })
559    {
560        return Err(federate_source::Error::Invalid);
561    }
562    Ok(())
563}
564
565/// Only a committed Policy session can be passed to this constructor by the
566/// host issuer. It derives every authority claim from the durable record.
567/// The www staging mint: byte-for-byte the previous claim shape.
568#[cfg(feature = "postgres")]
569pub(crate) fn committed_claims_for_host(
570    session: &Session,
571    now: i64,
572    source_issuer: &str,
573    source_subject: &str,
574    host: &federate_source::FederateHost,
575) -> Result<Claims, federate_source::Error> {
576    if session.client_id != federate_source::CLIENT {
577        return Err(federate_source::Error::Invalid);
578    }
579    committed_session_shape(session, now, source_issuer, source_subject, host)?;
580    let scope = session.scopes.join(" ");
581    let mut claims = Claims::new(session.subject.clone(), now, session.expires_at)
582        .with_sid(session.sid.clone())
583        .with_jti()
584        .with_federate_signer_suite(B64.encode(signer_suite_thumbprint(
585            hyprstream_session_store::SUITE,
586            &[&session.ed_public, &session.pq_public],
587        )))
588        .with_federate_signer_inventory(session.collision_inventory_id);
589    claims.iss = session.host.clone();
590    claims.aud = Some(session.resource.clone());
591    claims.client_id = Some(session.client_id.clone());
592    claims.tenant = Some(session.tenant.clone());
593    claims.scope = Some(scope);
594    claims.hs_signer_pq_key_v1 = Some(B64.encode(&session.pq_public));
595    claims.hs_source_issuer_v1 = Some(source_issuer.to_owned());
596    claims.hs_source_subject_v1 = Some(source_subject.to_owned());
597    claims.cnf = Some(Cnf {
598        jwk: Some(CnfJwk {
599            kty: "OKP".into(),
600            crv: "Ed25519".into(),
601            x: B64.encode(session.ed_public),
602        }),
603        jkt: None,
604        hs_signer_suite: None,
605    });
606    Ok(claims)
607}
608
609/// The TUI-class mint (W1.3): same durable-record shape, but stamps the
610/// TUI-consumer profile markers — namespaced `hs_tui_*` and DISTINCT from
611/// the www v1 suite/inventory markers — so the credential takes NORMAL JWT
612/// verification (never the svc.rs deferred federate branch) and carries NO
613/// registry|model consumer authority: every granted scope must target the
614/// `tui` service resource only.
615#[cfg(feature = "postgres")]
616pub(crate) fn committed_tui_claims_for_host(
617    session: &Session,
618    now: i64,
619    source_issuer: &str,
620    source_subject: &str,
621    host: &federate_source::FederateHost,
622    tui_client: &str,
623) -> Result<Claims, federate_source::Error> {
624    if session.client_id != tui_client {
625        return Err(federate_source::Error::Invalid);
626    }
627    committed_session_shape(session, now, source_issuer, source_subject, host)?;
628    // The TUI consumer profile cannot mint registry|model authority. This is
629    // the mint-side floor under Policy's per-client scope ceiling: even a
630    // Policy bug that granted a www scope to the TUI class stops here.
631    if session.scopes.iter().any(|text| {
632        Scope::parse(text)
633            .map(|scope| scope.resource != "tui")
634            .unwrap_or(true)
635    }) {
636        return Err(federate_source::Error::Invalid);
637    }
638    let scope = session.scopes.join(" ");
639    let mut claims = Claims::new(session.subject.clone(), now, session.expires_at)
640        .with_sid(session.sid.clone())
641        .with_jti()
642        .with_federate_tui_markers(
643            B64.encode(&session.pq_public),
644            source_issuer.to_owned(),
645            source_subject.to_owned(),
646        );
647    claims.iss = session.host.clone();
648    claims.aud = Some(session.resource.clone());
649    claims.client_id = Some(session.client_id.clone());
650    claims.tenant = Some(session.tenant.clone());
651    claims.scope = Some(scope);
652    // Holder binding stays the standard RFC 7800 `cnf.jwk` (the envelope
653    // signer must match it at dispatch); no www signer-suite/inventory
654    // digest is stamped for this class.
655    claims.cnf = Some(Cnf {
656        jwk: Some(CnfJwk {
657            kty: "OKP".into(),
658            crv: "Ed25519".into(),
659            x: B64.encode(session.ed_public),
660        }),
661        jkt: None,
662        hs_signer_suite: None,
663    });
664    Ok(claims)
665}
666
667/// Dispatch a committed session to its per-class mint by the session's
668/// Policy-bound `client_id`. An unconfigured TUI client (or any other
669/// client) fails closed: the W1.1 default-deny invariant.
670#[cfg(feature = "postgres")]
671pub(crate) fn committed_claims_for_class(
672    session: &Session,
673    now: i64,
674    source_issuer: &str,
675    source_subject: &str,
676    host: &federate_source::FederateHost,
677    tui_client: Option<&str>,
678) -> Result<Claims, federate_source::Error> {
679    if session.client_id == federate_source::CLIENT {
680        committed_claims_for_host(session, now, source_issuer, source_subject, host)
681    } else {
682        match tui_client {
683            Some(client) if client == session.client_id => committed_tui_claims_for_host(
684                session,
685                now,
686                source_issuer,
687                source_subject,
688                host,
689                client,
690            ),
691            _ => Err(federate_source::Error::Invalid),
692        }
693    }
694}
695
696/// Attach only the exact subject's authority-enrolled MAC clearance. Policy's
697/// action grants do not imply a clearance, and browser inputs cannot select it.
698#[cfg(feature = "postgres")]
699pub(crate) fn authorized_committed_claims_for_host(
700    session: &Session,
701    now: i64,
702    source_issuer: &str,
703    source_subject: &str,
704    resolver: &dyn super::token_exchange::SubjectContextResolver,
705    host: &federate_source::FederateHost,
706    tui_client: Option<&str>,
707) -> Result<Claims, federate_source::Error> {
708    let claims = committed_claims_for_class(
709        session,
710        now,
711        source_issuer,
712        source_subject,
713        host,
714        tui_client,
715    )?;
716    let context = resolver
717        .resolve(&claims.sub)
718        .ok_or(federate_source::Error::Unavailable)?;
719    Ok(claims.with_clearance(*context.clearance()))
720}
721
722#[cfg(feature = "postgres")]
723#[derive(Serialize)]
724pub(crate) struct ExchangeResponse {
725    access_token: String,
726    issued_token_type: &'static str,
727    token_type: &'static str,
728    expires_in: i64,
729    scope: String,
730    session_id: String,
731}
732
733#[cfg(feature = "postgres")]
734impl ExchangeResponse {
735    #[cfg(test)]
736    pub(crate) fn committed(
737        token: String,
738        session: &Session,
739        now: i64,
740        issuer: &str,
741        subject: &str,
742    ) -> Result<Self, federate_source::Error> {
743        Self::committed_for_host(
744            token,
745            session,
746            now,
747            issuer,
748            subject,
749            &federate_source::FederateHost::new(federate_source::HOST)
750                .map_err(|_| federate_source::Error::Invalid)?,
751            None,
752        )
753    }
754    pub(crate) fn committed_for_host(
755        token: String,
756        session: &Session,
757        now: i64,
758        source_issuer: &str,
759        source_subject: &str,
760        host: &federate_source::FederateHost,
761        tui_client: Option<&str>,
762    ) -> Result<Self, federate_source::Error> {
763        committed_claims_for_class(
764            session,
765            now,
766            source_issuer,
767            source_subject,
768            host,
769            tui_client,
770        )?;
771        if token.is_empty() || token.len() > MAX_SOURCE_TOKEN * 2 {
772            return Err(federate_source::Error::Invalid);
773        }
774        Ok(Self {
775            access_token: token,
776            issued_token_type: ACCESS_TOKEN_TYPE,
777            token_type: "PoP",
778            expires_in: session.expires_at - now,
779            scope: session.scopes.join(" "),
780            session_id: session.sid.clone(),
781        })
782    }
783}
784
785#[cfg(test)]
786#[allow(clippy::unwrap_used)]
787mod tests {
788    use super::*;
789    use serde_json::{json, Value};
790
791    fn exchange_form() -> String {
792        url::form_urlencoded::Serializer::new(String::new())
793            .append_pair("grant_type", EXCHANGE_GRANT)
794            .append_pair("hs_profile", PROFILE)
795            .append_pair("client_id", federate_source::CLIENT)
796            .append_pair("subject_token_type", ID_TOKEN_TYPE)
797            .append_pair("subject_token", "header.claims.signature")
798            .append_pair("requested_token_type", ACCESS_TOKEN_TYPE)
799            .append_pair("resource", federate_source::HOST)
800            .append_pair("scope", "query:registry:List")
801            .append_pair("challenge_id", &B64.encode([7u8; 32]))
802            .append_pair("ed25519_signature", &B64.encode([8u8; 64]))
803            .append_pair("ml_dsa65_signature", &B64.encode(vec![9u8; 3309]))
804            .finish()
805    }
806
807    #[test]
808    fn exact_exchange_form_rejects_ambiguity_and_authority_fields() -> anyhow::Result<()> {
809        let form = exchange_form();
810        let parsed = ExchangeRequest::parse(form.as_bytes())?;
811        assert_eq!(parsed.challenge_id()?, [7u8; 32]);
812        assert_eq!(parsed.requested_scope(), "query:registry:List");
813        for suffix in [
814            "&scope=query%3Amodel%3AList",
815            "&tenant=attacker",
816            "&actor_token=attacker",
817            "&hs_profile=generic",
818            "&%68s_profile=federate-session-v1",
819            "&resource=https%3A%2F%2Fattacker.invalid",
820        ] {
821            assert!(ExchangeRequest::parse(format!("{form}{suffix}").as_bytes()).is_err());
822        }
823        for (from, to) in [
824            ("federate-session-v1", "other"),
825            ("query%3Aregistry%3AList", "query%3Aregistry%3A%2A"),
826            ("id_token", "access_token"),
827        ] {
828            assert!(ExchangeRequest::parse(form.replacen(from, to, 1).as_bytes()).is_err());
829        }
830        assert!(ExchangeRequest::parse(&vec![b'x'; MAX_BODY + 1]).is_err());
831        assert!(ExchangeRequest::parse(
832            form.replace("challenge_id=", "challenge_id=bad").as_bytes()
833        )
834        .is_err());
835        assert!(ExchangeRequest::parse(
836            form.replace("ed25519_signature=", "ed25519_signature=bad")
837                .as_bytes()
838        )
839        .is_err());
840        Ok(())
841    }
842
843    #[cfg(feature = "postgres")]
844    fn committed_session() -> Session {
845        Session {
846            host: federate_source::HOST.into(),
847            sid: "sid-1".into(),
848            account_id: "account-1".into(),
849            subject: "alice".into(),
850            tenant: "tenant-1".into(),
851            client_id: federate_source::CLIENT.into(),
852            resource: federate_source::HOST.into(),
853            scopes: vec!["query:registry:List".into()],
854            grant_revision: "revision-1".into(),
855            ed_public: [1; 32],
856            pq_public: vec![2; 1952],
857            generation: [3; 32],
858            collision_inventory_id: [3; 32],
859            proof_epoch: 1,
860            expires_at: 1_800_000_120,
861        }
862    }
863
864    #[cfg(feature = "postgres")]
865    #[test]
866    fn malformed_tenant_is_rejected_at_mint_for_both_classes() {
867        // D4: the mint enforces the same tenant-component syntax as the HTTP
868        // authorization-domain middleware — for both client classes.
869        for bad_tenant in ["bad/tenant", "..", "a b", "*", ""] {
870            let mut session = committed_session();
871            session.tenant = bad_tenant.into();
872            assert!(
873                committed_claims_for_host(
874                    &session,
875                    1_800_000_000,
876                    federate_source::ISSUER,
877                    "subject",
878                    &federate_source::FederateHost::new(federate_source::HOST).unwrap(),
879                )
880                .is_err(),
881                "www mint accepted tenant {bad_tenant:?}"
882            );
883            let mut tui_session =
884                tui_session(&federate_source::FederateHost::new("https://vm-tui.example").unwrap());
885            tui_session.tenant = bad_tenant.into();
886            assert!(
887                committed_tui_claims_for_host(
888                    &tui_session,
889                    1_800_000_000,
890                    federate_source::ISSUER,
891                    "subject",
892                    &federate_source::FederateHost::new("https://vm-tui.example").unwrap(),
893                    TUI_CLIENT_ID,
894                )
895                .is_err(),
896                "TUI mint accepted tenant {bad_tenant:?}"
897            );
898        }
899    }
900
901    #[cfg(feature = "postgres")]
902    #[test]
903    fn committed_session_mints_only_exact_pop_claim_shape() -> anyhow::Result<()> {
904        let session = committed_session();
905        let claims = committed_claims(
906            &session,
907            1_800_000_000,
908            federate_source::ISSUER,
909            "opaque-atproto-connector-subject",
910        )?;
911        let value = serde_json::to_value(&claims)?;
912        assert_eq!(value["hs_profile"], PROFILE);
913        assert_eq!(value["iss"], federate_source::HOST);
914        assert_eq!(value["aud"], federate_source::HOST);
915        assert_eq!(value["sid"], session.sid);
916        assert_eq!(value["scope"], "query:registry:List");
917        assert_eq!(value["hs_signer_pq_key_v1"], B64.encode(&session.pq_public));
918        assert_eq!(
919            value["hs_signer_inventory_v1"],
920            B64.encode(session.collision_inventory_id)
921        );
922        assert!(value.get("hs_session_authority_generation").is_none());
923        assert_eq!(value["hs_source_issuer_v1"], federate_source::ISSUER);
924        assert_eq!(
925            value["hs_source_subject_v1"],
926            "opaque-atproto-connector-subject"
927        );
928        assert_eq!(
929            value["cnf"],
930            json!({"jwk":{"kty":"OKP","crv":"Ed25519","x":B64.encode(session.ed_public)}})
931        );
932        assert_eq!(
933            value["hs_signer_suite_v1"],
934            B64.encode(signer_suite_thumbprint(
935                hyprstream_session_store::SUITE,
936                &[&session.ed_public, &session.pq_public]
937            ))
938        );
939        let response = ExchangeResponse::committed(
940            "a.b.c".into(),
941            &session,
942            1_800_000_000,
943            federate_source::ISSUER,
944            "opaque-atproto-connector-subject",
945        )?;
946        let body = serde_json::to_value(response)?;
947        assert_eq!(body["token_type"], "PoP");
948        assert_eq!(body["issued_token_type"], ACCESS_TOKEN_TYPE);
949        assert_eq!(body["expires_in"], 120);
950        assert_eq!(body["session_id"], session.sid);
951        let mut invalid = session.clone();
952        invalid.proof_epoch = 0;
953        assert!(
954            committed_claims(&invalid, 1_800_000_000, federate_source::ISSUER, "subject").is_err()
955        );
956        invalid = session.clone();
957        invalid.client_id = "other".into();
958        assert!(
959            committed_claims(&invalid, 1_800_000_000, federate_source::ISSUER, "subject").is_err()
960        );
961        invalid = session.clone();
962        invalid.tenant = "*".into();
963        assert!(
964            committed_claims(&invalid, 1_800_000_000, federate_source::ISSUER, "subject").is_err()
965        );
966        assert!(committed_claims(
967            &session,
968            1_800_000_000,
969            "https://attacker.invalid",
970            "subject"
971        )
972        .is_err());
973        assert!(committed_claims(&session, 1_800_000_000, federate_source::ISSUER, "").is_err());
974        Ok(())
975    }
976
977    fn request() -> Value {
978        json!({
979            "profile": PROFILE,
980            "client_id": federate_source::CLIENT,
981            "subject_token": "header.claims.signature",
982            "subject_token_type": ID_TOKEN_TYPE,
983            "authorization_code": "test-code",
984            "resource": federate_source::HOST,
985            "scope": "query:registry:List",
986            "login_random": "a",
987            "state": "b",
988            "pkce_challenge": "c",
989            "ed25519_public": "d",
990            "ml_dsa65_public": "e"
991        })
992    }
993
994    #[test]
995    fn configured_resource_is_exact_for_challenge_and_exchange() -> anyhow::Result<()> {
996        for local in ["https://vm-a.example", "https://vm-b.example:8443"] {
997            let host = federate_source::FederateHost::new(local)?;
998            let mut body = request();
999            body["resource"] = local.into();
1000            assert!(
1001                ChallengeRequest::parse_for_host(&serde_json::to_vec(&body)?, &host, None).is_ok()
1002            );
1003            let form: String = url::form_urlencoded::Serializer::new(String::new())
1004                .extend_pairs(url::form_urlencoded::parse(exchange_form().as_bytes()).map(
1005                    |(k, v)| {
1006                        let v = if k == "resource" {
1007                            local.to_owned()
1008                        } else {
1009                            v.into_owned()
1010                        };
1011                        (k.into_owned(), v)
1012                    },
1013                ))
1014                .finish();
1015            assert!(ExchangeRequest::parse_for_host(form.as_bytes(), &host, None).is_ok());
1016            let other = federate_source::FederateHost::new("https://other.example")?;
1017            assert!(
1018                ChallengeRequest::parse_for_host(&serde_json::to_vec(&body)?, &other, None)
1019                    .is_err()
1020            );
1021            assert!(ExchangeRequest::parse_for_host(form.as_bytes(), &other, None).is_err());
1022        }
1023        Ok(())
1024    }
1025
1026    #[cfg(feature = "postgres")]
1027    #[test]
1028    fn configured_claims_reject_policy_record_from_another_host() -> anyhow::Result<()> {
1029        for local in ["https://vm-a.example", "https://vm-b.example:8443"] {
1030            let host = federate_source::FederateHost::new(local)?;
1031            let other = federate_source::FederateHost::new("https://other.example")?;
1032            let mut session = committed_session();
1033            session.host = local.into();
1034            session.resource = local.into();
1035            let claims = committed_claims_for_host(
1036                &session,
1037                1_800_000_000,
1038                federate_source::ISSUER,
1039                "source-sub",
1040                &host,
1041            )?;
1042            assert_eq!(claims.iss, local);
1043            assert_eq!(claims.aud.as_deref(), Some(local));
1044            assert!(committed_claims_for_host(
1045                &session,
1046                1_800_000_000,
1047                federate_source::ISSUER,
1048                "source-sub",
1049                &other
1050            )
1051            .is_err());
1052            session.resource = other.as_str().into();
1053            assert!(committed_claims_for_host(
1054                &session,
1055                1_800_000_000,
1056                federate_source::ISSUER,
1057                "source-sub",
1058                &host
1059            )
1060            .is_err());
1061        }
1062        Ok(())
1063    }
1064
1065    #[test]
1066    fn exact_profile_and_scope_envelope() -> anyhow::Result<()> {
1067        let valid = serde_json::to_vec(&request())?;
1068        assert_eq!(
1069            ChallengeRequest::parse(&valid)?.requested_scope(),
1070            "query:registry:List"
1071        );
1072        for (field, value) in [
1073            ("profile", "other"),
1074            ("client_id", "other"),
1075            (
1076                "subject_token_type",
1077                "urn:ietf:params:oauth:token-type:access_token",
1078            ),
1079            ("resource", "https://other.example"),
1080            ("scope", "openid"),
1081            ("scope", "query:registry:List query:registry:List"),
1082            ("scope", "write:model:Load query:registry:List"),
1083            ("scope", "query:registry:List\\evil"),
1084        ] {
1085            let mut changed = request();
1086            changed[field] = value.into();
1087            assert!(ChallengeRequest::parse(&serde_json::to_vec(&changed)?).is_err());
1088        }
1089        Ok(())
1090    }
1091
1092    // ── W1.3: the TUI client class on the challenge/exchange wire ──────────
1093
1094    const TUI_CLIENT_ID: &str = "hyprstream-tui-staging";
1095    const TUI_PROFILE_STR: &str = "federate-tui-v1";
1096
1097    fn tui_class() -> federate_source::ClientClass {
1098        federate_source::ClientClass::new(TUI_CLIENT_ID, "hyprstream-tui-aud", None).unwrap()
1099    }
1100
1101    #[test]
1102    fn w13_wire_accepts_the_tui_class_with_its_own_profile_string() -> anyhow::Result<()> {
1103        let host = federate_source::FederateHost::new("https://vm-tui.example")?;
1104        let mut body = request();
1105        body["client_id"] = TUI_CLIENT_ID.into();
1106        body["profile"] = TUI_PROFILE_STR.into();
1107        body["resource"] = "https://vm-tui.example".into();
1108        // Configured class + exact profile string: accepted.
1109        assert!(ChallengeRequest::parse_for_host(
1110            &serde_json::to_vec(&body)?,
1111            &host,
1112            Some(&tui_class())
1113        )
1114        .is_ok());
1115        let form: String = url::form_urlencoded::Serializer::new(String::new())
1116            .extend_pairs(
1117                url::form_urlencoded::parse(exchange_form().as_bytes()).map(|(k, v)| {
1118                    let v = match k.as_ref() {
1119                        "client_id" => TUI_CLIENT_ID.to_owned(),
1120                        "hs_profile" => TUI_PROFILE_STR.to_owned(),
1121                        "resource" => "https://vm-tui.example".to_owned(),
1122                        _ => v.into_owned(),
1123                    };
1124                    (k.into_owned(), v)
1125                }),
1126            )
1127            .finish();
1128        assert!(
1129            ExchangeRequest::parse_for_host(form.as_bytes(), &host, Some(&tui_class())).is_ok()
1130        );
1131        // Substitution, both directions: the www profile on the TUI client
1132        // and the TUI profile on the www client are both denied.
1133        let mut swapped = body.clone();
1134        swapped["profile"] = PROFILE.into();
1135        assert!(ChallengeRequest::parse_for_host(
1136            &serde_json::to_vec(&swapped)?,
1137            &host,
1138            Some(&tui_class())
1139        )
1140        .is_err());
1141        let mut www_profile_on_www = request();
1142        www_profile_on_www["profile"] = TUI_PROFILE_STR.into();
1143        assert!(ChallengeRequest::parse_for_host(
1144            &serde_json::to_vec(&www_profile_on_www)?,
1145            &host,
1146            Some(&tui_class())
1147        )
1148        .is_err());
1149        // Default-deny: the TUI class is not accepted when unconfigured.
1150        assert!(
1151            ChallengeRequest::parse_for_host(&serde_json::to_vec(&body)?, &host, None).is_err()
1152        );
1153        assert!(ExchangeRequest::parse_for_host(form.as_bytes(), &host, None).is_err());
1154        Ok(())
1155    }
1156
1157    // ── W1b: the device challenge envelope beside the code flow ───────────
1158
1159    fn device_request() -> Value {
1160        json!({
1161            "profile": federate_source::TUI_DEVICE_PROFILE,
1162            "client_id": TUI_CLIENT_ID,
1163            "subject_token": "header.claims.signature",
1164            "subject_token_type": ID_TOKEN_TYPE,
1165            "device_code": "test-device-code",
1166            "resource": federate_source::HOST,
1167            "scope": "connect:tui:session",
1168            "login_random": "a",
1169            "ed25519_public": "d",
1170            "ml_dsa65_public": "e"
1171        })
1172    }
1173
1174    fn class_form(profile: &str, client_id: &str, resource: &str) -> String {
1175        url::form_urlencoded::Serializer::new(String::new())
1176            .extend_pairs(
1177                url::form_urlencoded::parse(exchange_form().as_bytes()).map(|(k, v)| {
1178                    let v = match k.as_ref() {
1179                        "hs_profile" => profile.to_owned(),
1180                        "client_id" => client_id.to_owned(),
1181                        "resource" => resource.to_owned(),
1182                        _ => v.into_owned(),
1183                    };
1184                    (k.into_owned(), v)
1185                }),
1186            )
1187            .finish()
1188    }
1189
1190    #[test]
1191    fn w1b_device_wire_is_tui_class_only_and_flow_pinned() -> anyhow::Result<()> {
1192        let host = federate_source::FederateHost::new(federate_source::HOST)?;
1193        let body = device_request();
1194        // Configured TUI class + exact device profile: accepted, and the
1195        // envelope profile dispatches to the device variant.
1196        let parsed = AnyChallengeRequest::parse_for_host(
1197            &serde_json::to_vec(&body)?,
1198            &host,
1199            Some(&tui_class()),
1200        )?;
1201        assert!(matches!(parsed, AnyChallengeRequest::Device(_)));
1202        assert_eq!(parsed.profile(), federate_source::TUI_DEVICE_PROFILE);
1203        // A code-flow envelope dispatches to the code variant unchanged.
1204        let mut code = request();
1205        code["client_id"] = TUI_CLIENT_ID.into();
1206        code["profile"] = TUI_PROFILE_STR.into();
1207        code["resource"] = federate_source::HOST.into();
1208        let parsed = AnyChallengeRequest::parse_for_host(
1209            &serde_json::to_vec(&code)?,
1210            &host,
1211            Some(&tui_class()),
1212        )?;
1213        assert!(matches!(parsed, AnyChallengeRequest::Code(_)));
1214        // The staging class never accepts the device profile: the www flow
1215        // stays authorization-code only, fail-closed at parse.
1216        let mut staging = device_request();
1217        staging["client_id"] = federate_source::CLIENT.into();
1218        assert!(DeviceChallengeRequest::parse_for_host(
1219            &serde_json::to_vec(&staging)?,
1220            &host,
1221            Some(&tui_class())
1222        )
1223        .is_err());
1224        // Default-deny: an unconfigured second class resolves nothing.
1225        assert!(
1226            AnyChallengeRequest::parse_for_host(&serde_json::to_vec(&body)?, &host, None).is_err()
1227        );
1228        // Envelope integrity: missing/empty/non-ascii/oversized device_code,
1229        // unknown browser fields, and the code profile on the device
1230        // envelope are all denied.
1231        for (field, value) in [
1232            ("device_code", "".into()),
1233            ("device_code", "nonascii-é".into()),
1234        ] {
1235            let mut changed = device_request();
1236            changed[field] = value;
1237            assert!(AnyChallengeRequest::parse_for_host(
1238                &serde_json::to_vec(&changed)?,
1239                &host,
1240                Some(&tui_class())
1241            )
1242            .is_err());
1243        }
1244        let mut oversized = device_request();
1245        oversized["device_code"] = "x".repeat(MAX_CODE + 1).into();
1246        assert!(AnyChallengeRequest::parse_for_host(
1247            &serde_json::to_vec(&oversized)?,
1248            &host,
1249            Some(&tui_class())
1250        )
1251        .is_err());
1252        let mut browser_field = device_request();
1253        browser_field["state"] = "b".into();
1254        assert!(AnyChallengeRequest::parse_for_host(
1255            &serde_json::to_vec(&browser_field)?,
1256            &host,
1257            Some(&tui_class())
1258        )
1259        .is_err());
1260        let mut wrong_profile = device_request();
1261        wrong_profile["profile"] = TUI_PROFILE_STR.into();
1262        assert!(AnyChallengeRequest::parse_for_host(
1263            &serde_json::to_vec(&wrong_profile)?,
1264            &host,
1265            Some(&tui_class())
1266        )
1267        .is_err());
1268        // The exchange form of a configured TUI class accepts both its own
1269        // profile and the device profile (the handler pins the exact flow
1270        // against the pending challenge); the staging class rejects the
1271        // device profile outright.
1272        for profile in [TUI_PROFILE_STR, federate_source::TUI_DEVICE_PROFILE] {
1273            assert!(ExchangeRequest::parse_for_host(
1274                class_form(profile, TUI_CLIENT_ID, federate_source::HOST).as_bytes(),
1275                &host,
1276                Some(&tui_class())
1277            )
1278            .is_ok());
1279        }
1280        assert!(ExchangeRequest::parse_for_host(
1281            class_form(
1282                federate_source::TUI_DEVICE_PROFILE,
1283                federate_source::CLIENT,
1284                federate_source::HOST
1285            )
1286            .as_bytes(),
1287            &federate_source::FederateHost::new(federate_source::HOST)?,
1288            None
1289        )
1290        .is_err());
1291        Ok(())
1292    }
1293
1294    #[cfg(feature = "postgres")]
1295    fn tui_session(host: &federate_source::FederateHost) -> Session {
1296        let ed = [31; 32];
1297        let pq = vec![32; 1952];
1298        Session {
1299            host: host.as_str().into(),
1300            sid: "tui-sid".into(),
1301            account_id: "tui-account".into(),
1302            subject: "did:plc:abcdefghijklmnopqrstuvwx".into(),
1303            tenant: "tenant-a".into(),
1304            client_id: TUI_CLIENT_ID.into(),
1305            resource: host.as_str().into(),
1306            scopes: vec!["connect:tui:session".into(), "query:tui:session".into()],
1307            grant_revision: "revision-1".into(),
1308            ed_public: ed,
1309            pq_public: pq,
1310            generation: [3; 32],
1311            collision_inventory_id: [3; 32],
1312            proof_epoch: 1,
1313            expires_at: 1_800_000_120,
1314        }
1315    }
1316
1317    #[cfg(feature = "postgres")]
1318    #[test]
1319    fn w13_tui_mint_stamps_distinct_markers_and_no_consumer_authority() -> anyhow::Result<()> {
1320        let host = federate_source::FederateHost::new("https://vm-tui.example")?;
1321        let now = 1_800_000_000i64;
1322        let session = tui_session(&host);
1323        let claims = committed_claims_for_class(
1324            &session,
1325            now,
1326            federate_source::ISSUER,
1327            "opaque-atproto-connector-subject",
1328            &host,
1329            Some(TUI_CLIENT_ID),
1330        )?;
1331        let value = serde_json::to_value(&claims)?;
1332        // The exact TUI marker set, and NONE of the www markers.
1333        assert_eq!(value["hs_tui_profile"], TUI_PROFILE_STR);
1334        assert_eq!(
1335            value["hs_tui_signer_pq_key_v1"],
1336            B64.encode(&session.pq_public)
1337        );
1338        assert_eq!(value["hs_tui_source_issuer_v1"], federate_source::ISSUER);
1339        assert_eq!(
1340            value["hs_tui_source_subject_v1"],
1341            "opaque-atproto-connector-subject"
1342        );
1343        for www_marker in [
1344            "hs_profile",
1345            "hs_signer_suite_v1",
1346            "hs_signer_pq_key_v1",
1347            "hs_signer_inventory_v1",
1348            "hs_source_issuer_v1",
1349            "hs_source_subject_v1",
1350            "hs_session_authority_generation",
1351        ] {
1352            assert!(
1353                value.get(www_marker).is_none(),
1354                "TUI mint stamped the www marker {www_marker}"
1355            );
1356        }
1357        // Normal-verification routing: no federate marker, not reserved.
1358        assert!(!claims.has_federate_profile_marker());
1359        assert!(!claims.is_reserved_federate_credential(host.as_str()));
1360        assert_eq!(value["client_id"], TUI_CLIENT_ID);
1361        assert_eq!(value["scope"], "connect:tui:session query:tui:session");
1362        assert_eq!(
1363            value["cnf"],
1364            json!({"jwk":{"kty":"OKP","crv":"Ed25519","x":B64.encode(session.ed_public)}})
1365        );
1366
1367        // Registry|model consumer authority cannot ride the TUI mint, even
1368        // from a mutated Policy record.
1369        let mut smuggled = session.clone();
1370        smuggled.scopes = vec!["query:registry:List".into()];
1371        assert!(committed_tui_claims_for_host(
1372            &smuggled,
1373            now,
1374            federate_source::ISSUER,
1375            "subject",
1376            &host,
1377            TUI_CLIENT_ID
1378        )
1379        .is_err());
1380        let mut smuggled = session.clone();
1381        smuggled.scopes = vec!["infer:model:qwen2.5-0.5b-instruct:main".into()];
1382        assert!(committed_tui_claims_for_host(
1383            &smuggled,
1384            now,
1385            federate_source::ISSUER,
1386            "subject",
1387            &host,
1388            TUI_CLIENT_ID
1389        )
1390        .is_err());
1391
1392        // Default-deny: the TUI session does not mint when the class is
1393        // unconfigured, and the www mint still rejects a TUI-client record.
1394        assert!(committed_claims_for_class(
1395            &session,
1396            now,
1397            federate_source::ISSUER,
1398            "subject",
1399            &host,
1400            None
1401        )
1402        .is_err());
1403        assert!(committed_claims_for_host(
1404            &session,
1405            now,
1406            federate_source::ISSUER,
1407            "subject",
1408            &host
1409        )
1410        .is_err());
1411        // The www mint is unchanged: its exact session still mints the www
1412        // marker set.
1413        let www = committed_session();
1414        let www_claims = committed_claims(&www, now, federate_source::ISSUER, "subject")?;
1415        let www_value = serde_json::to_value(&www_claims)?;
1416        assert_eq!(www_value["hs_profile"], PROFILE);
1417        assert!(www_value.get("hs_tui_profile").is_none());
1418        Ok(())
1419    }
1420
1421    #[test]
1422    fn malformed_and_ambiguous_json_denied() -> anyhow::Result<()> {
1423        assert!(ChallengeRequest::parse(b"").is_err());
1424        assert!(ChallengeRequest::parse(&vec![b' '; MAX_BODY + 1]).is_err());
1425        let valid = String::from_utf8(serde_json::to_vec(&request())?)?;
1426        let duplicate = valid.replacen("\"profile\":", "\"profile\":\"other\",\"profile\":", 1);
1427        assert!(ChallengeRequest::parse(duplicate.as_bytes()).is_err());
1428        let mut unknown = request();
1429        unknown["tenant"] = "attacker".into();
1430        assert!(ChallengeRequest::parse(&serde_json::to_vec(&unknown)?).is_err());
1431        let mut code = request();
1432        code["authorization_code"] = "nonascii-é".into();
1433        assert!(ChallengeRequest::parse(&serde_json::to_vec(&code)?).is_err());
1434        Ok(())
1435    }
1436}