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