identity_kit/vc/validation/
credential.rs1use std::collections::BTreeSet;
4
5use crate::did::Uri;
6use crate::jose::{CompactJws, DefaultVerifier, Jwk, JwsHeader, JwsVerifier};
7use crate::vc::{Credential, CredentialV2, Jwt, JwtClaims, Party};
8
9use serde_json::Value;
10
11use super::{
12 CredentialStatus, CredentialValidationOptions, KeyReference, KeyResolver, KeyRole, StatusCheck,
13 StatusPolicy, TimeOptions, ValidationError, check_statuses, status_claim, status_claim_entry,
14};
15
16#[derive(Debug, Clone)]
19#[non_exhaustive]
20pub struct DecodedCredential {
21 pub header: JwsHeader,
23 pub claims: JwtClaims,
25 pub credential: Credential,
27}
28
29#[derive(Debug, Clone)]
31#[non_exhaustive]
32pub struct DecodedCredentialV2 {
33 pub header: JwsHeader,
35 pub claims: JwtClaims,
37 pub credential: CredentialV2,
39}
40
41pub struct JwtCredentialValidator<R, V = DefaultVerifier> {
102 resolver: R,
103 verifier: V,
104 status: Option<Box<dyn StatusCheck>>,
105}
106
107impl<R: KeyResolver, V: JwsVerifier> JwtCredentialValidator<R, V> {
108 pub fn new(resolver: R, verifier: V) -> Self {
111 Self {
112 resolver,
113 verifier,
114 status: None,
115 }
116 }
117
118 #[must_use]
120 pub fn with_status_check(mut self, check: impl StatusCheck + 'static) -> Self {
121 self.status = Some(Box::new(check));
122 self
123 }
124
125 pub fn resolver(&self) -> &R {
127 &self.resolver
128 }
129
130 pub fn verifier(&self) -> &V {
132 &self.verifier
133 }
134
135 pub fn has_status_check(&self) -> bool {
137 self.status.is_some()
138 }
139
140 pub async fn validate(
147 &self,
148 jwt: &Jwt,
149 options: &CredentialValidationOptions,
150 ) -> Result<DecodedCredential, ValidationError> {
151 let jws = jwt.decode()?;
152 let decoded = decode(&jws, &options.additional_typ)?;
153 let issuer = &decoded.credential.issuer;
154 let (reference, key) = self
155 .verify(&jws, KeyRole::Issuer, Some(issuer.id().as_str()))
156 .await?;
157 check_controller(issuer, &reference, &key, "issuer")?;
158 options.time.check_claims(&decoded.claims)?;
159 options.time.check(
160 Some(decoded.credential.issuance_date),
161 decoded.credential.expiration_date,
162 None,
163 )?;
164 let status = status_claim(&decoded.claims, options.status)?;
165 self.check_status(
166 decoded
167 .credential
168 .credential_status
169 .iter()
170 .map(CredentialStatus::Vcdm)
171 .chain(status.iter().map(status_claim_entry))
172 .collect(),
173 options.status,
174 options.time,
175 )
176 .await?;
177 Ok(decoded)
178 }
179
180 pub async fn validate_v2(
186 &self,
187 jwt: &Jwt,
188 options: &CredentialValidationOptions,
189 ) -> Result<DecodedCredentialV2, ValidationError> {
190 let jws = jwt.decode()?;
191 let decoded = decode_v2(&jws, &options.additional_typ)?;
192 let issuer = &decoded.credential.issuer;
193 let (reference, key) = self
194 .verify(&jws, KeyRole::Issuer, Some(issuer.id().as_str()))
195 .await?;
196 check_controller(issuer, &reference, &key, "issuer")?;
197 options.time.check_claims(&decoded.claims)?;
198 options.time.check(
199 decoded.credential.valid_from,
200 decoded.credential.valid_until,
201 None,
202 )?;
203 let status = status_claim(&decoded.claims, options.status)?;
204 self.check_status(
205 decoded
206 .credential
207 .statuses()
208 .map(CredentialStatus::Vcdm)
209 .chain(status.iter().map(status_claim_entry))
210 .collect(),
211 options.status,
212 options.time,
213 )
214 .await?;
215 Ok(decoded)
216 }
217
218 pub(super) async fn verify(
221 &self,
222 jws: &CompactJws,
223 role: KeyRole,
224 iss: Option<&str>,
225 ) -> Result<(KeyReference, Jwk), ValidationError> {
226 let reference = KeyReference::from_jws(jws, iss)?;
227 let key = self
228 .resolver
229 .resolve_key(&reference, role)
230 .await
231 .map_err(|source| ValidationError::KeyResolution {
232 key: Box::new(reference.clone()),
233 source,
234 })?;
235 jws.verify(&self.verifier, &key)?;
236 Ok((reference, key))
237 }
238
239 pub(super) async fn check_status(
241 &self,
242 statuses: Vec<CredentialStatus<'_>>,
243 policy: StatusPolicy,
244 time: TimeOptions,
245 ) -> Result<(), ValidationError> {
246 check_statuses(self.status.as_deref(), statuses, policy, time).await
247 }
248}
249
250impl<R: core::fmt::Debug, V: core::fmt::Debug> core::fmt::Debug for JwtCredentialValidator<R, V> {
251 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
252 f.debug_struct("JwtCredentialValidator")
253 .field("resolver", &self.resolver)
254 .field("verifier", &self.verifier)
255 .field("status", &self.status.as_ref().map(|_| "StatusCheck"))
256 .finish()
257 }
258}
259
260pub fn decode_credential(jwt: &Jwt) -> Result<DecodedCredential, ValidationError> {
268 decode(&jwt.decode()?, &NO_TYP)
269}
270
271pub fn decode_credential_v2(jwt: &Jwt) -> Result<DecodedCredentialV2, ValidationError> {
277 decode_v2(&jwt.decode()?, &NO_TYP)
278}
279
280pub(super) static NO_TYP: BTreeSet<String> = BTreeSet::new();
282
283pub(super) fn decode(
286 jws: &CompactJws,
287 additional_typ: &BTreeSet<String>,
288) -> Result<DecodedCredential, ValidationError> {
289 check_typ(jws.header(), "JWT", additional_typ)?;
290 let claims = plain_claims(jws)?;
291 let credential = Credential::from_jwt_claims(&claims)?;
292 Ok(DecodedCredential {
293 header: jws.header().clone(),
294 claims,
295 credential,
296 })
297}
298
299pub(super) fn decode_v2(
303 jws: &CompactJws,
304 additional_typ: &BTreeSet<String>,
305) -> Result<DecodedCredentialV2, ValidationError> {
306 check_typ(jws.header(), CredentialV2::JWT_TYP, additional_typ)?;
307 let claims = plain_claims(jws)?;
308 let credential = CredentialV2::from_jwt_claims(&claims)?;
309 Ok(DecodedCredentialV2 {
310 header: jws.header().clone(),
311 claims,
312 credential,
313 })
314}
315
316pub(super) fn plain_claims(jws: &CompactJws) -> Result<JwtClaims, ValidationError> {
319 let claims: JwtClaims =
320 serde_json::from_slice(jws.payload()).map_err(ValidationError::Payload)?;
321 match claims
322 .additional
323 .iter()
324 .find_map(|(name, value)| sd_jwt_member(name, value))
325 {
326 Some(claim) => Err(ValidationError::SdJwtPayload { claim }),
327 None => Ok(claims),
328 }
329}
330
331const SD_JWT_NAMES: [&str; 2] = ["_sd", "_sd_alg"];
334const ELLIPSIS: &str = "...";
335
336fn sd_jwt_member(name: &str, value: &Value) -> Option<&'static str> {
339 SD_JWT_NAMES
340 .into_iter()
341 .find(|reserved| *reserved == name)
342 .or_else(|| sd_jwt_name_in(value))
343}
344
345fn sd_jwt_name_in(value: &Value) -> Option<&'static str> {
347 match value {
348 Value::Object(object) => object
349 .iter()
350 .find_map(|(name, value)| sd_jwt_member(name, value)),
351 Value::Array(array) => array.iter().find_map(|element| match element {
352 Value::Object(object)
353 if object.len() == 1 && object.get(ELLIPSIS).is_some_and(Value::is_string) =>
354 {
355 Some(ELLIPSIS)
356 }
357 element => sd_jwt_name_in(element),
358 }),
359 _ => None,
360 }
361}
362
363pub(super) fn check_typ(
365 header: &JwsHeader,
366 expected: &'static str,
367 additional: &BTreeSet<String>,
368) -> Result<(), ValidationError> {
369 match header.typ.as_deref() {
370 Some(found) if found != expected && !additional.contains(found) => {
371 Err(ValidationError::UnexpectedTyp {
372 expected,
373 found: found.to_owned(),
374 })
375 }
376 _ => Ok(()),
377 }
378}
379
380pub(super) fn check_controller(
383 party: &Party,
384 reference: &KeyReference,
385 key: &Jwk,
386 role: &'static str,
387) -> Result<(), ValidationError> {
388 let id = party.id();
389 if !reference.binds_to(Some(id.as_str()), key) {
390 return Err(mismatch(role, id.clone(), reference.clone()));
391 }
392 Ok(())
393}
394
395fn mismatch(role: &'static str, id: Uri, key: KeyReference) -> ValidationError {
397 if role == "holder" {
398 ValidationError::HolderMismatch {
399 holder: id,
400 key: Box::new(key),
401 }
402 } else {
403 ValidationError::IssuerMismatch {
404 issuer: id,
405 key: Box::new(key),
406 }
407 }
408}