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