identity_credential 0.7.0-alpha.7

An implementation of the Verifiable Credentials standard.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// Copyright 2020-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::borrow::Cow;

use serde::Deserialize;
use serde::Serialize;

use identity_core::common::Context;
use identity_core::common::Object;
use identity_core::common::OneOrMany;
use identity_core::common::Timestamp;
use identity_core::common::Url;
use serde::de::DeserializeOwned;

use crate::credential::Credential;
use crate::credential::Evidence;
use crate::credential::Issuer;
use crate::credential::Policy;
use crate::credential::Proof;
use crate::credential::RefreshService;
use crate::credential::Schema;
use crate::credential::Status;
use crate::credential::Subject;
use crate::Error;
use crate::Result;

/// Implementation of JWT Encoding/Decoding according to https://w3c.github.io/vc-jwt/#version-1.1.
///
/// This type is opinionated in the following ways:
/// 1. Serialization tries to duplicate as little as possible between the required registered claims and the `vc` entry.
/// 2. Only allows serializing/deserializing claims "exp, iss, nbf &/or iat, jti, sub and vc". Other custom properties
/// must be set in the `vc` entry.
#[derive(Serialize, Deserialize)]
pub(crate) struct CredentialJwtClaims<'credential, T = Object>
where
  T: ToOwned + Serialize,
  <T as ToOwned>::Owned: DeserializeOwned,
{
  /// Represents the expirationDate encoded as a UNIX timestamp.  
  #[serde(skip_serializing_if = "Option::is_none")]
  exp: Option<i64>,
  /// Represents the issuer.
  pub(crate) iss: Cow<'credential, Issuer>,

  /// Represents the issuanceDate encoded as a UNIX timestamp.
  #[serde(flatten)]
  issuance_date: IssuanceDateClaims,

  /// Represents the id property of the credential.
  #[serde(skip_serializing_if = "Option::is_none")]
  jti: Option<Cow<'credential, Url>>,

  /// Represents the subject's id.
  #[serde(skip_serializing_if = "Option::is_none")]
  sub: Option<Cow<'credential, Url>>,

  vc: InnerCredential<'credential, T>,
}

impl<'credential, T> CredentialJwtClaims<'credential, T>
where
  T: ToOwned<Owned = T> + Serialize + DeserializeOwned,
{
  pub(super) fn new(credential: &'credential Credential<T>) -> Result<Self> {
    let Credential {
      context,
      id,
      types,
      credential_subject: OneOrMany::One(subject),
      issuer,
      issuance_date,
      expiration_date,
      credential_status,
      credential_schema,
      refresh_service,
      terms_of_use,
      evidence,
      non_transferable,
      properties,
      proof,
    } = credential
    else {
      return Err(Error::MoreThanOneSubjectInJwt);
    };

    Ok(Self {
      exp: expiration_date.map(|value| Timestamp::to_unix(&value)),
      iss: Cow::Borrowed(issuer),
      issuance_date: IssuanceDateClaims::new(*issuance_date),
      jti: id.as_ref().map(Cow::Borrowed),
      sub: subject.id.as_ref().map(Cow::Borrowed),
      vc: InnerCredential {
        context: Cow::Borrowed(context),
        id: None,
        types: Cow::Borrowed(types),
        credential_subject: InnerCredentialSubject::new(subject),
        issuance_date: None,
        expiration_date: None,
        credential_schema: Cow::Borrowed(credential_schema),
        credential_status: credential_status.as_ref().map(Cow::Borrowed),
        refresh_service: Cow::Borrowed(refresh_service),
        terms_of_use: Cow::Borrowed(terms_of_use),
        evidence: Cow::Borrowed(evidence),
        non_transferable: *non_transferable,
        properties: Cow::Borrowed(properties),
        proof: proof.as_ref().map(Cow::Borrowed),
      },
    })
  }
}

#[cfg(feature = "validator")]
impl<'credential, T> CredentialJwtClaims<'credential, T>
where
  T: ToOwned<Owned = T> + Serialize + DeserializeOwned,
{
  /// Checks whether the fields that are set in the `vc` object are consistent with the corresponding values
  /// set for the registered claims.
  fn check_consistency(&self) -> Result<()> {
    // Check consistency of issuanceDate
    let issuance_date_from_claims = self.issuance_date.to_issuance_date()?;
    if !self
      .vc
      .issuance_date
      .map(|value| value == issuance_date_from_claims)
      .unwrap_or(true)
    {
      return Err(Error::InconsistentCredentialJwtClaims("inconsistent issuanceDate"));
    };

    // Check consistency of expirationDate
    if !self
      .vc
      .expiration_date
      .map(|value| self.exp.filter(|exp| *exp == value.to_unix()).is_some())
      .unwrap_or(true)
    {
      return Err(Error::InconsistentCredentialJwtClaims(
        "inconsistent credential expirationDate",
      ));
    };

    // Check consistency of id
    if !self
      .vc
      .id
      .as_ref()
      .map(|value| self.jti.as_ref().filter(|jti| jti.as_ref() == value).is_some())
      .unwrap_or(true)
    {
      return Err(Error::InconsistentCredentialJwtClaims("inconsistent credential id"));
    };

    // Check consistency of credentialSubject
    if let Some(ref inner_credential_subject_id) = self.vc.credential_subject.id {
      let subject_claim = self.sub.as_ref().ok_or(Error::InconsistentCredentialJwtClaims(
        "inconsistent credentialSubject: expected identifier in sub",
      ))?;
      if subject_claim.as_ref() != inner_credential_subject_id {
        return Err(Error::InconsistentCredentialJwtClaims(
          "inconsistent credentialSubject: identifiers do not match",
        ));
      }
    };

    Ok(())
  }

  /// Converts the JWT representation into a [`Credential`].
  ///
  /// # Errors
  /// Errors if either timestamp conversion or [`Self::check_consistency`] fails.
  pub(crate) fn try_into_credential(self) -> Result<Credential<T>> {
    self.check_consistency()?;

    let Self {
      exp,
      iss,
      issuance_date,
      jti,
      sub,
      vc,
    } = self;

    let InnerCredential {
      context,
      id: _,
      types,
      credential_subject,
      credential_status,
      credential_schema,
      refresh_service,
      terms_of_use,
      evidence,
      non_transferable,
      properties,
      proof,
      issuance_date: _,
      expiration_date: _,
    } = vc;

    Ok(Credential {
      context: context.into_owned(),
      id: jti.map(Cow::into_owned),
      types: types.into_owned(),
      credential_subject: {
        OneOrMany::One(Subject {
          id: sub.map(Cow::into_owned),
          properties: credential_subject.properties.into_owned(),
        })
      },
      issuer: iss.into_owned(),
      issuance_date: issuance_date.to_issuance_date()?,
      expiration_date: exp
        .map(Timestamp::from_unix)
        .transpose()
        .map_err(|_| Error::TimestampConversionError)?,
      credential_status: credential_status.map(Cow::into_owned),
      credential_schema: credential_schema.into_owned(),
      refresh_service: refresh_service.into_owned(),
      terms_of_use: terms_of_use.into_owned(),
      evidence: evidence.into_owned(),
      non_transferable,
      properties: properties.into_owned(),
      proof: proof.map(Cow::into_owned),
    })
  }
}

/// The VC-JWT spec states that issuanceDate corresponds to the registered `nbf` claim,
/// but `iat` is also used in the ecosystem. This type aims to take care of this discrepancy on
/// a best effort basis.
#[derive(Serialize, Deserialize, Clone, Copy)]
pub(crate) struct IssuanceDateClaims {
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) iat: Option<i64>,
  #[serde(skip_serializing_if = "Option::is_none")]
  pub(crate) nbf: Option<i64>,
}

impl IssuanceDateClaims {
  pub(crate) fn new(issuance_date: Timestamp) -> Self {
    Self {
      iat: None,
      nbf: Some(issuance_date.to_unix()),
    }
  }
  /// Produces the `issuanceDate` value from `nbf` if it is set,
  /// otherwise falls back to `iat`. If none of these values are set an error is returned.
  #[cfg(feature = "validator")]
  pub(crate) fn to_issuance_date(self) -> Result<Timestamp> {
    if let Some(timestamp) = self
      .nbf
      .map(Timestamp::from_unix)
      .transpose()
      .map_err(|_| Error::TimestampConversionError)?
    {
      Ok(timestamp)
    } else {
      Timestamp::from_unix(self.iat.ok_or(Error::TimestampConversionError)?)
        .map_err(|_| Error::TimestampConversionError)
    }
  }
}

#[derive(Serialize, Deserialize)]
struct InnerCredentialSubject<'credential> {
  // Do not serialize this to save space as the value must be included in the `sub` claim.
  #[cfg(feature = "validator")]
  #[serde(skip_serializing)]
  id: Option<Url>,

  #[serde(flatten)]
  properties: Cow<'credential, Object>,
}

impl<'credential> InnerCredentialSubject<'credential> {
  fn new(subject: &'credential Subject) -> Self {
    Self {
      #[cfg(feature = "validator")]
      id: None,
      properties: Cow::Borrowed(&subject.properties),
    }
  }
}

/// Mostly copied from [`VerifiableCredential`] with the entries corresponding
/// to registered claims being the exception.
#[derive(Serialize, Deserialize)]
struct InnerCredential<'credential, T = Object>
where
  T: ToOwned + Serialize,
  <T as ToOwned>::Owned: DeserializeOwned,
{
  /// The JSON-LD context(s) applicable to the `Credential`.
  #[serde(rename = "@context")]
  context: Cow<'credential, OneOrMany<Context>>,
  /// A unique `URI` that may be used to identify the `Credential`.
  #[serde(skip_serializing_if = "Option::is_none")]
  id: Option<Url>,
  /// One or more URIs defining the type of the `Credential`.
  #[serde(rename = "type")]
  types: Cow<'credential, OneOrMany<String>>,
  /// One or more `Object`s representing the `Credential` subject(s).
  #[serde(rename = "credentialSubject")]
  credential_subject: InnerCredentialSubject<'credential>,
  /// A timestamp of when the `Credential` becomes valid.
  #[serde(rename = "issuanceDate", skip_serializing_if = "Option::is_none")]
  issuance_date: Option<Timestamp>,
  /// A timestamp of when the `Credential` should no longer be considered valid.
  #[serde(rename = "expirationDate", skip_serializing_if = "Option::is_none")]
  expiration_date: Option<Timestamp>,
  /// Information used to determine the current status of the `Credential`.
  #[serde(default, rename = "credentialStatus", skip_serializing_if = "Option::is_none")]
  credential_status: Option<Cow<'credential, Status>>,
  /// Information used to assist in the enforcement of a specific `Credential` structure.
  #[serde(default, rename = "credentialSchema", skip_serializing_if = "OneOrMany::is_empty")]
  credential_schema: Cow<'credential, OneOrMany<Schema>>,
  /// Service(s) used to refresh an expired `Credential`.
  #[serde(default, rename = "refreshService", skip_serializing_if = "OneOrMany::is_empty")]
  refresh_service: Cow<'credential, OneOrMany<RefreshService>>,
  /// Terms-of-use specified by the `Credential` issuer.
  #[serde(default, rename = "termsOfUse", skip_serializing_if = "OneOrMany::is_empty")]
  terms_of_use: Cow<'credential, OneOrMany<Policy>>,
  /// Human-readable evidence used to support the claims within the `Credential`.
  #[serde(default, skip_serializing_if = "OneOrMany::is_empty")]
  evidence: Cow<'credential, OneOrMany<Evidence>>,
  /// Indicates that the `Credential` must only be contained within a
  /// [`Presentation`][crate::presentation::Presentation] with a proof issued from the `Credential` subject.
  #[serde(rename = "nonTransferable", skip_serializing_if = "Option::is_none")]
  non_transferable: Option<bool>,
  /// Miscellaneous properties.
  #[serde(flatten)]
  properties: Cow<'credential, T>,
  /// Proof(s) used to verify a `Credential`
  #[serde(skip_serializing_if = "Option::is_none")]
  proof: Option<Cow<'credential, Proof>>,
}

#[cfg(test)]
mod tests {
  use identity_core::common::Object;
  use identity_core::convert::FromJson;
  use identity_core::convert::ToJson;

  use crate::credential::Credential;

  use super::CredentialJwtClaims;

  #[test]
  fn roundtrip() {
    let credential_json: &str = r#"
    {
      "@context": [
        "https://www.w3.org/2018/credentials/v1",
        "https://www.w3.org/2018/credentials/examples/v1"
      ],
      "id": "http://example.edu/credentials/3732",
      "type": ["VerifiableCredential", "UniversityDegreeCredential"],
      "issuer": "https://example.edu/issuers/14",
      "issuanceDate": "2010-01-01T19:23:24Z",
      "credentialSubject": {
        "id": "did:example:ebfeb1f712ebc6f1c276e12ec21",
        "degree": {
          "type": "BachelorDegree",
          "name": "Bachelor of Science in Mechanical Engineering"
        }
      }
    }"#;

    let expected_serialization_json: &str = r#"
    {
      "sub": "did:example:ebfeb1f712ebc6f1c276e12ec21",
      "jti": "http://example.edu/credentials/3732",
      "iss": "https://example.edu/issuers/14",
      "nbf":  1262373804,
      "vc": {
        "@context": [
        "https://www.w3.org/2018/credentials/v1",
        "https://www.w3.org/2018/credentials/examples/v1"
      ],
      "type": ["VerifiableCredential", "UniversityDegreeCredential"],
      "credentialSubject": {
        "degree": {
          "type": "BachelorDegree",
          "name": "Bachelor of Science in Mechanical Engineering"
          }
        }
      }
    }"#;

    let credential: Credential = Credential::from_json(credential_json).unwrap();
    let jwt_credential_claims: CredentialJwtClaims<'_> = CredentialJwtClaims::new(&credential).unwrap();
    let jwt_credential_claims_serialized: String = jwt_credential_claims.to_json().unwrap();
    // Compare JSON representations
    assert_eq!(
      Object::from_json(expected_serialization_json).unwrap(),
      Object::from_json(&jwt_credential_claims_serialized).unwrap()
    );

    // Retrieve the credential from the JWT serialization
    let retrieved_credential: Credential = {
      CredentialJwtClaims::<'static, Object>::from_json(&jwt_credential_claims_serialized)
        .unwrap()
        .try_into_credential()
        .unwrap()
    };

    assert_eq!(credential, retrieved_credential);
  }
}