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