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