Skip to main content

auth_framework/protocols/
gnap.rs

1//! GNAP (Grant Negotiation and Authorization Protocol) implementation.
2//!
3//! This module implements the GNAP specification (draft-ietf-gnap-core-protocol),
4//! providing an emerging next-generation alternative to OAuth 2.0 with stronger
5//! cryptographic binding and a unified request structure.
6//!
7//! # Implemented Features
8//!
9//! - Transaction lifecycle (create, continue, approve, deny)
10//! - Client key binding via JWK (ES256, RS256, EdDSA); a client key is required
11//! - Access granted only through a [`GnapAccessPolicy`] (default deny)
12//! - One-time interaction reference and hash (draft §4.2, §4.2.3)
13//! - Continuation token rotation on each use
14//! - Token management (revocation)
15//! - Subject information responses
16//! - Transaction expiration and cleanup
17
18use crate::errors::{AuthError, Result};
19use crate::server::security::dpop::DpopManager;
20use async_trait::async_trait;
21use base64::Engine as _;
22use serde::{Deserialize, Serialize};
23use sha2::{Digest, Sha256};
24use std::collections::HashMap;
25use std::sync::Arc;
26use tokio::sync::RwLock;
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct GnapConfig {
30    pub enabled: bool,
31    pub transaction_endpoint: String,
32    /// Base URL for interaction redirects (must be configured for production)
33    pub interaction_base_url: Option<String>,
34    /// Default access token lifetime in seconds
35    pub token_lifetime_secs: u64,
36    /// Transaction lifetime in seconds before expiration (default: 600 = 10 minutes)
37    pub transaction_lifetime_secs: u64,
38}
39
40impl Default for GnapConfig {
41    fn default() -> Self {
42        Self {
43            enabled: false,
44            transaction_endpoint: "/api/gnap/tx".to_string(),
45            interaction_base_url: None,
46            token_lifetime_secs: 3600,
47            transaction_lifetime_secs: 600,
48        }
49    }
50}
51
52/// A GNAP transaction request representing the client's intent
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct GnapTransactionRequest {
55    pub client: Option<GnapClientInfo>,
56    pub interact: Option<GnapInteractionRequirements>,
57    /// Requested access rights (draft-ietf-gnap-core-protocol §2)
58    pub access_token: Option<Vec<GnapAccessRequest>>,
59    /// Subject information request
60    pub subject: Option<GnapSubjectRequest>,
61}
62
63/// Description of a single access right being requested
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct GnapAccessRequest {
66    /// Type of access (e.g. "read", "write", or an API-specific identifier)
67    #[serde(rename = "type")]
68    pub access_type: String,
69    /// Actions within this type
70    #[serde(default)]
71    pub actions: Vec<String>,
72    /// Locations/URIs where this access applies
73    #[serde(default)]
74    pub locations: Vec<String>,
75}
76
77/// Subject information the client is requesting
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct GnapSubjectRequest {
80    /// Requested subject identifier formats
81    #[serde(default)]
82    pub sub_id_formats: Vec<String>,
83    /// Requested assertion formats (e.g. "id_token", "saml2")
84    #[serde(default)]
85    pub assertion_formats: Vec<String>,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct GnapClientInfo {
90    /// Client key in JWK format for cryptographic binding
91    pub key: Option<GnapClientKey>,
92    /// Client display information
93    pub display: Option<GnapClientDisplay>,
94}
95
96/// Client key with proof method (draft §7.1)
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct GnapClientKey {
99    /// Proof method: "httpsig", "mtls", "dpop", "jws", or "test"
100    pub proof: String,
101    /// JWK representation of the client's public key
102    pub jwk: GnapJwk,
103}
104
105/// Minimal JWK representation sufficient for GNAP key binding
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct GnapJwk {
108    /// Key type: "EC", "RSA", or "OKP"
109    pub kty: String,
110    /// Key ID (optional)
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub kid: Option<String>,
113
114    // EC fields (P-256 / ES256)
115    /// EC curve name
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub crv: Option<String>,
118    /// EC x coordinate (base64url)
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub x: Option<String>,
121    /// EC y coordinate (base64url)
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub y: Option<String>,
124
125    // RSA fields
126    /// RSA modulus (base64url)
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub n: Option<String>,
129    /// RSA exponent (base64url)
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub e: Option<String>,
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct GnapClientDisplay {
136    pub name: Option<String>,
137    pub uri: Option<String>,
138}
139
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct GnapInteractionRequirements {
142    pub start: Vec<String>,
143    pub finish: Option<GnapInteractionFinish>,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize)]
147pub struct GnapInteractionFinish {
148    pub method: String,
149    pub uri: String,
150    pub nonce: String,
151}
152
153impl GnapTransactionRequest {
154    /// Create a builder for a GNAP transaction request.
155    ///
156    /// # Example
157    /// ```rust
158    /// use auth_framework::protocols::gnap::GnapTransactionRequest;
159    ///
160    /// let req = GnapTransactionRequest::builder()
161    ///     .access("read", &["list"], &["https://api.example.com"])
162    ///     .subject_formats(vec!["opaque".into()])
163    ///     .build();
164    /// ```
165    pub fn builder() -> GnapTransactionRequestBuilder {
166        GnapTransactionRequestBuilder {
167            client: None,
168            interact: None,
169            access_token: Vec::new(),
170            subject: None,
171        }
172    }
173}
174
175/// Builder for [`GnapTransactionRequest`].
176pub struct GnapTransactionRequestBuilder {
177    client: Option<GnapClientInfo>,
178    interact: Option<GnapInteractionRequirements>,
179    access_token: Vec<GnapAccessRequest>,
180    subject: Option<GnapSubjectRequest>,
181}
182
183impl GnapTransactionRequestBuilder {
184    /// Set the client info with a key binding.
185    pub fn client(mut self, client: GnapClientInfo) -> Self {
186        self.client = Some(client);
187        self
188    }
189
190    /// Set client info from a key and proof method.
191    pub fn client_key(mut self, jwk: GnapJwk, proof: impl Into<String>) -> Self {
192        self.client = Some(GnapClientInfo {
193            key: Some(GnapClientKey {
194                proof: proof.into(),
195                jwk,
196            }),
197            display: None,
198        });
199        self
200    }
201
202    /// Set interaction requirements for redirect flow.
203    pub fn redirect_interaction(
204        mut self,
205        callback_uri: impl Into<String>,
206        nonce: impl Into<String>,
207    ) -> Self {
208        self.interact = Some(GnapInteractionRequirements {
209            start: vec!["redirect".to_string()],
210            finish: Some(GnapInteractionFinish {
211                method: "redirect".to_string(),
212                uri: callback_uri.into(),
213                nonce: nonce.into(),
214            }),
215        });
216        self
217    }
218
219    /// Set interaction requirements (raw).
220    pub fn interact(mut self, interact: GnapInteractionRequirements) -> Self {
221        self.interact = Some(interact);
222        self
223    }
224
225    /// Add an access request with type, actions, and locations.
226    pub fn access(
227        mut self,
228        access_type: impl Into<String>,
229        actions: &[impl AsRef<str>],
230        locations: &[impl AsRef<str>],
231    ) -> Self {
232        self.access_token.push(GnapAccessRequest {
233            access_type: access_type.into(),
234            actions: actions.iter().map(|a| a.as_ref().to_string()).collect(),
235            locations: locations.iter().map(|l| l.as_ref().to_string()).collect(),
236        });
237        self
238    }
239
240    /// Add a simple access request (type only, no actions/locations).
241    pub fn access_type(self, access_type: impl Into<String>) -> Self {
242        self.access(access_type, &[] as &[&str], &[] as &[&str])
243    }
244
245    /// Request subject information with the given identifier formats.
246    pub fn subject_formats(mut self, formats: Vec<String>) -> Self {
247        self.subject = Some(GnapSubjectRequest {
248            sub_id_formats: formats,
249            assertion_formats: vec![],
250        });
251        self
252    }
253
254    /// Request subject information (raw).
255    pub fn subject(mut self, subject: GnapSubjectRequest) -> Self {
256        self.subject = Some(subject);
257        self
258    }
259
260    /// Build the [`GnapTransactionRequest`].
261    pub fn build(self) -> GnapTransactionRequest {
262        GnapTransactionRequest {
263            client: self.client,
264            interact: self.interact,
265            access_token: if self.access_token.is_empty() {
266                None
267            } else {
268                Some(self.access_token)
269            },
270            subject: self.subject,
271        }
272    }
273}
274
275/// Internal state of a GNAP transaction
276#[derive(Debug, Clone, Serialize, Deserialize)]
277enum GnapTransactionState {
278    /// Waiting for user interaction
279    Pending,
280    /// User has approved; access token can be issued
281    Approved,
282    /// Transaction was denied or expired
283    Denied,
284}
285
286#[derive(Clone, Serialize, Deserialize)]
287struct GnapTransaction {
288    id: String,
289    state: GnapTransactionState,
290    request: GnapTransactionRequest,
291    continue_token: String,
292    created_at: u64,
293    /// Server-generated nonce for interaction hash verification (draft §4.2.3)
294    interact_nonce: Option<String>,
295    /// Subject identifier assigned after approval
296    subject_id: Option<String>,
297    /// One-time interaction reference issued when a finish-method transaction is approved
298    interact_ref: Option<String>,
299}
300
301impl std::fmt::Debug for GnapTransaction {
302    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
303        let mut d = f.debug_struct("GnapTransaction");
304        d.field("id", &self.id);
305        d.field("state", &self.state);
306        d.field("request", &self.request);
307        d.field(
308            "continue_token",
309            &crate::utils::redact::redacted(&self.continue_token),
310        );
311        d.field("created_at", &self.created_at);
312        d.field(
313            "interact_nonce",
314            &crate::utils::redact::redacted(&self.interact_nonce),
315        );
316        d.field("subject_id", &self.subject_id);
317        d.field(
318            "interact_ref",
319            &crate::utils::redact::redacted(&self.interact_ref),
320        );
321        d.finish()
322    }
323}
324
325/// A GNAP access token that has been issued and can be managed
326#[derive(Clone, Serialize, Deserialize)]
327struct GnapIssuedToken {
328    /// Opaque token value
329    pub value: String,
330    /// Access rights granted
331    pub access: Vec<GnapAccessRequest>,
332    /// Expiration timestamp (epoch seconds)
333    pub expires_at: u64,
334    /// Client key thumbprint that this token is bound to (if any)
335    pub key_thumbprint: Option<String>,
336    /// The proof method of that key (`dpop`, ...): how a request about this token is proved.
337    #[serde(default)]
338    pub key_proof: Option<String>,
339    /// The transaction that produced this token
340    pub transaction_id: String,
341}
342
343impl std::fmt::Debug for GnapIssuedToken {
344    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
345        let mut d = f.debug_struct("GnapIssuedToken");
346        d.field("value", &crate::utils::redact::redacted(&self.value));
347        d.field("access", &self.access);
348        d.field("expires_at", &self.expires_at);
349        d.field("key_thumbprint", &self.key_thumbprint);
350        d.field("key_proof", &self.key_proof);
351        d.field("transaction_id", &self.transaction_id);
352        d.finish()
353    }
354}
355
356/// The HTTP request a client key signs, handed to the `_with_proof` entry points.
357///
358/// Only the `dpop` proof method can be verified here: the proof is the request's `DPoP` header
359/// and must be signed by the key the client named in its request, for this method and URI.
360#[derive(Debug, Clone, Copy)]
361pub struct GnapProof<'a> {
362    /// HTTP method of the request (`htm`).
363    pub http_method: &'a str,
364    /// HTTP URI of the request, without query or fragment (`htu`).
365    pub http_uri: &'a str,
366    /// The request's `DPoP` header, if it had one.
367    pub dpop_proof: Option<&'a str>,
368    /// A server-issued DPoP nonce the proof must carry, if the caller uses them.
369    pub expected_nonce: Option<&'a str>,
370}
371
372/// Decides which access rights a client key is granted.
373///
374/// [`GnapService`] never issues an access token on its own authority: an integrator supplies a
375/// policy with [`GnapService::with_access_policy`], and the token carries exactly what the policy
376/// returns, which can be less than the client asked for. An empty return denies the request. A
377/// service without a policy denies every request for an access token.
378#[async_trait]
379pub trait GnapAccessPolicy: Send + Sync {
380    /// The rights to grant to the client key with this RFC 7638 `client_key_thumbprint` out of
381    /// the `requested` ones. Return an empty list to deny.
382    async fn grant(
383        &self,
384        client_key_thumbprint: &str,
385        requested: &[GnapAccessRequest],
386    ) -> Vec<GnapAccessRequest>;
387}
388
389/// What the authorization server hands back to the client when the resource owner approves a
390/// transaction that uses an interaction `finish` method (RFC 9635 section 4.2).
391///
392/// The integrator delivers both values to the client's finish URI. The client checks `hash`
393/// (section 4.2.3) and presents `interact_ref`, once, in its continuation request.
394#[derive(Clone, PartialEq, Eq)]
395pub struct GnapInteractionCompletion {
396    /// The one-time interaction reference, `None` when the transaction has no finish method.
397    pub interact_ref: Option<String>,
398    /// The interaction hash the client verifies, `None` when the transaction has no finish method.
399    pub hash: Option<String>,
400}
401
402impl std::fmt::Debug for GnapInteractionCompletion {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        let mut d = f.debug_struct("GnapInteractionCompletion");
405        d.field(
406            "interact_ref",
407            &crate::utils::redact::redacted(&self.interact_ref),
408        );
409        d.field("hash", &crate::utils::redact::redacted(&self.hash));
410        d.finish()
411    }
412}
413
414pub struct GnapService {
415    config: GnapConfig,
416    /// Decides what is granted; without one no access token is issued.
417    policy: Option<Arc<dyn GnapAccessPolicy>>,
418    /// Active transactions (keyed by transaction ID)
419    transactions: Arc<RwLock<HashMap<String, GnapTransaction>>>,
420    /// Issued access tokens (keyed by token value)
421    issued_tokens: Arc<RwLock<HashMap<String, GnapIssuedToken>>>,
422}
423
424/// Refusal of a client key whose proof method this crate cannot verify.
425const PROOF_NOT_SUPPORTED: &str = "GNAP proof method not supported";
426/// Refusal of a client key that came without the proof material to check it.
427const PROOF_REQUIRED: &str = "GNAP client key proof required: use the _with_proof entry point with the request's DPoP header";
428/// Refusal of a client key proof that did not verify.
429const PROOF_INVALID: &str = "GNAP client key proof invalid";
430/// Refusal of a request that names no client key (RFC 9635 section 2.3).
431const KEY_REQUIRED: &str = "GNAP client key required";
432/// Refusal to issue an access token when the service has no access policy.
433const POLICY_REQUIRED: &str = "GNAP access denied: no access policy is configured";
434/// Refusal to issue an access token when the policy grants nothing.
435const ACCESS_DENIED: &str = "GNAP access denied by policy";
436
437impl GnapService {
438    pub fn new(config: GnapConfig) -> Self {
439        Self {
440            config,
441            policy: None,
442            transactions: Arc::new(RwLock::new(HashMap::new())),
443            issued_tokens: Arc::new(RwLock::new(HashMap::new())),
444        }
445    }
446
447    /// Set the policy that decides what access tokens carry. Without one, every request for an
448    /// access token is denied.
449    pub fn with_access_policy(mut self, policy: Arc<dyn GnapAccessPolicy>) -> Self {
450        self.policy = Some(policy);
451        self
452    }
453
454    // ── Key Binding Helpers ──────────────────────────────────────────────
455
456    /// Compute the JWK thumbprint (RFC 7638) for key binding.
457    /// Uses the required members in lexicographic order per key type.
458    fn jwk_thumbprint(jwk: &GnapJwk) -> Result<String> {
459        let canonical = match jwk.kty.as_str() {
460            "EC" => {
461                let crv = jwk.crv.as_deref().unwrap_or("");
462                let x = jwk.x.as_deref().unwrap_or("");
463                let y = jwk.y.as_deref().unwrap_or("");
464                format!(r#"{{"crv":"{crv}","kty":"EC","x":"{x}","y":"{y}"}}"#)
465            }
466            "RSA" => {
467                let e = jwk.e.as_deref().unwrap_or("");
468                let n = jwk.n.as_deref().unwrap_or("");
469                format!(r#"{{"e":"{e}","kty":"RSA","n":"{n}"}}"#)
470            }
471            "OKP" => {
472                let crv = jwk.crv.as_deref().unwrap_or("");
473                let x = jwk.x.as_deref().unwrap_or("");
474                format!(r#"{{"crv":"{crv}","kty":"OKP","x":"{x}"}}"#)
475            }
476            other => {
477                return Err(AuthError::validation(format!(
478                    "Unsupported JWK key type: {other}"
479                )));
480            }
481        };
482        let hash = Sha256::digest(canonical.as_bytes());
483        Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash))
484    }
485
486    /// Reconstruct the raw public key bytes from a JWK and verify a
487    /// signature using `ring`. Supports ES256 (P-256) and RS256.
488    ///
489    /// This is called by middleware or application code that extracts the
490    /// HTTP message signature from the request before invoking the GNAP
491    /// transaction endpoints.
492    #[allow(dead_code)]
493    pub fn verify_jwk_signature(jwk: &GnapJwk, message: &[u8], signature: &[u8]) -> Result<()> {
494        use base64::Engine;
495        use ring::signature;
496
497        match jwk.kty.as_str() {
498            "EC" => {
499                let crv = jwk.crv.as_deref().unwrap_or("P-256");
500                if crv != "P-256" {
501                    return Err(AuthError::validation(format!(
502                        "Unsupported EC curve for GNAP: {crv}"
503                    )));
504                }
505                let x = base64::engine::general_purpose::URL_SAFE_NO_PAD
506                    .decode(jwk.x.as_deref().unwrap_or(""))
507                    .map_err(|e| AuthError::validation(format!("Invalid JWK x: {e}")))?;
508                let y = base64::engine::general_purpose::URL_SAFE_NO_PAD
509                    .decode(jwk.y.as_deref().unwrap_or(""))
510                    .map_err(|e| AuthError::validation(format!("Invalid JWK y: {e}")))?;
511
512                // Uncompressed point: 0x04 || x || y
513                let mut pk_bytes = Vec::with_capacity(1 + x.len() + y.len());
514                pk_bytes.push(0x04);
515                pk_bytes.extend_from_slice(&x);
516                pk_bytes.extend_from_slice(&y);
517
518                let key = signature::UnparsedPublicKey::new(
519                    &signature::ECDSA_P256_SHA256_ASN1,
520                    &pk_bytes,
521                );
522                key.verify(message, signature).map_err(|_| {
523                    AuthError::validation("GNAP client key signature verification failed (ES256)")
524                })
525            }
526            "RSA" => {
527                let n = base64::engine::general_purpose::URL_SAFE_NO_PAD
528                    .decode(jwk.n.as_deref().unwrap_or(""))
529                    .map_err(|e| AuthError::validation(format!("Invalid JWK n: {e}")))?;
530                let e = base64::engine::general_purpose::URL_SAFE_NO_PAD
531                    .decode(jwk.e.as_deref().unwrap_or(""))
532                    .map_err(|e| AuthError::validation(format!("Invalid JWK e: {e}")))?;
533
534                // DER-encode the RSA public key (PKCS#1)
535                let pk_der = Self::encode_rsa_public_key_der(&n, &e);
536
537                let key = signature::UnparsedPublicKey::new(
538                    &signature::RSA_PKCS1_2048_8192_SHA256,
539                    &pk_der,
540                );
541                key.verify(message, signature).map_err(|_| {
542                    AuthError::validation("GNAP client key signature verification failed (RS256)")
543                })
544            }
545            other => Err(AuthError::validation(format!(
546                "Unsupported JWK key type for signature: {other}"
547            ))),
548        }
549    }
550
551    /// Encode RSA n,e into a DER SubjectPublicKeyInfo structure for ring.
552    #[allow(dead_code)]
553    fn encode_rsa_public_key_der(n: &[u8], e: &[u8]) -> Vec<u8> {
554        // Build PKCS#1 RSAPublicKey: SEQUENCE { INTEGER n, INTEGER e }
555        fn der_integer(val: &[u8]) -> Vec<u8> {
556            // Strip leading zeros but ensure positive
557            let v = if !val.is_empty() && val[0] == 0 {
558                let stripped = val.iter().position(|&b| b != 0).unwrap_or(val.len() - 1);
559                &val[stripped..]
560            } else {
561                val
562            };
563            let needs_pad = !v.is_empty() && v[0] & 0x80 != 0;
564            let len = v.len() + if needs_pad { 1 } else { 0 };
565            let mut out = vec![0x02]; // INTEGER tag
566            der_encode_length(len, &mut out);
567            if needs_pad {
568                out.push(0x00);
569            }
570            out.extend_from_slice(v);
571            out
572        }
573
574        fn der_encode_length(len: usize, out: &mut Vec<u8>) {
575            if len < 0x80 {
576                out.push(len as u8);
577            } else if len < 0x100 {
578                out.push(0x81);
579                out.push(len as u8);
580            } else if len < 0x10000 {
581                out.push(0x82);
582                out.push((len >> 8) as u8);
583                out.push(len as u8);
584            } else {
585                out.push(0x83);
586                out.push((len >> 16) as u8);
587                out.push((len >> 8) as u8);
588                out.push(len as u8);
589            }
590        }
591
592        let n_der = der_integer(n);
593        let e_der = der_integer(e);
594        let rsa_seq_content_len = n_der.len() + e_der.len();
595        let mut rsa_seq = vec![0x30]; // SEQUENCE tag
596        der_encode_length(rsa_seq_content_len, &mut rsa_seq);
597        rsa_seq.extend_from_slice(&n_der);
598        rsa_seq.extend_from_slice(&e_der);
599
600        // Wrap in SubjectPublicKeyInfo:
601        // SEQUENCE { SEQUENCE { OID rsaEncryption, NULL }, BIT STRING { rsa_seq } }
602        let rsa_oid: &[u8] = &[
603            0x30, 0x0d, // SEQUENCE (AlgorithmIdentifier)
604            0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
605            0x01, // OID 1.2.840.113549.1.1.1
606            0x05, 0x00, // NULL
607        ];
608        let bitstring_len = 1 + rsa_seq.len(); // 1 byte for unused-bits count
609        let mut bitstring = vec![0x03]; // BIT STRING tag
610        der_encode_length(bitstring_len, &mut bitstring);
611        bitstring.push(0x00); // 0 unused bits
612        bitstring.extend_from_slice(&rsa_seq);
613
614        let spki_content_len = rsa_oid.len() + bitstring.len();
615        let mut spki = vec![0x30]; // outer SEQUENCE
616        der_encode_length(spki_content_len, &mut spki);
617        spki.extend_from_slice(rsa_oid);
618        spki.extend_from_slice(&bitstring);
619        spki
620    }
621
622    /// Validate the client key binding on a request.
623    /// Returns the key thumbprint if a key is present and valid.
624    ///
625    /// When `proof_message` and `proof_signature` are provided, the actual
626    /// cryptographic signature is verified against the client's JWK. For
627    /// proof methods other than "test", the caller (typically HTTP middleware)
628    /// must extract and supply the message and signature bytes from the
629    /// request (e.g. the HTTP Signature input string and its signature value).
630    pub fn validate_client_key_with_proof(
631        client: &Option<GnapClientInfo>,
632        proof_message: Option<&[u8]>,
633        proof_signature: Option<&[u8]>,
634    ) -> Result<Option<String>> {
635        let client = match client {
636            Some(c) => c,
637            None => return Ok(None),
638        };
639        let key = match &client.key {
640            Some(k) => k,
641            None => return Ok(None),
642        };
643
644        // Validate proof method is recognized
645        match key.proof.as_str() {
646            "httpsig" | "mtls" | "dpop" | "jws" | "test" => {}
647            other => {
648                return Err(AuthError::validation(format!(
649                    "GNAP proof method not supported: {other}"
650                )));
651            }
652        }
653
654        // Validate key type and required fields
655        Self::validate_jwk_fields(&key.jwk)?;
656
657        let thumbprint = Self::jwk_thumbprint(&key.jwk)?;
658
659        // A signature over bytes the caller chose is not a proof of the request, so no method
660        // is accepted here: use `handle_transaction_with_proof` for `dpop`. Only the unit-test
661        // method, which checks nothing, passes, and only in test builds.
662        let _ = (proof_message, proof_signature);
663        if !cfg!(test) || key.proof != "test" {
664            return Err(AuthError::validation(format!(
665                "{PROOF_NOT_SUPPORTED}: {}",
666                key.proof
667            )));
668        }
669
670        Ok(Some(thumbprint))
671    }
672
673    /// Validate that a JWK has the required fields for its key type.
674    fn validate_jwk_fields(jwk: &GnapJwk) -> Result<()> {
675        match jwk.kty.as_str() {
676            "EC" => {
677                if jwk.x.is_none() || jwk.y.is_none() {
678                    return Err(AuthError::validation(
679                        "EC JWK must include x and y coordinates",
680                    ));
681                }
682            }
683            "RSA" => {
684                if jwk.n.is_none() || jwk.e.is_none() {
685                    return Err(AuthError::validation(
686                        "RSA JWK must include n and e components",
687                    ));
688                }
689            }
690            "OKP" => {
691                if jwk.x.is_none() {
692                    return Err(AuthError::validation("OKP JWK must include x coordinate"));
693                }
694            }
695            other => {
696                return Err(AuthError::validation(format!(
697                    "Unsupported JWK key type: {other}"
698                )));
699            }
700        }
701        Ok(())
702    }
703
704    /// Validate the client key binding on a request (structural only, no
705    /// signature verification). Used internally when proof material is
706    /// not available at the protocol level (e.g., continuation polling).
707    fn validate_client_key(client: &Option<GnapClientInfo>) -> Result<Option<String>> {
708        let client = match client {
709            Some(c) => c,
710            None => return Ok(None),
711        };
712        let key = match &client.key {
713            Some(k) => k,
714            None => return Ok(None),
715        };
716
717        // Validate proof method is recognized
718        match key.proof.as_str() {
719            "httpsig" | "mtls" | "dpop" | "jws" | "test" => {}
720            other => {
721                return Err(AuthError::validation(format!(
722                    "GNAP proof method not supported: {other}"
723                )));
724            }
725        }
726
727        Self::validate_jwk_fields(&key.jwk)?;
728        let thumbprint = Self::jwk_thumbprint(&key.jwk)?;
729        Ok(Some(thumbprint))
730    }
731
732    /// Prove the client holds the key it named, and return that key's thumbprint.
733    ///
734    /// A request that names no client key is refused (RFC 9635 section 2.3). A request
735    /// that names one is accepted only when its proof is verified here: `dpop` against `dpop`'s
736    /// manager and the request's `DPoP` header. Every other method (`httpsig`, `mtls`, `jws`,
737    /// anything unknown) is refused, as is a `dpop` key with no proof material, so no proof
738    /// that was never checked can authorize a request.
739    async fn verify_client_proof(
740        client: &Option<GnapClientInfo>,
741        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
742    ) -> Result<Option<String>> {
743        let Some(thumbprint) = Self::validate_client_key(client)? else {
744            return Err(AuthError::validation(KEY_REQUIRED));
745        };
746        let Some(key) = client.as_ref().and_then(|c| c.key.as_ref()) else {
747            return Err(AuthError::validation(KEY_REQUIRED));
748        };
749        Self::check_key_proof(&key.proof, &thumbprint, dpop).await?;
750        Ok(Some(thumbprint))
751    }
752
753    /// The one place that decides which proof methods this build can verify, and verifies them. Issuance
754    /// (`verify_client_proof`) and token management (`verify_token_key_proof`) both call it, so a method cannot
755    /// be admitted at issuance and then have no way to rotate or revoke its token: a method added here is
756    /// added to both, and a method refused here is refused at both. Only `dpop` is verified; `test`, which
757    /// checks nothing, exists in unit-test builds only.
758    async fn check_key_proof(
759        method: &str,
760        thumbprint: &str,
761        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
762    ) -> Result<()> {
763        match method {
764            "dpop" => Self::check_dpop_proof(thumbprint, dpop).await,
765            #[cfg(test)]
766            "test" => Ok(()),
767            other => Err(AuthError::validation(format!(
768                "{PROOF_NOT_SUPPORTED}: {other}"
769            ))),
770        }
771    }
772
773    /// Check that the request's `DPoP` header is a fresh proof signed by the key with `thumbprint`, for this
774    /// method and URI. No proof material is a refusal, never a pass.
775    async fn check_dpop_proof(
776        thumbprint: &str,
777        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
778    ) -> Result<()> {
779        let Some((manager, proof)) = dpop else {
780            return Err(AuthError::validation(PROOF_REQUIRED));
781        };
782        let Some(header) = proof.dpop_proof else {
783            return Err(AuthError::validation(PROOF_REQUIRED));
784        };
785        match manager
786            .validate_dpop_proof_for_key(
787                header,
788                proof.http_method,
789                proof.http_uri,
790                None,
791                proof.expected_nonce,
792                Some(thumbprint),
793            )
794            .await
795        {
796            Ok(result) if result.is_valid => Ok(()),
797            _ => Err(AuthError::validation(PROOF_INVALID)),
798        }
799    }
800
801    /// The proof method of the key a request names, if it names one.
802    fn key_proof_method(client: &Option<GnapClientInfo>) -> Option<&str> {
803        client
804            .as_ref()
805            .and_then(|c| c.key.as_ref())
806            .map(|key| key.proof.as_str())
807    }
808
809    /// A request about a key-bound token is accepted only with a proof from that key (RFC 9635 section 6:
810    /// the management request is signed with the key the token is bound to). A bearer token has no key and
811    /// needs none. A token bound under a method this build cannot verify is refused, not waved through.
812    async fn verify_token_key_proof(
813        key_thumbprint: Option<&str>,
814        key_proof: Option<&str>,
815        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
816    ) -> Result<()> {
817        let Some(thumbprint) = key_thumbprint else {
818            return Ok(());
819        };
820        match key_proof {
821            Some(method) => Self::check_key_proof(method, thumbprint, dpop).await,
822            None => Err(AuthError::validation(PROOF_NOT_SUPPORTED)),
823        }
824    }
825
826    /// Look the token up and require the proof its key calls for, before anything is changed.
827    async fn require_token_key_proof(
828        &self,
829        token_value: &str,
830        not_found: &'static str,
831        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
832    ) -> Result<()> {
833        let (thumbprint, method) = {
834            let tokens = self.issued_tokens.read().await;
835            let token = tokens
836                .get(token_value)
837                .ok_or_else(|| AuthError::validation(not_found))?;
838            (token.key_thumbprint.clone(), token.key_proof.clone())
839        };
840        Self::verify_token_key_proof(thumbprint.as_deref(), method.as_deref(), dpop).await
841    }
842
843    // ── Interaction Hash ─────────────────────────────────────────────────
844
845    /// Compute the interaction hash per draft §4.2.3.
846    ///
847    /// hash = SHA-256( client_nonce + "\n" + server_nonce + "\n" + interact_ref + "\n" + tx_endpoint )
848    fn compute_interact_hash(
849        client_nonce: &str,
850        server_nonce: &str,
851        interact_ref: &str,
852        transaction_endpoint: &str,
853    ) -> String {
854        let input =
855            format!("{client_nonce}\n{server_nonce}\n{interact_ref}\n{transaction_endpoint}");
856        let hash = Sha256::digest(input.as_bytes());
857        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash)
858    }
859
860    // ── Token Issuance Helper ────────────────────────────────────────────
861
862    async fn build_access_token_response(
863        &self,
864        access_requests: &[GnapAccessRequest],
865        key_thumbprint: &Option<String>,
866        key_proof: Option<&str>,
867        transaction_id: &str,
868    ) -> Result<serde_json::Map<String, serde_json::Value>> {
869        // The policy, not the request, decides what the token carries.
870        let policy = self
871            .policy
872            .as_ref()
873            .ok_or_else(|| AuthError::validation(POLICY_REQUIRED))?;
874        let thumbprint = key_thumbprint
875            .as_deref()
876            .ok_or_else(|| AuthError::validation(KEY_REQUIRED))?;
877        let granted = policy.grant(thumbprint, access_requests).await;
878        if granted.is_empty() {
879            return Err(AuthError::validation(ACCESS_DENIED));
880        }
881        let access_requests = granted.as_slice();
882
883        let access_token = uuid::Uuid::new_v4().to_string();
884        let now = std::time::SystemTime::now()
885            .duration_since(std::time::UNIX_EPOCH)
886            .unwrap_or_default()
887            .as_secs();
888
889        let issued = GnapIssuedToken {
890            value: access_token.clone(),
891            access: access_requests.to_vec(),
892            expires_at: now + self.config.token_lifetime_secs,
893            key_thumbprint: key_thumbprint.clone(),
894            key_proof: key_proof.map(str::to_string),
895            transaction_id: transaction_id.to_string(),
896        };
897
898        // Stored before the response is returned: a client that uses the token at once finds it.
899        self.issued_tokens
900            .write()
901            .await
902            .insert(access_token.clone(), issued);
903
904        let mut token_obj = serde_json::Map::new();
905        token_obj.insert("value".to_string(), serde_json::Value::String(access_token));
906        token_obj.insert(
907            "expires_in".to_string(),
908            serde_json::Value::Number(self.config.token_lifetime_secs.into()),
909        );
910
911        // Include manage URI for token lifecycle operations
912        token_obj.insert(
913            "manage".to_string(),
914            serde_json::Value::String(format!("{}/token", self.config.transaction_endpoint)),
915        );
916
917        // If key-bound, indicate the key binding
918        if key_thumbprint.is_some() {
919            token_obj.insert("key".to_string(), serde_json::Value::Bool(true));
920        }
921
922        let access_json: Vec<serde_json::Value> = access_requests
923            .iter()
924            .map(|a| serde_json::to_value(a).unwrap_or_default())
925            .collect();
926        token_obj.insert("access".to_string(), serde_json::Value::Array(access_json));
927
928        Ok(token_obj)
929    }
930
931    // ── Transaction Lifecycle ────────────────────────────────────────────
932
933    /// Handle a new transaction request without proof material. Tests only: in a build every
934    /// request must come through [`Self::handle_transaction_with_proof`].
935    #[cfg(test)]
936    async fn handle_transaction(
937        &self,
938        request: GnapTransactionRequest,
939    ) -> Result<serde_json::Value> {
940        self.handle_transaction_inner(request, None).await
941    }
942
943    /// Handle a new GNAP transaction request (RFC 9635 section 2). The request must name a
944    /// client key with the `dpop` proof method, and `proof` carries the request's `DPoP` header,
945    /// which must be signed by that key. A request that names no client key is refused, and no
946    /// access token is issued unless the service has an access policy that grants something.
947    pub async fn handle_transaction_with_proof(
948        &self,
949        dpop: &DpopManager,
950        proof: &GnapProof<'_>,
951        request: GnapTransactionRequest,
952    ) -> Result<serde_json::Value> {
953        self.handle_transaction_inner(request, Some((dpop, proof)))
954            .await
955    }
956
957    async fn handle_transaction_inner(
958        &self,
959        request: GnapTransactionRequest,
960        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
961    ) -> Result<serde_json::Value> {
962        if !self.config.enabled {
963            return Err(AuthError::config("GNAP protocol is currently disabled"));
964        }
965
966        // Validate that the request asks for something
967        if request.access_token.is_none() && request.subject.is_none() {
968            return Err(AuthError::validation(
969                "GNAP request must include at least one of access_token or subject",
970            ));
971        }
972
973        // Validate client key if provided (draft §7.1)
974        let key_thumbprint = Self::verify_client_proof(&request.client, dpop).await?;
975
976        let transaction_id = uuid::Uuid::new_v4().to_string();
977        let continue_token = uuid::Uuid::new_v4().to_string();
978
979        let now = std::time::SystemTime::now()
980            .duration_since(std::time::UNIX_EPOCH)
981            .unwrap_or_default()
982            .as_secs();
983
984        let mut response = serde_json::Map::new();
985
986        // Generate a server nonce for interaction hash verification
987        let interact_nonce = if request.interact.is_some() {
988            let nonce = uuid::Uuid::new_v4().to_string();
989            Some(nonce)
990        } else {
991            None
992        };
993
994        // If interaction is requested, generate interaction response
995        if let Some(ref interact) = request.interact {
996            let base_url = self.config.interaction_base_url.as_deref().ok_or_else(|| {
997                AuthError::config(
998                    "GNAP interaction_base_url must be configured for interactive flows",
999                )
1000            })?;
1001
1002            let interact_url = format!("{}/interact/{}", base_url, transaction_id);
1003
1004            let mut interact_res = serde_json::Map::new();
1005
1006            if interact.start.iter().any(|m| m == "redirect") {
1007                interact_res.insert(
1008                    "redirect".to_string(),
1009                    serde_json::Value::String(interact_url),
1010                );
1011            }
1012
1013            if let Some(ref finish) = interact.finish {
1014                // Return server nonce for client to compute interaction hash
1015                interact_res.insert(
1016                    "finish".to_string(),
1017                    serde_json::Value::String(interact_nonce.clone().unwrap_or_default()),
1018                );
1019                // Echo the finish method + nonce so client knows the protocol
1020                let _ = &finish.nonce; // client_nonce is used later for hash
1021            }
1022
1023            response.insert(
1024                "interact".to_string(),
1025                serde_json::Value::Object(interact_res),
1026            );
1027
1028            // Store pending transaction
1029            let txn = GnapTransaction {
1030                id: transaction_id.clone(),
1031                state: GnapTransactionState::Pending,
1032                request: request.clone(),
1033                continue_token: continue_token.clone(),
1034                created_at: now,
1035                interact_nonce: interact_nonce.clone(),
1036                subject_id: None,
1037                interact_ref: None,
1038            };
1039            self.transactions.write().await.insert(transaction_id, txn);
1040        } else {
1041            // No interaction required — issue token directly if access requested
1042            if let Some(ref access_requests) = request.access_token {
1043                let token_obj = self
1044                    .build_access_token_response(
1045                        access_requests,
1046                        &key_thumbprint,
1047                        Self::key_proof_method(&request.client),
1048                        "direct",
1049                    )
1050                    .await?;
1051                response.insert(
1052                    "access_token".to_string(),
1053                    serde_json::Value::Object(token_obj),
1054                );
1055            }
1056
1057            // If subject info was requested, include it (draft §2.2)
1058            if let Some(ref subject_req) = request.subject {
1059                let subject_resp = Self::build_subject_response(subject_req, None);
1060                response.insert(
1061                    "subject".to_string(),
1062                    serde_json::Value::Object(subject_resp),
1063                );
1064            }
1065        }
1066
1067        // Provide continuation endpoint (with rotatable token)
1068        let mut continue_obj = serde_json::Map::new();
1069        let mut ct_token = serde_json::Map::new();
1070        ct_token.insert(
1071            "value".to_string(),
1072            serde_json::Value::String(continue_token),
1073        );
1074        continue_obj.insert(
1075            "access_token".to_string(),
1076            serde_json::Value::Object(ct_token),
1077        );
1078        continue_obj.insert(
1079            "uri".to_string(),
1080            serde_json::Value::String(format!("{}/continue", self.config.transaction_endpoint)),
1081        );
1082
1083        response.insert(
1084            "continue".to_string(),
1085            serde_json::Value::Object(continue_obj),
1086        );
1087
1088        Ok(serde_json::Value::Object(response))
1089    }
1090
1091    /// Continue a transaction without proof material. Tests only: in a build every continuation
1092    /// must come through [`Self::continue_transaction_with_proof`].
1093    #[cfg(test)]
1094    async fn continue_transaction(
1095        &self,
1096        transaction_id: &str,
1097        continue_token: &str,
1098        interact_ref: Option<&str>,
1099        interact_hash: Option<&str>,
1100    ) -> Result<serde_json::Value> {
1101        self.continue_transaction_inner(
1102            transaction_id,
1103            continue_token,
1104            interact_ref,
1105            interact_hash,
1106            None,
1107        )
1108        .await
1109    }
1110
1111    /// Continue a GNAP transaction (polling or post-interaction), RFC 9635 section 5.
1112    ///
1113    /// The continuation request must carry a `DPoP` proof signed by the transaction's client
1114    /// key. A transaction that uses a finish method continues only with the one-time
1115    /// `interact_ref` that [`Self::approve_transaction`] returned. The continuation token is
1116    /// **rotated on every successful call**, preventing replay of old continuation responses.
1117    pub async fn continue_transaction_with_proof(
1118        &self,
1119        dpop: &DpopManager,
1120        proof: &GnapProof<'_>,
1121        transaction_id: &str,
1122        continue_token: &str,
1123        interact_ref: Option<&str>,
1124        interact_hash: Option<&str>,
1125    ) -> Result<serde_json::Value> {
1126        self.continue_transaction_inner(
1127            transaction_id,
1128            continue_token,
1129            interact_ref,
1130            interact_hash,
1131            Some((dpop, proof)),
1132        )
1133        .await
1134    }
1135
1136    async fn continue_transaction_inner(
1137        &self,
1138        transaction_id: &str,
1139        continue_token: &str,
1140        interact_ref: Option<&str>,
1141        interact_hash: Option<&str>,
1142        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
1143    ) -> Result<serde_json::Value> {
1144        // Take a write lock so we can rotate the continuation token atomically
1145        let mut transactions = self.transactions.write().await;
1146        let txn = transactions
1147            .get_mut(transaction_id)
1148            .ok_or_else(|| AuthError::validation("Transaction not found or expired"))?;
1149
1150        // Enforce transaction expiration
1151        let now = std::time::SystemTime::now()
1152            .duration_since(std::time::UNIX_EPOCH)
1153            .unwrap_or_default()
1154            .as_secs();
1155        if now.saturating_sub(txn.created_at) > self.config.transaction_lifetime_secs {
1156            transactions.remove(transaction_id);
1157            return Err(AuthError::validation("Transaction has expired"));
1158        }
1159
1160        // Verify continuation token
1161        if txn.continue_token != continue_token {
1162            return Err(AuthError::validation("Invalid continuation token"));
1163        }
1164
1165        // An approved transaction that uses a finish method continues only with the one-time
1166        // interaction reference issued at approval, and a reference nobody issued is refused.
1167        // Checked before the token is rotated, so a refused request leaves the token usable.
1168        match (txn.interact_ref.as_deref(), interact_ref) {
1169            (Some(issued), Some(given)) => {
1170                if !bool::from(subtle::ConstantTimeEq::ct_eq(
1171                    issued.as_bytes(),
1172                    given.as_bytes(),
1173                )) {
1174                    return Err(AuthError::validation("Invalid interaction reference"));
1175                }
1176            }
1177            (Some(_), None) | (None, Some(_)) => {
1178                return Err(AuthError::validation("Invalid interaction reference"));
1179            }
1180            (None, None) => {}
1181        }
1182
1183        // A transaction whose client named a key continues only for that key. This runs before
1184        // the token is rotated, so a request without that key's proof leaves the token usable.
1185        let verified_thumbprint = Self::verify_client_proof(&txn.request.client, dpop).await?;
1186
1187        // Rotate the continuation token (draft §5.1)
1188        let new_continue_token = uuid::Uuid::new_v4().to_string();
1189        txn.continue_token = new_continue_token.clone();
1190
1191        // If interaction hash is provided, verify it (draft §4.2.3)
1192        if let (Some(hash), Some(iref)) = (interact_hash, interact_ref) {
1193            let server_nonce = txn.interact_nonce.as_deref().ok_or_else(|| {
1194                AuthError::validation("No interaction nonce for this transaction")
1195            })?;
1196            let client_nonce = txn
1197                .request
1198                .interact
1199                .as_ref()
1200                .and_then(|i| i.finish.as_ref())
1201                .map(|f| f.nonce.as_str())
1202                .unwrap_or("");
1203
1204            let expected = Self::compute_interact_hash(
1205                client_nonce,
1206                server_nonce,
1207                iref,
1208                &self.config.transaction_endpoint,
1209            );
1210            if hash != expected {
1211                return Err(AuthError::validation(
1212                    "Interaction hash verification failed (draft §4.2.3)",
1213                ));
1214            }
1215        }
1216
1217        let result = match txn.state {
1218            GnapTransactionState::Pending => {
1219                // Still waiting for user interaction
1220                let mut resp = serde_json::Map::new();
1221                let mut cont = serde_json::Map::new();
1222                cont.insert(
1223                    "uri".to_string(),
1224                    serde_json::Value::String(format!(
1225                        "{}/continue",
1226                        self.config.transaction_endpoint
1227                    )),
1228                );
1229                cont.insert("wait".to_string(), serde_json::Value::Number(5.into()));
1230                let mut ct = serde_json::Map::new();
1231                ct.insert(
1232                    "value".to_string(),
1233                    serde_json::Value::String(new_continue_token),
1234                );
1235                cont.insert("access_token".to_string(), serde_json::Value::Object(ct));
1236                resp.insert("continue".to_string(), serde_json::Value::Object(cont));
1237                Ok(serde_json::Value::Object(resp))
1238            }
1239            GnapTransactionState::Approved => {
1240                let key_thumbprint = verified_thumbprint;
1241
1242                let mut response = serde_json::Map::new();
1243
1244                // Issue access token (the policy decides what it carries)
1245                let mut refused = None;
1246                if let Some(ref access_requests) = txn.request.access_token {
1247                    match self
1248                        .build_access_token_response(
1249                            access_requests,
1250                            &key_thumbprint,
1251                            Self::key_proof_method(&txn.request.client),
1252                            transaction_id,
1253                        )
1254                        .await
1255                    {
1256                        Ok(token_obj) => {
1257                            response.insert(
1258                                "access_token".to_string(),
1259                                serde_json::Value::Object(token_obj),
1260                            );
1261                        }
1262                        Err(e) => refused = Some(e),
1263                    }
1264                }
1265
1266                // Include subject info if requested and available
1267                if let Some(ref subject_req) = txn.request.subject {
1268                    let subject_resp =
1269                        Self::build_subject_response(subject_req, txn.subject_id.as_deref());
1270                    response.insert(
1271                        "subject".to_string(),
1272                        serde_json::Value::Object(subject_resp),
1273                    );
1274                }
1275
1276                match refused {
1277                    Some(e) => Err(e),
1278                    None => Ok(serde_json::Value::Object(response)),
1279                }
1280            }
1281            GnapTransactionState::Denied => Err(AuthError::validation(
1282                "Transaction was denied by the resource owner",
1283            )),
1284        };
1285
1286        // Remove completed/denied transactions
1287        if matches!(
1288            txn.state,
1289            GnapTransactionState::Approved | GnapTransactionState::Denied
1290        ) {
1291            transactions.remove(transaction_id);
1292        }
1293
1294        result
1295    }
1296
1297    /// Approve a pending transaction (called after user interaction).
1298    /// Optionally sets the subject identifier for subject-info responses.
1299    ///
1300    /// For a transaction that uses a finish method this issues the one-time interaction
1301    /// reference and its hash (RFC 9635 section 4.2); deliver both to the client's finish URI.
1302    pub async fn approve_transaction(
1303        &self,
1304        transaction_id: &str,
1305        subject_id: Option<&str>,
1306    ) -> Result<GnapInteractionCompletion> {
1307        let mut transactions = self.transactions.write().await;
1308        let txn = transactions
1309            .get_mut(transaction_id)
1310            .ok_or_else(|| AuthError::validation("Transaction not found"))?;
1311        txn.state = GnapTransactionState::Approved;
1312        if let Some(sid) = subject_id {
1313            txn.subject_id = Some(sid.to_string());
1314        }
1315        let client_nonce = txn
1316            .request
1317            .interact
1318            .as_ref()
1319            .and_then(|i| i.finish.as_ref())
1320            .map(|f| f.nonce.clone());
1321        let Some(client_nonce) = client_nonce else {
1322            return Ok(GnapInteractionCompletion {
1323                interact_ref: None,
1324                hash: None,
1325            });
1326        };
1327        let interact_ref = txn
1328            .interact_ref
1329            .get_or_insert_with(|| uuid::Uuid::new_v4().simple().to_string())
1330            .clone();
1331        let hash = Self::compute_interact_hash(
1332            &client_nonce,
1333            txn.interact_nonce.as_deref().unwrap_or(""),
1334            &interact_ref,
1335            &self.config.transaction_endpoint,
1336        );
1337        Ok(GnapInteractionCompletion {
1338            interact_ref: Some(interact_ref),
1339            hash: Some(hash),
1340        })
1341    }
1342
1343    /// Deny a pending transaction
1344    pub async fn deny_transaction(&self, transaction_id: &str) -> Result<()> {
1345        let mut transactions = self.transactions.write().await;
1346        let txn = transactions
1347            .get_mut(transaction_id)
1348            .ok_or_else(|| AuthError::validation("Transaction not found"))?;
1349        txn.state = GnapTransactionState::Denied;
1350        Ok(())
1351    }
1352
1353    // ── Token Management (draft §6) ─────────────────────────────────────
1354
1355    /// Revoke an issued access token (draft §6.2 — DELETE on manage URI).
1356    pub async fn revoke_token_with_proof(
1357        &self,
1358        dpop: &DpopManager,
1359        proof: &GnapProof<'_>,
1360        token_value: &str,
1361    ) -> Result<()> {
1362        self.revoke_token_inner(token_value, Some((dpop, proof)))
1363            .await
1364    }
1365
1366    /// Unit tests only: revoke without a proof. A bound token is refused unless its method is the test one.
1367    #[cfg(test)]
1368    pub async fn revoke_token(&self, token_value: &str) -> Result<()> {
1369        self.revoke_token_inner(token_value, None).await
1370    }
1371
1372    async fn revoke_token_inner(
1373        &self,
1374        token_value: &str,
1375        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
1376    ) -> Result<()> {
1377        self.require_token_key_proof(token_value, "Token not found", dpop)
1378            .await?;
1379        let mut tokens = self.issued_tokens.write().await;
1380        if tokens.remove(token_value).is_none() {
1381            return Err(AuthError::validation("Token not found"));
1382        }
1383        Ok(())
1384    }
1385
1386    /// Rotate an issued access token (draft §6.1 — POST on manage URI).
1387    /// Returns a new token with the same access rights and key binding.
1388    pub async fn rotate_token_with_proof(
1389        &self,
1390        dpop: &DpopManager,
1391        proof: &GnapProof<'_>,
1392        old_token_value: &str,
1393    ) -> Result<serde_json::Value> {
1394        self.rotate_token_inner(old_token_value, Some((dpop, proof)))
1395            .await
1396    }
1397
1398    /// Unit tests only: rotate without a proof. A bound token is refused unless its method is the test one.
1399    #[cfg(test)]
1400    pub async fn rotate_token(&self, old_token_value: &str) -> Result<serde_json::Value> {
1401        self.rotate_token_inner(old_token_value, None).await
1402    }
1403
1404    async fn rotate_token_inner(
1405        &self,
1406        old_token_value: &str,
1407        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
1408    ) -> Result<serde_json::Value> {
1409        self.require_token_key_proof(old_token_value, "Token not found or already revoked", dpop)
1410            .await?;
1411        let mut tokens = self.issued_tokens.write().await;
1412        let old = tokens
1413            .remove(old_token_value)
1414            .ok_or_else(|| AuthError::validation("Token not found or already revoked"))?;
1415
1416        let now = std::time::SystemTime::now()
1417            .duration_since(std::time::UNIX_EPOCH)
1418            .unwrap_or_default()
1419            .as_secs();
1420
1421        if now >= old.expires_at {
1422            return Err(AuthError::validation("Token has expired"));
1423        }
1424
1425        let new_value = uuid::Uuid::new_v4().to_string();
1426        let new_token = GnapIssuedToken {
1427            value: new_value.clone(),
1428            access: old.access.clone(),
1429            expires_at: now + self.config.token_lifetime_secs,
1430            key_thumbprint: old.key_thumbprint.clone(),
1431            key_proof: old.key_proof.clone(),
1432            transaction_id: old.transaction_id,
1433        };
1434
1435        let mut token_obj = serde_json::Map::new();
1436        token_obj.insert(
1437            "value".to_string(),
1438            serde_json::Value::String(new_value.clone()),
1439        );
1440        token_obj.insert(
1441            "expires_in".to_string(),
1442            serde_json::Value::Number(self.config.token_lifetime_secs.into()),
1443        );
1444        token_obj.insert(
1445            "manage".to_string(),
1446            serde_json::Value::String(format!("{}/token", self.config.transaction_endpoint)),
1447        );
1448        if new_token.key_thumbprint.is_some() {
1449            token_obj.insert("key".to_string(), serde_json::Value::Bool(true));
1450        }
1451        let access_json: Vec<serde_json::Value> = old
1452            .access
1453            .iter()
1454            .map(|a| serde_json::to_value(a).unwrap_or_default())
1455            .collect();
1456        token_obj.insert("access".to_string(), serde_json::Value::Array(access_json));
1457
1458        tokens.insert(new_value, new_token);
1459        drop(tokens);
1460
1461        Ok(serde_json::Value::Object(token_obj))
1462    }
1463
1464    /// Introspect a token — check if it is valid and return its access rights.
1465    pub async fn introspect_token(&self, token_value: &str) -> Result<Option<serde_json::Value>> {
1466        let tokens = self.issued_tokens.read().await;
1467        let token = match tokens.get(token_value) {
1468            Some(t) => t,
1469            None => return Ok(None),
1470        };
1471
1472        let now = std::time::SystemTime::now()
1473            .duration_since(std::time::UNIX_EPOCH)
1474            .unwrap_or_default()
1475            .as_secs();
1476
1477        if now >= token.expires_at {
1478            return Ok(None);
1479        }
1480
1481        let access_json: Vec<serde_json::Value> = token
1482            .access
1483            .iter()
1484            .map(|a| serde_json::to_value(a).unwrap_or_default())
1485            .collect();
1486
1487        let mut result = serde_json::Map::new();
1488        result.insert("active".to_string(), serde_json::Value::Bool(true));
1489        result.insert("access".to_string(), serde_json::Value::Array(access_json));
1490        result.insert(
1491            "expires_in".to_string(),
1492            serde_json::Value::Number((token.expires_at - now).into()),
1493        );
1494        if let Some(ref tp) = token.key_thumbprint {
1495            result.insert(
1496                "key_thumbprint".to_string(),
1497                serde_json::Value::String(tp.clone()),
1498            );
1499        }
1500        result.insert(
1501            "key_bound".to_string(),
1502            serde_json::Value::Bool(token.key_thumbprint.is_some()),
1503        );
1504
1505        Ok(Some(serde_json::Value::Object(result)))
1506    }
1507
1508    /// Validate that a key-bound token is being used with the correct key.
1509    ///
1510    /// For tokens issued with a client key binding, verify that the
1511    /// presenting client's JWK thumbprint matches the stored binding.
1512    /// Returns `Ok(true)` if the token is not key-bound (no restriction).
1513    pub async fn validate_token_key_binding(
1514        &self,
1515        token_value: &str,
1516        presenting_jwk: &GnapJwk,
1517    ) -> Result<bool> {
1518        let tokens = self.issued_tokens.read().await;
1519        let token = match tokens.get(token_value) {
1520            Some(t) => t,
1521            None => return Err(AuthError::validation("Token not found")),
1522        };
1523
1524        let now = std::time::SystemTime::now()
1525            .duration_since(std::time::UNIX_EPOCH)
1526            .unwrap_or_default()
1527            .as_secs();
1528        if now >= token.expires_at {
1529            return Err(AuthError::validation("Token has expired"));
1530        }
1531
1532        match &token.key_thumbprint {
1533            None => Ok(true), // Not key-bound → any presenter is fine
1534            Some(expected_tp) => {
1535                let presenting_tp = Self::jwk_thumbprint(presenting_jwk)?;
1536                Ok(
1537                    subtle::ConstantTimeEq::ct_eq(expected_tp.as_bytes(), presenting_tp.as_bytes())
1538                        .into(),
1539                )
1540            }
1541        }
1542    }
1543
1544    // ── Subject Info Response (draft §2.2) ───────────────────────────────
1545
1546    /// Build a subject information response based on what was requested.
1547    fn build_subject_response(
1548        request: &GnapSubjectRequest,
1549        subject_id: Option<&str>,
1550    ) -> serde_json::Map<String, serde_json::Value> {
1551        let mut resp = serde_json::Map::new();
1552
1553        // Return sub_ids in requested formats
1554        if let Some(sid) = subject_id {
1555            let mut sub_ids = Vec::new();
1556            for fmt in &request.sub_id_formats {
1557                match fmt.as_str() {
1558                    "opaque" => {
1559                        sub_ids.push(serde_json::json!({
1560                            "format": "opaque",
1561                            "id": sid,
1562                        }));
1563                    }
1564                    "email" => {
1565                        // Only include if the subject ID looks like an email
1566                        if sid.contains('@') {
1567                            sub_ids.push(serde_json::json!({
1568                                "format": "email",
1569                                "email": sid,
1570                            }));
1571                        }
1572                    }
1573                    "iss_sub" => {
1574                        sub_ids.push(serde_json::json!({
1575                            "format": "iss_sub",
1576                            "iss": "self",
1577                            "sub": sid,
1578                        }));
1579                    }
1580                    _ => {} // Unknown format — skip
1581                }
1582            }
1583            if sub_ids.is_empty() {
1584                // Default to opaque if no recognized format
1585                sub_ids.push(serde_json::json!({
1586                    "format": "opaque",
1587                    "id": sid,
1588                }));
1589            }
1590            resp.insert("sub_ids".to_string(), serde_json::Value::Array(sub_ids));
1591        }
1592
1593        resp
1594    }
1595
1596    // ── Cleanup ──────────────────────────────────────────────────────────
1597
1598    /// Remove expired transactions from the in-memory store.
1599    pub async fn cleanup_expired_transactions(&self) {
1600        let now = std::time::SystemTime::now()
1601            .duration_since(std::time::UNIX_EPOCH)
1602            .unwrap_or_default()
1603            .as_secs();
1604        let lifetime = self.config.transaction_lifetime_secs;
1605        self.transactions
1606            .write()
1607            .await
1608            .retain(|_, t| now.saturating_sub(t.created_at) <= lifetime);
1609    }
1610
1611    /// Remove expired access tokens from the in-memory store.
1612    pub async fn cleanup_expired_tokens(&self) {
1613        let now = std::time::SystemTime::now()
1614            .duration_since(std::time::UNIX_EPOCH)
1615            .unwrap_or_default()
1616            .as_secs();
1617        self.issued_tokens
1618            .write()
1619            .await
1620            .retain(|_, t| now < t.expires_at);
1621    }
1622}
1623
1624/// Test policy: grants everything requested.
1625#[cfg(test)]
1626struct AllowAllPolicy;
1627
1628#[cfg(test)]
1629#[async_trait]
1630impl GnapAccessPolicy for AllowAllPolicy {
1631    async fn grant(
1632        &self,
1633        _client_key_thumbprint: &str,
1634        requested: &[GnapAccessRequest],
1635    ) -> Vec<GnapAccessRequest> {
1636        requested.to_vec()
1637    }
1638}
1639
1640#[cfg(test)]
1641mod tests {
1642    use super::*;
1643
1644    fn test_service() -> GnapService {
1645        GnapService::new(test_config()).with_access_policy(Arc::new(AllowAllPolicy))
1646    }
1647
1648    fn test_config() -> GnapConfig {
1649        GnapConfig {
1650            enabled: true,
1651            transaction_endpoint: "/api/gnap/tx".to_string(),
1652            interaction_base_url: Some("https://auth.example.test".to_string()),
1653            token_lifetime_secs: 3600,
1654            transaction_lifetime_secs: 600,
1655        }
1656    }
1657
1658    fn test_ec_jwk() -> GnapJwk {
1659        GnapJwk {
1660            kty: "EC".to_string(),
1661            kid: Some("test-key-1".to_string()),
1662            crv: Some("P-256".to_string()),
1663            x: Some("f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU".to_string()),
1664            y: Some("x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0".to_string()),
1665            n: None,
1666            e: None,
1667        }
1668    }
1669
1670    fn test_rsa_jwk() -> GnapJwk {
1671        GnapJwk {
1672            kty: "RSA".to_string(),
1673            kid: Some("test-rsa-1".to_string()),
1674            crv: None,
1675            x: None,
1676            y: None,
1677            n: Some("0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM".to_string()),
1678            e: Some("AQAB".to_string()),
1679        }
1680    }
1681
1682    fn test_client_info(jwk: GnapJwk) -> GnapClientInfo {
1683        GnapClientInfo {
1684            key: Some(GnapClientKey {
1685                proof: "test".to_string(),
1686                jwk,
1687            }),
1688            display: Some(GnapClientDisplay {
1689                name: Some("Test Client".to_string()),
1690                uri: Some("https://client.example.test".to_string()),
1691            }),
1692        }
1693    }
1694
1695    // ── Config & Construction ────────────────────────────────────────────
1696
1697    #[test]
1698    fn test_gnap_config_defaults() {
1699        let config = GnapConfig::default();
1700        assert!(!config.enabled);
1701        assert_eq!(config.token_lifetime_secs, 3600);
1702        assert_eq!(config.transaction_lifetime_secs, 600);
1703        assert!(config.interaction_base_url.is_none());
1704    }
1705
1706    #[test]
1707    fn test_gnap_service_creation() {
1708        let service = test_service();
1709        assert!(service.config.enabled);
1710    }
1711
1712    // ── JWK Thumbprint (RFC 7638) ────────────────────────────────────────
1713
1714    #[test]
1715    fn test_jwk_thumbprint_ec() {
1716        let jwk = test_ec_jwk();
1717        let tp = GnapService::jwk_thumbprint(&jwk).unwrap();
1718        assert!(!tp.is_empty());
1719        // Thumbprint is base64url-encoded SHA-256 → 43 chars
1720        assert_eq!(tp.len(), 43);
1721    }
1722
1723    #[test]
1724    fn test_jwk_thumbprint_rsa() {
1725        let jwk = test_rsa_jwk();
1726        let tp = GnapService::jwk_thumbprint(&jwk).unwrap();
1727        assert!(!tp.is_empty());
1728        assert_eq!(tp.len(), 43);
1729    }
1730
1731    #[test]
1732    fn test_jwk_thumbprint_deterministic() {
1733        let jwk = test_ec_jwk();
1734        let tp1 = GnapService::jwk_thumbprint(&jwk).unwrap();
1735        let tp2 = GnapService::jwk_thumbprint(&jwk).unwrap();
1736        assert_eq!(tp1, tp2);
1737    }
1738
1739    #[test]
1740    fn test_jwk_thumbprint_different_keys() {
1741        let tp_ec = GnapService::jwk_thumbprint(&test_ec_jwk()).unwrap();
1742        let tp_rsa = GnapService::jwk_thumbprint(&test_rsa_jwk()).unwrap();
1743        assert_ne!(tp_ec, tp_rsa);
1744    }
1745
1746    #[test]
1747    fn test_jwk_thumbprint_unsupported_type() {
1748        let jwk = GnapJwk {
1749            kty: "UNKNOWN".to_string(),
1750            kid: None,
1751            crv: None,
1752            x: None,
1753            y: None,
1754            n: None,
1755            e: None,
1756        };
1757        assert!(GnapService::jwk_thumbprint(&jwk).is_err());
1758    }
1759
1760    // ── Client Key Validation ────────────────────────────────────────────
1761
1762    #[test]
1763    fn test_validate_client_key_ec() {
1764        let client = Some(test_client_info(test_ec_jwk()));
1765        let tp = GnapService::validate_client_key(&client).unwrap();
1766        assert!(tp.is_some());
1767    }
1768
1769    #[test]
1770    fn test_validate_client_key_rsa() {
1771        let client = Some(test_client_info(test_rsa_jwk()));
1772        let tp = GnapService::validate_client_key(&client).unwrap();
1773        assert!(tp.is_some());
1774    }
1775
1776    #[test]
1777    fn test_validate_client_key_none() {
1778        let tp = GnapService::validate_client_key(&None).unwrap();
1779        assert!(tp.is_none());
1780    }
1781
1782    #[test]
1783    fn test_validate_client_key_no_key() {
1784        let client = Some(GnapClientInfo {
1785            key: None,
1786            display: None,
1787        });
1788        let tp = GnapService::validate_client_key(&client).unwrap();
1789        assert!(tp.is_none());
1790    }
1791
1792    #[test]
1793    fn test_validate_client_key_invalid_proof_method() {
1794        let client = Some(GnapClientInfo {
1795            key: Some(GnapClientKey {
1796                proof: "invalid_method".to_string(),
1797                jwk: test_ec_jwk(),
1798            }),
1799            display: None,
1800        });
1801        assert!(GnapService::validate_client_key(&client).is_err());
1802    }
1803
1804    #[test]
1805    fn test_validate_client_key_ec_missing_y() {
1806        let mut jwk = test_ec_jwk();
1807        jwk.y = None;
1808        let client = Some(test_client_info(jwk));
1809        assert!(GnapService::validate_client_key(&client).is_err());
1810    }
1811
1812    #[test]
1813    fn test_validate_client_key_rsa_missing_e() {
1814        let mut jwk = test_rsa_jwk();
1815        jwk.e = None;
1816        let client = Some(test_client_info(jwk));
1817        assert!(GnapService::validate_client_key(&client).is_err());
1818    }
1819
1820    #[test]
1821    fn test_validate_client_key_with_proof_test_mode() {
1822        let client = Some(test_client_info(test_ec_jwk()));
1823        let tp = GnapService::validate_client_key_with_proof(&client, None, None).unwrap();
1824        assert!(tp.is_some());
1825    }
1826
1827    // ── Interaction Hash ─────────────────────────────────────────────────
1828
1829    #[test]
1830    fn test_compute_interact_hash_deterministic() {
1831        let h1 = GnapService::compute_interact_hash("cn1", "sn1", "ref1", "/tx");
1832        let h2 = GnapService::compute_interact_hash("cn1", "sn1", "ref1", "/tx");
1833        assert_eq!(h1, h2);
1834    }
1835
1836    #[test]
1837    fn test_compute_interact_hash_different_inputs() {
1838        let h1 = GnapService::compute_interact_hash("cn1", "sn1", "ref1", "/tx");
1839        let h2 = GnapService::compute_interact_hash("cn2", "sn1", "ref1", "/tx");
1840        assert_ne!(h1, h2);
1841    }
1842
1843    // ── Transaction Lifecycle ────────────────────────────────────────────
1844
1845    #[tokio::test]
1846    async fn test_transaction_disabled() {
1847        let mut config = test_config();
1848        config.enabled = false;
1849        let service = GnapService::new(config).with_access_policy(Arc::new(AllowAllPolicy));
1850        let req = GnapTransactionRequest {
1851            client: Some(test_client_info(test_ec_jwk())),
1852            interact: None,
1853            access_token: Some(vec![GnapAccessRequest {
1854                access_type: "read".to_string(),
1855                actions: vec![],
1856                locations: vec![],
1857            }]),
1858            subject: None,
1859        };
1860        assert!(service.handle_transaction(req).await.is_err());
1861    }
1862
1863    #[tokio::test]
1864    async fn test_transaction_requires_access_or_subject() {
1865        let service = test_service();
1866        let req = GnapTransactionRequest {
1867            client: Some(test_client_info(test_ec_jwk())),
1868            interact: None,
1869            access_token: None,
1870            subject: None,
1871        };
1872        assert!(service.handle_transaction(req).await.is_err());
1873    }
1874
1875    #[tokio::test]
1876    async fn test_transaction_direct_token_issuance() {
1877        let service = test_service();
1878        let req = GnapTransactionRequest {
1879            client: Some(test_client_info(test_ec_jwk())),
1880            interact: None,
1881            access_token: Some(vec![GnapAccessRequest {
1882                access_type: "read".to_string(),
1883                actions: vec!["list".to_string()],
1884                locations: vec!["https://api.test/resources".to_string()],
1885            }]),
1886            subject: None,
1887        };
1888        let resp = service.handle_transaction(req).await.unwrap();
1889        let obj = resp.as_object().unwrap();
1890        assert!(obj.contains_key("access_token"));
1891        assert!(obj.contains_key("continue"));
1892
1893        let token_obj = obj["access_token"].as_object().unwrap();
1894        assert!(token_obj.contains_key("value"));
1895        assert!(token_obj.contains_key("expires_in"));
1896        assert!(token_obj.contains_key("manage"));
1897        assert_eq!(token_obj.get("key").and_then(|v| v.as_bool()), Some(true));
1898    }
1899
1900    #[tokio::test]
1901    async fn test_transaction_with_interaction() {
1902        let service = test_service();
1903        let req = GnapTransactionRequest {
1904            client: Some(test_client_info(test_ec_jwk())),
1905            interact: Some(GnapInteractionRequirements {
1906                start: vec!["redirect".to_string()],
1907                finish: Some(GnapInteractionFinish {
1908                    method: "redirect".to_string(),
1909                    uri: "https://client.test/callback".to_string(),
1910                    nonce: "client-nonce-123".to_string(),
1911                }),
1912            }),
1913            access_token: Some(vec![GnapAccessRequest {
1914                access_type: "write".to_string(),
1915                actions: vec![],
1916                locations: vec![],
1917            }]),
1918            subject: None,
1919        };
1920        let resp = service.handle_transaction(req).await.unwrap();
1921        let obj = resp.as_object().unwrap();
1922        assert!(obj.contains_key("interact"));
1923        assert!(obj.contains_key("continue"));
1924
1925        let interact = obj["interact"].as_object().unwrap();
1926        assert!(interact.contains_key("redirect"));
1927        assert!(interact.contains_key("finish"));
1928    }
1929
1930    #[tokio::test]
1931    async fn test_transaction_subject_only() {
1932        let service = test_service();
1933        let req = GnapTransactionRequest {
1934            client: Some(test_client_info(test_ec_jwk())),
1935            interact: None,
1936            access_token: None,
1937            subject: Some(GnapSubjectRequest {
1938                sub_id_formats: vec!["opaque".to_string()],
1939                assertion_formats: vec![],
1940            }),
1941        };
1942        let resp = service.handle_transaction(req).await.unwrap();
1943        let obj = resp.as_object().unwrap();
1944        assert!(obj.contains_key("subject"));
1945    }
1946
1947    // ── Approve / Deny / Continue ────────────────────────────────────────
1948
1949    #[tokio::test]
1950    async fn test_approve_and_continue() {
1951        let service = test_service();
1952
1953        // Create interactive transaction
1954        let req = GnapTransactionRequest {
1955            client: Some(test_client_info(test_ec_jwk())),
1956            interact: Some(GnapInteractionRequirements {
1957                start: vec!["redirect".to_string()],
1958                finish: None,
1959            }),
1960            access_token: Some(vec![GnapAccessRequest {
1961                access_type: "read".to_string(),
1962                actions: vec![],
1963                locations: vec![],
1964            }]),
1965            subject: None,
1966        };
1967        let resp = service.handle_transaction(req).await.unwrap();
1968        let cont = resp["continue"]["access_token"]["value"].as_str().unwrap();
1969
1970        // Get transaction ID from the stored transactions
1971        let txn_id = {
1972            let txns = service.transactions.read().await;
1973            txns.keys().next().unwrap().clone()
1974        };
1975
1976        // Continue before approval → pending
1977        let poll = service
1978            .continue_transaction(&txn_id, cont, None, None)
1979            .await;
1980        assert!(
1981            poll.is_err() || {
1982                let r = poll.unwrap();
1983                r.as_object().unwrap().contains_key("continue")
1984            }
1985        );
1986
1987        // Get updated continuation token
1988        let new_cont = {
1989            let txns = service.transactions.read().await;
1990            txns.get(&txn_id).unwrap().continue_token.clone()
1991        };
1992
1993        // Approve
1994        service
1995            .approve_transaction(&txn_id, Some("user-42"))
1996            .await
1997            .unwrap();
1998
1999        // Continue after approval → get token
2000        let result = service
2001            .continue_transaction(&txn_id, &new_cont, None, None)
2002            .await
2003            .unwrap();
2004        assert!(result.as_object().unwrap().contains_key("access_token"));
2005    }
2006
2007    #[tokio::test]
2008    async fn test_deny_transaction() {
2009        let service = test_service();
2010        let req = GnapTransactionRequest {
2011            client: Some(test_client_info(test_ec_jwk())),
2012            interact: Some(GnapInteractionRequirements {
2013                start: vec!["redirect".to_string()],
2014                finish: None,
2015            }),
2016            access_token: Some(vec![GnapAccessRequest {
2017                access_type: "read".to_string(),
2018                actions: vec![],
2019                locations: vec![],
2020            }]),
2021            subject: None,
2022        };
2023        service.handle_transaction(req).await.unwrap();
2024        let txn_id = {
2025            let txns = service.transactions.read().await;
2026            txns.keys().next().unwrap().clone()
2027        };
2028
2029        service.deny_transaction(&txn_id).await.unwrap();
2030
2031        let cont = {
2032            let txns = service.transactions.read().await;
2033            txns.get(&txn_id).unwrap().continue_token.clone()
2034        };
2035        let result = service
2036            .continue_transaction(&txn_id, &cont, None, None)
2037            .await;
2038        assert!(result.is_err());
2039    }
2040
2041    #[tokio::test]
2042    async fn test_continue_invalid_token() {
2043        let service = test_service();
2044        let req = GnapTransactionRequest {
2045            client: Some(test_client_info(test_ec_jwk())),
2046            interact: Some(GnapInteractionRequirements {
2047                start: vec!["redirect".to_string()],
2048                finish: None,
2049            }),
2050            access_token: Some(vec![GnapAccessRequest {
2051                access_type: "read".to_string(),
2052                actions: vec![],
2053                locations: vec![],
2054            }]),
2055            subject: None,
2056        };
2057        service.handle_transaction(req).await.unwrap();
2058        let txn_id = {
2059            let txns = service.transactions.read().await;
2060            txns.keys().next().unwrap().clone()
2061        };
2062        let result = service
2063            .continue_transaction(&txn_id, "bad-token", None, None)
2064            .await;
2065        assert!(result.is_err());
2066    }
2067
2068    // ── Token Management ─────────────────────────────────────────────────
2069
2070    #[tokio::test]
2071    async fn test_token_revocation() {
2072        let service = test_service();
2073        let req = GnapTransactionRequest {
2074            client: Some(test_client_info(test_ec_jwk())),
2075            interact: None,
2076            access_token: Some(vec![GnapAccessRequest {
2077                access_type: "read".to_string(),
2078                actions: vec![],
2079                locations: vec![],
2080            }]),
2081            subject: None,
2082        };
2083        let resp = service.handle_transaction(req).await.unwrap();
2084        let token_value = resp["access_token"]["value"].as_str().unwrap();
2085
2086        // Small delay so the spawned insert task completes
2087        tokio::task::yield_now().await;
2088        tokio::task::yield_now().await;
2089
2090        // Introspect before revocation
2091        let info = service.introspect_token(token_value).await.unwrap();
2092        assert!(info.is_some());
2093        assert_eq!(info.as_ref().unwrap()["active"], true);
2094
2095        // Revoke
2096        service.revoke_token(token_value).await.unwrap();
2097
2098        // Introspect after revocation
2099        let info = service.introspect_token(token_value).await.unwrap();
2100        assert!(info.is_none());
2101    }
2102
2103    #[tokio::test]
2104    async fn test_token_rotation() {
2105        let service = test_service();
2106        let req = GnapTransactionRequest {
2107            client: Some(test_client_info(test_ec_jwk())),
2108            interact: None,
2109            access_token: Some(vec![GnapAccessRequest {
2110                access_type: "write".to_string(),
2111                actions: vec!["create".to_string()],
2112                locations: vec![],
2113            }]),
2114            subject: None,
2115        };
2116        let resp = service.handle_transaction(req).await.unwrap();
2117        let old_token = resp["access_token"]["value"].as_str().unwrap().to_string();
2118
2119        // Wait for spawned insert
2120        tokio::task::yield_now().await;
2121        tokio::task::yield_now().await;
2122
2123        // Rotate
2124        let new_resp = service.rotate_token(&old_token).await.unwrap();
2125        let new_token = new_resp["value"].as_str().unwrap();
2126        assert_ne!(old_token, new_token);
2127
2128        // Old token should be gone
2129        let old_info = service.introspect_token(&old_token).await.unwrap();
2130        assert!(old_info.is_none());
2131
2132        // New token should be active
2133        let new_info = service.introspect_token(new_token).await.unwrap();
2134        assert!(new_info.is_some());
2135        assert_eq!(new_info.unwrap()["active"], true);
2136    }
2137
2138    #[tokio::test]
2139    async fn test_revoke_nonexistent_token() {
2140        let service = test_service();
2141        assert!(service.revoke_token("nonexistent").await.is_err());
2142    }
2143
2144    #[tokio::test]
2145    async fn test_introspect_nonexistent_token() {
2146        let service = test_service();
2147        let info = service.introspect_token("nonexistent").await.unwrap();
2148        assert!(info.is_none());
2149    }
2150
2151    // ── Key Binding Verification ─────────────────────────────────────────
2152
2153    #[tokio::test]
2154    async fn test_token_key_binding_check() {
2155        let service = test_service();
2156        let ec_jwk = test_ec_jwk();
2157        let req = GnapTransactionRequest {
2158            client: Some(test_client_info(ec_jwk.clone())),
2159            interact: None,
2160            access_token: Some(vec![GnapAccessRequest {
2161                access_type: "read".to_string(),
2162                actions: vec![],
2163                locations: vec![],
2164            }]),
2165            subject: None,
2166        };
2167        let resp = service.handle_transaction(req).await.unwrap();
2168        let token_value = resp["access_token"]["value"].as_str().unwrap();
2169
2170        tokio::task::yield_now().await;
2171        tokio::task::yield_now().await;
2172
2173        // Same key → should pass
2174        let ok = service
2175            .validate_token_key_binding(token_value, &ec_jwk)
2176            .await
2177            .unwrap();
2178        assert!(ok);
2179
2180        // Different key → should fail
2181        let other_jwk = test_rsa_jwk();
2182        let bad = service
2183            .validate_token_key_binding(token_value, &other_jwk)
2184            .await
2185            .unwrap();
2186        assert!(!bad);
2187    }
2188
2189    // ── Subject Info ─────────────────────────────────────────────────────
2190
2191    #[test]
2192    fn test_build_subject_response_opaque() {
2193        let req = GnapSubjectRequest {
2194            sub_id_formats: vec!["opaque".to_string()],
2195            assertion_formats: vec![],
2196        };
2197        let resp = GnapService::build_subject_response(&req, Some("user-42"));
2198        let sub_ids = resp["sub_ids"].as_array().unwrap();
2199        assert_eq!(sub_ids.len(), 1);
2200        assert_eq!(sub_ids[0]["format"], "opaque");
2201        assert_eq!(sub_ids[0]["id"], "user-42");
2202    }
2203
2204    #[test]
2205    fn test_build_subject_response_email() {
2206        let req = GnapSubjectRequest {
2207            sub_id_formats: vec!["email".to_string()],
2208            assertion_formats: vec![],
2209        };
2210        let resp = GnapService::build_subject_response(&req, Some("user@example.test"));
2211        let sub_ids = resp["sub_ids"].as_array().unwrap();
2212        assert_eq!(sub_ids.len(), 1);
2213        assert_eq!(sub_ids[0]["format"], "email");
2214    }
2215
2216    #[test]
2217    fn test_build_subject_response_email_not_email() {
2218        let req = GnapSubjectRequest {
2219            sub_id_formats: vec!["email".to_string()],
2220            assertion_formats: vec![],
2221        };
2222        // Subject is not an email → defaults to opaque
2223        let resp = GnapService::build_subject_response(&req, Some("user-42"));
2224        let sub_ids = resp["sub_ids"].as_array().unwrap();
2225        assert_eq!(sub_ids[0]["format"], "opaque");
2226    }
2227
2228    #[test]
2229    fn test_build_subject_response_iss_sub() {
2230        let req = GnapSubjectRequest {
2231            sub_id_formats: vec!["iss_sub".to_string()],
2232            assertion_formats: vec![],
2233        };
2234        let resp = GnapService::build_subject_response(&req, Some("user-42"));
2235        let sub_ids = resp["sub_ids"].as_array().unwrap();
2236        assert_eq!(sub_ids[0]["format"], "iss_sub");
2237        assert_eq!(sub_ids[0]["sub"], "user-42");
2238    }
2239
2240    #[test]
2241    fn test_build_subject_response_no_subject() {
2242        let req = GnapSubjectRequest {
2243            sub_id_formats: vec!["opaque".to_string()],
2244            assertion_formats: vec![],
2245        };
2246        let resp = GnapService::build_subject_response(&req, None);
2247        assert!(!resp.contains_key("sub_ids"));
2248    }
2249
2250    // ── Continuation Token Rotation ──────────────────────────────────────
2251
2252    #[tokio::test]
2253    async fn test_continuation_token_rotates() {
2254        let service = test_service();
2255        let req = GnapTransactionRequest {
2256            client: Some(test_client_info(test_ec_jwk())),
2257            interact: Some(GnapInteractionRequirements {
2258                start: vec!["redirect".to_string()],
2259                finish: None,
2260            }),
2261            access_token: Some(vec![GnapAccessRequest {
2262                access_type: "read".to_string(),
2263                actions: vec![],
2264                locations: vec![],
2265            }]),
2266            subject: None,
2267        };
2268        let resp = service.handle_transaction(req).await.unwrap();
2269        let cont1 = resp["continue"]["access_token"]["value"]
2270            .as_str()
2271            .unwrap()
2272            .to_string();
2273
2274        let txn_id = {
2275            let txns = service.transactions.read().await;
2276            txns.keys().next().unwrap().clone()
2277        };
2278
2279        // First continue → token is rotated
2280        let _ = service
2281            .continue_transaction(&txn_id, &cont1, None, None)
2282            .await;
2283
2284        let cont2 = {
2285            let txns = service.transactions.read().await;
2286            txns.get(&txn_id).unwrap().continue_token.clone()
2287        };
2288        assert_ne!(cont1, cont2, "Continuation token must rotate on each use");
2289
2290        // Old token should not work
2291        let reuse = service
2292            .continue_transaction(&txn_id, &cont1, None, None)
2293            .await;
2294        assert!(reuse.is_err(), "Old continuation token must be rejected");
2295    }
2296
2297    // ── Cleanup ──────────────────────────────────────────────────────────
2298
2299    #[tokio::test]
2300    async fn test_cleanup_expired_transactions() {
2301        let mut config = test_config();
2302        config.transaction_lifetime_secs = 1; // 1 second lifetime
2303        let service = GnapService::new(config).with_access_policy(Arc::new(AllowAllPolicy));
2304
2305        let req = GnapTransactionRequest {
2306            client: Some(test_client_info(test_ec_jwk())),
2307            interact: Some(GnapInteractionRequirements {
2308                start: vec!["redirect".to_string()],
2309                finish: None,
2310            }),
2311            access_token: Some(vec![GnapAccessRequest {
2312                access_type: "read".to_string(),
2313                actions: vec![],
2314                locations: vec![],
2315            }]),
2316            subject: None,
2317        };
2318        service.handle_transaction(req).await.unwrap();
2319        assert_eq!(service.transactions.read().await.len(), 1);
2320
2321        // Manually backdate the transaction so it appears expired
2322        {
2323            let mut txns = service.transactions.write().await;
2324            for txn in txns.values_mut() {
2325                txn.created_at = txn.created_at.saturating_sub(10);
2326            }
2327        }
2328
2329        service.cleanup_expired_transactions().await;
2330        assert_eq!(service.transactions.read().await.len(), 0);
2331    }
2332
2333    // ── Interaction Hash Verification ────────────────────────────────────
2334
2335    #[tokio::test]
2336    async fn test_interaction_hash_verification() {
2337        let service = test_service();
2338        let client_nonce = "client-nonce-abc";
2339        let req = GnapTransactionRequest {
2340            client: Some(test_client_info(test_ec_jwk())),
2341            interact: Some(GnapInteractionRequirements {
2342                start: vec!["redirect".to_string()],
2343                finish: Some(GnapInteractionFinish {
2344                    method: "redirect".to_string(),
2345                    uri: "https://client.test/cb".to_string(),
2346                    nonce: client_nonce.to_string(),
2347                }),
2348            }),
2349            access_token: Some(vec![GnapAccessRequest {
2350                access_type: "read".to_string(),
2351                actions: vec![],
2352                locations: vec![],
2353            }]),
2354            subject: None,
2355        };
2356        service.handle_transaction(req).await.unwrap();
2357
2358        let (txn_id, cont, server_nonce) = {
2359            let txns = service.transactions.read().await;
2360            let (id, txn) = txns.iter().next().unwrap();
2361            (
2362                id.clone(),
2363                txn.continue_token.clone(),
2364                txn.interact_nonce.clone().unwrap(),
2365            )
2366        };
2367
2368        let done = service.approve_transaction(&txn_id, None).await.unwrap();
2369        let interact_ref = done.interact_ref.as_deref().unwrap();
2370        let correct_hash = GnapService::compute_interact_hash(
2371            client_nonce,
2372            &server_nonce,
2373            interact_ref,
2374            &service.config.transaction_endpoint,
2375        );
2376        assert_eq!(done.hash.as_deref(), Some(correct_hash.as_str()));
2377
2378        // Wrong hash → fails
2379        let bad = service
2380            .continue_transaction(&txn_id, &cont, Some(interact_ref), Some("bad-hash"))
2381            .await;
2382        assert!(bad.is_err());
2383
2384        // Get fresh continuation token after the failed attempt rotated it
2385        let fresh_cont = {
2386            let txns = service.transactions.read().await;
2387            txns.get(&txn_id).unwrap().continue_token.clone()
2388        };
2389
2390        // Correct hash → succeeds
2391        let good = service
2392            .continue_transaction(
2393                &txn_id,
2394                &fresh_cont,
2395                Some(interact_ref),
2396                Some(&correct_hash),
2397            )
2398            .await;
2399        assert!(good.is_ok());
2400    }
2401
2402    /// An approved transaction that uses a finish method: the transaction id, its continuation
2403    /// token, the interaction hash and the one-time interaction reference issued at approval.
2404    async fn interact_transaction(service: &GnapService) -> (String, String, String, String) {
2405        let client_nonce = "client-nonce-abc";
2406        let req = GnapTransactionRequest {
2407            client: Some(test_client_info(test_ec_jwk())),
2408            interact: Some(GnapInteractionRequirements {
2409                start: vec!["redirect".to_string()],
2410                finish: Some(GnapInteractionFinish {
2411                    method: "redirect".to_string(),
2412                    uri: "https://client.test/cb".to_string(),
2413                    nonce: client_nonce.to_string(),
2414                }),
2415            }),
2416            access_token: Some(vec![GnapAccessRequest {
2417                access_type: "read".to_string(),
2418                actions: vec![],
2419                locations: vec![],
2420            }]),
2421            subject: None,
2422        };
2423        service.handle_transaction(req).await.unwrap();
2424        let (id, cont) = {
2425            let txns = service.transactions.read().await;
2426            let (id, txn) = txns.iter().next().unwrap();
2427            (id.clone(), txn.continue_token.clone())
2428        };
2429        let done = service.approve_transaction(&id, None).await.unwrap();
2430        let interact_ref = done.interact_ref.unwrap();
2431        let hash = done.hash.unwrap();
2432        let txns = service.transactions.read().await;
2433        let txn = txns.get(&id).unwrap();
2434        assert_eq!(
2435            hash,
2436            GnapService::compute_interact_hash(
2437                client_nonce,
2438                txn.interact_nonce.as_deref().unwrap(),
2439                &interact_ref,
2440                &service.config.transaction_endpoint,
2441            ),
2442            "the hash approve returns is the section 4.2.3 hash"
2443        );
2444        (id, cont, hash, interact_ref)
2445    }
2446
2447    #[tokio::test]
2448    async fn test_continuation_token_must_match_exactly() {
2449        let service = test_service();
2450        let (txn_id, cont, _, iref) = interact_transaction(&service).await;
2451
2452        let mut near_miss = cont.clone();
2453        near_miss.pop();
2454        near_miss.push(if cont.ends_with('0') { '1' } else { '0' });
2455        let too_long = format!("{cont}0");
2456        let prefix = cont[..cont.len() - 1].to_string();
2457        for bad in [near_miss, too_long, prefix, String::new()] {
2458            assert!(
2459                service
2460                    .continue_transaction(&txn_id, &bad, None, None)
2461                    .await
2462                    .is_err(),
2463                "token {bad:?} must be refused"
2464            );
2465        }
2466        assert!(
2467            service
2468                .continue_transaction(&txn_id, &cont, Some(&iref), None)
2469                .await
2470                .is_ok()
2471        );
2472    }
2473
2474    #[test]
2475    fn test_gnap_transaction_request_builder_access() {
2476        let req = GnapTransactionRequest::builder()
2477            .access("read", &["list", "get"], &["https://api.test/resources"])
2478            .build();
2479
2480        assert!(req.client.is_none());
2481        assert!(req.interact.is_none());
2482        let access = req.access_token.unwrap();
2483        assert_eq!(access.len(), 1);
2484        assert_eq!(access[0].access_type, "read");
2485        assert_eq!(access[0].actions, vec!["list", "get"]);
2486    }
2487
2488    #[test]
2489    fn test_gnap_transaction_request_builder_full() {
2490        let jwk = test_ec_jwk();
2491        let req = GnapTransactionRequest::builder()
2492            .client_key(jwk, "test")
2493            .redirect_interaction("https://client.test/cb", "nonce-123")
2494            .access_type("write")
2495            .subject_formats(vec!["opaque".into()])
2496            .build();
2497
2498        assert!(req.client.is_some());
2499        assert!(req.interact.is_some());
2500        assert!(req.access_token.is_some());
2501        assert!(req.subject.is_some());
2502        assert_eq!(req.subject.unwrap().sub_id_formats, vec!["opaque"]);
2503    }
2504
2505    #[test]
2506    fn test_gnap_transaction_request_builder_empty() {
2507        let req = GnapTransactionRequest::builder().build();
2508        assert!(req.client.is_none());
2509        assert!(req.interact.is_none());
2510        assert!(req.access_token.is_none());
2511        assert!(req.subject.is_none());
2512    }
2513}
2514
2515/// A client key's proof is verified or refused: no proof that was never checked authorizes a
2516/// request. Each refusal is paired with the accepted case built the same way, so a test cannot
2517/// pass because every request fails for one shared reason.
2518#[cfg(test)]
2519mod proof_verification_tests {
2520    use super::*;
2521    use crate::security::secure_jwt::{SecureJwtConfig, SecureJwtValidator};
2522    use jsonwebtoken::{Algorithm, EncodingKey};
2523    use serde_json::json;
2524
2525    const URI: &str = "https://as.example.test/api/gnap/tx";
2526    const CONTINUE_URI: &str = "https://as.example.test/api/gnap/tx/continue";
2527
2528    struct ClientKey {
2529        signing: EncodingKey,
2530        jwk: GnapJwk,
2531    }
2532
2533    fn client_key() -> ClientKey {
2534        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2535        let raw = key.public_key_raw();
2536        let point = &raw[raw.len() - 65..];
2537        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
2538        ClientKey {
2539            signing: EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
2540            jwk: GnapJwk {
2541                kty: "EC".to_string(),
2542                kid: None,
2543                crv: Some("P-256".to_string()),
2544                x: Some(b64.encode(&point[1..33])),
2545                y: Some(b64.encode(&point[33..65])),
2546                n: None,
2547                e: None,
2548            },
2549        }
2550    }
2551
2552    /// A DPoP proof for `htm` `htu`, signed by `signer` and naming `named` in its header.
2553    fn dpop_header(
2554        signer: &ClientKey,
2555        named: &ClientKey,
2556        htm: &str,
2557        htu: &str,
2558        jti: &str,
2559    ) -> String {
2560        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
2561        let jwk = serde_json::to_value(&named.jwk).unwrap();
2562        let header = json!({"typ": "dpop+jwt", "alg": "ES256", "jwk": jwk});
2563        let claims = json!({
2564            "jti": jti, "htm": htm, "htu": htu, "iat": chrono::Utc::now().timestamp()
2565        });
2566        let si = format!(
2567            "{}.{}",
2568            b64.encode(header.to_string()),
2569            b64.encode(claims.to_string())
2570        );
2571        let sig =
2572            jsonwebtoken::crypto::sign(si.as_bytes(), &signer.signing, Algorithm::ES256).unwrap();
2573        format!("{si}.{sig}")
2574    }
2575
2576    fn manager() -> DpopManager {
2577        DpopManager::new(SecureJwtValidator::new(SecureJwtConfig::default()).unwrap())
2578    }
2579
2580    fn service() -> GnapService {
2581        GnapService::new(GnapConfig {
2582            enabled: true,
2583            transaction_endpoint: "/api/gnap/tx".to_string(),
2584            interaction_base_url: Some("https://as.example.test".to_string()),
2585            token_lifetime_secs: 3600,
2586            transaction_lifetime_secs: 600,
2587        })
2588        .with_access_policy(Arc::new(AllowAllPolicy))
2589    }
2590
2591    fn request(key: &ClientKey, proof: &str, interact: bool) -> GnapTransactionRequest {
2592        let mut builder = GnapTransactionRequest::builder()
2593            .client_key(key.jwk.clone(), proof)
2594            .access_type("read");
2595        if interact {
2596            builder = builder.redirect_interaction("https://client.test/cb", "client-nonce");
2597        }
2598        builder.build()
2599    }
2600
2601    fn proof<'a>(header: Option<&'a str>, uri: &'a str) -> GnapProof<'a> {
2602        GnapProof {
2603            http_method: "POST",
2604            http_uri: uri,
2605            dpop_proof: header,
2606            expected_nonce: None,
2607        }
2608    }
2609
2610    fn refusal(result: Result<serde_json::Value>) -> String {
2611        result.expect_err("the request must be refused").to_string()
2612    }
2613
2614    const MANAGE_URI: &str = "https://as.example.test/api/gnap/token/1";
2615
2616    /// A token issued to `key` over a proved, non-interactive request.
2617    async fn issued_token(
2618        svc: &GnapService,
2619        dpop: &DpopManager,
2620        key: &ClientKey,
2621        jti: &str,
2622    ) -> String {
2623        let header = dpop_header(key, key, "POST", URI, jti);
2624        let resp = svc
2625            .handle_transaction_with_proof(
2626                dpop,
2627                &proof(Some(&header), URI),
2628                request(key, "dpop", false),
2629            )
2630            .await
2631            .unwrap();
2632        resp["access_token"]["value"].as_str().unwrap().to_string()
2633    }
2634
2635    async fn is_live(svc: &GnapService, token: &str) -> bool {
2636        svc.introspect_token(token).await.unwrap().is_some()
2637    }
2638
2639    fn refused_with<T: std::fmt::Debug>(result: Result<T>) -> String {
2640        result.expect_err("the request must be refused").to_string()
2641    }
2642
2643    #[tokio::test]
2644    async fn a_key_bound_token_is_rotated_only_with_a_proof_from_its_key() {
2645        let (svc, dpop, key) = (service(), manager(), client_key());
2646        let token = issued_token(&svc, &dpop, &key, "jti-issue").await;
2647        // The value alone is not enough, however it is presented.
2648        assert!(refused_with(svc.rotate_token(&token).await).contains("proof required"));
2649        assert!(
2650            refused_with(
2651                svc.rotate_token_with_proof(&dpop, &proof(None, MANAGE_URI), &token)
2652                    .await
2653            )
2654            .contains("proof required")
2655        );
2656        // A proof signed by another key is not enough.
2657        let other = client_key();
2658        let forged = dpop_header(&other, &other, "POST", MANAGE_URI, "jti-forged");
2659        assert!(
2660            refused_with(
2661                svc.rotate_token_with_proof(&dpop, &proof(Some(&forged), MANAGE_URI), &token)
2662                    .await
2663            )
2664            .contains("proof invalid")
2665        );
2666        // A proof for another URI is not enough.
2667        let elsewhere = dpop_header(
2668            &key,
2669            &key,
2670            "POST",
2671            "https://as.example.test/elsewhere",
2672            "jti-elsewhere",
2673        );
2674        assert!(
2675            refused_with(
2676                svc.rotate_token_with_proof(&dpop, &proof(Some(&elsewhere), MANAGE_URI), &token)
2677                    .await
2678            )
2679            .contains("proof invalid")
2680        );
2681        assert!(
2682            is_live(&svc, &token).await,
2683            "none of the refusals touched the token"
2684        );
2685        // Control: the key's own proof rotates it, and the old value is gone.
2686        let good = dpop_header(&key, &key, "POST", MANAGE_URI, "jti-rotate");
2687        let rotated = svc
2688            .rotate_token_with_proof(&dpop, &proof(Some(&good), MANAGE_URI), &token)
2689            .await
2690            .unwrap();
2691        let new_value = rotated["value"].as_str().unwrap().to_string();
2692        assert_ne!(new_value, token);
2693        assert!(!is_live(&svc, &token).await);
2694        assert!(
2695            is_live(&svc, &new_value).await,
2696            "the rotated token keeps its key binding"
2697        );
2698        // The new token is bound to the same key: the value alone does not rotate it either.
2699        assert!(refused_with(svc.rotate_token(&new_value).await).contains("proof required"));
2700    }
2701
2702    #[tokio::test]
2703    async fn a_key_bound_token_is_revoked_only_with_a_proof_from_its_key() {
2704        let (svc, dpop, key) = (service(), manager(), client_key());
2705        let token = issued_token(&svc, &dpop, &key, "jti-issue").await;
2706        assert!(refused_with(svc.revoke_token(&token).await).contains("proof required"));
2707        let other = client_key();
2708        let forged = dpop_header(&other, &other, "POST", MANAGE_URI, "jti-forged");
2709        assert!(
2710            refused_with(
2711                svc.revoke_token_with_proof(&dpop, &proof(Some(&forged), MANAGE_URI), &token)
2712                    .await
2713            )
2714            .contains("proof invalid")
2715        );
2716        assert!(
2717            is_live(&svc, &token).await,
2718            "the refusals left the token usable"
2719        );
2720        let good = dpop_header(&key, &key, "POST", MANAGE_URI, "jti-revoke");
2721        svc.revoke_token_with_proof(&dpop, &proof(Some(&good), MANAGE_URI), &token)
2722            .await
2723            .unwrap();
2724        assert!(!is_live(&svc, &token).await);
2725    }
2726
2727    #[tokio::test]
2728    async fn a_management_proof_is_good_for_one_request() {
2729        let (svc, dpop, key) = (service(), manager(), client_key());
2730        let first = issued_token(&svc, &dpop, &key, "jti-a").await;
2731        let second = issued_token(&svc, &dpop, &key, "jti-b").await;
2732        let header = dpop_header(&key, &key, "POST", MANAGE_URI, "jti-once");
2733        svc.revoke_token_with_proof(&dpop, &proof(Some(&header), MANAGE_URI), &first)
2734            .await
2735            .unwrap();
2736        // The same proof, replayed against another token, is refused and that token survives.
2737        assert!(
2738            refused_with(
2739                svc.revoke_token_with_proof(&dpop, &proof(Some(&header), MANAGE_URI), &second)
2740                    .await
2741            )
2742            .contains("proof invalid")
2743        );
2744        assert!(is_live(&svc, &second).await);
2745    }
2746
2747    #[tokio::test]
2748    async fn an_unknown_token_is_refused_whatever_the_proof() {
2749        let (svc, dpop, key) = (service(), manager(), client_key());
2750        let header = dpop_header(&key, &key, "POST", MANAGE_URI, "jti-unknown");
2751        let p = proof(Some(&header), MANAGE_URI);
2752        assert!(
2753            refused_with(
2754                svc.revoke_token_with_proof(&dpop, &p, "no-such-token")
2755                    .await
2756            )
2757            .contains("not found")
2758        );
2759        assert!(
2760            refused_with(
2761                svc.rotate_token_with_proof(&dpop, &p, "no-such-token")
2762                    .await
2763            )
2764            .contains("not found")
2765        );
2766    }
2767
2768    #[tokio::test]
2769    async fn a_dpop_proof_signed_by_the_named_key_is_accepted() {
2770        let (svc, dpop, key) = (service(), manager(), client_key());
2771        let header = dpop_header(&key, &key, "POST", URI, "jti-ok");
2772        let resp = svc
2773            .handle_transaction_with_proof(
2774                &dpop,
2775                &proof(Some(&header), URI),
2776                request(&key, "dpop", false),
2777            )
2778            .await
2779            .unwrap();
2780        assert!(resp["access_token"]["value"].is_string());
2781    }
2782
2783    #[tokio::test]
2784    async fn a_dpop_key_with_no_proof_is_refused() {
2785        let (svc, dpop, key) = (service(), manager(), client_key());
2786        // Through the entry point that takes no proof at all.
2787        let msg = refusal(svc.handle_transaction(request(&key, "dpop", false)).await);
2788        assert!(msg.contains("proof required"), "{msg}");
2789        // And through the one that does, with no DPoP header.
2790        let msg = refusal(
2791            svc.handle_transaction_with_proof(
2792                &dpop,
2793                &proof(None, URI),
2794                request(&key, "dpop", false),
2795            )
2796            .await,
2797        );
2798        assert!(msg.contains("proof required"), "{msg}");
2799    }
2800
2801    #[tokio::test]
2802    async fn a_dpop_proof_from_another_key_is_refused() {
2803        let (svc, dpop) = (service(), manager());
2804        let (victim, attacker) = (client_key(), client_key());
2805        // The attacker names the victim's key but can only sign with its own.
2806        let forged = dpop_header(&attacker, &victim, "POST", URI, "jti-forged");
2807        let msg = refusal(
2808            svc.handle_transaction_with_proof(
2809                &dpop,
2810                &proof(Some(&forged), URI),
2811                request(&victim, "dpop", false),
2812            )
2813            .await,
2814        );
2815        assert!(msg.contains("proof invalid"), "{msg}");
2816        // The attacker's own proof, naming the attacker's own key, is fine: the key is the
2817        // only thing that differs.
2818        let own = dpop_header(&attacker, &attacker, "POST", URI, "jti-own");
2819        svc.handle_transaction_with_proof(
2820            &dpop,
2821            &proof(Some(&own), URI),
2822            request(&attacker, "dpop", false),
2823        )
2824        .await
2825        .unwrap();
2826    }
2827
2828    #[tokio::test]
2829    async fn a_dpop_proof_for_another_method_or_uri_is_refused() {
2830        let (svc, dpop, key) = (service(), manager(), client_key());
2831        let other_uri = dpop_header(&key, &key, "POST", "https://other.example/tx", "jti-uri");
2832        let msg = refusal(
2833            svc.handle_transaction_with_proof(
2834                &dpop,
2835                &proof(Some(&other_uri), URI),
2836                request(&key, "dpop", false),
2837            )
2838            .await,
2839        );
2840        assert!(msg.contains("proof invalid"), "{msg}");
2841        let other_method = dpop_header(&key, &key, "GET", URI, "jti-method");
2842        let msg = refusal(
2843            svc.handle_transaction_with_proof(
2844                &dpop,
2845                &proof(Some(&other_method), URI),
2846                request(&key, "dpop", false),
2847            )
2848            .await,
2849        );
2850        assert!(msg.contains("proof invalid"), "{msg}");
2851    }
2852
2853    #[tokio::test]
2854    async fn a_dpop_proof_cannot_be_replayed() {
2855        let (svc, dpop, key) = (service(), manager(), client_key());
2856        let header = dpop_header(&key, &key, "POST", URI, "jti-once");
2857        let go = || async {
2858            svc.handle_transaction_with_proof(
2859                &dpop,
2860                &proof(Some(&header), URI),
2861                request(&key, "dpop", false),
2862            )
2863            .await
2864        };
2865        go().await.unwrap();
2866        assert!(refusal(go().await).contains("proof invalid"));
2867    }
2868
2869    #[tokio::test]
2870    async fn httpsig_mtls_and_jws_are_refused_not_accepted_unverified() {
2871        let (svc, dpop, key) = (service(), manager(), client_key());
2872        // A valid DPoP header does not rescue a method that is not DPoP.
2873        let header = dpop_header(&key, &key, "POST", URI, "jti-other-method");
2874        for method in ["httpsig", "mtls", "jws", "no-such-method"] {
2875            let msg = refusal(svc.handle_transaction(request(&key, method, false)).await);
2876            assert!(
2877                msg.contains("proof method not supported"),
2878                "{method}: {msg}"
2879            );
2880            let msg = refusal(
2881                svc.handle_transaction_with_proof(
2882                    &dpop,
2883                    &proof(Some(&header), URI),
2884                    request(&key, method, false),
2885                )
2886                .await,
2887            );
2888            assert!(
2889                msg.contains("proof method not supported"),
2890                "{method}: {msg}"
2891            );
2892        }
2893        // A request that names no key is refused too (RFC 9635 section 2.3).
2894        let anonymous = GnapTransactionRequest::builder()
2895            .access_type("read")
2896            .build();
2897        let msg = refusal(svc.handle_transaction(anonymous).await);
2898        assert!(msg.contains("client key required"), "{msg}");
2899    }
2900
2901    #[tokio::test]
2902    async fn issuance_and_management_admit_exactly_the_same_proof_methods() {
2903        // A method admitted at issuance but not at management would leave a token that cannot be revoked
2904        // (Pip review). Both gates call `check_key_proof`; this fails if they ever diverge.
2905        let key = client_key();
2906        let thumbprint = GnapService::jwk_thumbprint(&key.jwk).unwrap();
2907        let not_supported = |e: AuthError| e.to_string().contains(PROOF_NOT_SUPPORTED);
2908        let mut admitted = Vec::new();
2909        for method in [
2910            "dpop", "test", "httpsig", "mtls", "jws", "", "DPOP", "none", "bogus",
2911        ] {
2912            let client = Some(GnapClientInfo {
2913                key: Some(GnapClientKey {
2914                    proof: method.to_string(),
2915                    jwk: key.jwk.clone(),
2916                }),
2917                display: None,
2918            });
2919            // with no proof material, a verifiable method fails for want of a proof, an unsupported one for
2920            // want of support: the two outcomes tell them apart without needing a valid proof
2921            let issuance = GnapService::verify_client_proof(&client, None).await;
2922            let management =
2923                GnapService::verify_token_key_proof(Some(&thumbprint), Some(method), None).await;
2924            let issued = match &issuance {
2925                Ok(_) => true,
2926                Err(e) => !not_supported(AuthError::validation(e.to_string())),
2927            };
2928            let managed = match &management {
2929                Ok(()) => true,
2930                Err(e) => !not_supported(AuthError::validation(e.to_string())),
2931            };
2932            assert_eq!(
2933                issued, managed,
2934                "{method:?}: issuance {issuance:?} but management {management:?}"
2935            );
2936            if issued {
2937                admitted.push(method);
2938            }
2939        }
2940        // the methods this build verifies, pinned: a new one has to be added on purpose
2941        assert_eq!(admitted, ["dpop", "test"]);
2942        // a token with no recorded method is refused at management, never waved through
2943        let none = GnapService::verify_token_key_proof(Some(&thumbprint), None, None).await;
2944        assert!(none.is_err());
2945    }
2946
2947    #[test]
2948    fn the_unit_test_proof_method_is_not_a_way_around_the_refusals() {
2949        // `validate_client_key_with_proof` has no proof to check, so it refuses a real method.
2950        let key = client_key();
2951        for method in ["dpop", "httpsig", "mtls", "jws"] {
2952            let client = Some(GnapClientInfo {
2953                key: Some(GnapClientKey {
2954                    proof: method.to_string(),
2955                    jwk: key.jwk.clone(),
2956                }),
2957                display: None,
2958            });
2959            let err = GnapService::validate_client_key_with_proof(&client, Some(b"m"), Some(b"s"))
2960                .unwrap_err()
2961                .to_string();
2962            assert!(
2963                err.contains("proof method not supported"),
2964                "{method}: {err}"
2965            );
2966        }
2967    }
2968
2969    #[tokio::test]
2970    async fn a_key_bound_transaction_continues_only_with_a_proof_from_that_key() {
2971        let (svc, dpop, key) = (service(), manager(), client_key());
2972        let first = dpop_header(&key, &key, "POST", URI, "jti-start");
2973        let resp = svc
2974            .handle_transaction_with_proof(
2975                &dpop,
2976                &proof(Some(&first), URI),
2977                request(&key, "dpop", true),
2978            )
2979            .await
2980            .unwrap();
2981        let cont = resp["continue"]["access_token"]["value"]
2982            .as_str()
2983            .unwrap()
2984            .to_string();
2985        let txn_id = svc.transactions.read().await.keys().next().unwrap().clone();
2986        let iref = svc
2987            .approve_transaction(&txn_id, Some("user-1"))
2988            .await
2989            .unwrap()
2990            .interact_ref
2991            .unwrap();
2992
2993        // The continuation token alone is not enough for a key-bound transaction.
2994        let msg = refusal(
2995            svc.continue_transaction(&txn_id, &cont, Some(&iref), None)
2996                .await,
2997        );
2998        assert!(msg.contains("proof required"), "{msg}");
2999        // Nor is a proof from another key, and neither burns the holder's token.
3000        let other = client_key();
3001        let forged = dpop_header(&other, &key, "POST", CONTINUE_URI, "jti-c-forged");
3002        let msg = refusal(
3003            svc.continue_transaction_with_proof(
3004                &dpop,
3005                &proof(Some(&forged), CONTINUE_URI),
3006                &txn_id,
3007                &cont,
3008                Some(&iref),
3009                None,
3010            )
3011            .await,
3012        );
3013        assert!(msg.contains("proof invalid"), "{msg}");
3014        // The key's own proof, with the same token, completes the transaction.
3015        let good = dpop_header(&key, &key, "POST", CONTINUE_URI, "jti-c-ok");
3016        let done = svc
3017            .continue_transaction_with_proof(
3018                &dpop,
3019                &proof(Some(&good), CONTINUE_URI),
3020                &txn_id,
3021                &cont,
3022                Some(&iref),
3023                None,
3024            )
3025            .await
3026            .unwrap();
3027        assert!(done["access_token"]["value"].is_string());
3028    }
3029}
3030
3031/// Access is granted by an integrator's policy, a client key is required, a finished interaction
3032/// is proved by its one-time reference, and an issued token is usable at once.
3033#[cfg(test)]
3034mod hardening_tests {
3035    use super::*;
3036    use std::sync::Mutex;
3037
3038    fn config() -> GnapConfig {
3039        GnapConfig {
3040            enabled: true,
3041            transaction_endpoint: "/api/gnap/tx".to_string(),
3042            interaction_base_url: Some("https://as.example.test".to_string()),
3043            token_lifetime_secs: 3600,
3044            transaction_lifetime_secs: 600,
3045        }
3046    }
3047
3048    fn jwk() -> GnapJwk {
3049        GnapJwk {
3050            kty: "EC".to_string(),
3051            kid: None,
3052            crv: Some("P-256".to_string()),
3053            x: Some("f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU".to_string()),
3054            y: Some("x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0".to_string()),
3055            n: None,
3056            e: None,
3057        }
3058    }
3059
3060    fn keyed() -> Option<GnapClientInfo> {
3061        Some(GnapClientInfo {
3062            key: Some(GnapClientKey {
3063                proof: "test".to_string(),
3064                jwk: jwk(),
3065            }),
3066            display: None,
3067        })
3068    }
3069
3070    fn rights(kinds: &[&str]) -> Vec<GnapAccessRequest> {
3071        kinds
3072            .iter()
3073            .map(|k| GnapAccessRequest {
3074                access_type: (*k).to_string(),
3075                actions: vec![],
3076                locations: vec![],
3077            })
3078            .collect()
3079    }
3080
3081    fn request(
3082        client: Option<GnapClientInfo>,
3083        kinds: &[&str],
3084        finish: bool,
3085    ) -> GnapTransactionRequest {
3086        GnapTransactionRequest {
3087            client,
3088            interact: finish.then(|| GnapInteractionRequirements {
3089                start: vec!["redirect".to_string()],
3090                finish: Some(GnapInteractionFinish {
3091                    method: "redirect".to_string(),
3092                    uri: "https://client.test/cb".to_string(),
3093                    nonce: "client-nonce".to_string(),
3094                }),
3095            }),
3096            access_token: Some(rights(kinds)),
3097            subject: None,
3098        }
3099    }
3100
3101    struct Records(Mutex<Vec<String>>);
3102
3103    #[async_trait]
3104    impl GnapAccessPolicy for Records {
3105        async fn grant(
3106            &self,
3107            thumbprint: &str,
3108            requested: &[GnapAccessRequest],
3109        ) -> Vec<GnapAccessRequest> {
3110            self.0.lock().unwrap().push(thumbprint.to_string());
3111            requested.to_vec()
3112        }
3113    }
3114
3115    /// Grants only `read`, whatever was asked for.
3116    struct ReadOnly;
3117
3118    #[async_trait]
3119    impl GnapAccessPolicy for ReadOnly {
3120        async fn grant(&self, _: &str, requested: &[GnapAccessRequest]) -> Vec<GnapAccessRequest> {
3121            requested
3122                .iter()
3123                .filter(|r| r.access_type == "read")
3124                .cloned()
3125                .collect()
3126        }
3127    }
3128
3129    fn with(policy: impl GnapAccessPolicy + 'static) -> GnapService {
3130        GnapService::new(config()).with_access_policy(Arc::new(policy))
3131    }
3132
3133    fn message<T>(r: Result<T>) -> String {
3134        match r {
3135            Ok(_) => "accepted".to_string(),
3136            Err(e) => e.to_string(),
3137        }
3138    }
3139
3140    // ── Policy ───────────────────────────────────────────────────────────
3141
3142    #[tokio::test]
3143    async fn a_service_without_a_policy_issues_no_access_token() {
3144        let none = GnapService::new(config());
3145        let msg = message(
3146            none.handle_transaction(request(keyed(), &["read"], false))
3147                .await,
3148        );
3149        assert!(msg.contains("no access policy"), "{msg}");
3150        assert!(none.issued_tokens.read().await.is_empty());
3151
3152        // Control: the same request is served once a policy grants it.
3153        let served = with(AllowAllPolicy)
3154            .handle_transaction(request(keyed(), &["read"], false))
3155            .await
3156            .unwrap();
3157        assert!(served["access_token"]["value"].is_string());
3158    }
3159
3160    #[tokio::test]
3161    async fn the_token_carries_what_the_policy_grants_not_what_was_requested() {
3162        let svc = with(ReadOnly);
3163        let resp = svc
3164            .handle_transaction(request(keyed(), &["admin", "read"], false))
3165            .await
3166            .unwrap();
3167        let granted = resp["access_token"]["access"].as_array().unwrap();
3168        assert_eq!(granted.len(), 1);
3169        assert_eq!(granted[0]["type"], "read");
3170        let value = resp["access_token"]["value"].as_str().unwrap();
3171        let introspected = svc.introspect_token(value).await.unwrap().unwrap();
3172        assert_eq!(introspected["access"].as_array().unwrap().len(), 1);
3173
3174        // A request for nothing the policy grants is denied, and nothing is stored.
3175        let before = svc.issued_tokens.read().await.len();
3176        let msg = message(
3177            svc.handle_transaction(request(keyed(), &["admin"], false))
3178                .await,
3179        );
3180        assert!(msg.contains("denied by policy"), "{msg}");
3181        assert_eq!(svc.issued_tokens.read().await.len(), before);
3182    }
3183
3184    #[tokio::test]
3185    async fn the_policy_is_told_which_key_is_asking() {
3186        let records = Arc::new(Records(Mutex::new(Vec::new())));
3187        let svc = GnapService::new(config()).with_access_policy(records.clone());
3188        svc.handle_transaction(request(keyed(), &["read"], false))
3189            .await
3190            .unwrap();
3191        let expected = GnapService::jwk_thumbprint(&jwk()).unwrap();
3192        assert_eq!(*records.0.lock().unwrap(), vec![expected]);
3193    }
3194
3195    #[tokio::test]
3196    async fn a_policy_that_denies_after_approval_ends_the_transaction() {
3197        let svc = with(ReadOnly);
3198        svc.handle_transaction(request(keyed(), &["admin"], true))
3199            .await
3200            .unwrap();
3201        let (id, cont) = {
3202            let txns = svc.transactions.read().await;
3203            let (id, t) = txns.iter().next().unwrap();
3204            (id.clone(), t.continue_token.clone())
3205        };
3206        let iref = svc
3207            .approve_transaction(&id, None)
3208            .await
3209            .unwrap()
3210            .interact_ref
3211            .unwrap();
3212        let msg = message(
3213            svc.continue_transaction(&id, &cont, Some(&iref), None)
3214                .await,
3215        );
3216        assert!(msg.contains("denied by policy"), "{msg}");
3217        assert!(svc.transactions.read().await.is_empty());
3218    }
3219
3220    // ── Client key ───────────────────────────────────────────────────────
3221
3222    #[tokio::test]
3223    async fn a_request_without_a_client_key_is_refused() {
3224        let svc = with(AllowAllPolicy);
3225        for client in [
3226            None,
3227            Some(GnapClientInfo {
3228                key: None,
3229                display: None,
3230            }),
3231        ] {
3232            let msg = message(
3233                svc.handle_transaction(request(client, &["read"], false))
3234                    .await,
3235            );
3236            assert!(msg.contains("client key required"), "{msg}");
3237        }
3238        // A subject-only request needs a key as well.
3239        let subject_only = GnapTransactionRequest {
3240            client: None,
3241            interact: None,
3242            access_token: None,
3243            subject: Some(GnapSubjectRequest {
3244                sub_id_formats: vec!["opaque".to_string()],
3245                assertion_formats: vec![],
3246            }),
3247        };
3248        let msg = message(svc.handle_transaction(subject_only).await);
3249        assert!(msg.contains("client key required"), "{msg}");
3250        assert!(svc.issued_tokens.read().await.is_empty());
3251
3252        // Control: with a key the same request is served.
3253        assert!(
3254            svc.handle_transaction(request(keyed(), &["read"], false))
3255                .await
3256                .is_ok()
3257        );
3258    }
3259
3260    // ── Interaction reference ────────────────────────────────────────────
3261
3262    async fn pending(svc: &GnapService, finish: bool) -> (String, String) {
3263        let before: Vec<String> = svc.transactions.read().await.keys().cloned().collect();
3264        let mut req = request(keyed(), &["read"], finish);
3265        if !finish {
3266            // Polling: interaction starts at the AS but the client names no finish method.
3267            req.interact = Some(GnapInteractionRequirements {
3268                start: vec!["redirect".to_string()],
3269                finish: None,
3270            });
3271        }
3272        svc.handle_transaction(req).await.unwrap();
3273        let txns = svc.transactions.read().await;
3274        let (id, t) = txns.iter().find(|(k, _)| !before.contains(*k)).unwrap();
3275        (id.clone(), t.continue_token.clone())
3276    }
3277
3278    #[tokio::test]
3279    async fn an_approved_finish_transaction_continues_only_with_its_own_reference() {
3280        let svc = with(AllowAllPolicy);
3281        let (id, cont) = pending(&svc, true).await;
3282        let (other_id, _) = pending(&svc, true).await;
3283        let iref = svc
3284            .approve_transaction(&id, None)
3285            .await
3286            .unwrap()
3287            .interact_ref
3288            .unwrap();
3289        let other_ref = svc
3290            .approve_transaction(&other_id, None)
3291            .await
3292            .unwrap()
3293            .interact_ref
3294            .unwrap();
3295        assert_ne!(iref, other_ref);
3296
3297        // No reference, a made-up one, and another transaction's one are all refused ...
3298        for given in [None, Some("garbage"), Some(other_ref.as_str())] {
3299            let msg = message(svc.continue_transaction(&id, &cont, given, None).await);
3300            assert!(
3301                (msg.contains("Invalid") || msg.contains("not found")),
3302                "{given:?}: {msg}"
3303            );
3304        }
3305        // ... and none of them used up the continuation token or the reference.
3306        let done = svc
3307            .continue_transaction(&id, &cont, Some(&iref), None)
3308            .await
3309            .unwrap();
3310        assert!(done["access_token"]["value"].is_string());
3311
3312        // The reference works once: the finished transaction is gone.
3313        let msg = message(
3314            svc.continue_transaction(&id, &cont, Some(&iref), None)
3315                .await,
3316        );
3317        assert!(
3318            (msg.contains("Invalid") || msg.contains("not found")),
3319            "{msg}"
3320        );
3321    }
3322
3323    #[tokio::test]
3324    async fn a_polling_transaction_needs_no_reference_and_refuses_one_nobody_issued() {
3325        let svc = with(AllowAllPolicy);
3326        let (id, cont) = pending(&svc, false).await;
3327        svc.approve_transaction(&id, None).await.unwrap();
3328        let msg = message(
3329            svc.continue_transaction(&id, &cont, Some("garbage"), None)
3330                .await,
3331        );
3332        assert!(
3333            (msg.contains("Invalid") || msg.contains("not found")),
3334            "{msg}"
3335        );
3336        // Control: polling without a reference gets the token.
3337        let done = svc
3338            .continue_transaction(&id, &cont, None, None)
3339            .await
3340            .unwrap();
3341        assert!(done["access_token"]["value"].is_string());
3342    }
3343
3344    #[tokio::test]
3345    async fn approval_returns_the_reference_and_hash_only_for_a_finish_transaction() {
3346        let svc = with(AllowAllPolicy);
3347        let (finishing, _) = pending(&svc, true).await;
3348        let (polling, _) = pending(&svc, false).await;
3349        let with_finish = svc.approve_transaction(&finishing, None).await.unwrap();
3350        assert!(with_finish.interact_ref.is_some() && with_finish.hash.is_some());
3351        let without = svc.approve_transaction(&polling, None).await.unwrap();
3352        assert_eq!(
3353            without,
3354            GnapInteractionCompletion {
3355                interact_ref: None,
3356                hash: None
3357            }
3358        );
3359        // Approving twice does not mint a second reference.
3360        let again = svc.approve_transaction(&finishing, None).await.unwrap();
3361        assert_eq!(again, with_finish);
3362    }
3363
3364    // ── Token is stored before it is returned ────────────────────────────
3365
3366    async fn use_at_once(svc: &GnapService, n: usize) -> usize {
3367        let mut unknown = 0;
3368        for _ in 0..n {
3369            let resp = svc
3370                .handle_transaction(request(keyed(), &["read"], false))
3371                .await
3372                .unwrap();
3373            let value = resp["access_token"]["value"].as_str().unwrap();
3374            if svc.introspect_token(value).await.unwrap().is_none() {
3375                unknown += 1;
3376            }
3377        }
3378        unknown
3379    }
3380
3381    #[tokio::test]
3382    async fn a_token_is_known_the_moment_it_is_returned_on_one_thread() {
3383        assert_eq!(use_at_once(&with(AllowAllPolicy), 100).await, 0);
3384    }
3385
3386    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
3387    async fn a_token_is_known_the_moment_it_is_returned_on_many_threads() {
3388        assert_eq!(use_at_once(&with(AllowAllPolicy), 300).await, 0);
3389    }
3390}