Skip to main content

wellfare_core/
credentials.rs

1//! Verifiable-credential status cache and presentation building — Restricted vault records.
2//!
3//! Implements the master plan's credential items (audit CRE-01..09). Two honesty
4//! boundaries are load-bearing and documented at their point of use:
5//!
6//! 1. [`evaluate_state`] is a **status cache**, not cryptographic verification. It classifies
7//!    a credential from cheap, local facts (expiry, an issuer-trust allow-list, claim presence).
8//!    It does NOT check an issuer signature, a revocation registry, or a proof — a
9//!    `VerificationState::IssuerTrusted` value means "the issuer DID is on the caller's trust
10//!    list", never "the credential's signature verified". Real proof verification lives in the
11//!    identity / key-vault layer.
12//!
13//! 2. [`build_presentation`] is **plain JSON field selection**, NOT cryptographic selective
14//!    disclosure. It simply drops the claim keys the holder did not select. It gives no
15//!    unlinkability, no zero-knowledge property, and no proof that the omitted claims exist or
16//!    that the disclosed ones were signed. The type is named [`FieldSelectedPresentation`] so it
17//!    cannot be mistaken for ZK selective disclosure (plan §Q11).
18
19use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::record::{
23    EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
24};
25
26/// Locally-derived verification status of a credential.
27///
28/// This is a **cache of cheap local checks**, ordered from weakest to strongest confidence,
29/// with `Revoked`/`Expired` as terminal negative states. It is explicitly NOT a statement about
30/// cryptographic validity (see the module header).
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum VerificationState {
34    /// No local evidence of validity (e.g. no claims, unknown issuer).
35    Unverified,
36    /// Has at least one claim — the shape looks like a credential. Not a schema-conformance proof.
37    SchemaValid,
38    /// The issuer DID is on the caller-supplied trust allow-list. Not a signature check.
39    IssuerTrusted,
40    /// The holder / issuer marked this credential revoked. Terminal.
41    Revoked,
42    /// The credential's `expires_at_unix` is in the past. Terminal.
43    Expired,
44}
45
46impl Default for VerificationState {
47    fn default() -> Self {
48        Self::Unverified
49    }
50}
51
52/// A verifiable-credential envelope as held in the WellFair vault.
53///
54/// `claims` is an ordered key/value list (not a map) so presentation selection is deterministic
55/// and duplicate keys round-trip faithfully. The credential is Restricted.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct CredentialRecord {
58    pub id: String,
59    pub issuer_did: String,
60    pub subject_did: String,
61    pub credential_type: String,
62    pub claims: Vec<(String, String)>,
63    pub issued_at_unix: u32,
64    /// High-resolution instant (T71 bridge). Preferred over `issued_at_unix`
65    /// when present; the u32 field is kept for backward-compatible deserialization.
66    #[serde(skip_serializing_if = "Option::is_none", default)]
67    pub issued_at_instant: Option<InstantBridge>,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub expires_at_unix: Option<u32>,
70    /// High-resolution expiry instant (T71 bridge). Preferred over
71    /// `expires_at_unix` when present.
72    #[serde(skip_serializing_if = "Option::is_none", default)]
73    pub expires_at_instant: Option<InstantBridge>,
74    #[serde(default)]
75    pub verification_state: VerificationState,
76}
77
78impl CredentialRecord {
79    /// Creates a new instance.
80    pub fn new(
81        issuer_did: impl Into<String>,
82        subject_did: impl Into<String>,
83        credential_type: impl Into<String>,
84        issued_at_unix: u32,
85    ) -> Self {
86        Self {
87            id: Uuid::new_v4().to_string(),
88            issuer_did: issuer_did.into(),
89            subject_did: subject_did.into(),
90            credential_type: credential_type.into(),
91            claims: Vec::new(),
92            issued_at_unix,
93            issued_at_instant: Some(InstantBridge::from_coarse(issued_at_unix)),
94            expires_at_unix: None,
95            expires_at_instant: None,
96            verification_state: VerificationState::Unverified,
97        }
98    }
99
100    /// Resolve the issued-at instant, preferring the high-resolution
101    /// `InstantBridge` field when present (T71 bridge).
102    pub fn issued_at(&self) -> InstantBridge {
103        self.issued_at_instant
104            .unwrap_or_else(|| InstantBridge::from_coarse(self.issued_at_unix))
105    }
106
107    /// Resolve the expiry instant, preferring the high-resolution
108    /// `InstantBridge` field when present (T71 bridge).
109    pub fn expires_at(&self) -> Option<InstantBridge> {
110        self.expires_at_instant
111            .or_else(|| self.expires_at_unix.map(|t| InstantBridge::from_coarse(t)))
112    }
113
114    /// Add a claim key/value pair (builder-style). Order is preserved.
115    pub fn with_claim(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
116        self.claims.push((key.into(), value.into()));
117        self
118    }
119}
120
121/// A holder-driven request for a subset of a credential's claims.
122///
123/// This models *which* claim keys a verifier asked for (or the holder chose to reveal). It carries
124/// no cryptographic material — see [`build_presentation`] for the honesty boundary.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PresentationRequest {
127    /// The credential the presentation is derived from.
128    pub credential_id: String,
129    /// The claim keys to disclose. Keys absent from the credential are ignored.
130    pub selected_claim_keys: Vec<String>,
131}
132
133impl PresentationRequest {
134    /// Creates a new instance.
135    pub fn new(credential_id: impl Into<String>, selected_claim_keys: Vec<String>) -> Self {
136        Self {
137            credential_id: credential_id.into(),
138            selected_claim_keys,
139        }
140    }
141}
142
143/// The result of [`build_presentation`]: a credential reduced to the holder-selected claim keys.
144///
145/// **Honesty boundary — this is plain JSON field selection, not cryptographic selective
146/// disclosure.** The omitted claims are simply not copied in. There is no unlinkability, no
147/// zero-knowledge proof, and no cryptographic assurance that the disclosed claims were signed by
148/// the issuer or that undisclosed claims exist. Do not treat a `FieldSelectedPresentation` as a
149/// ZK / BBS+ selective-disclosure proof. The type name encodes this distinction on purpose.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151pub struct FieldSelectedPresentation {
152    pub credential_id: String,
153    pub issuer_did: String,
154    pub subject_did: String,
155    pub credential_type: String,
156    /// Only the claims whose keys were selected AND present on the credential.
157    pub disclosed_claims: Vec<(String, String)>,
158    /// The verification state copied from the source credential at build time (a cached hint,
159    /// not a re-verification).
160    pub verification_state: VerificationState,
161}
162
163/// Classify a credential from cheap local facts. **Status cache, NOT cryptographic verification**
164/// (see the module header): no signature, revocation-registry, or proof check is performed.
165///
166/// Precedence:
167/// - `Revoked` if the stored state is already `Revoked` (revocation is sticky).
168/// - `Expired` if `expires_at_unix` is set and `<= now_unix`.
169/// - else `IssuerTrusted` if `issuer_did` is in `trusted_issuers`.
170/// - else `SchemaValid` if the credential carries at least one claim.
171/// - else `Unverified`.
172pub fn evaluate_state(
173    cred: &CredentialRecord,
174    trusted_issuers: &[String],
175    now_unix: u32,
176) -> VerificationState {
177    if cred.verification_state == VerificationState::Revoked {
178        return VerificationState::Revoked;
179    }
180    if let Some(expiry) = cred.expires_at_unix {
181        if expiry <= now_unix {
182            return VerificationState::Expired;
183        }
184    }
185    if trusted_issuers.iter().any(|i| i == &cred.issuer_did) {
186        return VerificationState::IssuerTrusted;
187    }
188    if !cred.claims.is_empty() {
189        return VerificationState::SchemaValid;
190    }
191    VerificationState::Unverified
192}
193
194/// Build a field-selected presentation of `cred`, disclosing only claims whose keys appear in
195/// `selected_claim_keys`. Keys requested but absent on the credential are silently skipped; the
196/// disclosed order follows the credential's own claim order (deterministic).
197///
198/// **This is field selection, not selective disclosure** — see [`FieldSelectedPresentation`].
199pub fn build_presentation(
200    cred: &CredentialRecord,
201    selected_claim_keys: &[String],
202) -> FieldSelectedPresentation {
203    let disclosed_claims: Vec<(String, String)> = cred
204        .claims
205        .iter()
206        .filter(|(k, _)| selected_claim_keys.iter().any(|s| s == k))
207        .cloned()
208        .collect();
209    FieldSelectedPresentation {
210        credential_id: cred.id.clone(),
211        issuer_did: cred.issuer_did.clone(),
212        subject_did: cred.subject_did.clone(),
213        credential_type: cred.credential_type.clone(),
214        disclosed_claims,
215        verification_state: cred.verification_state,
216    }
217}
218
219///  record ID.
220pub fn credential_record_id(uuid: &str) -> String {
221    format!("urn:wellfair:credential:{uuid}")
222}
223
224/// Build the Restricted record envelope for a credential.
225///
226/// Credentials are third-party attestations, so evidence is `ClinicianObserved`-style external
227/// assertion rather than self-report; we classify them as `Inferred` provenance because the local
228/// vault did not observe the underlying fact directly — it holds an issuer's claim. Epistemic
229/// status is `Asserted` (the issuer asserts it); trust is expressed via `verification_state`, not
230/// by weakening the epistemic status.
231pub fn build_credential_envelope(
232    cred: &CredentialRecord,
233    owner_did: &str,
234    author_did: &str,
235    asserted_unix: u32,
236    blob_hash: Option<String>,
237) -> RecordEnvelope {
238    RecordEnvelope {
239        id: credential_record_id(&cred.id),
240        owner_did: owner_did.to_string(),
241        author_did: author_did.to_string(),
242        proxy_did: None,
243        epistemic_status: EpistemicStatus::Asserted,
244        evidence_type: EvidenceType::Inferred,
245        sensitivity: SensitivityClass::Restricted,
246        asserted_time_unix: asserted_unix,
247        asserted_instant: None,
248        valid_time_start_unix: Some(cred.issued_at_unix),
249        valid_time_start_instant: cred.issued_at_instant,
250        valid_time_end_unix: cred.expires_at_unix,
251        valid_time_end_instant: cred.expires_at_instant,
252        predecessor_id: None,
253        blob_hash,
254        tombstone: false,
255    }
256}
257
258///  summary.
259pub fn credential_summary(cred: &CredentialRecord) -> String {
260    serde_json::json!({
261        "credential_type": cred.credential_type,
262        "issuer_did": cred.issuer_did,
263        "subject_did": cred.subject_did,
264        "claim_count": cred.claims.len(),
265        "issued_at_unix": cred.issued_at_unix,
266        "expires_at_unix": cred.expires_at_unix,
267        "verification_state": cred.verification_state,
268    })
269    .to_string()
270}
271
272///  summary.
273pub fn presentation_summary(pres: &FieldSelectedPresentation) -> String {
274    serde_json::json!({
275        "credential_id": pres.credential_id,
276        "credential_type": pres.credential_type,
277        "issuer_did": pres.issuer_did,
278        "disclosed_keys": pres
279            .disclosed_claims
280            .iter()
281            .map(|(k, _)| k.clone())
282            .collect::<Vec<_>>(),
283        "verification_state": pres.verification_state,
284        // Names the honesty boundary in the stored projection itself.
285        "disclosure_kind": "field_selection_not_zk",
286    })
287    .to_string()
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    fn sample_cred() -> CredentialRecord {
295        CredentialRecord::new(
296            "did:wf:issuer",
297            "did:wf:subject",
298            "ProofOfAddress",
299            1_700_000_000,
300        )
301        .with_claim("full_name", "Jane Roe")
302        .with_claim("street", "1 Camper Lane")
303        .with_claim("postcode", "3000")
304    }
305
306    #[test]
307    fn credential_envelope_kind_and_class() {
308        let cred = sample_cred();
309        let env = build_credential_envelope(
310            &cred,
311            "did:wf:owner",
312            "did:wf:owner",
313            1_700_000_100,
314            Some("blobhash".into()),
315        );
316        assert!(env.id.contains(":credential:"));
317        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
318        assert_eq!(env.evidence_type, EvidenceType::Inferred);
319        assert_eq!(env.epistemic_status, EpistemicStatus::Asserted);
320        // The central journal dispatcher must classify a credential id as "credential",
321        // not fall through to the generic "record" arm.
322        assert_eq!(
323            crate::conditions::journal_kind_for_record_id(&env.id),
324            "credential"
325        );
326    }
327
328    #[test]
329    fn envelope_valid_time_end_tracks_expiry() {
330        let mut cred = sample_cred();
331        cred.expires_at_unix = Some(1_800_000_000);
332        let env = build_credential_envelope(&cred, "did:wf:owner", "did:wf:owner", 1, None);
333        assert_eq!(env.valid_time_start_unix, Some(1_700_000_000));
334        assert_eq!(env.valid_time_end_unix, Some(1_800_000_000));
335    }
336
337    #[test]
338    fn evaluate_state_expired_beats_trusted() {
339        let mut cred = sample_cred();
340        cred.expires_at_unix = Some(1_000);
341        let trusted = vec!["did:wf:issuer".to_string()];
342        // now is past expiry — Expired must win even though the issuer is trusted.
343        assert_eq!(
344            evaluate_state(&cred, &trusted, 2_000),
345            VerificationState::Expired
346        );
347    }
348
349    #[test]
350    fn evaluate_state_issuer_trusted_when_not_expired() {
351        let mut cred = sample_cred();
352        // Far-future but within u32 range (u32::MAX ≈ year 2106).
353        cred.expires_at_unix = Some(4_000_000_000);
354        let trusted = vec!["did:wf:issuer".to_string()];
355        assert_eq!(
356            evaluate_state(&cred, &trusted, 1_700_000_000),
357            VerificationState::IssuerTrusted
358        );
359    }
360
361    #[test]
362    fn evaluate_state_schema_valid_when_untrusted_issuer_has_claims() {
363        let cred = sample_cred(); // untrusted issuer, has claims, no expiry
364        assert_eq!(
365            evaluate_state(&cred, &[], 1_700_000_000),
366            VerificationState::SchemaValid
367        );
368    }
369
370    #[test]
371    fn evaluate_state_unverified_when_no_claims_and_untrusted() {
372        let cred = CredentialRecord::new("did:wf:issuer", "did:wf:subject", "Empty", 1_700_000_000);
373        assert_eq!(
374            evaluate_state(&cred, &[], 1_700_000_000),
375            VerificationState::Unverified
376        );
377    }
378
379    #[test]
380    fn evaluate_state_revoked_is_sticky() {
381        let mut cred = sample_cred();
382        cred.verification_state = VerificationState::Revoked;
383        let trusted = vec!["did:wf:issuer".to_string()];
384        // Even a trusted, unexpired, claim-bearing credential stays Revoked.
385        assert_eq!(
386            evaluate_state(&cred, &trusted, 1_700_000_000),
387            VerificationState::Revoked
388        );
389    }
390
391    #[test]
392    fn build_presentation_returns_only_selected_claims() {
393        let cred = sample_cred();
394        let selected = vec!["full_name".to_string(), "postcode".to_string()];
395        let pres = build_presentation(&cred, &selected);
396
397        // Only the two selected claims are present, in credential order.
398        assert_eq!(pres.disclosed_claims.len(), 2);
399        assert_eq!(pres.disclosed_claims[0].0, "full_name");
400        assert_eq!(pres.disclosed_claims[1].0, "postcode");
401
402        // The unselected claim is omitted entirely — no key, no value.
403        assert!(!pres.disclosed_claims.iter().any(|(k, _)| k == "street"));
404        let json = presentation_summary(&pres);
405        assert!(!json.contains("street"));
406        assert!(!json.contains("1 Camper Lane"));
407
408        // Provenance metadata is carried through.
409        assert_eq!(pres.credential_id, cred.id);
410        assert_eq!(pres.issuer_did, "did:wf:issuer");
411        // The honesty boundary is named in the summary projection.
412        assert!(json.contains("field_selection_not_zk"));
413    }
414
415    #[test]
416    fn build_presentation_ignores_unknown_selected_keys() {
417        let cred = sample_cred();
418        let selected = vec!["full_name".to_string(), "does_not_exist".to_string()];
419        let pres = build_presentation(&cred, &selected);
420        assert_eq!(pres.disclosed_claims.len(), 1);
421        assert_eq!(pres.disclosed_claims[0].0, "full_name");
422    }
423
424    #[test]
425    fn build_presentation_empty_selection_discloses_nothing() {
426        let cred = sample_cred();
427        let pres = build_presentation(&cred, &[]);
428        assert!(pres.disclosed_claims.is_empty());
429    }
430
431    #[test]
432    fn credential_summary_includes_primary_fields() {
433        let cred = sample_cred();
434        let summary = credential_summary(&cred);
435        assert!(summary.contains("ProofOfAddress"));
436        assert!(summary.contains("did:wf:issuer"));
437        // Claim count, not raw claim values, in the summary.
438        assert!(summary.contains("\"claim_count\":3"));
439    }
440}