Skip to main content

oxilite_vc/
lib.rs

1//! Verifiable Credentials in oxilite, on top of [`oxilite_jsonld`].
2//!
3//! A credential is stored verbatim under its `id`, its RDF goes into the named graph of the
4//! same IRI, and its issuer, subject, types and validity window are indexed for lookups
5//! without SPARQL. Structure is checked with [`ssi_vc`] (VCDM v1.1 and v2.0); the W3C
6//! credential, security, Data Integrity and DID contexts come bundled with
7//! [`ssi_json_ld`], so credentials convert offline, on D1 too.
8//!
9//! Proofs are **not** verified: storing a credential is not a claim that it is valid.
10//! Use the `ssi` crates on the JSON returned by `get_credential` for that.
11//!
12//! This crate is sans-IO; the `oxilite` crate (feature `vc`) provides `Store::credentials()`.
13//!
14// @lat: [[architecture#JSON-LD documents#Verifiable Credentials]]
15
16use json_syntax::{Parse, Print};
17use oxilite_jsonld::{
18    DocumentFilter, DocumentInput, DocumentMeta, JsonLdError, JsonLdOptions, MissingKey,
19};
20use std::fmt;
21
22pub use oxilite_jsonld::{GraphStrategy, KeyStrategy, MetadataIndexes, StoredDocument};
23
24/// Context loader of the bundled W3C contexts (credentials v1/v2, security, Data Integrity,
25/// cryptosuites, DID v1…).
26pub type BundledContexts = ssi_json_ld::ContextLoader;
27
28/// The bundled contexts, used before persisted ones.
29pub fn bundled_contexts() -> BundledContexts {
30    ssi_json_ld::ContextLoader::empty().with_static_loader()
31}
32
33/// Credential lookups: [`DocumentFilter`] over credential metadata.
34pub type CredentialFilter = DocumentFilter;
35
36/// The first `@context` of VCDM 1.1.
37pub const CREDENTIALS_V1: &str = "https://www.w3.org/2018/credentials/v1";
38/// The first `@context` of VCDM 2.0.
39pub const CREDENTIALS_V2: &str = "https://www.w3.org/ns/credentials/v2";
40
41const XSD_DATE_TIME: &str = "http://www.w3.org/2001/XMLSchema#dateTime";
42
43/// Options of a credential handle.
44#[derive(Debug, Clone)]
45pub struct CredentialOptions {
46    /// Keys, graphs, contexts and indexes (by default: key = `id`, graph = key, credentials
47    /// without `id` keyed by content hash).
48    pub jsonld: JsonLdOptions,
49    /// Also store each credential embedded in a presentation as a document of its own.
50    pub embed_presentation_credentials: bool,
51}
52
53impl Default for CredentialOptions {
54    fn default() -> Self {
55        Self {
56            jsonld: JsonLdOptions {
57                on_missing_key: MissingKey::ContentHash,
58                ..Default::default()
59            },
60            embed_presentation_credentials: true,
61        }
62    }
63}
64
65/// Data model version of a credential or presentation.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum Profile {
68    Vc1,
69    Vc2,
70    Vp1,
71    Vp2,
72}
73
74impl Profile {
75    pub fn as_str(self) -> &'static str {
76        match self {
77            Self::Vc1 => "vc1",
78            Self::Vc2 => "vc2",
79            Self::Vp1 => "vp1",
80            Self::Vp2 => "vp2",
81        }
82    }
83}
84
85impl fmt::Display for Profile {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str(self.as_str())
88    }
89}
90
91/// Keys written by `put_presentation`.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct PresentationKeys {
94    /// The presentation's key.
95    pub key: String,
96    /// Keys of the embedded credentials stored on their own.
97    pub credentials: Vec<String>,
98}
99
100fn invalid(msg: impl Into<String>) -> JsonLdError {
101    JsonLdError::Invalid(msg.into())
102}
103
104/// The data model version, from the first `@context`.
105fn version(doc: &serde_json::Value) -> Result<u8, JsonLdError> {
106    let first = match &doc["@context"] {
107        serde_json::Value::Array(a) => a.first(),
108        v @ serde_json::Value::String(_) => Some(v),
109        _ => None,
110    };
111    match first.and_then(serde_json::Value::as_str) {
112        Some(CREDENTIALS_V1) => Ok(1),
113        Some(CREDENTIALS_V2) => Ok(2),
114        _ => Err(invalid(format!(
115            "the first @context must be {CREDENTIALS_V2} (VCDM 2.0) or {CREDENTIALS_V1} (VCDM 1.1)"
116        ))),
117    }
118}
119
120fn parse(json: &str) -> Result<serde_json::Value, JsonLdError> {
121    serde_json::from_str(json).map_err(|e| JsonLdError::Json(e.to_string()))
122}
123
124fn id_of(v: &serde_json::Value) -> Option<String> {
125    match v {
126        serde_json::Value::String(s) => Some(s.clone()),
127        serde_json::Value::Object(o) => o.get("id").and_then(|i| i.as_str()).map(str::to_owned),
128        _ => None,
129    }
130}
131
132fn strings(v: &serde_json::Value) -> Vec<String> {
133    match v {
134        serde_json::Value::String(s) => vec![s.clone()],
135        serde_json::Value::Array(a) => a
136            .iter()
137            .filter_map(|t| t.as_str().map(str::to_owned))
138            .collect(),
139        _ => Vec::new(),
140    }
141}
142
143fn time(v: &serde_json::Value) -> Option<f64> {
144    oxilite_core::encoding::timestamp(v.as_str()?, XSD_DATE_TIME)
145}
146
147/// Checks a credential's structure and extracts its metadata.
148pub fn credential_input(json: &str, key: Option<String>) -> Result<DocumentInput, JsonLdError> {
149    let doc = parse(json)?;
150    let profile = match version(&doc)? {
151        1 => {
152            serde_json::from_value::<ssi_vc::v1::JsonCredential>(doc.clone())
153                .map_err(|e| invalid(format!("not a VCDM 1.1 credential: {e}")))?;
154            Profile::Vc1
155        }
156        _ => {
157            serde_json::from_value::<ssi_vc::v2::JsonCredential>(doc.clone())
158                .map_err(|e| invalid(format!("not a VCDM 2.0 credential: {e}")))?;
159            Profile::Vc2
160        }
161    };
162    let subject = match &doc["credentialSubject"] {
163        serde_json::Value::Array(a) => a.iter().find_map(id_of),
164        v => id_of(v),
165    };
166    let meta = DocumentMeta {
167        profile: profile.as_str().into(),
168        issuer: id_of(&doc["issuer"]),
169        subject,
170        types: strings(&doc["type"]),
171        valid_from: time(&doc["validFrom"]).or_else(|| time(&doc["issuanceDate"])),
172        valid_until: time(&doc["validUntil"]).or_else(|| time(&doc["expirationDate"])),
173        refs: Vec::new(),
174    };
175    Ok(DocumentInput {
176        json: json.to_owned(),
177        key,
178        meta,
179    })
180}
181
182/// Checks a presentation and prepares it, plus (when enabled) each embedded credential as a
183/// document of its own. The presentation comes first.
184pub fn presentation_inputs(
185    json: &str,
186    key: Option<String>,
187    options: &CredentialOptions,
188) -> Result<Vec<DocumentInput>, JsonLdError> {
189    let doc = parse(json)?;
190    let v = version(&doc)?;
191    let profile = if v == 1 {
192        serde_json::from_value::<ssi_vc::v1::JsonPresentation<json_syntax::Value>>(doc.clone())
193            .map_err(|e| invalid(format!("not a VCDM 1.1 presentation: {e}")))?;
194        Profile::Vp1
195    } else {
196        serde_json::from_value::<ssi_vc::v2::syntax::JsonPresentation<json_syntax::Value>>(
197            doc.clone(),
198        )
199        .map_err(|e| invalid(format!("not a VCDM 2.0 presentation: {e}")))?;
200        Profile::Vp2
201    };
202    let mut embedded = Vec::new();
203    if options.embed_presentation_credentials {
204        // Re-read with json-syntax, which keeps member order, to print embedded credentials.
205        let (tree, _) =
206            json_syntax::Value::parse_str(json).map_err(|e| JsonLdError::Json(e.to_string()))?;
207        let vcs = tree
208            .as_object()
209            .and_then(|o| o.get_unique("verifiableCredential").ok().flatten());
210        let items: Vec<&json_syntax::Value> = match vcs {
211            Some(json_syntax::Value::Array(a)) => a.iter().collect(),
212            Some(v) => vec![v],
213            None => Vec::new(),
214        };
215        for item in items {
216            let Some(obj) = item.as_object() else {
217                continue;
218            };
219            // Enveloped credentials (VC-JOSE/COSE) carry no JSON-LD body to store.
220            let types = obj
221                .get_unique("type")
222                .ok()
223                .flatten()
224                .map(|t| t.compact_print().to_string())
225                .unwrap_or_default();
226            if types.contains("EnvelopedVerifiableCredential") {
227                continue;
228            }
229            let text = item.compact_print().to_string();
230            let mut input = credential_input(&text, None)
231                .map_err(|e| invalid(format!("embedded credential: {e}")))?;
232            let (tree, _) = json_syntax::Value::parse_str(&text)
233                .map_err(|e| JsonLdError::Json(e.to_string()))?;
234            let k = options.jsonld.key_for(&text, &tree, None)?;
235            input.key = Some(k);
236            embedded.push(input);
237        }
238    }
239    let holder = id_of(&doc["holder"]);
240    let mut vp = DocumentInput {
241        json: json.to_owned(),
242        key,
243        meta: DocumentMeta {
244            profile: profile.as_str().into(),
245            issuer: None,
246            subject: holder,
247            types: strings(&doc["type"]),
248            valid_from: None,
249            valid_until: None,
250            refs: embedded.iter().filter_map(|e| e.key.clone()).collect(),
251        },
252    };
253    if vp.key.is_none() {
254        let (tree, _) =
255            json_syntax::Value::parse_str(json).map_err(|e| JsonLdError::Json(e.to_string()))?;
256        vp.key = Some(options.jsonld.key_for(json, &tree, None)?);
257    }
258    let mut out = vec![vp];
259    out.extend(embedded);
260    Ok(out)
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn detects_versions_and_metadata() {
269        let v1 = r#"{"@context": ["https://www.w3.org/2018/credentials/v1"], "id": "urn:uuid:1", "type": ["VerifiableCredential"], "issuer": {"id": "did:example:i"}, "issuanceDate": "2020-01-01T00:00:00Z", "expirationDate": "2030-01-01T00:00:00Z", "credentialSubject": {"id": "did:example:s"}}"#;
270        let i = credential_input(v1, None).unwrap();
271        assert_eq!(i.meta.profile, "vc1");
272        assert_eq!(i.meta.issuer.as_deref(), Some("did:example:i"));
273        assert_eq!(i.meta.subject.as_deref(), Some("did:example:s"));
274        assert_eq!(i.meta.valid_from, Some(1_577_836_800.0));
275        assert_eq!(i.meta.valid_until, Some(1_893_456_000.0));
276        let bad = r#"{"@context": ["https://example.org/ctx"], "type": ["VerifiableCredential"]}"#;
277        assert!(matches!(
278            credential_input(bad, None),
279            Err(JsonLdError::Invalid(_))
280        ));
281    }
282}