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