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