identity_credential/sd_jwt_vc/
claims.rs

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
// Copyright 2020-2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::ops::Deref;
use std::ops::DerefMut;

use identity_core::common::StringOrUrl;
use identity_core::common::Timestamp;
use identity_core::common::Url;
use sd_jwt_payload_rework::Disclosure;
use sd_jwt_payload_rework::SdJwtClaims;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

use super::Error;
use super::Result;
use super::Status;

/// JOSE payload claims for SD-JWT VC.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SdJwtVcClaims {
  /// Issuer.
  pub iss: Url,
  /// Not before.
  /// See [RFC7519 section 4.1.5](https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.5) for more information.
  pub nbf: Option<Timestamp>,
  /// Expiration.
  /// See [RFC7519 section 4.1.4](https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.4) for more information.
  pub exp: Option<Timestamp>,
  /// Verifiable credential type.
  /// See [SD-JWT VC specification](https://www.ietf.org/archive/id/draft-ietf-oauth-sd-jwt-vc-04.html#type-claim)
  /// for more information.
  pub vct: StringOrUrl,
  /// Token's status.
  /// See [OAuth status list specification](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-status-list-02)
  /// for more information.
  pub status: Option<Status>,
  /// Issued at.
  /// See [RFC7519 section 4.1.6](https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.6) for more information.
  pub iat: Option<Timestamp>,
  /// Subject.
  /// See [RFC7519 section 4.1.2](https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.2) for more information.
  pub sub: Option<StringOrUrl>,
  #[serde(flatten)]
  pub(crate) sd_jwt_claims: SdJwtClaims,
}

impl Deref for SdJwtVcClaims {
  type Target = SdJwtClaims;
  fn deref(&self) -> &Self::Target {
    &self.sd_jwt_claims
  }
}

impl DerefMut for SdJwtVcClaims {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.sd_jwt_claims
  }
}

impl SdJwtVcClaims {
  pub(crate) fn try_from_sd_jwt_claims(mut claims: SdJwtClaims, disclosures: &[Disclosure]) -> Result<Self> {
    let check_disclosed = |claim_name: &'static str| {
      disclosures
        .iter()
        .any(|disclosure| disclosure.claim_name.as_deref() == Some(claim_name))
        .then_some(Error::DisclosedClaim(claim_name))
    };
    let iss = claims
      .remove("iss")
      .ok_or(Error::MissingClaim("iss"))
      .map_err(|e| check_disclosed("iss").unwrap_or(e))
      .and_then(|value| {
        value
          .as_str()
          .and_then(|s| Url::parse(s).ok())
          .ok_or_else(|| Error::InvalidClaimValue {
            name: "iss",
            expected: "URL",
            found: value,
          })
      })?;
    let nbf = {
      if let Some(value) = claims.remove("nbf") {
        value
          .as_number()
          .and_then(|t| t.as_i64())
          .and_then(|t| Timestamp::from_unix(t).ok())
          .ok_or_else(|| Error::InvalidClaimValue {
            name: "nbf",
            expected: "unix timestamp",
            found: value,
          })
          .map(Some)?
      } else {
        if let Some(err) = check_disclosed("nbf") {
          return Err(err);
        }
        None
      }
    };
    let exp = {
      if let Some(value) = claims.remove("exp") {
        value
          .as_number()
          .and_then(|t| t.as_i64())
          .and_then(|t| Timestamp::from_unix(t).ok())
          .ok_or_else(|| Error::InvalidClaimValue {
            name: "exp",
            expected: "unix timestamp",
            found: value,
          })
          .map(Some)?
      } else {
        if let Some(err) = check_disclosed("exp") {
          return Err(err);
        }
        None
      }
    };
    let vct = claims
      .remove("vct")
      .ok_or(Error::MissingClaim("vct"))
      .map_err(|e| check_disclosed("vct").unwrap_or(e))
      .and_then(|value| {
        value
          .as_str()
          .and_then(|s| StringOrUrl::parse(s).ok())
          .ok_or_else(|| Error::InvalidClaimValue {
            name: "vct",
            expected: "String or URL",
            found: value,
          })
      })?;
    let status = {
      if let Some(value) = claims.remove("status") {
        serde_json::from_value::<Status>(value.clone())
          .map_err(|_| Error::InvalidClaimValue {
            name: "status",
            expected: "credential's status object",
            found: value,
          })
          .map(Some)?
      } else {
        if let Some(err) = check_disclosed("status") {
          return Err(err);
        }
        None
      }
    };
    let sub = claims
      .remove("sub")
      .map(|value| {
        value
          .as_str()
          .and_then(|s| StringOrUrl::parse(s).ok())
          .ok_or_else(|| Error::InvalidClaimValue {
            name: "sub",
            expected: "String or URL",
            found: value,
          })
      })
      .transpose()?;
    let iat = claims
      .remove("iat")
      .map(|value| {
        value
          .as_number()
          .and_then(|t| t.as_i64())
          .and_then(|t| Timestamp::from_unix(t).ok())
          .ok_or_else(|| Error::InvalidClaimValue {
            name: "iat",
            expected: "unix timestamp",
            found: value,
          })
      })
      .transpose()?;

    Ok(Self {
      iss,
      nbf,
      exp,
      vct,
      status,
      iat,
      sub,
      sd_jwt_claims: claims,
    })
  }
}

impl From<SdJwtVcClaims> for SdJwtClaims {
  fn from(claims: SdJwtVcClaims) -> Self {
    let SdJwtVcClaims {
      iss,
      nbf,
      exp,
      vct,
      status,
      iat,
      sub,
      mut sd_jwt_claims,
    } = claims;

    sd_jwt_claims.insert("iss".to_string(), Value::String(iss.into_string()));
    nbf.and_then(|t| sd_jwt_claims.insert("nbf".to_string(), Value::Number(t.to_unix().into())));
    exp.and_then(|t| sd_jwt_claims.insert("exp".to_string(), Value::Number(t.to_unix().into())));
    sd_jwt_claims.insert("vct".to_string(), Value::String(vct.into()));
    status.and_then(|status| sd_jwt_claims.insert("status".to_string(), serde_json::to_value(status).unwrap()));
    iat.and_then(|t| sd_jwt_claims.insert("iat".to_string(), Value::Number(t.to_unix().into())));
    sub.and_then(|sub| sd_jwt_claims.insert("sub".to_string(), Value::String(sub.into())));

    sd_jwt_claims
  }
}