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