identity_credential/validator/jpt_presentation_validation/
jpt_presentation_validator.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
218
219
220
221
222
223
224
225
226
// Copyright 2020-2024 IOTA Stiftung, Fondazione Links
// SPDX-License-Identifier: Apache-2.0

use std::str::FromStr;

use identity_core::common::Url;
use identity_core::convert::FromJson;
use identity_core::convert::ToJson;
use identity_did::CoreDID;
use identity_did::DIDUrl;
use identity_document::document::CoreDocument;
use jsonprooftoken::encoding::SerializationType;
use jsonprooftoken::jpt::claims::JptClaims;
use jsonprooftoken::jwk::key::Jwk as JwkExt;
use jsonprooftoken::jwp::presented::JwpPresentedDecoder;

use crate::credential::Credential;
use crate::credential::CredentialJwtClaims;
use crate::credential::Jpt;
use crate::validator::CompoundCredentialValidationError;
use crate::validator::FailFast;
use crate::validator::JwtCredentialValidatorUtils;
use crate::validator::JwtValidationError;
use crate::validator::SignerContext;

use super::DecodedJptPresentation;
use super::JptPresentationValidationOptions;

/// A type for decoding and validating Presented [`Credential`]s in JPT format.
#[non_exhaustive]
pub struct JptPresentationValidator;

impl JptPresentationValidator {
  /// Decodes and validates a Presented [`Credential`] issued as a JPT (JWP Presented Form). A
  /// [`DecodedJptPresentation`] is returned upon success.
  ///
  /// The following properties are validated according to `options`:
  /// - the holder's proof on the JWP,
  /// - the expiration date,
  /// - the issuance date,
  /// - the semantic structure.
  pub fn validate<DOC, T>(
    presentation_jpt: &Jpt,
    issuer: &DOC,
    options: &JptPresentationValidationOptions,
    fail_fast: FailFast,
  ) -> Result<DecodedJptPresentation<T>, CompoundCredentialValidationError>
  where
    T: ToOwned<Owned = T> + serde::Serialize + serde::de::DeserializeOwned,
    DOC: AsRef<CoreDocument>,
  {
    // First verify the JWP proof and decode the result into a presented credential token, then apply all other
    // validations.
    let presented_credential_token =
      Self::verify_proof(presentation_jpt, issuer, options).map_err(|err| CompoundCredentialValidationError {
        validation_errors: [err].into(),
      })?;

    let credential: &Credential<T> = &presented_credential_token.credential;

    Self::validate_presented_credential::<T>(credential, fail_fast)?;

    Ok(presented_credential_token)
  }

  pub(crate) fn validate_presented_credential<T>(
    credential: &Credential<T>,
    fail_fast: FailFast,
  ) -> Result<(), CompoundCredentialValidationError>
  where
    T: ToOwned<Owned = T> + serde::Serialize + serde::de::DeserializeOwned,
  {
    let structure_validation = std::iter::once_with(|| JwtCredentialValidatorUtils::check_structure(credential));

    let validation_units_iter = structure_validation;

    let validation_units_error_iter = validation_units_iter.filter_map(|result| result.err());
    let validation_errors: Vec<JwtValidationError> = match fail_fast {
      FailFast::FirstError => validation_units_error_iter.take(1).collect(),
      FailFast::AllErrors => validation_units_error_iter.collect(),
    };

    if validation_errors.is_empty() {
      Ok(())
    } else {
      Err(CompoundCredentialValidationError { validation_errors })
    }
  }

  /// Proof verification function
  fn verify_proof<DOC, T>(
    presentation_jpt: &Jpt,
    issuer: &DOC,
    options: &JptPresentationValidationOptions,
  ) -> Result<DecodedJptPresentation<T>, JwtValidationError>
  where
    T: ToOwned<Owned = T> + serde::Serialize + serde::de::DeserializeOwned,
    DOC: AsRef<CoreDocument>,
  {
    let decoded: JwpPresentedDecoder =
      JwpPresentedDecoder::decode(presentation_jpt.as_str(), SerializationType::COMPACT)
        .map_err(JwtValidationError::JwpDecodingError)?;

    let nonce: Option<&String> = options.nonce.as_ref();
    // Validate the nonce
    if decoded.get_presentation_header().nonce() != nonce {
      return Err(JwtValidationError::JwsDecodingError(
        identity_verification::jose::error::Error::InvalidParam("invalid nonce value"),
      ));
    }

    // If no method_url is set, parse the `kid` to a DID Url which should be the identifier
    // of a verification method in a trusted issuer's DID document.
    let method_id: DIDUrl = match &options.verification_options.method_id {
      Some(method_id) => method_id.clone(),
      None => {
        let kid: &str = decoded
          .get_issuer_header()
          .kid()
          .ok_or(JwtValidationError::MethodDataLookupError {
            source: None,
            message: "could not extract kid from protected header",
            signer_ctx: SignerContext::Issuer,
          })?;

        // Convert kid to DIDUrl
        DIDUrl::parse(kid).map_err(|err| JwtValidationError::MethodDataLookupError {
          source: Some(err.into()),
          message: "could not parse kid as a DID Url",
          signer_ctx: SignerContext::Issuer,
        })?
      }
    };

    // check issuer
    let issuer: &CoreDocument = issuer.as_ref();

    if issuer.id() != method_id.did() {
      return Err(JwtValidationError::DocumentMismatch(SignerContext::Issuer));
    }

    // Obtain the public key from the issuer's DID document
    let public_key: JwkExt = issuer
      .resolve_method(&method_id, options.verification_options.method_scope)
      .and_then(|method| method.data().public_key_jwk())
      .and_then(|k| k.try_into().ok()) //Conversio into jsonprooftoken::Jwk type
      .ok_or_else(|| JwtValidationError::MethodDataLookupError {
        source: None,
        message: "could not extract JWK from a method identified by kid",
        signer_ctx: SignerContext::Issuer,
      })?;

    let credential_token = Self::verify_decoded_jwp(decoded, &public_key)?;

    // Check that the DID component of the parsed `kid` does indeed correspond to the issuer in the credential before
    // returning.
    let issuer_id: CoreDID = JwtCredentialValidatorUtils::extract_issuer(&credential_token.credential)?;
    if &issuer_id != method_id.did() {
      return Err(JwtValidationError::IdentifierMismatch {
        signer_ctx: SignerContext::Issuer,
      });
    };
    Ok(credential_token)
  }

  /// Verify the decoded presented JWP proof using the given `public_key`.
  fn verify_decoded_jwp<T>(
    decoded: JwpPresentedDecoder,
    public_key: &JwkExt,
  ) -> Result<DecodedJptPresentation<T>, JwtValidationError>
  where
    T: ToOwned<Owned = T> + serde::Serialize + serde::de::DeserializeOwned,
  {
    // Verify Jwp proof
    let decoded_jwp = decoded
      .verify(public_key)
      .map_err(JwtValidationError::JwpProofVerificationError)?;

    let claims = decoded_jwp.get_claims().ok_or("Claims not present").map_err(|err| {
      JwtValidationError::CredentialStructure(crate::Error::JptClaimsSetDeserializationError(err.into()))
    })?;
    let payloads = decoded_jwp.get_payloads();
    let mut jpt_claims = JptClaims::from_claims_and_payloads(claims, payloads);
    // if not set the deserializatioon will throw an error since even the iat is not set, so we set this to 0
    jpt_claims.nbf.map_or_else(
      || {
        jpt_claims.set_nbf(0);
      },
      |_| (),
    );

    let jpt_claims_json = jpt_claims.to_json_vec().map_err(|err| {
      JwtValidationError::CredentialStructure(crate::Error::JptClaimsSetDeserializationError(err.into()))
    })?;

    // Deserialize the raw claims
    let credential_claims: CredentialJwtClaims<'_, T> = CredentialJwtClaims::from_json_slice(&jpt_claims_json)
      .map_err(|err| {
        JwtValidationError::CredentialStructure(crate::Error::JwtClaimsSetDeserializationError(err.into()))
      })?;

    let custom_claims = credential_claims.custom.clone();

    // Construct the credential token containing the credential and the protected header.
    let credential: Credential<T> = credential_claims
      .try_into_credential()
      .map_err(JwtValidationError::CredentialStructure)?;

    let aud: Option<Url> = decoded_jwp.get_presentation_protected_header().aud().and_then(|aud| {
      Url::from_str(aud)
        .map_err(|_| {
          JwtValidationError::JwsDecodingError(identity_verification::jose::error::Error::InvalidParam(
            "invalid audience value",
          ))
        })
        .ok()
    });

    Ok(DecodedJptPresentation {
      credential,
      aud,
      custom_claims,
      decoded_jwp,
    })
  }
}