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