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)
11//! - Interaction hash verification (draft §4.2.3)
12//! - Continuation token rotation on each use
13//! - Token management (revocation)
14//! - Subject information responses
15//! - Transaction expiration and cleanup
16
17use crate::errors::{AuthError, Result};
18use crate::server::security::dpop::DpopManager;
19use base64::Engine as _;
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22use std::collections::HashMap;
23use std::sync::Arc;
24use tokio::sync::RwLock;
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct GnapConfig {
28    pub enabled: bool,
29    pub transaction_endpoint: String,
30    /// Base URL for interaction redirects (must be configured for production)
31    pub interaction_base_url: Option<String>,
32    /// Default access token lifetime in seconds
33    pub token_lifetime_secs: u64,
34    /// Transaction lifetime in seconds before expiration (default: 600 = 10 minutes)
35    pub transaction_lifetime_secs: u64,
36}
37
38impl Default for GnapConfig {
39    fn default() -> Self {
40        Self {
41            enabled: false,
42            transaction_endpoint: "/api/gnap/tx".to_string(),
43            interaction_base_url: None,
44            token_lifetime_secs: 3600,
45            transaction_lifetime_secs: 600,
46        }
47    }
48}
49
50/// A GNAP transaction request representing the client's intent
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct GnapTransactionRequest {
53    pub client: Option<GnapClientInfo>,
54    pub interact: Option<GnapInteractionRequirements>,
55    /// Requested access rights (draft-ietf-gnap-core-protocol §2)
56    pub access_token: Option<Vec<GnapAccessRequest>>,
57    /// Subject information request
58    pub subject: Option<GnapSubjectRequest>,
59}
60
61/// Description of a single access right being requested
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct GnapAccessRequest {
64    /// Type of access (e.g. "read", "write", or an API-specific identifier)
65    #[serde(rename = "type")]
66    pub access_type: String,
67    /// Actions within this type
68    #[serde(default)]
69    pub actions: Vec<String>,
70    /// Locations/URIs where this access applies
71    #[serde(default)]
72    pub locations: Vec<String>,
73}
74
75/// Subject information the client is requesting
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct GnapSubjectRequest {
78    /// Requested subject identifier formats
79    #[serde(default)]
80    pub sub_id_formats: Vec<String>,
81    /// Requested assertion formats (e.g. "id_token", "saml2")
82    #[serde(default)]
83    pub assertion_formats: Vec<String>,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct GnapClientInfo {
88    /// Client key in JWK format for cryptographic binding
89    pub key: Option<GnapClientKey>,
90    /// Client display information
91    pub display: Option<GnapClientDisplay>,
92}
93
94/// Client key with proof method (draft §7.1)
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct GnapClientKey {
97    /// Proof method: "httpsig", "mtls", "dpop", "jws", or "test"
98    pub proof: String,
99    /// JWK representation of the client's public key
100    pub jwk: GnapJwk,
101}
102
103/// Minimal JWK representation sufficient for GNAP key binding
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct GnapJwk {
106    /// Key type: "EC", "RSA", or "OKP"
107    pub kty: String,
108    /// Key ID (optional)
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub kid: Option<String>,
111
112    // EC fields (P-256 / ES256)
113    /// EC curve name
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub crv: Option<String>,
116    /// EC x coordinate (base64url)
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub x: Option<String>,
119    /// EC y coordinate (base64url)
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub y: Option<String>,
122
123    // RSA fields
124    /// RSA modulus (base64url)
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub n: Option<String>,
127    /// RSA exponent (base64url)
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub e: Option<String>,
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct GnapClientDisplay {
134    pub name: Option<String>,
135    pub uri: Option<String>,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct GnapInteractionRequirements {
140    pub start: Vec<String>,
141    pub finish: Option<GnapInteractionFinish>,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct GnapInteractionFinish {
146    pub method: String,
147    pub uri: String,
148    pub nonce: String,
149}
150
151impl GnapTransactionRequest {
152    /// Create a builder for a GNAP transaction request.
153    ///
154    /// # Example
155    /// ```rust
156    /// use auth_framework::protocols::gnap::GnapTransactionRequest;
157    ///
158    /// let req = GnapTransactionRequest::builder()
159    ///     .access("read", &["list"], &["https://api.example.com"])
160    ///     .subject_formats(vec!["opaque".into()])
161    ///     .build();
162    /// ```
163    pub fn builder() -> GnapTransactionRequestBuilder {
164        GnapTransactionRequestBuilder {
165            client: None,
166            interact: None,
167            access_token: Vec::new(),
168            subject: None,
169        }
170    }
171}
172
173/// Builder for [`GnapTransactionRequest`].
174pub struct GnapTransactionRequestBuilder {
175    client: Option<GnapClientInfo>,
176    interact: Option<GnapInteractionRequirements>,
177    access_token: Vec<GnapAccessRequest>,
178    subject: Option<GnapSubjectRequest>,
179}
180
181impl GnapTransactionRequestBuilder {
182    /// Set the client info with a key binding.
183    pub fn client(mut self, client: GnapClientInfo) -> Self {
184        self.client = Some(client);
185        self
186    }
187
188    /// Set client info from a key and proof method.
189    pub fn client_key(mut self, jwk: GnapJwk, proof: impl Into<String>) -> Self {
190        self.client = Some(GnapClientInfo {
191            key: Some(GnapClientKey {
192                proof: proof.into(),
193                jwk,
194            }),
195            display: None,
196        });
197        self
198    }
199
200    /// Set interaction requirements for redirect flow.
201    pub fn redirect_interaction(
202        mut self,
203        callback_uri: impl Into<String>,
204        nonce: impl Into<String>,
205    ) -> Self {
206        self.interact = Some(GnapInteractionRequirements {
207            start: vec!["redirect".to_string()],
208            finish: Some(GnapInteractionFinish {
209                method: "redirect".to_string(),
210                uri: callback_uri.into(),
211                nonce: nonce.into(),
212            }),
213        });
214        self
215    }
216
217    /// Set interaction requirements (raw).
218    pub fn interact(mut self, interact: GnapInteractionRequirements) -> Self {
219        self.interact = Some(interact);
220        self
221    }
222
223    /// Add an access request with type, actions, and locations.
224    pub fn access(
225        mut self,
226        access_type: impl Into<String>,
227        actions: &[impl AsRef<str>],
228        locations: &[impl AsRef<str>],
229    ) -> Self {
230        self.access_token.push(GnapAccessRequest {
231            access_type: access_type.into(),
232            actions: actions.iter().map(|a| a.as_ref().to_string()).collect(),
233            locations: locations.iter().map(|l| l.as_ref().to_string()).collect(),
234        });
235        self
236    }
237
238    /// Add a simple access request (type only, no actions/locations).
239    pub fn access_type(self, access_type: impl Into<String>) -> Self {
240        self.access(access_type, &[] as &[&str], &[] as &[&str])
241    }
242
243    /// Request subject information with the given identifier formats.
244    pub fn subject_formats(mut self, formats: Vec<String>) -> Self {
245        self.subject = Some(GnapSubjectRequest {
246            sub_id_formats: formats,
247            assertion_formats: vec![],
248        });
249        self
250    }
251
252    /// Request subject information (raw).
253    pub fn subject(mut self, subject: GnapSubjectRequest) -> Self {
254        self.subject = Some(subject);
255        self
256    }
257
258    /// Build the [`GnapTransactionRequest`].
259    pub fn build(self) -> GnapTransactionRequest {
260        GnapTransactionRequest {
261            client: self.client,
262            interact: self.interact,
263            access_token: if self.access_token.is_empty() {
264                None
265            } else {
266                Some(self.access_token)
267            },
268            subject: self.subject,
269        }
270    }
271}
272
273/// Internal state of a GNAP transaction
274#[derive(Debug, Clone, Serialize, Deserialize)]
275enum GnapTransactionState {
276    /// Waiting for user interaction
277    Pending,
278    /// User has approved; access token can be issued
279    Approved,
280    /// Transaction was denied or expired
281    Denied,
282}
283
284#[derive(Clone, Serialize, Deserialize)]
285struct GnapTransaction {
286    id: String,
287    state: GnapTransactionState,
288    request: GnapTransactionRequest,
289    continue_token: String,
290    created_at: u64,
291    /// Server-generated nonce for interaction hash verification (draft §4.2.3)
292    interact_nonce: Option<String>,
293    /// Subject identifier assigned after approval
294    subject_id: Option<String>,
295}
296
297impl std::fmt::Debug for GnapTransaction {
298    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299        let mut d = f.debug_struct("GnapTransaction");
300        d.field("id", &self.id);
301        d.field("state", &self.state);
302        d.field("request", &self.request);
303        d.field(
304            "continue_token",
305            &crate::utils::redact::redacted(&self.continue_token),
306        );
307        d.field("created_at", &self.created_at);
308        d.field(
309            "interact_nonce",
310            &crate::utils::redact::redacted(&self.interact_nonce),
311        );
312        d.field("subject_id", &self.subject_id);
313        d.finish()
314    }
315}
316
317/// A GNAP access token that has been issued and can be managed
318#[derive(Clone, Serialize, Deserialize)]
319struct GnapIssuedToken {
320    /// Opaque token value
321    pub value: String,
322    /// Access rights granted
323    pub access: Vec<GnapAccessRequest>,
324    /// Expiration timestamp (epoch seconds)
325    pub expires_at: u64,
326    /// Client key thumbprint that this token is bound to (if any)
327    pub key_thumbprint: Option<String>,
328    /// The transaction that produced this token
329    pub transaction_id: String,
330}
331
332impl std::fmt::Debug for GnapIssuedToken {
333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        let mut d = f.debug_struct("GnapIssuedToken");
335        d.field("value", &crate::utils::redact::redacted(&self.value));
336        d.field("access", &self.access);
337        d.field("expires_at", &self.expires_at);
338        d.field("key_thumbprint", &self.key_thumbprint);
339        d.field("transaction_id", &self.transaction_id);
340        d.finish()
341    }
342}
343
344/// The HTTP request a client key signs, handed to the `_with_proof` entry points.
345///
346/// Only the `dpop` proof method can be verified here: the proof is the request's `DPoP` header
347/// and must be signed by the key the client named in its request, for this method and URI.
348#[derive(Debug, Clone, Copy)]
349pub struct GnapProof<'a> {
350    /// HTTP method of the request (`htm`).
351    pub http_method: &'a str,
352    /// HTTP URI of the request, without query or fragment (`htu`).
353    pub http_uri: &'a str,
354    /// The request's `DPoP` header, if it had one.
355    pub dpop_proof: Option<&'a str>,
356    /// A server-issued DPoP nonce the proof must carry, if the caller uses them.
357    pub expected_nonce: Option<&'a str>,
358}
359
360pub struct GnapService {
361    config: GnapConfig,
362    /// Active transactions (keyed by transaction ID)
363    transactions: Arc<RwLock<HashMap<String, GnapTransaction>>>,
364    /// Issued access tokens (keyed by token value)
365    issued_tokens: Arc<RwLock<HashMap<String, GnapIssuedToken>>>,
366}
367
368/// The one message every refused `continue_transaction` call returns, so a caller cannot tell an
369/// unknown transaction from an expired one, a wrong token or a wrong interaction hash.
370const INVALID_CONTINUATION: &str = "Invalid continuation request";
371
372/// Refusal of a client key whose proof method this crate cannot verify.
373const PROOF_NOT_SUPPORTED: &str = "GNAP proof method not supported";
374/// Refusal of a client key that came without the proof material to check it.
375const PROOF_REQUIRED: &str = "GNAP client key proof required: use the _with_proof entry point with the request's DPoP header";
376/// Refusal of a client key proof that did not verify.
377const PROOF_INVALID: &str = "GNAP client key proof invalid";
378
379impl GnapService {
380    pub fn new(config: GnapConfig) -> Self {
381        Self {
382            config,
383            transactions: Arc::new(RwLock::new(HashMap::new())),
384            issued_tokens: Arc::new(RwLock::new(HashMap::new())),
385        }
386    }
387
388    // ── Key Binding Helpers ──────────────────────────────────────────────
389
390    /// Compute the JWK thumbprint (RFC 7638) for key binding.
391    /// Uses the required members in lexicographic order per key type.
392    fn jwk_thumbprint(jwk: &GnapJwk) -> Result<String> {
393        let canonical = match jwk.kty.as_str() {
394            "EC" => {
395                let crv = jwk.crv.as_deref().unwrap_or("");
396                let x = jwk.x.as_deref().unwrap_or("");
397                let y = jwk.y.as_deref().unwrap_or("");
398                format!(r#"{{"crv":"{crv}","kty":"EC","x":"{x}","y":"{y}"}}"#)
399            }
400            "RSA" => {
401                let e = jwk.e.as_deref().unwrap_or("");
402                let n = jwk.n.as_deref().unwrap_or("");
403                format!(r#"{{"e":"{e}","kty":"RSA","n":"{n}"}}"#)
404            }
405            "OKP" => {
406                let crv = jwk.crv.as_deref().unwrap_or("");
407                let x = jwk.x.as_deref().unwrap_or("");
408                format!(r#"{{"crv":"{crv}","kty":"OKP","x":"{x}"}}"#)
409            }
410            other => {
411                return Err(AuthError::validation(format!(
412                    "Unsupported JWK key type: {other}"
413                )));
414            }
415        };
416        let hash = Sha256::digest(canonical.as_bytes());
417        Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash))
418    }
419
420    /// Reconstruct the raw public key bytes from a JWK and verify a
421    /// signature using `ring`. Supports ES256 (P-256) and RS256.
422    ///
423    /// This is called by middleware or application code that extracts the
424    /// HTTP message signature from the request before invoking the GNAP
425    /// transaction endpoints.
426    pub fn verify_jwk_signature(jwk: &GnapJwk, message: &[u8], signature: &[u8]) -> Result<()> {
427        use base64::Engine;
428        use ring::signature;
429
430        match jwk.kty.as_str() {
431            "EC" => {
432                let crv = jwk.crv.as_deref().unwrap_or("P-256");
433                if crv != "P-256" {
434                    return Err(AuthError::validation(format!(
435                        "Unsupported EC curve for GNAP: {crv}"
436                    )));
437                }
438                let x = base64::engine::general_purpose::URL_SAFE_NO_PAD
439                    .decode(jwk.x.as_deref().unwrap_or(""))
440                    .map_err(|e| AuthError::validation(format!("Invalid JWK x: {e}")))?;
441                let y = base64::engine::general_purpose::URL_SAFE_NO_PAD
442                    .decode(jwk.y.as_deref().unwrap_or(""))
443                    .map_err(|e| AuthError::validation(format!("Invalid JWK y: {e}")))?;
444
445                // Uncompressed point: 0x04 || x || y
446                let mut pk_bytes = Vec::with_capacity(1 + x.len() + y.len());
447                pk_bytes.push(0x04);
448                pk_bytes.extend_from_slice(&x);
449                pk_bytes.extend_from_slice(&y);
450
451                let key = signature::UnparsedPublicKey::new(
452                    &signature::ECDSA_P256_SHA256_ASN1,
453                    &pk_bytes,
454                );
455                key.verify(message, signature).map_err(|_| {
456                    AuthError::validation("GNAP client key signature verification failed (ES256)")
457                })
458            }
459            "RSA" => {
460                let n = base64::engine::general_purpose::URL_SAFE_NO_PAD
461                    .decode(jwk.n.as_deref().unwrap_or(""))
462                    .map_err(|e| AuthError::validation(format!("Invalid JWK n: {e}")))?;
463                let e = base64::engine::general_purpose::URL_SAFE_NO_PAD
464                    .decode(jwk.e.as_deref().unwrap_or(""))
465                    .map_err(|e| AuthError::validation(format!("Invalid JWK e: {e}")))?;
466
467                // DER-encode the RSA public key (PKCS#1)
468                let pk_der = Self::encode_rsa_public_key_der(&n, &e);
469
470                let key = signature::UnparsedPublicKey::new(
471                    &signature::RSA_PKCS1_2048_8192_SHA256,
472                    &pk_der,
473                );
474                key.verify(message, signature).map_err(|_| {
475                    AuthError::validation("GNAP client key signature verification failed (RS256)")
476                })
477            }
478            other => Err(AuthError::validation(format!(
479                "Unsupported JWK key type for signature: {other}"
480            ))),
481        }
482    }
483
484    /// Encode RSA n,e into a DER SubjectPublicKeyInfo structure for ring.
485    fn encode_rsa_public_key_der(n: &[u8], e: &[u8]) -> Vec<u8> {
486        // Build PKCS#1 RSAPublicKey: SEQUENCE { INTEGER n, INTEGER e }
487        fn der_integer(val: &[u8]) -> Vec<u8> {
488            // Strip leading zeros but ensure positive
489            let v = if !val.is_empty() && val[0] == 0 {
490                let stripped = val.iter().position(|&b| b != 0).unwrap_or(val.len() - 1);
491                &val[stripped..]
492            } else {
493                val
494            };
495            let needs_pad = !v.is_empty() && v[0] & 0x80 != 0;
496            let len = v.len() + if needs_pad { 1 } else { 0 };
497            let mut out = vec![0x02]; // INTEGER tag
498            der_encode_length(len, &mut out);
499            if needs_pad {
500                out.push(0x00);
501            }
502            out.extend_from_slice(v);
503            out
504        }
505
506        fn der_encode_length(len: usize, out: &mut Vec<u8>) {
507            if len < 0x80 {
508                out.push(len as u8);
509            } else if len < 0x100 {
510                out.push(0x81);
511                out.push(len as u8);
512            } else if len < 0x10000 {
513                out.push(0x82);
514                out.push((len >> 8) as u8);
515                out.push(len as u8);
516            } else {
517                out.push(0x83);
518                out.push((len >> 16) as u8);
519                out.push((len >> 8) as u8);
520                out.push(len as u8);
521            }
522        }
523
524        let n_der = der_integer(n);
525        let e_der = der_integer(e);
526        let rsa_seq_content_len = n_der.len() + e_der.len();
527        let mut rsa_seq = vec![0x30]; // SEQUENCE tag
528        der_encode_length(rsa_seq_content_len, &mut rsa_seq);
529        rsa_seq.extend_from_slice(&n_der);
530        rsa_seq.extend_from_slice(&e_der);
531
532        // Wrap in SubjectPublicKeyInfo:
533        // SEQUENCE { SEQUENCE { OID rsaEncryption, NULL }, BIT STRING { rsa_seq } }
534        let rsa_oid: &[u8] = &[
535            0x30, 0x0d, // SEQUENCE (AlgorithmIdentifier)
536            0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
537            0x01, // OID 1.2.840.113549.1.1.1
538            0x05, 0x00, // NULL
539        ];
540        let bitstring_len = 1 + rsa_seq.len(); // 1 byte for unused-bits count
541        let mut bitstring = vec![0x03]; // BIT STRING tag
542        der_encode_length(bitstring_len, &mut bitstring);
543        bitstring.push(0x00); // 0 unused bits
544        bitstring.extend_from_slice(&rsa_seq);
545
546        let spki_content_len = rsa_oid.len() + bitstring.len();
547        let mut spki = vec![0x30]; // outer SEQUENCE
548        der_encode_length(spki_content_len, &mut spki);
549        spki.extend_from_slice(rsa_oid);
550        spki.extend_from_slice(&bitstring);
551        spki
552    }
553
554    /// Validate the client key binding on a request.
555    /// Returns the key thumbprint if a key is present and valid.
556    ///
557    /// When `proof_message` and `proof_signature` are provided, the actual
558    /// cryptographic signature is verified against the client's JWK. For
559    /// proof methods other than "test", the caller (typically HTTP middleware)
560    /// must extract and supply the message and signature bytes from the
561    /// request (e.g. the HTTP Signature input string and its signature value).
562    pub fn validate_client_key_with_proof(
563        client: &Option<GnapClientInfo>,
564        proof_message: Option<&[u8]>,
565        proof_signature: Option<&[u8]>,
566    ) -> Result<Option<String>> {
567        let client = match client {
568            Some(c) => c,
569            None => return Ok(None),
570        };
571        let key = match &client.key {
572            Some(k) => k,
573            None => return Ok(None),
574        };
575
576        // Validate proof method is recognized
577        match key.proof.as_str() {
578            "httpsig" | "mtls" | "dpop" | "jws" | "test" => {}
579            other => {
580                return Err(AuthError::validation(format!(
581                    "GNAP proof method not supported: {other}"
582                )));
583            }
584        }
585
586        // Validate key type and required fields
587        Self::validate_jwk_fields(&key.jwk)?;
588
589        let thumbprint = Self::jwk_thumbprint(&key.jwk)?;
590
591        // A signature over bytes the caller chose is not a proof of the request, so no method
592        // is accepted here: use `handle_transaction_with_proof` for `dpop`. Only the unit-test
593        // method, which checks nothing, passes, and only in test builds.
594        let _ = (proof_message, proof_signature);
595        if !cfg!(test) || key.proof != "test" {
596            return Err(AuthError::validation(format!(
597                "{PROOF_NOT_SUPPORTED}: {}",
598                key.proof
599            )));
600        }
601
602        Ok(Some(thumbprint))
603    }
604
605    /// Validate that a JWK has the required fields for its key type.
606    fn validate_jwk_fields(jwk: &GnapJwk) -> Result<()> {
607        match jwk.kty.as_str() {
608            "EC" => {
609                if jwk.x.is_none() || jwk.y.is_none() {
610                    return Err(AuthError::validation(
611                        "EC JWK must include x and y coordinates",
612                    ));
613                }
614            }
615            "RSA" => {
616                if jwk.n.is_none() || jwk.e.is_none() {
617                    return Err(AuthError::validation(
618                        "RSA JWK must include n and e components",
619                    ));
620                }
621            }
622            "OKP" => {
623                if jwk.x.is_none() {
624                    return Err(AuthError::validation("OKP JWK must include x coordinate"));
625                }
626            }
627            other => {
628                return Err(AuthError::validation(format!(
629                    "Unsupported JWK key type: {other}"
630                )));
631            }
632        }
633        Ok(())
634    }
635
636    /// Validate the client key binding on a request (structural only, no
637    /// signature verification). Used internally when proof material is
638    /// not available at the protocol level (e.g., continuation polling).
639    fn validate_client_key(client: &Option<GnapClientInfo>) -> Result<Option<String>> {
640        let client = match client {
641            Some(c) => c,
642            None => return Ok(None),
643        };
644        let key = match &client.key {
645            Some(k) => k,
646            None => return Ok(None),
647        };
648
649        // Validate proof method is recognized
650        match key.proof.as_str() {
651            "httpsig" | "mtls" | "dpop" | "jws" | "test" => {}
652            other => {
653                return Err(AuthError::validation(format!(
654                    "GNAP proof method not supported: {other}"
655                )));
656            }
657        }
658
659        Self::validate_jwk_fields(&key.jwk)?;
660        let thumbprint = Self::jwk_thumbprint(&key.jwk)?;
661        Ok(Some(thumbprint))
662    }
663
664    /// Prove the client holds the key it named, and return that key's thumbprint.
665    ///
666    /// A request that names no client key is anonymous and passes with no thumbprint. A request
667    /// that names one is accepted only when its proof is verified here: `dpop` against `dpop`'s
668    /// manager and the request's `DPoP` header. Every other method (`httpsig`, `mtls`, `jws`,
669    /// anything unknown) is refused, as is a `dpop` key with no proof material, so no proof
670    /// that was never checked can authorize a request.
671    async fn verify_client_proof(
672        client: &Option<GnapClientInfo>,
673        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
674    ) -> Result<Option<String>> {
675        let Some(thumbprint) = Self::validate_client_key(client)? else {
676            return Ok(None);
677        };
678        let Some(key) = client.as_ref().and_then(|c| c.key.as_ref()) else {
679            return Ok(None);
680        };
681        match key.proof.as_str() {
682            "dpop" => {
683                let Some((manager, proof)) = dpop else {
684                    return Err(AuthError::validation(PROOF_REQUIRED));
685                };
686                let Some(header) = proof.dpop_proof else {
687                    return Err(AuthError::validation(PROOF_REQUIRED));
688                };
689                match manager
690                    .validate_dpop_proof_for_key(
691                        header,
692                        proof.http_method,
693                        proof.http_uri,
694                        None,
695                        proof.expected_nonce,
696                        Some(&thumbprint),
697                    )
698                    .await
699                {
700                    Ok(result) if result.is_valid => {}
701                    _ => return Err(AuthError::validation(PROOF_INVALID)),
702                }
703            }
704            // Unit tests only: a method that checks nothing must never be accepted in a build.
705            #[cfg(test)]
706            "test" => {}
707            other => {
708                return Err(AuthError::validation(format!(
709                    "{PROOF_NOT_SUPPORTED}: {other}"
710                )));
711            }
712        }
713        Ok(Some(thumbprint))
714    }
715
716    // ── Interaction Hash ─────────────────────────────────────────────────
717
718    /// Compute the interaction hash per draft §4.2.3.
719    ///
720    /// hash = SHA-256( client_nonce + "\n" + server_nonce + "\n" + interact_ref + "\n" + tx_endpoint )
721    fn compute_interact_hash(
722        client_nonce: &str,
723        server_nonce: &str,
724        interact_ref: &str,
725        transaction_endpoint: &str,
726    ) -> String {
727        let input =
728            format!("{client_nonce}\n{server_nonce}\n{interact_ref}\n{transaction_endpoint}");
729        let hash = Sha256::digest(input.as_bytes());
730        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(hash)
731    }
732
733    // ── Token Issuance Helper ────────────────────────────────────────────
734
735    fn build_access_token_response(
736        &self,
737        access_requests: &[GnapAccessRequest],
738        key_thumbprint: &Option<String>,
739        transaction_id: &str,
740    ) -> serde_json::Map<String, serde_json::Value> {
741        let access_token = uuid::Uuid::new_v4().to_string();
742        let now = std::time::SystemTime::now()
743            .duration_since(std::time::UNIX_EPOCH)
744            .unwrap_or_default()
745            .as_secs();
746
747        let issued = GnapIssuedToken {
748            value: access_token.clone(),
749            access: access_requests.to_vec(),
750            expires_at: now + self.config.token_lifetime_secs,
751            key_thumbprint: key_thumbprint.clone(),
752            transaction_id: transaction_id.to_string(),
753        };
754
755        // Store in issued_tokens (fire-and-forget via blocking write is fine
756        // since we return the response synchronously within an async context)
757        let tokens = Arc::clone(&self.issued_tokens);
758        let token_value = access_token.clone();
759        let issued_clone = issued;
760        tokio::spawn(async move {
761            tokens.write().await.insert(token_value, issued_clone);
762        });
763
764        let mut token_obj = serde_json::Map::new();
765        token_obj.insert("value".to_string(), serde_json::Value::String(access_token));
766        token_obj.insert(
767            "expires_in".to_string(),
768            serde_json::Value::Number(self.config.token_lifetime_secs.into()),
769        );
770
771        // Include manage URI for token lifecycle operations
772        token_obj.insert(
773            "manage".to_string(),
774            serde_json::Value::String(format!("{}/token", self.config.transaction_endpoint)),
775        );
776
777        // If key-bound, indicate the key binding
778        if key_thumbprint.is_some() {
779            token_obj.insert("key".to_string(), serde_json::Value::Bool(true));
780        }
781
782        let access_json: Vec<serde_json::Value> = access_requests
783            .iter()
784            .map(|a| serde_json::to_value(a).unwrap_or_default())
785            .collect();
786        token_obj.insert("access".to_string(), serde_json::Value::Array(access_json));
787
788        token_obj
789    }
790
791    // ── Transaction Lifecycle ────────────────────────────────────────────
792
793    /// Handle a new GNAP transaction request (draft-ietf-gnap-core-protocol §2)
794    pub async fn handle_transaction(
795        &self,
796        request: GnapTransactionRequest,
797    ) -> Result<serde_json::Value> {
798        self.handle_transaction_inner(request, None).await
799    }
800
801    /// Like [`Self::handle_transaction`], for a request that names a client key with the `dpop`
802    /// proof method: `proof` carries the request's `DPoP` header, which must be signed by that
803    /// key. A request without a client key behaves as in `handle_transaction`.
804    pub async fn handle_transaction_with_proof(
805        &self,
806        dpop: &DpopManager,
807        proof: &GnapProof<'_>,
808        request: GnapTransactionRequest,
809    ) -> Result<serde_json::Value> {
810        self.handle_transaction_inner(request, Some((dpop, proof)))
811            .await
812    }
813
814    async fn handle_transaction_inner(
815        &self,
816        request: GnapTransactionRequest,
817        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
818    ) -> Result<serde_json::Value> {
819        if !self.config.enabled {
820            return Err(AuthError::config("GNAP protocol is currently disabled"));
821        }
822
823        // Validate that the request asks for something
824        if request.access_token.is_none() && request.subject.is_none() {
825            return Err(AuthError::validation(
826                "GNAP request must include at least one of access_token or subject",
827            ));
828        }
829
830        // Validate client key if provided (draft §7.1)
831        let key_thumbprint = Self::verify_client_proof(&request.client, dpop).await?;
832
833        let transaction_id = uuid::Uuid::new_v4().to_string();
834        let continue_token = uuid::Uuid::new_v4().to_string();
835
836        let now = std::time::SystemTime::now()
837            .duration_since(std::time::UNIX_EPOCH)
838            .unwrap_or_default()
839            .as_secs();
840
841        let mut response = serde_json::Map::new();
842
843        // Generate a server nonce for interaction hash verification
844        let interact_nonce = if request.interact.is_some() {
845            let nonce = uuid::Uuid::new_v4().to_string();
846            Some(nonce)
847        } else {
848            None
849        };
850
851        // If interaction is requested, generate interaction response
852        if let Some(ref interact) = request.interact {
853            let base_url = self.config.interaction_base_url.as_deref().ok_or_else(|| {
854                AuthError::config(
855                    "GNAP interaction_base_url must be configured for interactive flows",
856                )
857            })?;
858
859            let interact_url = format!("{}/interact/{}", base_url, transaction_id);
860
861            let mut interact_res = serde_json::Map::new();
862
863            if interact.start.iter().any(|m| m == "redirect") {
864                interact_res.insert(
865                    "redirect".to_string(),
866                    serde_json::Value::String(interact_url),
867                );
868            }
869
870            if let Some(ref finish) = interact.finish {
871                // Return server nonce for client to compute interaction hash
872                interact_res.insert(
873                    "finish".to_string(),
874                    serde_json::Value::String(interact_nonce.clone().unwrap_or_default()),
875                );
876                // Echo the finish method + nonce so client knows the protocol
877                let _ = &finish.nonce; // client_nonce is used later for hash
878            }
879
880            response.insert(
881                "interact".to_string(),
882                serde_json::Value::Object(interact_res),
883            );
884
885            // Store pending transaction
886            let txn = GnapTransaction {
887                id: transaction_id.clone(),
888                state: GnapTransactionState::Pending,
889                request: request.clone(),
890                continue_token: continue_token.clone(),
891                created_at: now,
892                interact_nonce: interact_nonce.clone(),
893                subject_id: None,
894            };
895            self.transactions.write().await.insert(transaction_id, txn);
896        } else {
897            // No interaction required — issue token directly if access requested
898            if let Some(ref access_requests) = request.access_token {
899                let token_obj =
900                    self.build_access_token_response(access_requests, &key_thumbprint, "direct");
901                response.insert(
902                    "access_token".to_string(),
903                    serde_json::Value::Object(token_obj),
904                );
905            }
906
907            // If subject info was requested, include it (draft §2.2)
908            if let Some(ref subject_req) = request.subject {
909                let subject_resp = Self::build_subject_response(subject_req, None);
910                response.insert(
911                    "subject".to_string(),
912                    serde_json::Value::Object(subject_resp),
913                );
914            }
915        }
916
917        // Provide continuation endpoint (with rotatable token)
918        let mut continue_obj = serde_json::Map::new();
919        let mut ct_token = serde_json::Map::new();
920        ct_token.insert(
921            "value".to_string(),
922            serde_json::Value::String(continue_token),
923        );
924        continue_obj.insert(
925            "access_token".to_string(),
926            serde_json::Value::Object(ct_token),
927        );
928        continue_obj.insert(
929            "uri".to_string(),
930            serde_json::Value::String(format!("{}/continue", self.config.transaction_endpoint)),
931        );
932
933        response.insert(
934            "continue".to_string(),
935            serde_json::Value::Object(continue_obj),
936        );
937
938        Ok(serde_json::Value::Object(response))
939    }
940
941    /// Continue a GNAP transaction (polling or post-interaction).
942    ///
943    /// The continuation token is **rotated on every successful call** per
944    /// draft §5.1, preventing replay of old continuation responses.
945    pub async fn continue_transaction(
946        &self,
947        transaction_id: &str,
948        continue_token: &str,
949        interact_ref: Option<&str>,
950        interact_hash: Option<&str>,
951    ) -> Result<serde_json::Value> {
952        self.continue_transaction_inner(
953            transaction_id,
954            continue_token,
955            interact_ref,
956            interact_hash,
957            None,
958        )
959        .await
960    }
961
962    /// Like [`Self::continue_transaction`], for a transaction whose client named a `dpop` key:
963    /// the continuation request must carry a `DPoP` proof signed by that same key (draft §5.1).
964    pub async fn continue_transaction_with_proof(
965        &self,
966        dpop: &DpopManager,
967        proof: &GnapProof<'_>,
968        transaction_id: &str,
969        continue_token: &str,
970        interact_ref: Option<&str>,
971        interact_hash: Option<&str>,
972    ) -> Result<serde_json::Value> {
973        self.continue_transaction_inner(
974            transaction_id,
975            continue_token,
976            interact_ref,
977            interact_hash,
978            Some((dpop, proof)),
979        )
980        .await
981    }
982
983    async fn continue_transaction_inner(
984        &self,
985        transaction_id: &str,
986        continue_token: &str,
987        interact_ref: Option<&str>,
988        interact_hash: Option<&str>,
989        dpop: Option<(&DpopManager, &GnapProof<'_>)>,
990    ) -> Result<serde_json::Value> {
991        // Take a write lock so we can rotate the continuation token atomically
992        let mut transactions = self.transactions.write().await;
993        let txn = transactions
994            .get_mut(transaction_id)
995            .ok_or_else(|| AuthError::validation(INVALID_CONTINUATION))?;
996
997        // Enforce transaction expiration
998        let now = std::time::SystemTime::now()
999            .duration_since(std::time::UNIX_EPOCH)
1000            .unwrap_or_default()
1001            .as_secs();
1002        if now.saturating_sub(txn.created_at) > self.config.transaction_lifetime_secs {
1003            transactions.remove(transaction_id);
1004            return Err(AuthError::validation(INVALID_CONTINUATION));
1005        }
1006
1007        // Verify continuation token. `ct_eq` examines every byte of two slices of equal
1008        // length; a length mismatch returns early, which reveals only the length of a
1009        // UUID-formatted token.
1010        if !bool::from(subtle::ConstantTimeEq::ct_eq(
1011            txn.continue_token.as_bytes(),
1012            continue_token.as_bytes(),
1013        )) {
1014            return Err(AuthError::validation(INVALID_CONTINUATION));
1015        }
1016
1017        // If interaction hash is provided, verify it (draft §4.2.3). This runs before the
1018        // token is rotated, so a request that fails the check leaves the holder's token usable.
1019        if let (Some(hash), Some(iref)) = (interact_hash, interact_ref) {
1020            let server_nonce = txn.interact_nonce.as_deref().ok_or_else(|| {
1021                AuthError::validation("No interaction nonce for this transaction")
1022            })?;
1023            let client_nonce = txn
1024                .request
1025                .interact
1026                .as_ref()
1027                .and_then(|i| i.finish.as_ref())
1028                .map(|f| f.nonce.as_str())
1029                .unwrap_or("");
1030
1031            let expected = Self::compute_interact_hash(
1032                client_nonce,
1033                server_nonce,
1034                iref,
1035                &self.config.transaction_endpoint,
1036            );
1037            if !bool::from(subtle::ConstantTimeEq::ct_eq(
1038                hash.as_bytes(),
1039                expected.as_bytes(),
1040            )) {
1041                return Err(AuthError::validation(INVALID_CONTINUATION));
1042            }
1043        }
1044
1045        // A transaction whose client named a key continues only for that key: verify the proof
1046        // before the token is rotated, so a refused request leaves the holder's token usable.
1047        let verified_thumbprint = Self::verify_client_proof(&txn.request.client, dpop).await?;
1048
1049        // Rotate the continuation token (draft §5.1)
1050        let new_continue_token = uuid::Uuid::new_v4().to_string();
1051        txn.continue_token = new_continue_token.clone();
1052
1053        let result = match txn.state {
1054            GnapTransactionState::Pending => {
1055                // Still waiting for user interaction
1056                let mut resp = serde_json::Map::new();
1057                let mut cont = serde_json::Map::new();
1058                cont.insert(
1059                    "uri".to_string(),
1060                    serde_json::Value::String(format!(
1061                        "{}/continue",
1062                        self.config.transaction_endpoint
1063                    )),
1064                );
1065                cont.insert("wait".to_string(), serde_json::Value::Number(5.into()));
1066                let mut ct = serde_json::Map::new();
1067                ct.insert(
1068                    "value".to_string(),
1069                    serde_json::Value::String(new_continue_token),
1070                );
1071                cont.insert("access_token".to_string(), serde_json::Value::Object(ct));
1072                resp.insert("continue".to_string(), serde_json::Value::Object(cont));
1073                Ok(serde_json::Value::Object(resp))
1074            }
1075            GnapTransactionState::Approved => {
1076                let key_thumbprint = verified_thumbprint;
1077
1078                let mut response = serde_json::Map::new();
1079
1080                // Issue access token
1081                if let Some(ref access_requests) = txn.request.access_token {
1082                    let token_obj = self.build_access_token_response(
1083                        access_requests,
1084                        &key_thumbprint,
1085                        transaction_id,
1086                    );
1087                    response.insert(
1088                        "access_token".to_string(),
1089                        serde_json::Value::Object(token_obj),
1090                    );
1091                }
1092
1093                // Include subject info if requested and available
1094                if let Some(ref subject_req) = txn.request.subject {
1095                    let subject_resp =
1096                        Self::build_subject_response(subject_req, txn.subject_id.as_deref());
1097                    response.insert(
1098                        "subject".to_string(),
1099                        serde_json::Value::Object(subject_resp),
1100                    );
1101                }
1102
1103                Ok(serde_json::Value::Object(response))
1104            }
1105            GnapTransactionState::Denied => Err(AuthError::validation(
1106                "Transaction was denied by the resource owner",
1107            )),
1108        };
1109
1110        // Remove completed/denied transactions
1111        if matches!(
1112            txn.state,
1113            GnapTransactionState::Approved | GnapTransactionState::Denied
1114        ) {
1115            transactions.remove(transaction_id);
1116        }
1117
1118        result
1119    }
1120
1121    /// Approve a pending transaction (called after user interaction).
1122    /// Optionally sets the subject identifier for subject-info responses.
1123    pub async fn approve_transaction(
1124        &self,
1125        transaction_id: &str,
1126        subject_id: Option<&str>,
1127    ) -> Result<()> {
1128        let mut transactions = self.transactions.write().await;
1129        let txn = transactions
1130            .get_mut(transaction_id)
1131            .ok_or_else(|| AuthError::validation("Transaction not found"))?;
1132        txn.state = GnapTransactionState::Approved;
1133        if let Some(sid) = subject_id {
1134            txn.subject_id = Some(sid.to_string());
1135        }
1136        Ok(())
1137    }
1138
1139    /// Deny a pending transaction
1140    pub async fn deny_transaction(&self, transaction_id: &str) -> Result<()> {
1141        let mut transactions = self.transactions.write().await;
1142        let txn = transactions
1143            .get_mut(transaction_id)
1144            .ok_or_else(|| AuthError::validation("Transaction not found"))?;
1145        txn.state = GnapTransactionState::Denied;
1146        Ok(())
1147    }
1148
1149    // ── Token Management (draft §6) ─────────────────────────────────────
1150
1151    /// Revoke an issued access token (draft §6.2 — DELETE on manage URI).
1152    pub async fn revoke_token(&self, token_value: &str) -> Result<()> {
1153        let mut tokens = self.issued_tokens.write().await;
1154        if tokens.remove(token_value).is_none() {
1155            return Err(AuthError::validation("Token not found"));
1156        }
1157        Ok(())
1158    }
1159
1160    /// Rotate an issued access token (draft §6.1 — POST on manage URI).
1161    /// Returns a new token with the same access rights and key binding.
1162    pub async fn rotate_token(&self, old_token_value: &str) -> Result<serde_json::Value> {
1163        let mut tokens = self.issued_tokens.write().await;
1164        let old = tokens
1165            .remove(old_token_value)
1166            .ok_or_else(|| AuthError::validation("Token not found or already revoked"))?;
1167
1168        let now = std::time::SystemTime::now()
1169            .duration_since(std::time::UNIX_EPOCH)
1170            .unwrap_or_default()
1171            .as_secs();
1172
1173        if now >= old.expires_at {
1174            return Err(AuthError::validation("Token has expired"));
1175        }
1176
1177        let new_value = uuid::Uuid::new_v4().to_string();
1178        let new_token = GnapIssuedToken {
1179            value: new_value.clone(),
1180            access: old.access.clone(),
1181            expires_at: now + self.config.token_lifetime_secs,
1182            key_thumbprint: old.key_thumbprint.clone(),
1183            transaction_id: old.transaction_id,
1184        };
1185
1186        let mut token_obj = serde_json::Map::new();
1187        token_obj.insert(
1188            "value".to_string(),
1189            serde_json::Value::String(new_value.clone()),
1190        );
1191        token_obj.insert(
1192            "expires_in".to_string(),
1193            serde_json::Value::Number(self.config.token_lifetime_secs.into()),
1194        );
1195        token_obj.insert(
1196            "manage".to_string(),
1197            serde_json::Value::String(format!("{}/token", self.config.transaction_endpoint)),
1198        );
1199        if new_token.key_thumbprint.is_some() {
1200            token_obj.insert("key".to_string(), serde_json::Value::Bool(true));
1201        }
1202        let access_json: Vec<serde_json::Value> = old
1203            .access
1204            .iter()
1205            .map(|a| serde_json::to_value(a).unwrap_or_default())
1206            .collect();
1207        token_obj.insert("access".to_string(), serde_json::Value::Array(access_json));
1208
1209        tokens.insert(new_value, new_token);
1210        drop(tokens);
1211
1212        Ok(serde_json::Value::Object(token_obj))
1213    }
1214
1215    /// Introspect a token — check if it is valid and return its access rights.
1216    pub async fn introspect_token(&self, token_value: &str) -> Result<Option<serde_json::Value>> {
1217        let tokens = self.issued_tokens.read().await;
1218        let token = match tokens.get(token_value) {
1219            Some(t) => t,
1220            None => return Ok(None),
1221        };
1222
1223        let now = std::time::SystemTime::now()
1224            .duration_since(std::time::UNIX_EPOCH)
1225            .unwrap_or_default()
1226            .as_secs();
1227
1228        if now >= token.expires_at {
1229            return Ok(None);
1230        }
1231
1232        let access_json: Vec<serde_json::Value> = token
1233            .access
1234            .iter()
1235            .map(|a| serde_json::to_value(a).unwrap_or_default())
1236            .collect();
1237
1238        let mut result = serde_json::Map::new();
1239        result.insert("active".to_string(), serde_json::Value::Bool(true));
1240        result.insert("access".to_string(), serde_json::Value::Array(access_json));
1241        result.insert(
1242            "expires_in".to_string(),
1243            serde_json::Value::Number((token.expires_at - now).into()),
1244        );
1245        if let Some(ref tp) = token.key_thumbprint {
1246            result.insert(
1247                "key_thumbprint".to_string(),
1248                serde_json::Value::String(tp.clone()),
1249            );
1250        }
1251        result.insert(
1252            "key_bound".to_string(),
1253            serde_json::Value::Bool(token.key_thumbprint.is_some()),
1254        );
1255
1256        Ok(Some(serde_json::Value::Object(result)))
1257    }
1258
1259    /// Validate that a key-bound token is being used with the correct key.
1260    ///
1261    /// For tokens issued with a client key binding, verify that the
1262    /// presenting client's JWK thumbprint matches the stored binding.
1263    /// Returns `Ok(true)` if the token is not key-bound (no restriction).
1264    pub async fn validate_token_key_binding(
1265        &self,
1266        token_value: &str,
1267        presenting_jwk: &GnapJwk,
1268    ) -> Result<bool> {
1269        let tokens = self.issued_tokens.read().await;
1270        let token = match tokens.get(token_value) {
1271            Some(t) => t,
1272            None => return Err(AuthError::validation("Token not found")),
1273        };
1274
1275        let now = std::time::SystemTime::now()
1276            .duration_since(std::time::UNIX_EPOCH)
1277            .unwrap_or_default()
1278            .as_secs();
1279        if now >= token.expires_at {
1280            return Err(AuthError::validation("Token has expired"));
1281        }
1282
1283        match &token.key_thumbprint {
1284            None => Ok(true), // Not key-bound → any presenter is fine
1285            Some(expected_tp) => {
1286                let presenting_tp = Self::jwk_thumbprint(presenting_jwk)?;
1287                Ok(
1288                    subtle::ConstantTimeEq::ct_eq(expected_tp.as_bytes(), presenting_tp.as_bytes())
1289                        .into(),
1290                )
1291            }
1292        }
1293    }
1294
1295    // ── Subject Info Response (draft §2.2) ───────────────────────────────
1296
1297    /// Build a subject information response based on what was requested.
1298    fn build_subject_response(
1299        request: &GnapSubjectRequest,
1300        subject_id: Option<&str>,
1301    ) -> serde_json::Map<String, serde_json::Value> {
1302        let mut resp = serde_json::Map::new();
1303
1304        // Return sub_ids in requested formats
1305        if let Some(sid) = subject_id {
1306            let mut sub_ids = Vec::new();
1307            for fmt in &request.sub_id_formats {
1308                match fmt.as_str() {
1309                    "opaque" => {
1310                        sub_ids.push(serde_json::json!({
1311                            "format": "opaque",
1312                            "id": sid,
1313                        }));
1314                    }
1315                    "email" => {
1316                        // Only include if the subject ID looks like an email
1317                        if sid.contains('@') {
1318                            sub_ids.push(serde_json::json!({
1319                                "format": "email",
1320                                "email": sid,
1321                            }));
1322                        }
1323                    }
1324                    "iss_sub" => {
1325                        sub_ids.push(serde_json::json!({
1326                            "format": "iss_sub",
1327                            "iss": "self",
1328                            "sub": sid,
1329                        }));
1330                    }
1331                    _ => {} // Unknown format — skip
1332                }
1333            }
1334            if sub_ids.is_empty() {
1335                // Default to opaque if no recognized format
1336                sub_ids.push(serde_json::json!({
1337                    "format": "opaque",
1338                    "id": sid,
1339                }));
1340            }
1341            resp.insert("sub_ids".to_string(), serde_json::Value::Array(sub_ids));
1342        }
1343
1344        resp
1345    }
1346
1347    // ── Cleanup ──────────────────────────────────────────────────────────
1348
1349    /// Remove expired transactions from the in-memory store.
1350    pub async fn cleanup_expired_transactions(&self) {
1351        let now = std::time::SystemTime::now()
1352            .duration_since(std::time::UNIX_EPOCH)
1353            .unwrap_or_default()
1354            .as_secs();
1355        let lifetime = self.config.transaction_lifetime_secs;
1356        self.transactions
1357            .write()
1358            .await
1359            .retain(|_, t| now.saturating_sub(t.created_at) <= lifetime);
1360    }
1361
1362    /// Remove expired access tokens from the in-memory store.
1363    pub async fn cleanup_expired_tokens(&self) {
1364        let now = std::time::SystemTime::now()
1365            .duration_since(std::time::UNIX_EPOCH)
1366            .unwrap_or_default()
1367            .as_secs();
1368        self.issued_tokens
1369            .write()
1370            .await
1371            .retain(|_, t| now < t.expires_at);
1372    }
1373}
1374
1375#[cfg(test)]
1376mod tests {
1377    use super::*;
1378
1379    fn test_config() -> GnapConfig {
1380        GnapConfig {
1381            enabled: true,
1382            transaction_endpoint: "/api/gnap/tx".to_string(),
1383            interaction_base_url: Some("https://auth.example.test".to_string()),
1384            token_lifetime_secs: 3600,
1385            transaction_lifetime_secs: 600,
1386        }
1387    }
1388
1389    fn test_ec_jwk() -> GnapJwk {
1390        GnapJwk {
1391            kty: "EC".to_string(),
1392            kid: Some("test-key-1".to_string()),
1393            crv: Some("P-256".to_string()),
1394            x: Some("f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU".to_string()),
1395            y: Some("x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0".to_string()),
1396            n: None,
1397            e: None,
1398        }
1399    }
1400
1401    fn test_rsa_jwk() -> GnapJwk {
1402        GnapJwk {
1403            kty: "RSA".to_string(),
1404            kid: Some("test-rsa-1".to_string()),
1405            crv: None,
1406            x: None,
1407            y: None,
1408            n: Some("0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM".to_string()),
1409            e: Some("AQAB".to_string()),
1410        }
1411    }
1412
1413    fn test_client_info(jwk: GnapJwk) -> GnapClientInfo {
1414        GnapClientInfo {
1415            key: Some(GnapClientKey {
1416                proof: "test".to_string(),
1417                jwk,
1418            }),
1419            display: Some(GnapClientDisplay {
1420                name: Some("Test Client".to_string()),
1421                uri: Some("https://client.example.test".to_string()),
1422            }),
1423        }
1424    }
1425
1426    // ── Config & Construction ────────────────────────────────────────────
1427
1428    #[test]
1429    fn test_gnap_config_defaults() {
1430        let config = GnapConfig::default();
1431        assert!(!config.enabled);
1432        assert_eq!(config.token_lifetime_secs, 3600);
1433        assert_eq!(config.transaction_lifetime_secs, 600);
1434        assert!(config.interaction_base_url.is_none());
1435    }
1436
1437    #[test]
1438    fn test_gnap_service_creation() {
1439        let service = GnapService::new(test_config());
1440        assert!(service.config.enabled);
1441    }
1442
1443    // ── JWK Thumbprint (RFC 7638) ────────────────────────────────────────
1444
1445    #[test]
1446    fn test_jwk_thumbprint_ec() {
1447        let jwk = test_ec_jwk();
1448        let tp = GnapService::jwk_thumbprint(&jwk).unwrap();
1449        assert!(!tp.is_empty());
1450        // Thumbprint is base64url-encoded SHA-256 → 43 chars
1451        assert_eq!(tp.len(), 43);
1452    }
1453
1454    #[test]
1455    fn test_jwk_thumbprint_rsa() {
1456        let jwk = test_rsa_jwk();
1457        let tp = GnapService::jwk_thumbprint(&jwk).unwrap();
1458        assert!(!tp.is_empty());
1459        assert_eq!(tp.len(), 43);
1460    }
1461
1462    #[test]
1463    fn test_jwk_thumbprint_deterministic() {
1464        let jwk = test_ec_jwk();
1465        let tp1 = GnapService::jwk_thumbprint(&jwk).unwrap();
1466        let tp2 = GnapService::jwk_thumbprint(&jwk).unwrap();
1467        assert_eq!(tp1, tp2);
1468    }
1469
1470    #[test]
1471    fn test_jwk_thumbprint_different_keys() {
1472        let tp_ec = GnapService::jwk_thumbprint(&test_ec_jwk()).unwrap();
1473        let tp_rsa = GnapService::jwk_thumbprint(&test_rsa_jwk()).unwrap();
1474        assert_ne!(tp_ec, tp_rsa);
1475    }
1476
1477    #[test]
1478    fn test_jwk_thumbprint_unsupported_type() {
1479        let jwk = GnapJwk {
1480            kty: "UNKNOWN".to_string(),
1481            kid: None,
1482            crv: None,
1483            x: None,
1484            y: None,
1485            n: None,
1486            e: None,
1487        };
1488        assert!(GnapService::jwk_thumbprint(&jwk).is_err());
1489    }
1490
1491    // ── Client Key Validation ────────────────────────────────────────────
1492
1493    #[test]
1494    fn test_validate_client_key_ec() {
1495        let client = Some(test_client_info(test_ec_jwk()));
1496        let tp = GnapService::validate_client_key(&client).unwrap();
1497        assert!(tp.is_some());
1498    }
1499
1500    #[test]
1501    fn test_validate_client_key_rsa() {
1502        let client = Some(test_client_info(test_rsa_jwk()));
1503        let tp = GnapService::validate_client_key(&client).unwrap();
1504        assert!(tp.is_some());
1505    }
1506
1507    #[test]
1508    fn test_validate_client_key_none() {
1509        let tp = GnapService::validate_client_key(&None).unwrap();
1510        assert!(tp.is_none());
1511    }
1512
1513    #[test]
1514    fn test_validate_client_key_no_key() {
1515        let client = Some(GnapClientInfo {
1516            key: None,
1517            display: None,
1518        });
1519        let tp = GnapService::validate_client_key(&client).unwrap();
1520        assert!(tp.is_none());
1521    }
1522
1523    #[test]
1524    fn test_validate_client_key_invalid_proof_method() {
1525        let client = Some(GnapClientInfo {
1526            key: Some(GnapClientKey {
1527                proof: "invalid_method".to_string(),
1528                jwk: test_ec_jwk(),
1529            }),
1530            display: None,
1531        });
1532        assert!(GnapService::validate_client_key(&client).is_err());
1533    }
1534
1535    #[test]
1536    fn test_validate_client_key_ec_missing_y() {
1537        let mut jwk = test_ec_jwk();
1538        jwk.y = None;
1539        let client = Some(test_client_info(jwk));
1540        assert!(GnapService::validate_client_key(&client).is_err());
1541    }
1542
1543    #[test]
1544    fn test_validate_client_key_rsa_missing_e() {
1545        let mut jwk = test_rsa_jwk();
1546        jwk.e = None;
1547        let client = Some(test_client_info(jwk));
1548        assert!(GnapService::validate_client_key(&client).is_err());
1549    }
1550
1551    #[test]
1552    fn test_validate_client_key_with_proof_test_mode() {
1553        let client = Some(test_client_info(test_ec_jwk()));
1554        let tp = GnapService::validate_client_key_with_proof(&client, None, None).unwrap();
1555        assert!(tp.is_some());
1556    }
1557
1558    // ── Interaction Hash ─────────────────────────────────────────────────
1559
1560    #[test]
1561    fn test_compute_interact_hash_deterministic() {
1562        let h1 = GnapService::compute_interact_hash("cn1", "sn1", "ref1", "/tx");
1563        let h2 = GnapService::compute_interact_hash("cn1", "sn1", "ref1", "/tx");
1564        assert_eq!(h1, h2);
1565    }
1566
1567    #[test]
1568    fn test_compute_interact_hash_different_inputs() {
1569        let h1 = GnapService::compute_interact_hash("cn1", "sn1", "ref1", "/tx");
1570        let h2 = GnapService::compute_interact_hash("cn2", "sn1", "ref1", "/tx");
1571        assert_ne!(h1, h2);
1572    }
1573
1574    // ── Transaction Lifecycle ────────────────────────────────────────────
1575
1576    #[tokio::test]
1577    async fn test_transaction_disabled() {
1578        let mut config = test_config();
1579        config.enabled = false;
1580        let service = GnapService::new(config);
1581        let req = GnapTransactionRequest {
1582            client: None,
1583            interact: None,
1584            access_token: Some(vec![GnapAccessRequest {
1585                access_type: "read".to_string(),
1586                actions: vec![],
1587                locations: vec![],
1588            }]),
1589            subject: None,
1590        };
1591        assert!(service.handle_transaction(req).await.is_err());
1592    }
1593
1594    #[tokio::test]
1595    async fn test_transaction_requires_access_or_subject() {
1596        let service = GnapService::new(test_config());
1597        let req = GnapTransactionRequest {
1598            client: None,
1599            interact: None,
1600            access_token: None,
1601            subject: None,
1602        };
1603        assert!(service.handle_transaction(req).await.is_err());
1604    }
1605
1606    #[tokio::test]
1607    async fn test_transaction_direct_token_issuance() {
1608        let service = GnapService::new(test_config());
1609        let req = GnapTransactionRequest {
1610            client: Some(test_client_info(test_ec_jwk())),
1611            interact: None,
1612            access_token: Some(vec![GnapAccessRequest {
1613                access_type: "read".to_string(),
1614                actions: vec!["list".to_string()],
1615                locations: vec!["https://api.test/resources".to_string()],
1616            }]),
1617            subject: None,
1618        };
1619        let resp = service.handle_transaction(req).await.unwrap();
1620        let obj = resp.as_object().unwrap();
1621        assert!(obj.contains_key("access_token"));
1622        assert!(obj.contains_key("continue"));
1623
1624        let token_obj = obj["access_token"].as_object().unwrap();
1625        assert!(token_obj.contains_key("value"));
1626        assert!(token_obj.contains_key("expires_in"));
1627        assert!(token_obj.contains_key("manage"));
1628        assert_eq!(token_obj.get("key").and_then(|v| v.as_bool()), Some(true));
1629    }
1630
1631    #[tokio::test]
1632    async fn test_transaction_with_interaction() {
1633        let service = GnapService::new(test_config());
1634        let req = GnapTransactionRequest {
1635            client: Some(test_client_info(test_ec_jwk())),
1636            interact: Some(GnapInteractionRequirements {
1637                start: vec!["redirect".to_string()],
1638                finish: Some(GnapInteractionFinish {
1639                    method: "redirect".to_string(),
1640                    uri: "https://client.test/callback".to_string(),
1641                    nonce: "client-nonce-123".to_string(),
1642                }),
1643            }),
1644            access_token: Some(vec![GnapAccessRequest {
1645                access_type: "write".to_string(),
1646                actions: vec![],
1647                locations: vec![],
1648            }]),
1649            subject: None,
1650        };
1651        let resp = service.handle_transaction(req).await.unwrap();
1652        let obj = resp.as_object().unwrap();
1653        assert!(obj.contains_key("interact"));
1654        assert!(obj.contains_key("continue"));
1655
1656        let interact = obj["interact"].as_object().unwrap();
1657        assert!(interact.contains_key("redirect"));
1658        assert!(interact.contains_key("finish"));
1659    }
1660
1661    #[tokio::test]
1662    async fn test_transaction_subject_only() {
1663        let service = GnapService::new(test_config());
1664        let req = GnapTransactionRequest {
1665            client: None,
1666            interact: None,
1667            access_token: None,
1668            subject: Some(GnapSubjectRequest {
1669                sub_id_formats: vec!["opaque".to_string()],
1670                assertion_formats: vec![],
1671            }),
1672        };
1673        let resp = service.handle_transaction(req).await.unwrap();
1674        let obj = resp.as_object().unwrap();
1675        assert!(obj.contains_key("subject"));
1676    }
1677
1678    // ── Approve / Deny / Continue ────────────────────────────────────────
1679
1680    #[tokio::test]
1681    async fn test_approve_and_continue() {
1682        let service = GnapService::new(test_config());
1683
1684        // Create interactive transaction
1685        let req = GnapTransactionRequest {
1686            client: Some(test_client_info(test_ec_jwk())),
1687            interact: Some(GnapInteractionRequirements {
1688                start: vec!["redirect".to_string()],
1689                finish: None,
1690            }),
1691            access_token: Some(vec![GnapAccessRequest {
1692                access_type: "read".to_string(),
1693                actions: vec![],
1694                locations: vec![],
1695            }]),
1696            subject: None,
1697        };
1698        let resp = service.handle_transaction(req).await.unwrap();
1699        let cont = resp["continue"]["access_token"]["value"].as_str().unwrap();
1700
1701        // Get transaction ID from the stored transactions
1702        let txn_id = {
1703            let txns = service.transactions.read().await;
1704            txns.keys().next().unwrap().clone()
1705        };
1706
1707        // Continue before approval → pending
1708        let poll = service
1709            .continue_transaction(&txn_id, cont, None, None)
1710            .await;
1711        assert!(
1712            poll.is_err() || {
1713                let r = poll.unwrap();
1714                r.as_object().unwrap().contains_key("continue")
1715            }
1716        );
1717
1718        // Get updated continuation token
1719        let new_cont = {
1720            let txns = service.transactions.read().await;
1721            txns.get(&txn_id).unwrap().continue_token.clone()
1722        };
1723
1724        // Approve
1725        service
1726            .approve_transaction(&txn_id, Some("user-42"))
1727            .await
1728            .unwrap();
1729
1730        // Continue after approval → get token
1731        let result = service
1732            .continue_transaction(&txn_id, &new_cont, None, None)
1733            .await
1734            .unwrap();
1735        assert!(result.as_object().unwrap().contains_key("access_token"));
1736    }
1737
1738    #[tokio::test]
1739    async fn test_deny_transaction() {
1740        let service = GnapService::new(test_config());
1741        let req = GnapTransactionRequest {
1742            client: None,
1743            interact: Some(GnapInteractionRequirements {
1744                start: vec!["redirect".to_string()],
1745                finish: None,
1746            }),
1747            access_token: Some(vec![GnapAccessRequest {
1748                access_type: "read".to_string(),
1749                actions: vec![],
1750                locations: vec![],
1751            }]),
1752            subject: None,
1753        };
1754        service.handle_transaction(req).await.unwrap();
1755        let txn_id = {
1756            let txns = service.transactions.read().await;
1757            txns.keys().next().unwrap().clone()
1758        };
1759
1760        service.deny_transaction(&txn_id).await.unwrap();
1761
1762        let cont = {
1763            let txns = service.transactions.read().await;
1764            txns.get(&txn_id).unwrap().continue_token.clone()
1765        };
1766        let result = service
1767            .continue_transaction(&txn_id, &cont, None, None)
1768            .await;
1769        assert!(result.is_err());
1770    }
1771
1772    #[tokio::test]
1773    async fn test_continue_invalid_token() {
1774        let service = GnapService::new(test_config());
1775        let req = GnapTransactionRequest {
1776            client: None,
1777            interact: Some(GnapInteractionRequirements {
1778                start: vec!["redirect".to_string()],
1779                finish: None,
1780            }),
1781            access_token: Some(vec![GnapAccessRequest {
1782                access_type: "read".to_string(),
1783                actions: vec![],
1784                locations: vec![],
1785            }]),
1786            subject: None,
1787        };
1788        service.handle_transaction(req).await.unwrap();
1789        let txn_id = {
1790            let txns = service.transactions.read().await;
1791            txns.keys().next().unwrap().clone()
1792        };
1793        let result = service
1794            .continue_transaction(&txn_id, "bad-token", None, None)
1795            .await;
1796        assert!(result.is_err());
1797    }
1798
1799    // ── Token Management ─────────────────────────────────────────────────
1800
1801    #[tokio::test]
1802    async fn test_token_revocation() {
1803        let service = GnapService::new(test_config());
1804        let req = GnapTransactionRequest {
1805            client: None,
1806            interact: None,
1807            access_token: Some(vec![GnapAccessRequest {
1808                access_type: "read".to_string(),
1809                actions: vec![],
1810                locations: vec![],
1811            }]),
1812            subject: None,
1813        };
1814        let resp = service.handle_transaction(req).await.unwrap();
1815        let token_value = resp["access_token"]["value"].as_str().unwrap();
1816
1817        // Small delay so the spawned insert task completes
1818        tokio::task::yield_now().await;
1819        tokio::task::yield_now().await;
1820
1821        // Introspect before revocation
1822        let info = service.introspect_token(token_value).await.unwrap();
1823        assert!(info.is_some());
1824        assert_eq!(info.as_ref().unwrap()["active"], true);
1825
1826        // Revoke
1827        service.revoke_token(token_value).await.unwrap();
1828
1829        // Introspect after revocation
1830        let info = service.introspect_token(token_value).await.unwrap();
1831        assert!(info.is_none());
1832    }
1833
1834    #[tokio::test]
1835    async fn test_token_rotation() {
1836        let service = GnapService::new(test_config());
1837        let req = GnapTransactionRequest {
1838            client: None,
1839            interact: None,
1840            access_token: Some(vec![GnapAccessRequest {
1841                access_type: "write".to_string(),
1842                actions: vec!["create".to_string()],
1843                locations: vec![],
1844            }]),
1845            subject: None,
1846        };
1847        let resp = service.handle_transaction(req).await.unwrap();
1848        let old_token = resp["access_token"]["value"].as_str().unwrap().to_string();
1849
1850        // Wait for spawned insert
1851        tokio::task::yield_now().await;
1852        tokio::task::yield_now().await;
1853
1854        // Rotate
1855        let new_resp = service.rotate_token(&old_token).await.unwrap();
1856        let new_token = new_resp["value"].as_str().unwrap();
1857        assert_ne!(old_token, new_token);
1858
1859        // Old token should be gone
1860        let old_info = service.introspect_token(&old_token).await.unwrap();
1861        assert!(old_info.is_none());
1862
1863        // New token should be active
1864        let new_info = service.introspect_token(new_token).await.unwrap();
1865        assert!(new_info.is_some());
1866        assert_eq!(new_info.unwrap()["active"], true);
1867    }
1868
1869    #[tokio::test]
1870    async fn test_revoke_nonexistent_token() {
1871        let service = GnapService::new(test_config());
1872        assert!(service.revoke_token("nonexistent").await.is_err());
1873    }
1874
1875    #[tokio::test]
1876    async fn test_introspect_nonexistent_token() {
1877        let service = GnapService::new(test_config());
1878        let info = service.introspect_token("nonexistent").await.unwrap();
1879        assert!(info.is_none());
1880    }
1881
1882    // ── Key Binding Verification ─────────────────────────────────────────
1883
1884    #[tokio::test]
1885    async fn test_token_key_binding_check() {
1886        let service = GnapService::new(test_config());
1887        let ec_jwk = test_ec_jwk();
1888        let req = GnapTransactionRequest {
1889            client: Some(test_client_info(ec_jwk.clone())),
1890            interact: None,
1891            access_token: Some(vec![GnapAccessRequest {
1892                access_type: "read".to_string(),
1893                actions: vec![],
1894                locations: vec![],
1895            }]),
1896            subject: None,
1897        };
1898        let resp = service.handle_transaction(req).await.unwrap();
1899        let token_value = resp["access_token"]["value"].as_str().unwrap();
1900
1901        tokio::task::yield_now().await;
1902        tokio::task::yield_now().await;
1903
1904        // Same key → should pass
1905        let ok = service
1906            .validate_token_key_binding(token_value, &ec_jwk)
1907            .await
1908            .unwrap();
1909        assert!(ok);
1910
1911        // Different key → should fail
1912        let other_jwk = test_rsa_jwk();
1913        let bad = service
1914            .validate_token_key_binding(token_value, &other_jwk)
1915            .await
1916            .unwrap();
1917        assert!(!bad);
1918    }
1919
1920    // ── Subject Info ─────────────────────────────────────────────────────
1921
1922    #[test]
1923    fn test_build_subject_response_opaque() {
1924        let req = GnapSubjectRequest {
1925            sub_id_formats: vec!["opaque".to_string()],
1926            assertion_formats: vec![],
1927        };
1928        let resp = GnapService::build_subject_response(&req, Some("user-42"));
1929        let sub_ids = resp["sub_ids"].as_array().unwrap();
1930        assert_eq!(sub_ids.len(), 1);
1931        assert_eq!(sub_ids[0]["format"], "opaque");
1932        assert_eq!(sub_ids[0]["id"], "user-42");
1933    }
1934
1935    #[test]
1936    fn test_build_subject_response_email() {
1937        let req = GnapSubjectRequest {
1938            sub_id_formats: vec!["email".to_string()],
1939            assertion_formats: vec![],
1940        };
1941        let resp = GnapService::build_subject_response(&req, Some("user@example.test"));
1942        let sub_ids = resp["sub_ids"].as_array().unwrap();
1943        assert_eq!(sub_ids.len(), 1);
1944        assert_eq!(sub_ids[0]["format"], "email");
1945    }
1946
1947    #[test]
1948    fn test_build_subject_response_email_not_email() {
1949        let req = GnapSubjectRequest {
1950            sub_id_formats: vec!["email".to_string()],
1951            assertion_formats: vec![],
1952        };
1953        // Subject is not an email → defaults to opaque
1954        let resp = GnapService::build_subject_response(&req, Some("user-42"));
1955        let sub_ids = resp["sub_ids"].as_array().unwrap();
1956        assert_eq!(sub_ids[0]["format"], "opaque");
1957    }
1958
1959    #[test]
1960    fn test_build_subject_response_iss_sub() {
1961        let req = GnapSubjectRequest {
1962            sub_id_formats: vec!["iss_sub".to_string()],
1963            assertion_formats: vec![],
1964        };
1965        let resp = GnapService::build_subject_response(&req, Some("user-42"));
1966        let sub_ids = resp["sub_ids"].as_array().unwrap();
1967        assert_eq!(sub_ids[0]["format"], "iss_sub");
1968        assert_eq!(sub_ids[0]["sub"], "user-42");
1969    }
1970
1971    #[test]
1972    fn test_build_subject_response_no_subject() {
1973        let req = GnapSubjectRequest {
1974            sub_id_formats: vec!["opaque".to_string()],
1975            assertion_formats: vec![],
1976        };
1977        let resp = GnapService::build_subject_response(&req, None);
1978        assert!(!resp.contains_key("sub_ids"));
1979    }
1980
1981    // ── Continuation Token Rotation ──────────────────────────────────────
1982
1983    #[tokio::test]
1984    async fn test_continuation_token_rotates() {
1985        let service = GnapService::new(test_config());
1986        let req = GnapTransactionRequest {
1987            client: None,
1988            interact: Some(GnapInteractionRequirements {
1989                start: vec!["redirect".to_string()],
1990                finish: None,
1991            }),
1992            access_token: Some(vec![GnapAccessRequest {
1993                access_type: "read".to_string(),
1994                actions: vec![],
1995                locations: vec![],
1996            }]),
1997            subject: None,
1998        };
1999        let resp = service.handle_transaction(req).await.unwrap();
2000        let cont1 = resp["continue"]["access_token"]["value"]
2001            .as_str()
2002            .unwrap()
2003            .to_string();
2004
2005        let txn_id = {
2006            let txns = service.transactions.read().await;
2007            txns.keys().next().unwrap().clone()
2008        };
2009
2010        // First continue → token is rotated
2011        let _ = service
2012            .continue_transaction(&txn_id, &cont1, None, None)
2013            .await;
2014
2015        let cont2 = {
2016            let txns = service.transactions.read().await;
2017            txns.get(&txn_id).unwrap().continue_token.clone()
2018        };
2019        assert_ne!(cont1, cont2, "Continuation token must rotate on each use");
2020
2021        // Old token should not work
2022        let reuse = service
2023            .continue_transaction(&txn_id, &cont1, None, None)
2024            .await;
2025        assert!(reuse.is_err(), "Old continuation token must be rejected");
2026    }
2027
2028    // ── Cleanup ──────────────────────────────────────────────────────────
2029
2030    #[tokio::test]
2031    async fn test_cleanup_expired_transactions() {
2032        let mut config = test_config();
2033        config.transaction_lifetime_secs = 1; // 1 second lifetime
2034        let service = GnapService::new(config);
2035
2036        let req = GnapTransactionRequest {
2037            client: None,
2038            interact: Some(GnapInteractionRequirements {
2039                start: vec!["redirect".to_string()],
2040                finish: None,
2041            }),
2042            access_token: Some(vec![GnapAccessRequest {
2043                access_type: "read".to_string(),
2044                actions: vec![],
2045                locations: vec![],
2046            }]),
2047            subject: None,
2048        };
2049        service.handle_transaction(req).await.unwrap();
2050        assert_eq!(service.transactions.read().await.len(), 1);
2051
2052        // Manually backdate the transaction so it appears expired
2053        {
2054            let mut txns = service.transactions.write().await;
2055            for txn in txns.values_mut() {
2056                txn.created_at = txn.created_at.saturating_sub(10);
2057            }
2058        }
2059
2060        service.cleanup_expired_transactions().await;
2061        assert_eq!(service.transactions.read().await.len(), 0);
2062    }
2063
2064    // ── Interaction Hash Verification ────────────────────────────────────
2065
2066    #[tokio::test]
2067    async fn test_interaction_hash_verification() {
2068        let service = GnapService::new(test_config());
2069        let client_nonce = "client-nonce-abc";
2070        let req = GnapTransactionRequest {
2071            client: None,
2072            interact: Some(GnapInteractionRequirements {
2073                start: vec!["redirect".to_string()],
2074                finish: Some(GnapInteractionFinish {
2075                    method: "redirect".to_string(),
2076                    uri: "https://client.test/cb".to_string(),
2077                    nonce: client_nonce.to_string(),
2078                }),
2079            }),
2080            access_token: Some(vec![GnapAccessRequest {
2081                access_type: "read".to_string(),
2082                actions: vec![],
2083                locations: vec![],
2084            }]),
2085            subject: None,
2086        };
2087        service.handle_transaction(req).await.unwrap();
2088
2089        let (txn_id, cont, server_nonce) = {
2090            let txns = service.transactions.read().await;
2091            let (id, txn) = txns.iter().next().unwrap();
2092            (
2093                id.clone(),
2094                txn.continue_token.clone(),
2095                txn.interact_nonce.clone().unwrap(),
2096            )
2097        };
2098
2099        let interact_ref = "test-interact-ref";
2100        let correct_hash = GnapService::compute_interact_hash(
2101            client_nonce,
2102            &server_nonce,
2103            interact_ref,
2104            &service.config.transaction_endpoint,
2105        );
2106
2107        // Wrong hash → fails
2108        let bad = service
2109            .continue_transaction(&txn_id, &cont, Some(interact_ref), Some("bad-hash"))
2110            .await;
2111        assert!(bad.is_err());
2112
2113        // The failed attempt did not use up the continuation token: the same token still works
2114        let good = service
2115            .continue_transaction(&txn_id, &cont, Some(interact_ref), Some(&correct_hash))
2116            .await;
2117        assert!(good.is_ok());
2118    }
2119
2120    /// A pending transaction that asks for an interaction hash, with the client nonce, the
2121    /// transaction id, its continuation token and the correct hash for `interact_ref`.
2122    async fn interact_transaction(
2123        service: &GnapService,
2124        interact_ref: &str,
2125    ) -> (String, String, String) {
2126        let client_nonce = "client-nonce-abc";
2127        let req = GnapTransactionRequest {
2128            client: None,
2129            interact: Some(GnapInteractionRequirements {
2130                start: vec!["redirect".to_string()],
2131                finish: Some(GnapInteractionFinish {
2132                    method: "redirect".to_string(),
2133                    uri: "https://client.test/cb".to_string(),
2134                    nonce: client_nonce.to_string(),
2135                }),
2136            }),
2137            access_token: Some(vec![GnapAccessRequest {
2138                access_type: "read".to_string(),
2139                actions: vec![],
2140                locations: vec![],
2141            }]),
2142            subject: None,
2143        };
2144        service.handle_transaction(req).await.unwrap();
2145        let txns = service.transactions.read().await;
2146        let (id, txn) = txns.iter().next().unwrap();
2147        let hash = GnapService::compute_interact_hash(
2148            client_nonce,
2149            txn.interact_nonce.as_deref().unwrap(),
2150            interact_ref,
2151            &service.config.transaction_endpoint,
2152        );
2153        (id.clone(), txn.continue_token.clone(), hash)
2154    }
2155
2156    #[tokio::test]
2157    async fn test_failed_hash_check_does_not_use_up_the_continuation_token() {
2158        let service = GnapService::new(test_config());
2159        let (txn_id, cont, hash) = interact_transaction(&service, "ref-1").await;
2160
2161        // Same length as the real hash, one character different
2162        let mut wrong = hash.clone();
2163        wrong.pop();
2164        wrong.push(if hash.ends_with('a') { 'b' } else { 'a' });
2165        assert_eq!(wrong.len(), hash.len());
2166
2167        for _ in 0..3 {
2168            let bad = service
2169                .continue_transaction(&txn_id, &cont, Some("ref-1"), Some(&wrong))
2170                .await;
2171            assert!(bad.is_err());
2172        }
2173        // The token the client was given is the one stored
2174        let stored = service
2175            .transactions
2176            .read()
2177            .await
2178            .get(&txn_id)
2179            .unwrap()
2180            .continue_token
2181            .clone();
2182        assert_eq!(stored, cont);
2183        assert!(
2184            service
2185                .continue_transaction(&txn_id, &cont, Some("ref-1"), Some(&hash))
2186                .await
2187                .is_ok()
2188        );
2189    }
2190
2191    #[tokio::test]
2192    async fn test_every_refused_continuation_returns_the_same_message() {
2193        let service = GnapService::new(test_config());
2194        let (txn_id, cont, hash) = interact_transaction(&service, "ref-1").await;
2195
2196        let unknown = service
2197            .continue_transaction("no-such-transaction", &cont, None, None)
2198            .await
2199            .unwrap_err()
2200            .to_string();
2201        let wrong_token = service
2202            .continue_transaction(&txn_id, "not-the-token", None, None)
2203            .await
2204            .unwrap_err()
2205            .to_string();
2206        let wrong_hash = service
2207            .continue_transaction(&txn_id, &cont, Some("ref-1"), Some("not-the-hash"))
2208            .await
2209            .unwrap_err()
2210            .to_string();
2211        {
2212            let mut txns = service.transactions.write().await;
2213            txns.get_mut(&txn_id).unwrap().created_at = 0;
2214        }
2215        let expired = service
2216            .continue_transaction(&txn_id, &cont, Some("ref-1"), Some(&hash))
2217            .await
2218            .unwrap_err()
2219            .to_string();
2220
2221        assert_eq!(unknown, wrong_token);
2222        assert_eq!(unknown, wrong_hash);
2223        assert_eq!(unknown, expired);
2224        assert!(unknown.contains(INVALID_CONTINUATION));
2225    }
2226
2227    #[tokio::test]
2228    async fn test_continuation_token_must_match_exactly() {
2229        let service = GnapService::new(test_config());
2230        let (txn_id, cont, _) = interact_transaction(&service, "ref-1").await;
2231
2232        let mut near_miss = cont.clone();
2233        near_miss.pop();
2234        near_miss.push(if cont.ends_with('0') { '1' } else { '0' });
2235        let too_long = format!("{cont}0");
2236        let prefix = cont[..cont.len() - 1].to_string();
2237        for bad in [near_miss, too_long, prefix, String::new()] {
2238            assert!(
2239                service
2240                    .continue_transaction(&txn_id, &bad, None, None)
2241                    .await
2242                    .is_err(),
2243                "token {bad:?} must be refused"
2244            );
2245        }
2246        assert!(
2247            service
2248                .continue_transaction(&txn_id, &cont, None, None)
2249                .await
2250                .is_ok()
2251        );
2252    }
2253
2254    #[test]
2255    fn test_gnap_transaction_request_builder_access() {
2256        let req = GnapTransactionRequest::builder()
2257            .access("read", &["list", "get"], &["https://api.test/resources"])
2258            .build();
2259
2260        assert!(req.client.is_none());
2261        assert!(req.interact.is_none());
2262        let access = req.access_token.unwrap();
2263        assert_eq!(access.len(), 1);
2264        assert_eq!(access[0].access_type, "read");
2265        assert_eq!(access[0].actions, vec!["list", "get"]);
2266    }
2267
2268    #[test]
2269    fn test_gnap_transaction_request_builder_full() {
2270        let jwk = test_ec_jwk();
2271        let req = GnapTransactionRequest::builder()
2272            .client_key(jwk, "test")
2273            .redirect_interaction("https://client.test/cb", "nonce-123")
2274            .access_type("write")
2275            .subject_formats(vec!["opaque".into()])
2276            .build();
2277
2278        assert!(req.client.is_some());
2279        assert!(req.interact.is_some());
2280        assert!(req.access_token.is_some());
2281        assert!(req.subject.is_some());
2282        assert_eq!(req.subject.unwrap().sub_id_formats, vec!["opaque"]);
2283    }
2284
2285    #[test]
2286    fn test_gnap_transaction_request_builder_empty() {
2287        let req = GnapTransactionRequest::builder().build();
2288        assert!(req.client.is_none());
2289        assert!(req.interact.is_none());
2290        assert!(req.access_token.is_none());
2291        assert!(req.subject.is_none());
2292    }
2293}
2294
2295/// A client key's proof is verified or refused: no proof that was never checked authorizes a
2296/// request. Each refusal is paired with the accepted case built the same way, so a test cannot
2297/// pass because every request fails for one shared reason.
2298#[cfg(test)]
2299mod proof_verification_tests {
2300    use super::*;
2301    use crate::security::secure_jwt::{SecureJwtConfig, SecureJwtValidator};
2302    use jsonwebtoken::{Algorithm, EncodingKey};
2303    use serde_json::json;
2304
2305    const URI: &str = "https://as.example.test/api/gnap/tx";
2306    const CONTINUE_URI: &str = "https://as.example.test/api/gnap/tx/continue";
2307
2308    struct ClientKey {
2309        signing: EncodingKey,
2310        jwk: GnapJwk,
2311    }
2312
2313    fn client_key() -> ClientKey {
2314        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
2315        let raw = key.public_key_raw();
2316        let point = &raw[raw.len() - 65..];
2317        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
2318        ClientKey {
2319            signing: EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
2320            jwk: GnapJwk {
2321                kty: "EC".to_string(),
2322                kid: None,
2323                crv: Some("P-256".to_string()),
2324                x: Some(b64.encode(&point[1..33])),
2325                y: Some(b64.encode(&point[33..65])),
2326                n: None,
2327                e: None,
2328            },
2329        }
2330    }
2331
2332    /// A DPoP proof for `htm` `htu`, signed by `signer` and naming `named` in its header.
2333    fn dpop_header(
2334        signer: &ClientKey,
2335        named: &ClientKey,
2336        htm: &str,
2337        htu: &str,
2338        jti: &str,
2339    ) -> String {
2340        let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
2341        let jwk = serde_json::to_value(&named.jwk).unwrap();
2342        let header = json!({"typ": "dpop+jwt", "alg": "ES256", "jwk": jwk});
2343        let claims = json!({
2344            "jti": jti, "htm": htm, "htu": htu, "iat": chrono::Utc::now().timestamp()
2345        });
2346        let si = format!(
2347            "{}.{}",
2348            b64.encode(header.to_string()),
2349            b64.encode(claims.to_string())
2350        );
2351        let sig =
2352            jsonwebtoken::crypto::sign(si.as_bytes(), &signer.signing, Algorithm::ES256).unwrap();
2353        format!("{si}.{sig}")
2354    }
2355
2356    fn manager() -> DpopManager {
2357        DpopManager::new(SecureJwtValidator::new(SecureJwtConfig::default()).unwrap())
2358    }
2359
2360    fn service() -> GnapService {
2361        GnapService::new(GnapConfig {
2362            enabled: true,
2363            transaction_endpoint: "/api/gnap/tx".to_string(),
2364            interaction_base_url: Some("https://as.example.test".to_string()),
2365            token_lifetime_secs: 3600,
2366            transaction_lifetime_secs: 600,
2367        })
2368    }
2369
2370    fn request(key: &ClientKey, proof: &str, interact: bool) -> GnapTransactionRequest {
2371        let mut builder = GnapTransactionRequest::builder()
2372            .client_key(key.jwk.clone(), proof)
2373            .access_type("read");
2374        if interact {
2375            builder = builder.redirect_interaction("https://client.test/cb", "client-nonce");
2376        }
2377        builder.build()
2378    }
2379
2380    fn proof<'a>(header: Option<&'a str>, uri: &'a str) -> GnapProof<'a> {
2381        GnapProof {
2382            http_method: "POST",
2383            http_uri: uri,
2384            dpop_proof: header,
2385            expected_nonce: None,
2386        }
2387    }
2388
2389    fn refusal(result: Result<serde_json::Value>) -> String {
2390        result.expect_err("the request must be refused").to_string()
2391    }
2392
2393    #[tokio::test]
2394    async fn a_dpop_proof_signed_by_the_named_key_is_accepted() {
2395        let (svc, dpop, key) = (service(), manager(), client_key());
2396        let header = dpop_header(&key, &key, "POST", URI, "jti-ok");
2397        let resp = svc
2398            .handle_transaction_with_proof(
2399                &dpop,
2400                &proof(Some(&header), URI),
2401                request(&key, "dpop", false),
2402            )
2403            .await
2404            .unwrap();
2405        assert!(resp["access_token"]["value"].is_string());
2406    }
2407
2408    #[tokio::test]
2409    async fn a_dpop_key_with_no_proof_is_refused() {
2410        let (svc, dpop, key) = (service(), manager(), client_key());
2411        // Through the entry point that takes no proof at all.
2412        let msg = refusal(svc.handle_transaction(request(&key, "dpop", false)).await);
2413        assert!(msg.contains("proof required"), "{msg}");
2414        // And through the one that does, with no DPoP header.
2415        let msg = refusal(
2416            svc.handle_transaction_with_proof(
2417                &dpop,
2418                &proof(None, URI),
2419                request(&key, "dpop", false),
2420            )
2421            .await,
2422        );
2423        assert!(msg.contains("proof required"), "{msg}");
2424    }
2425
2426    #[tokio::test]
2427    async fn a_dpop_proof_from_another_key_is_refused() {
2428        let (svc, dpop) = (service(), manager());
2429        let (victim, attacker) = (client_key(), client_key());
2430        // The attacker names the victim's key but can only sign with its own.
2431        let forged = dpop_header(&attacker, &victim, "POST", URI, "jti-forged");
2432        let msg = refusal(
2433            svc.handle_transaction_with_proof(
2434                &dpop,
2435                &proof(Some(&forged), URI),
2436                request(&victim, "dpop", false),
2437            )
2438            .await,
2439        );
2440        assert!(msg.contains("proof invalid"), "{msg}");
2441        // The attacker's own proof, naming the attacker's own key, is fine: the key is the
2442        // only thing that differs.
2443        let own = dpop_header(&attacker, &attacker, "POST", URI, "jti-own");
2444        svc.handle_transaction_with_proof(
2445            &dpop,
2446            &proof(Some(&own), URI),
2447            request(&attacker, "dpop", false),
2448        )
2449        .await
2450        .unwrap();
2451    }
2452
2453    #[tokio::test]
2454    async fn a_dpop_proof_for_another_method_or_uri_is_refused() {
2455        let (svc, dpop, key) = (service(), manager(), client_key());
2456        let other_uri = dpop_header(&key, &key, "POST", "https://other.example/tx", "jti-uri");
2457        let msg = refusal(
2458            svc.handle_transaction_with_proof(
2459                &dpop,
2460                &proof(Some(&other_uri), URI),
2461                request(&key, "dpop", false),
2462            )
2463            .await,
2464        );
2465        assert!(msg.contains("proof invalid"), "{msg}");
2466        let other_method = dpop_header(&key, &key, "GET", URI, "jti-method");
2467        let msg = refusal(
2468            svc.handle_transaction_with_proof(
2469                &dpop,
2470                &proof(Some(&other_method), URI),
2471                request(&key, "dpop", false),
2472            )
2473            .await,
2474        );
2475        assert!(msg.contains("proof invalid"), "{msg}");
2476    }
2477
2478    #[tokio::test]
2479    async fn a_dpop_proof_cannot_be_replayed() {
2480        let (svc, dpop, key) = (service(), manager(), client_key());
2481        let header = dpop_header(&key, &key, "POST", URI, "jti-once");
2482        let go = || async {
2483            svc.handle_transaction_with_proof(
2484                &dpop,
2485                &proof(Some(&header), URI),
2486                request(&key, "dpop", false),
2487            )
2488            .await
2489        };
2490        go().await.unwrap();
2491        assert!(refusal(go().await).contains("proof invalid"));
2492    }
2493
2494    #[tokio::test]
2495    async fn httpsig_mtls_and_jws_are_refused_not_accepted_unverified() {
2496        let (svc, dpop, key) = (service(), manager(), client_key());
2497        // A valid DPoP header does not rescue a method that is not DPoP.
2498        let header = dpop_header(&key, &key, "POST", URI, "jti-other-method");
2499        for method in ["httpsig", "mtls", "jws", "no-such-method"] {
2500            let msg = refusal(svc.handle_transaction(request(&key, method, false)).await);
2501            assert!(
2502                msg.contains("proof method not supported"),
2503                "{method}: {msg}"
2504            );
2505            let msg = refusal(
2506                svc.handle_transaction_with_proof(
2507                    &dpop,
2508                    &proof(Some(&header), URI),
2509                    request(&key, method, false),
2510                )
2511                .await,
2512            );
2513            assert!(
2514                msg.contains("proof method not supported"),
2515                "{method}: {msg}"
2516            );
2517        }
2518        // The same request as a client with no key still works: only a named key is refused.
2519        let anonymous = GnapTransactionRequest::builder()
2520            .access_type("read")
2521            .build();
2522        svc.handle_transaction(anonymous).await.unwrap();
2523    }
2524
2525    #[test]
2526    fn the_unit_test_proof_method_is_not_a_way_around_the_refusals() {
2527        // `validate_client_key_with_proof` has no proof to check, so it refuses a real method.
2528        let key = client_key();
2529        for method in ["dpop", "httpsig", "mtls", "jws"] {
2530            let client = Some(GnapClientInfo {
2531                key: Some(GnapClientKey {
2532                    proof: method.to_string(),
2533                    jwk: key.jwk.clone(),
2534                }),
2535                display: None,
2536            });
2537            let err = GnapService::validate_client_key_with_proof(&client, Some(b"m"), Some(b"s"))
2538                .unwrap_err()
2539                .to_string();
2540            assert!(
2541                err.contains("proof method not supported"),
2542                "{method}: {err}"
2543            );
2544        }
2545    }
2546
2547    #[tokio::test]
2548    async fn a_key_bound_transaction_continues_only_with_a_proof_from_that_key() {
2549        let (svc, dpop, key) = (service(), manager(), client_key());
2550        let first = dpop_header(&key, &key, "POST", URI, "jti-start");
2551        let resp = svc
2552            .handle_transaction_with_proof(
2553                &dpop,
2554                &proof(Some(&first), URI),
2555                request(&key, "dpop", true),
2556            )
2557            .await
2558            .unwrap();
2559        let cont = resp["continue"]["access_token"]["value"]
2560            .as_str()
2561            .unwrap()
2562            .to_string();
2563        let txn_id = svc.transactions.read().await.keys().next().unwrap().clone();
2564        svc.approve_transaction(&txn_id, Some("user-1"))
2565            .await
2566            .unwrap();
2567
2568        // The continuation token alone is not enough for a key-bound transaction.
2569        let msg = refusal(svc.continue_transaction(&txn_id, &cont, None, None).await);
2570        assert!(msg.contains("proof required"), "{msg}");
2571        // Nor is a proof from another key, and neither burns the holder's token.
2572        let other = client_key();
2573        let forged = dpop_header(&other, &key, "POST", CONTINUE_URI, "jti-c-forged");
2574        let msg = refusal(
2575            svc.continue_transaction_with_proof(
2576                &dpop,
2577                &proof(Some(&forged), CONTINUE_URI),
2578                &txn_id,
2579                &cont,
2580                None,
2581                None,
2582            )
2583            .await,
2584        );
2585        assert!(msg.contains("proof invalid"), "{msg}");
2586        // The key's own proof, with the same token, completes the transaction.
2587        let good = dpop_header(&key, &key, "POST", CONTINUE_URI, "jti-c-ok");
2588        let done = svc
2589            .continue_transaction_with_proof(
2590                &dpop,
2591                &proof(Some(&good), CONTINUE_URI),
2592                &txn_id,
2593                &cont,
2594                None,
2595                None,
2596            )
2597            .await
2598            .unwrap();
2599        assert!(done["access_token"]["value"].is_string());
2600    }
2601}