Skip to main content

auth_framework/protocols/
openid4vci.rs

1//! OpenID for Verifiable Credential Issuance (OpenID4VCI).
2//!
3//! Implements the issuer-side of the OpenID4VCI specification for issuing
4//! Verifiable Credentials using OAuth 2.0 authorization flows.
5//!
6//! # Architecture
7//!
8//! - **Credential Issuer Metadata** — discovery endpoint for supported credentials
9//! - **Credential Offer** — issuer-initiated issuance flow
10//! - **Token → Credential** — exchange access tokens for VCs
11//! - **Credential format support** — `jwt_vc_json` and `ldp_vc`
12//!
13//! # References
14//!
15//! - [OpenID4VCI spec](https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html)
16
17use crate::errors::{AuthError, Result};
18use serde::{Deserialize, Serialize};
19use std::collections::HashMap;
20use std::sync::Arc;
21use std::time::{SystemTime, UNIX_EPOCH};
22use tokio::sync::RwLock;
23use uuid::Uuid;
24
25// ── Credential format ───────────────────────────────────────────────
26
27/// Supported Verifiable Credential formats.
28#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
29pub enum CredentialFormat {
30    /// JWT-based VC (W3C VC Data Model, JWT encoding).
31    #[serde(rename = "jwt_vc_json")]
32    JwtVcJson,
33    /// JSON-LD with Linked Data Proofs.
34    #[serde(rename = "ldp_vc")]
35    LdpVc,
36    /// SD-JWT VC.
37    #[serde(rename = "vc+sd-jwt")]
38    SdJwtVc,
39}
40
41// ── Issuer Metadata (§10.2) ─────────────────────────────────────────
42
43/// Credential Issuer Metadata.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct IssuerMetadata {
46    /// The Credential Issuer's identifier (URL).
47    pub credential_issuer: String,
48    /// URL of the Credential Endpoint.
49    pub credential_endpoint: String,
50    /// URL of the Batch Credential Endpoint (optional).
51    #[serde(default)]
52    pub batch_credential_endpoint: Option<String>,
53    /// Supported credential configurations.
54    pub credential_configurations_supported: HashMap<String, CredentialConfiguration>,
55    /// Display properties for the issuer.
56    #[serde(default)]
57    pub display: Vec<IssuerDisplay>,
58}
59
60impl IssuerMetadata {
61    /// Build issuer metadata from the issuer URL.
62    ///
63    /// The credential endpoint defaults to `{issuer}/credential`. Use
64    /// [`credential_endpoint`](Self::credential_endpoint) to override.
65    ///
66    /// # Example
67    /// ```rust
68    /// use auth_framework::protocols::openid4vci::*;
69    ///
70    /// let meta = IssuerMetadata::builder("https://issuer.example.com")
71    ///     .add_credential("Degree", CredentialConfiguration::new(CredentialFormat::JwtVcJson)
72    ///         .scope("degree")
73    ///         .signing_algorithms(vec!["ES256"]))
74    ///     .display("Example University", Some("en"))
75    ///     .build();
76    /// assert!(meta.credential_configurations_supported.contains_key("Degree"));
77    /// ```
78    pub fn builder(issuer: impl Into<String>) -> IssuerMetadataBuilder {
79        let issuer = issuer.into();
80        let endpoint = format!("{}/credential", issuer);
81        IssuerMetadataBuilder {
82            issuer,
83            credential_endpoint: endpoint,
84            batch_credential_endpoint: None,
85            configs: HashMap::new(),
86            display: Vec::new(),
87        }
88    }
89}
90
91/// Builder for [`IssuerMetadata`].
92pub struct IssuerMetadataBuilder {
93    issuer: String,
94    credential_endpoint: String,
95    batch_credential_endpoint: Option<String>,
96    configs: HashMap<String, CredentialConfiguration>,
97    display: Vec<IssuerDisplay>,
98}
99
100impl IssuerMetadataBuilder {
101    /// Override the credential endpoint URL.
102    pub fn credential_endpoint(mut self, url: impl Into<String>) -> Self {
103        self.credential_endpoint = url.into();
104        self
105    }
106
107    /// Set the batch credential endpoint URL.
108    pub fn batch_credential_endpoint(mut self, url: impl Into<String>) -> Self {
109        self.batch_credential_endpoint = Some(url.into());
110        self
111    }
112
113    /// Add a supported credential configuration.
114    pub fn add_credential(
115        mut self,
116        id: impl Into<String>,
117        config: CredentialConfiguration,
118    ) -> Self {
119        self.configs.insert(id.into(), config);
120        self
121    }
122
123    /// Add a display entry for the issuer.
124    pub fn display(mut self, name: impl Into<String>, locale: Option<&str>) -> Self {
125        self.display.push(IssuerDisplay {
126            name: name.into(),
127            locale: locale.map(String::from),
128        });
129        self
130    }
131
132    /// Consume the builder and produce [`IssuerMetadata`].
133    pub fn build(self) -> IssuerMetadata {
134        IssuerMetadata {
135            credential_issuer: self.issuer,
136            credential_endpoint: self.credential_endpoint,
137            batch_credential_endpoint: self.batch_credential_endpoint,
138            credential_configurations_supported: self.configs,
139            display: self.display,
140        }
141    }
142}
143
144/// Display properties for an issuer.
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct IssuerDisplay {
147    pub name: String,
148    #[serde(default)]
149    pub locale: Option<String>,
150}
151
152/// Configuration for a supported credential type.
153#[derive(Debug, Clone, Serialize, Deserialize)]
154pub struct CredentialConfiguration {
155    /// Credential format.
156    pub format: CredentialFormat,
157    /// Scope value for requesting this credential.
158    #[serde(default)]
159    pub scope: Option<String>,
160    /// Cryptographic binding methods supported.
161    #[serde(default)]
162    pub cryptographic_binding_methods_supported: Vec<String>,
163    /// Credential signing algorithms supported.
164    #[serde(default)]
165    pub credential_signing_alg_values_supported: Vec<String>,
166    /// Display properties.
167    #[serde(default)]
168    pub display: Vec<CredentialDisplay>,
169    /// Credential definition (type, claims).
170    #[serde(default)]
171    pub credential_definition: Option<CredentialDefinition>,
172}
173
174impl CredentialConfiguration {
175    /// Create a new credential configuration for the given format.
176    ///
177    /// # Example
178    /// ```rust
179    /// use auth_framework::protocols::openid4vci::{CredentialConfiguration, CredentialFormat};
180    ///
181    /// let cfg = CredentialConfiguration::new(CredentialFormat::JwtVcJson)
182    ///     .scope("degree")
183    ///     .signing_algorithms(vec!["ES256"]);
184    /// assert_eq!(cfg.format, CredentialFormat::JwtVcJson);
185    /// assert_eq!(cfg.scope.as_deref(), Some("degree"));
186    /// ```
187    pub fn new(format: CredentialFormat) -> Self {
188        Self {
189            format,
190            scope: None,
191            cryptographic_binding_methods_supported: Vec::new(),
192            credential_signing_alg_values_supported: Vec::new(),
193            display: Vec::new(),
194            credential_definition: None,
195        }
196    }
197
198    /// Set the scope value.
199    pub fn scope(mut self, scope: impl Into<String>) -> Self {
200        self.scope = Some(scope.into());
201        self
202    }
203
204    /// Set the supported cryptographic binding methods.
205    pub fn binding_methods(mut self, methods: Vec<impl Into<String>>) -> Self {
206        self.cryptographic_binding_methods_supported =
207            methods.into_iter().map(Into::into).collect();
208        self
209    }
210
211    /// Set the supported signing algorithms.
212    pub fn signing_algorithms(mut self, algs: Vec<impl Into<String>>) -> Self {
213        self.credential_signing_alg_values_supported = algs.into_iter().map(Into::into).collect();
214        self
215    }
216
217    /// Add a display entry.
218    pub fn with_display(mut self, display: CredentialDisplay) -> Self {
219        self.display.push(display);
220        self
221    }
222
223    /// Set the credential definition.
224    pub fn with_definition(mut self, definition: CredentialDefinition) -> Self {
225        self.credential_definition = Some(definition);
226        self
227    }
228}
229
230/// Display properties for a credential type.
231#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct CredentialDisplay {
233    pub name: String,
234    #[serde(default)]
235    pub locale: Option<String>,
236    #[serde(default)]
237    pub description: Option<String>,
238    #[serde(default)]
239    pub background_color: Option<String>,
240    #[serde(default)]
241    pub text_color: Option<String>,
242}
243
244/// Credential definition per the spec.
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct CredentialDefinition {
247    #[serde(rename = "type")]
248    pub types: Vec<String>,
249    #[serde(default)]
250    pub credential_subject: Option<HashMap<String, ClaimMetadata>>,
251}
252
253/// Metadata about a credential claim.
254#[derive(Debug, Clone, Serialize, Deserialize)]
255pub struct ClaimMetadata {
256    #[serde(default)]
257    pub mandatory: bool,
258    #[serde(default)]
259    pub display: Vec<ClaimDisplay>,
260}
261
262/// Display info for a claim.
263#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct ClaimDisplay {
265    pub name: String,
266    #[serde(default)]
267    pub locale: Option<String>,
268}
269
270// ── Credential Offer (§4.1) ─────────────────────────────────────────
271
272/// A Credential Offer from the issuer to the holder.
273#[derive(Debug, Clone, Serialize, Deserialize)]
274pub struct CredentialOffer {
275    /// The issuer URL.
276    pub credential_issuer: String,
277    /// List of credential configuration IDs offered.
278    pub credential_configuration_ids: Vec<String>,
279    /// Pre-authorized code grant parameters (optional).
280    #[serde(default)]
281    pub grants: Option<CredentialOfferGrants>,
282}
283
284#[derive(Debug, Clone, Serialize, Deserialize)]
285pub struct CredentialOfferGrants {
286    /// Authorization code grant.
287    #[serde(default, rename = "authorization_code")]
288    pub authorization_code: Option<AuthorizationCodeGrant>,
289    /// Pre-authorized code grant.
290    #[serde(
291        default,
292        rename = "urn:ietf:params:oauth:grant-type:pre-authorized_code"
293    )]
294    pub pre_authorized_code: Option<PreAuthorizedCodeGrant>,
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct AuthorizationCodeGrant {
299    #[serde(default)]
300    pub issuer_state: Option<String>,
301}
302
303#[derive(Clone, Serialize, Deserialize)]
304pub struct PreAuthorizedCodeGrant {
305    #[serde(rename = "pre-authorized_code")]
306    pub pre_authorized_code: String,
307    #[serde(default)]
308    pub user_pin_required: bool,
309}
310
311impl std::fmt::Debug for PreAuthorizedCodeGrant {
312    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313        let mut d = f.debug_struct("PreAuthorizedCodeGrant");
314        d.field(
315            "pre_authorized_code",
316            &crate::utils::redact::redacted(&self.pre_authorized_code),
317        );
318        d.field("user_pin_required", &self.user_pin_required);
319        d.finish()
320    }
321}
322
323// ── Credential Request (§7.2) ───────────────────────────────────────
324
325/// A credential request from the wallet/holder.
326#[derive(Debug, Clone, Serialize, Deserialize)]
327pub struct CredentialRequest {
328    /// Credential format.
329    pub format: CredentialFormat,
330    /// Credential definition (types, etc.).
331    #[serde(default)]
332    pub credential_definition: Option<CredentialDefinition>,
333    /// Proof of key possession.
334    #[serde(default)]
335    pub proof: Option<CredentialProof>,
336}
337
338/// Proof of possession in a credential request.
339#[derive(Clone, Serialize, Deserialize)]
340pub struct CredentialProof {
341    /// Proof type (e.g., "jwt").
342    pub proof_type: String,
343    /// The proof value (JWT or other).
344    #[serde(default)]
345    pub jwt: Option<String>,
346}
347
348impl std::fmt::Debug for CredentialProof {
349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350        let mut d = f.debug_struct("CredentialProof");
351        d.field("proof_type", &self.proof_type);
352        d.field("jwt", &crate::utils::redact::redacted(&self.jwt));
353        d.finish()
354    }
355}
356
357// ── Credential Response (§7.3) ──────────────────────────────────────
358
359/// Credential issuance response.
360#[derive(Clone, Serialize, Deserialize)]
361pub struct CredentialResponse {
362    /// The issued credential (format-specific).
363    #[serde(default)]
364    pub credential: Option<serde_json::Value>,
365    /// Transaction ID for deferred issuance.
366    #[serde(default)]
367    pub transaction_id: Option<String>,
368    /// Nonce for subsequent requests.
369    #[serde(default)]
370    pub c_nonce: Option<String>,
371    /// Nonce lifetime in seconds.
372    #[serde(default)]
373    pub c_nonce_expires_in: Option<u64>,
374}
375
376impl std::fmt::Debug for CredentialResponse {
377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378        let mut d = f.debug_struct("CredentialResponse");
379        d.field(
380            "credential",
381            &crate::utils::redact::redacted(&self.credential),
382        );
383        d.field("transaction_id", &self.transaction_id);
384        d.field("c_nonce", &self.c_nonce);
385        d.field("c_nonce_expires_in", &self.c_nonce_expires_in);
386        d.finish()
387    }
388}
389
390impl CredentialResponse {
391    /// Create an immediate issuance response containing the credential.
392    ///
393    /// # Example
394    /// ```rust
395    /// use auth_framework::protocols::openid4vci::CredentialResponse;
396    ///
397    /// let resp = CredentialResponse::immediate(
398    ///     serde_json::json!({"vc": "..."}),
399    ///     "nonce-abc",
400    ///     300,
401    /// );
402    /// assert!(resp.credential.is_some());
403    /// assert!(resp.transaction_id.is_none());
404    /// ```
405    pub fn immediate(
406        credential: serde_json::Value,
407        c_nonce: impl Into<String>,
408        c_nonce_expires_in: u64,
409    ) -> Self {
410        Self {
411            credential: Some(credential),
412            transaction_id: None,
413            c_nonce: Some(c_nonce.into()),
414            c_nonce_expires_in: Some(c_nonce_expires_in),
415        }
416    }
417
418    /// Create a deferred issuance response with a transaction ID.
419    ///
420    /// # Example
421    /// ```rust
422    /// use auth_framework::protocols::openid4vci::CredentialResponse;
423    ///
424    /// let resp = CredentialResponse::deferred("tx-123", "nonce-xyz", 300);
425    /// assert!(resp.credential.is_none());
426    /// assert_eq!(resp.transaction_id.as_deref(), Some("tx-123"));
427    /// ```
428    pub fn deferred(
429        transaction_id: impl Into<String>,
430        c_nonce: impl Into<String>,
431        c_nonce_expires_in: u64,
432    ) -> Self {
433        Self {
434            credential: None,
435            transaction_id: Some(transaction_id.into()),
436            c_nonce: Some(c_nonce.into()),
437            c_nonce_expires_in: Some(c_nonce_expires_in),
438        }
439    }
440
441    /// Create a completed deferred response (credential ready, no nonce needed).
442    pub fn completed(credential: serde_json::Value) -> Self {
443        Self {
444            credential: Some(credential),
445            transaction_id: None,
446            c_nonce: None,
447            c_nonce_expires_in: None,
448        }
449    }
450}
451
452// ── Credential Issuer Service ───────────────────────────────────────
453
454fn base64_url_decode(input: &str) -> Result<Vec<u8>> {
455    use base64::Engine;
456    base64::engine::general_purpose::URL_SAFE_NO_PAD
457        .decode(input)
458        .map_err(|e| AuthError::validation(format!("Base64url decode error: {e}")))
459}
460
461/// Pending credential issuance (deferred).
462struct PendingIssuance {
463    request: CredentialRequest,
464    subject_id: String,
465    created_at: u64,
466}
467
468/// OpenID4VCI Credential Issuer.
469pub struct CredentialIssuer {
470    metadata: IssuerMetadata,
471    /// Pre-authorized codes → (credential_config_id, subject_id).
472    pre_auth_codes: Arc<RwLock<HashMap<String, (String, String)>>>,
473    /// Deferred issuance: transaction_id → pending issuance.
474    deferred: Arc<RwLock<HashMap<String, PendingIssuance>>>,
475    /// Active c_nonces for proof validation.
476    nonces: Arc<RwLock<HashMap<String, u64>>>,
477}
478
479impl CredentialIssuer {
480    /// Create a new credential issuer.
481    pub fn new(metadata: IssuerMetadata) -> Self {
482        Self {
483            metadata,
484            pre_auth_codes: Arc::new(RwLock::new(HashMap::new())),
485            deferred: Arc::new(RwLock::new(HashMap::new())),
486            nonces: Arc::new(RwLock::new(HashMap::new())),
487        }
488    }
489
490    /// Get the issuer metadata (for the discovery endpoint).
491    pub fn metadata(&self) -> &IssuerMetadata {
492        &self.metadata
493    }
494
495    /// Generate a fresh c_nonce.
496    pub async fn generate_nonce(&self, lifetime_secs: u64) -> String {
497        let nonce = Uuid::new_v4().to_string();
498        let expires = SystemTime::now()
499            .duration_since(UNIX_EPOCH)
500            .unwrap_or_default()
501            .as_secs()
502            + lifetime_secs;
503        self.nonces.write().await.insert(nonce.clone(), expires);
504        nonce
505    }
506
507    /// Validate a c_nonce.
508    pub async fn validate_nonce(&self, nonce: &str) -> bool {
509        let now = SystemTime::now()
510            .duration_since(UNIX_EPOCH)
511            .unwrap_or_default()
512            .as_secs();
513        let nonces = self.nonces.read().await;
514        matches!(nonces.get(nonce), Some(&exp) if exp > now)
515    }
516
517    /// Consume a c_nonce (single use).
518    pub async fn consume_nonce(&self, nonce: &str) -> bool {
519        let now = SystemTime::now()
520            .duration_since(UNIX_EPOCH)
521            .unwrap_or_default()
522            .as_secs();
523        let mut nonces = self.nonces.write().await;
524        matches!(nonces.remove(nonce), Some(exp) if exp > now)
525    }
526
527    /// Create a credential offer with a pre-authorized code.
528    pub async fn create_offer(
529        &self,
530        credential_config_ids: Vec<String>,
531        subject_id: &str,
532    ) -> Result<CredentialOffer> {
533        if credential_config_ids.is_empty() {
534            return Err(AuthError::validation(
535                "At least one credential configuration ID is required",
536            ));
537        }
538
539        // Validate that all config IDs are supported
540        for id in &credential_config_ids {
541            if !self
542                .metadata
543                .credential_configurations_supported
544                .contains_key(id)
545            {
546                return Err(AuthError::validation(format!(
547                    "Unknown credential configuration: {id}"
548                )));
549            }
550        }
551
552        let code = Uuid::new_v4().to_string();
553        self.pre_auth_codes.write().await.insert(
554            code.clone(),
555            (credential_config_ids[0].clone(), subject_id.to_string()),
556        );
557
558        Ok(CredentialOffer {
559            credential_issuer: self.metadata.credential_issuer.clone(),
560            credential_configuration_ids: credential_config_ids,
561            grants: Some(CredentialOfferGrants {
562                authorization_code: None,
563                pre_authorized_code: Some(PreAuthorizedCodeGrant {
564                    pre_authorized_code: code,
565                    user_pin_required: false,
566                }),
567            }),
568        })
569    }
570
571    /// Validate a pre-authorized code and return (config_id, subject_id).
572    pub async fn validate_pre_auth_code(&self, code: &str) -> Result<(String, String)> {
573        self.pre_auth_codes
574            .write()
575            .await
576            .remove(code)
577            .ok_or_else(|| AuthError::validation("Invalid or expired pre-authorized code"))
578    }
579
580    /// Process a credential request and produce a response.
581    ///
582    /// This validates the request format, checks the proof if present,
583    /// and returns either the credential or a deferred transaction ID.
584    pub async fn issue_credential(
585        &self,
586        request: &CredentialRequest,
587        subject_id: &str,
588        credential_data: Option<serde_json::Value>,
589    ) -> Result<CredentialResponse> {
590        // Validate the credential format is supported
591        let supported = self
592            .metadata
593            .credential_configurations_supported
594            .values()
595            .any(|c| c.format == request.format);
596        if !supported {
597            return Err(AuthError::validation(format!(
598                "Unsupported credential format: {:?}",
599                request.format
600            )));
601        }
602
603        // If proof is provided, validate it
604        if let Some(ref proof) = request.proof {
605            self.validate_proof(proof).await?;
606        }
607
608        // Generate a new c_nonce
609        let c_nonce = self.generate_nonce(300).await;
610
611        match credential_data {
612            Some(data) => Ok(CredentialResponse::immediate(data, c_nonce, 300)),
613            None => {
614                // Deferred issuance
615                let tx_id = Uuid::new_v4().to_string();
616                let now = SystemTime::now()
617                    .duration_since(UNIX_EPOCH)
618                    .unwrap_or_default()
619                    .as_secs();
620                self.deferred.write().await.insert(
621                    tx_id.clone(),
622                    PendingIssuance {
623                        request: request.clone(),
624                        subject_id: subject_id.to_string(),
625                        created_at: now,
626                    },
627                );
628                Ok(CredentialResponse::deferred(tx_id, c_nonce, 300))
629            }
630        }
631    }
632
633    /// Validate a proof of possession JWT.
634    ///
635    /// Checks:
636    /// - `proof_type` is `"jwt"`
637    /// - JWT value is present and structurally valid (3-part compact serialization)
638    /// - c_nonce claim is present and matches a live nonce (consumed on success)
639    async fn validate_proof(&self, proof: &CredentialProof) -> Result<()> {
640        if proof.proof_type != "jwt" {
641            return Err(AuthError::validation(format!(
642                "Unsupported proof type: {}",
643                proof.proof_type
644            )));
645        }
646        let jwt = proof
647            .jwt
648            .as_deref()
649            .ok_or_else(|| AuthError::validation("JWT proof value is missing"))?;
650
651        // Structural check — must be 3-part JWS compact serialization
652        let parts: Vec<&str> = jwt.split('.').collect();
653        if parts.len() != 3 {
654            return Err(AuthError::validation(
655                "Proof JWT must be compact JWS (header.payload.signature)",
656            ));
657        }
658
659        // Decode payload and check c_nonce
660        let payload_bytes = base64_url_decode(parts[1])?;
661        let payload: serde_json::Value = serde_json::from_slice(&payload_bytes)
662            .map_err(|e| AuthError::validation(format!("Invalid proof JWT payload: {e}")))?;
663
664        if let Some(nonce) = payload.get("nonce").and_then(|v| v.as_str())
665            && !self.consume_nonce(nonce).await
666        {
667            return Err(AuthError::validation(
668                "Proof JWT nonce is invalid or expired",
669            ));
670        }
671
672        Ok(())
673    }
674
675    /// Process a batch credential request (§8).
676    ///
677    /// Issues multiple credentials in a single response, one per request.
678    pub async fn issue_batch(
679        &self,
680        requests: &[CredentialRequest],
681        subject_id: &str,
682        credential_data: &[Option<serde_json::Value>],
683    ) -> Result<Vec<CredentialResponse>> {
684        if requests.is_empty() {
685            return Err(AuthError::validation(
686                "Batch request must contain at least one credential request",
687            ));
688        }
689        if requests.len() != credential_data.len() {
690            return Err(AuthError::validation(
691                "Credential data array length must match requests array length",
692            ));
693        }
694
695        let mut responses = Vec::with_capacity(requests.len());
696        for (req, data) in requests.iter().zip(credential_data.iter()) {
697            let resp = self.issue_credential(req, subject_id, data.clone()).await?;
698            responses.push(resp);
699        }
700        Ok(responses)
701    }
702
703    /// Complete a deferred credential issuance.
704    pub async fn complete_deferred(
705        &self,
706        transaction_id: &str,
707        credential_data: serde_json::Value,
708    ) -> Result<CredentialResponse> {
709        let pending = self
710            .deferred
711            .write()
712            .await
713            .remove(transaction_id)
714            .ok_or_else(|| AuthError::validation("Unknown or expired transaction ID"))?;
715
716        let mut credential = match credential_data {
717            serde_json::Value::Object(map) => map,
718            _ => {
719                return Err(AuthError::validation(
720                    "Deferred credential data must be a JSON object",
721                ));
722            }
723        };
724
725        credential
726            .entry("sub".to_string())
727            .or_insert_with(|| serde_json::Value::String(pending.subject_id.clone()));
728        credential.entry("format".to_string()).or_insert_with(|| {
729            serde_json::to_value(&pending.request.format).unwrap_or(serde_json::Value::Null)
730        });
731        credential
732            .entry("issuance_requested_at".to_string())
733            .or_insert_with(|| {
734                serde_json::Value::Number(serde_json::Number::from(pending.created_at))
735            });
736        if let Some(definition) = pending.request.credential_definition {
737            credential
738                .entry("credential_definition".to_string())
739                .or_insert_with(|| {
740                    serde_json::to_value(definition).unwrap_or(serde_json::Value::Null)
741                });
742        }
743
744        Ok(CredentialResponse::completed(serde_json::Value::Object(
745            credential,
746        )))
747    }
748
749    /// Get the count of pending deferred issuances.
750    pub async fn pending_count(&self) -> usize {
751        self.deferred.read().await.len()
752    }
753
754    /// Clean up expired nonces.
755    pub async fn cleanup_nonces(&self) -> usize {
756        let now = SystemTime::now()
757            .duration_since(UNIX_EPOCH)
758            .unwrap_or_default()
759            .as_secs();
760        let mut nonces = self.nonces.write().await;
761        let before = nonces.len();
762        nonces.retain(|_, exp| *exp > now);
763        before - nonces.len()
764    }
765}
766
767#[cfg(test)]
768mod tests {
769    use super::*;
770
771    fn test_metadata() -> IssuerMetadata {
772        IssuerMetadata::builder("https://issuer.example.com")
773            .add_credential(
774                "UniversityDegree",
775                CredentialConfiguration::new(CredentialFormat::JwtVcJson)
776                    .scope("degree")
777                    .binding_methods(vec!["did:key"])
778                    .signing_algorithms(vec!["ES256"])
779                    .with_display(CredentialDisplay {
780                        name: "University Degree".to_string(),
781                        locale: Some("en".to_string()),
782                        description: Some("A university degree credential".to_string()),
783                        background_color: Some("#12107c".to_string()),
784                        text_color: Some("#ffffff".to_string()),
785                    })
786                    .with_definition(CredentialDefinition {
787                        types: vec![
788                            "VerifiableCredential".to_string(),
789                            "UniversityDegreeCredential".to_string(),
790                        ],
791                        credential_subject: None,
792                    }),
793            )
794            .display("Example University", Some("en"))
795            .build()
796    }
797
798    // ── Credential format serialization ─────────────────────────
799
800    #[test]
801    fn test_credential_format_serialization() {
802        assert_eq!(
803            serde_json::to_string(&CredentialFormat::JwtVcJson).unwrap(),
804            r#""jwt_vc_json""#
805        );
806        assert_eq!(
807            serde_json::to_string(&CredentialFormat::LdpVc).unwrap(),
808            r#""ldp_vc""#
809        );
810        assert_eq!(
811            serde_json::to_string(&CredentialFormat::SdJwtVc).unwrap(),
812            r#""vc+sd-jwt""#
813        );
814    }
815
816    // ── Metadata ────────────────────────────────────────────────
817
818    #[test]
819    fn test_issuer_metadata_serialization() {
820        let meta = test_metadata();
821        let json = serde_json::to_value(&meta).unwrap();
822        assert_eq!(json["credential_issuer"], "https://issuer.example.com");
823        assert!(json["credential_configurations_supported"]["UniversityDegree"].is_object());
824    }
825
826    #[test]
827    fn test_metadata_roundtrip() {
828        let meta = test_metadata();
829        let json_str = serde_json::to_string(&meta).unwrap();
830        let parsed: IssuerMetadata = serde_json::from_str(&json_str).unwrap();
831        assert_eq!(parsed.credential_issuer, meta.credential_issuer);
832        assert!(
833            parsed
834                .credential_configurations_supported
835                .contains_key("UniversityDegree")
836        );
837    }
838
839    // ── Credential Offer ────────────────────────────────────────
840
841    #[tokio::test]
842    async fn test_create_offer() {
843        let issuer = CredentialIssuer::new(test_metadata());
844        let offer = issuer
845            .create_offer(vec!["UniversityDegree".to_string()], "user-1")
846            .await
847            .unwrap();
848
849        assert_eq!(offer.credential_issuer, "https://issuer.example.com");
850        assert_eq!(offer.credential_configuration_ids, vec!["UniversityDegree"]);
851        let grants = offer.grants.unwrap();
852        assert!(grants.pre_authorized_code.is_some());
853    }
854
855    #[tokio::test]
856    async fn test_create_offer_invalid_config() {
857        let issuer = CredentialIssuer::new(test_metadata());
858        let result = issuer
859            .create_offer(vec!["NonExistent".to_string()], "user-1")
860            .await;
861        assert!(result.is_err());
862    }
863
864    #[tokio::test]
865    async fn test_create_offer_empty_configs() {
866        let issuer = CredentialIssuer::new(test_metadata());
867        let result = issuer.create_offer(vec![], "user-1").await;
868        assert!(result.is_err());
869    }
870
871    // ── Pre-authorized code ─────────────────────────────────────
872
873    #[tokio::test]
874    async fn test_pre_auth_code_flow() {
875        let issuer = CredentialIssuer::new(test_metadata());
876        let offer = issuer
877            .create_offer(vec!["UniversityDegree".to_string()], "user-1")
878            .await
879            .unwrap();
880
881        let code = &offer
882            .grants
883            .unwrap()
884            .pre_authorized_code
885            .unwrap()
886            .pre_authorized_code;
887
888        let (config_id, subject_id) = issuer.validate_pre_auth_code(code).await.unwrap();
889        assert_eq!(config_id, "UniversityDegree");
890        assert_eq!(subject_id, "user-1");
891
892        // Code is single-use
893        assert!(issuer.validate_pre_auth_code(code).await.is_err());
894    }
895
896    // ── Nonce management ────────────────────────────────────────
897
898    #[tokio::test]
899    async fn test_nonce_lifecycle() {
900        let issuer = CredentialIssuer::new(test_metadata());
901        let nonce = issuer.generate_nonce(300).await;
902
903        assert!(issuer.validate_nonce(&nonce).await);
904        assert!(issuer.consume_nonce(&nonce).await);
905        // After consumption
906        assert!(!issuer.validate_nonce(&nonce).await);
907        assert!(!issuer.consume_nonce(&nonce).await);
908    }
909
910    #[tokio::test]
911    async fn test_nonce_invalid() {
912        let issuer = CredentialIssuer::new(test_metadata());
913        assert!(!issuer.validate_nonce("nonexistent").await);
914    }
915
916    // ── Credential issuance ─────────────────────────────────────
917
918    #[tokio::test]
919    async fn test_issue_credential_immediate() {
920        let issuer = CredentialIssuer::new(test_metadata());
921        let request = CredentialRequest {
922            format: CredentialFormat::JwtVcJson,
923            credential_definition: None,
924            proof: None,
925        };
926
927        let cred_data = serde_json::json!({
928            "@context": ["https://www.w3.org/2018/credentials/v1"],
929            "type": ["VerifiableCredential", "UniversityDegreeCredential"],
930            "credentialSubject": {
931                "degree": {
932                    "type": "BachelorDegree",
933                    "name": "Bachelor of Science"
934                }
935            }
936        });
937
938        let resp = issuer
939            .issue_credential(&request, "user-1", Some(cred_data))
940            .await
941            .unwrap();
942
943        assert!(resp.credential.is_some());
944        assert!(resp.transaction_id.is_none());
945        assert!(resp.c_nonce.is_some());
946    }
947
948    #[tokio::test]
949    async fn test_issue_credential_deferred() {
950        let issuer = CredentialIssuer::new(test_metadata());
951        let request = CredentialRequest {
952            format: CredentialFormat::JwtVcJson,
953            credential_definition: None,
954            proof: None,
955        };
956
957        let resp = issuer
958            .issue_credential(&request, "user-1", None)
959            .await
960            .unwrap();
961
962        assert!(resp.credential.is_none());
963        assert!(resp.transaction_id.is_some());
964        assert_eq!(issuer.pending_count().await, 1);
965
966        // Complete deferred
967        let tx_id = resp.transaction_id.unwrap();
968        let final_resp = issuer
969            .complete_deferred(&tx_id, serde_json::json!({"credential": "data"}))
970            .await
971            .unwrap();
972        assert!(final_resp.credential.is_some());
973        let completed = final_resp.credential.unwrap();
974        assert_eq!(completed["credential"], "data");
975        assert_eq!(completed["sub"], "user-1");
976        assert_eq!(completed["format"], "jwt_vc_json");
977        assert!(completed["issuance_requested_at"].is_number());
978        assert_eq!(issuer.pending_count().await, 0);
979    }
980
981    #[tokio::test]
982    async fn test_issue_credential_unsupported_format() {
983        let issuer = CredentialIssuer::new(test_metadata());
984        let request = CredentialRequest {
985            format: CredentialFormat::LdpVc,
986            credential_definition: None,
987            proof: None,
988        };
989
990        let result = issuer.issue_credential(&request, "user-1", None).await;
991        assert!(result.is_err());
992    }
993
994    #[tokio::test]
995    async fn test_issue_credential_invalid_proof_type() {
996        let issuer = CredentialIssuer::new(test_metadata());
997        let request = CredentialRequest {
998            format: CredentialFormat::JwtVcJson,
999            credential_definition: None,
1000            proof: Some(CredentialProof {
1001                proof_type: "ldp".to_string(),
1002                jwt: None,
1003            }),
1004        };
1005
1006        let result = issuer
1007            .issue_credential(&request, "user-1", Some(serde_json::json!({})))
1008            .await;
1009        assert!(result.is_err());
1010    }
1011
1012    #[tokio::test]
1013    async fn test_issue_credential_missing_jwt_proof() {
1014        let issuer = CredentialIssuer::new(test_metadata());
1015        let request = CredentialRequest {
1016            format: CredentialFormat::JwtVcJson,
1017            credential_definition: None,
1018            proof: Some(CredentialProof {
1019                proof_type: "jwt".to_string(),
1020                jwt: None,
1021            }),
1022        };
1023
1024        let result = issuer
1025            .issue_credential(&request, "user-1", Some(serde_json::json!({})))
1026            .await;
1027        assert!(result.is_err());
1028    }
1029
1030    // ── Deferred issuance ───────────────────────────────────────
1031
1032    #[tokio::test]
1033    async fn test_complete_deferred_invalid_tx() {
1034        let issuer = CredentialIssuer::new(test_metadata());
1035        let result = issuer
1036            .complete_deferred("nonexistent", serde_json::json!({}))
1037            .await;
1038        assert!(result.is_err());
1039    }
1040
1041    // ── Credential offer serialization ──────────────────────────
1042
1043    #[test]
1044    fn test_credential_offer_roundtrip() {
1045        let offer = CredentialOffer {
1046            credential_issuer: "https://issuer.example".to_string(),
1047            credential_configuration_ids: vec!["DegreeCredential".to_string()],
1048            grants: Some(CredentialOfferGrants {
1049                authorization_code: None,
1050                pre_authorized_code: Some(PreAuthorizedCodeGrant {
1051                    pre_authorized_code: "code123".to_string(),
1052                    user_pin_required: true,
1053                }),
1054            }),
1055        };
1056        let json = serde_json::to_string(&offer).unwrap();
1057        let parsed: CredentialOffer = serde_json::from_str(&json).unwrap();
1058        assert_eq!(parsed.credential_issuer, offer.credential_issuer);
1059        assert!(
1060            parsed
1061                .grants
1062                .unwrap()
1063                .pre_authorized_code
1064                .unwrap()
1065                .user_pin_required
1066        );
1067    }
1068
1069    // ── Request / Response models ───────────────────────────────
1070
1071    #[test]
1072    fn test_credential_request_serialization() {
1073        let req = CredentialRequest {
1074            format: CredentialFormat::JwtVcJson,
1075            credential_definition: Some(CredentialDefinition {
1076                types: vec!["VerifiableCredential".to_string()],
1077                credential_subject: None,
1078            }),
1079            proof: Some(CredentialProof {
1080                proof_type: "jwt".to_string(),
1081                jwt: Some("eyJ...".to_string()),
1082            }),
1083        };
1084        let json = serde_json::to_value(&req).unwrap();
1085        assert_eq!(json["format"], "jwt_vc_json");
1086        assert!(json["proof"]["jwt"].is_string());
1087    }
1088
1089    // ── Builder / factory helpers ───────────────────────────────
1090
1091    #[test]
1092    fn test_credential_response_immediate() {
1093        let resp = CredentialResponse::immediate(serde_json::json!({"vc": "data"}), "nonce-1", 300);
1094        assert!(resp.credential.is_some());
1095        assert!(resp.transaction_id.is_none());
1096        assert_eq!(resp.c_nonce.as_deref(), Some("nonce-1"));
1097        assert_eq!(resp.c_nonce_expires_in, Some(300));
1098    }
1099
1100    #[test]
1101    fn test_credential_response_deferred() {
1102        let resp = CredentialResponse::deferred("tx-1", "nonce-2", 600);
1103        assert!(resp.credential.is_none());
1104        assert_eq!(resp.transaction_id.as_deref(), Some("tx-1"));
1105        assert_eq!(resp.c_nonce.as_deref(), Some("nonce-2"));
1106    }
1107
1108    #[test]
1109    fn test_credential_response_completed() {
1110        let resp = CredentialResponse::completed(serde_json::json!({"done": true}));
1111        assert!(resp.credential.is_some());
1112        assert!(resp.transaction_id.is_none());
1113        assert!(resp.c_nonce.is_none());
1114    }
1115
1116    #[test]
1117    fn test_credential_configuration_builder() {
1118        let cfg = CredentialConfiguration::new(CredentialFormat::JwtVcJson)
1119            .scope("degree")
1120            .binding_methods(vec!["did:key"])
1121            .signing_algorithms(vec!["ES256", "EdDSA"]);
1122        assert_eq!(cfg.format, CredentialFormat::JwtVcJson);
1123        assert_eq!(cfg.scope.as_deref(), Some("degree"));
1124        assert_eq!(cfg.cryptographic_binding_methods_supported, vec!["did:key"]);
1125        assert_eq!(cfg.credential_signing_alg_values_supported.len(), 2);
1126    }
1127
1128    #[test]
1129    fn test_issuer_metadata_builder() {
1130        let meta = IssuerMetadata::builder("https://issuer.example.com")
1131            .add_credential(
1132                "TestCred",
1133                CredentialConfiguration::new(CredentialFormat::SdJwtVc).scope("test"),
1134            )
1135            .display("Test Issuer", None)
1136            .build();
1137        assert_eq!(meta.credential_issuer, "https://issuer.example.com");
1138        assert_eq!(
1139            meta.credential_endpoint,
1140            "https://issuer.example.com/credential"
1141        );
1142        assert!(
1143            meta.credential_configurations_supported
1144                .contains_key("TestCred")
1145        );
1146        assert_eq!(meta.display[0].name, "Test Issuer");
1147        assert!(meta.display[0].locale.is_none());
1148    }
1149
1150    #[test]
1151    fn test_issuer_metadata_builder_custom_endpoint() {
1152        let meta = IssuerMetadata::builder("https://example.com")
1153            .credential_endpoint("https://example.com/api/vc/issue")
1154            .batch_credential_endpoint("https://example.com/api/vc/batch")
1155            .build();
1156        assert_eq!(meta.credential_endpoint, "https://example.com/api/vc/issue");
1157        assert_eq!(
1158            meta.batch_credential_endpoint.as_deref(),
1159            Some("https://example.com/api/vc/batch")
1160        );
1161    }
1162}