Skip to content

Commit

Permalink
Allow custom JWT claims for credentials (#1237)
Browse files Browse the repository at this point in the history
  • Loading branch information
abdulmth authored Sep 20, 2023
1 parent 1644831 commit e429809
Show file tree
Hide file tree
Showing 19 changed files with 128 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use identity_iota::credential::DecodedJwtCredential;
use wasm_bindgen::prelude::*;

use crate::common::RecordStringAny;
use crate::credential::WasmCredential;
use crate::jose::WasmJwsHeader;

Expand All @@ -28,6 +29,18 @@ impl WasmDecodedJwtCredential {
WasmJwsHeader(self.0.header.as_ref().clone())
}

/// The custom claims parsed from the JWT.
#[wasm_bindgen(js_name = customClaims)]
pub fn custom_claims(&self) -> Option<RecordStringAny> {
match &self.0.custom_claims {
Some(claims) => JsValue::from_serde(&claims.clone())
.map(|js_val| js_val.unchecked_into::<RecordStringAny>())
.ok(),

None => None,
}
}

/// Consumes the object and returns the decoded credential.
///
/// ### Warning
Expand Down
7 changes: 6 additions & 1 deletion bindings/wasm/src/did/wasm_core_document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::common::MapStringAny;
use crate::common::OptionOneOrManyString;
use crate::common::PromiseString;
use crate::common::PromiseVoid;
use crate::common::RecordStringAny;
use crate::common::UDIDUrlQuery;
use crate::common::UOneOrManyNumber;
use crate::credential::ArrayCoreDID;
Expand Down Expand Up @@ -677,16 +678,20 @@ impl WasmCoreDocument {
fragment: String,
credential: &WasmCredential,
options: &WasmJwsSignatureOptions,
custom_claims: Option<RecordStringAny>,
) -> Result<PromiseJwt> {
let storage_clone: Rc<WasmStorageInner> = storage.0.clone();
let options_clone: JwsSignatureOptions = options.0.clone();
let document_lock_clone: Rc<CoreDocumentLock> = self.0.clone();
let credential_clone: Credential = credential.0.clone();
let custom: Option<Object> = custom_claims
.map(|claims| claims.into_serde().wasm_result())
.transpose()?;
let promise: Promise = future_to_promise(async move {
document_lock_clone
.read()
.await
.create_credential_jwt(&credential_clone, &storage_clone, &fragment, &options_clone)
.create_credential_jwt(&credential_clone, &storage_clone, &fragment, &options_clone, custom)
.await
.wasm_result()
.map(WasmJwt::new)
Expand Down
8 changes: 7 additions & 1 deletion bindings/wasm/src/iota/iota_document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use std::rc::Rc;

use identity_iota::core::Object;
use identity_iota::core::OneOrMany;
use identity_iota::core::OrderedSet;
use identity_iota::core::Timestamp;
Expand Down Expand Up @@ -37,6 +38,7 @@ use crate::common::OptionOneOrManyString;
use crate::common::OptionTimestamp;
use crate::common::PromiseString;
use crate::common::PromiseVoid;
use crate::common::RecordStringAny;
use crate::common::UDIDUrlQuery;
use crate::common::UOneOrManyNumber;
use crate::common::WasmTimestamp;
Expand Down Expand Up @@ -723,16 +725,20 @@ impl WasmIotaDocument {
fragment: String,
credential: &WasmCredential,
options: &WasmJwsSignatureOptions,
custom_claims: Option<RecordStringAny>,
) -> Result<PromiseJwt> {
let storage_clone: Rc<WasmStorageInner> = storage.0.clone();
let options_clone: JwsSignatureOptions = options.0.clone();
let document_lock_clone: Rc<IotaDocumentLock> = self.0.clone();
let credential_clone: Credential = credential.0.clone();
let custom: Option<Object> = custom_claims
.map(|claims| claims.into_serde().wasm_result())
.transpose()?;
let promise: Promise = future_to_promise(async move {
document_lock_clone
.read()
.await
.create_credential_jwt(&credential_clone, &storage_clone, &fragment, &options_clone)
.create_credential_jwt(&credential_clone, &storage_clone, &fragment, &options_clone, custom)
.await
.wasm_result()
.map(WasmJwt::new)
Expand Down
19 changes: 11 additions & 8 deletions bindings/wasm/tests/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,19 +135,21 @@ describe("#JwkStorageDocument", function() {
fragment,
credential,
new JwsSignatureOptions(),
{ testkey: "test-value" },
);

// Check that the credentialJwt can be decoded and verified
let credentialValidator = new JwtCredentialValidator();
const credentialRetrieved = credentialValidator

const decoded = credentialValidator
.validate(
credentialJwt,
doc,
new JwtCredentialValidationOptions(),
FailFast.FirstError,
)
.credential();
assert.deepStrictEqual(credentialRetrieved.toJSON(), credential.toJSON());
);
assert.deepStrictEqual(decoded.customClaims(), { testkey: "test-value" });
assert.deepStrictEqual(decoded.credential().toJSON(), credential.toJSON());

// Also check using our custom verifier
let credentialValidatorCustom = new JwtCredentialValidator(customVerifier);
Expand Down Expand Up @@ -245,19 +247,20 @@ describe("#JwkStorageDocument", function() {
fragment,
credential,
new JwsSignatureOptions(),
{ "test-key": "test-value" },
);

// Check that the credentialJwt can be decoded and verified
let credentialValidator = new JwtCredentialValidator();
const credentialRetrieved = credentialValidator
const decoded = credentialValidator
.validate(
credentialJwt,
doc,
new JwtCredentialValidationOptions(),
FailFast.FirstError,
)
.credential();
assert.deepStrictEqual(credentialRetrieved.toJSON(), credential.toJSON());
);
assert.deepStrictEqual(decoded.customClaims(), { "test-key": "test-value" });
assert.deepStrictEqual(decoded.credential().toJSON(), credential.toJSON());

// Also check using our custom verifier
let credentialValidatorCustom = new JwtCredentialValidator(customVerifier);
Expand Down
9 changes: 8 additions & 1 deletion examples/0_basic/5_create_vc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use examples::create_did;
use examples::MemStorage;
use identity_iota::core::Object;

use identity_iota::credential::DecodedJwtCredential;
use identity_iota::credential::Jwt;
use identity_iota::credential::JwtCredentialValidationOptions;
Expand Down Expand Up @@ -86,7 +87,13 @@ async fn main() -> anyhow::Result<()> {
.build()?;

let credential_jwt: Jwt = issuer_document
.create_credential_jwt(&credential, &issuer_storage, &fragment, &JwsSignatureOptions::default())
.create_credential_jwt(
&credential,
&issuer_storage,
&fragment,
&JwsSignatureOptions::default(),
None,
)
.await?;

// Before sending this credential to the holder the issuer wants to validate that some properties
Expand Down
1 change: 1 addition & 0 deletions examples/0_basic/6_create_vp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ async fn main() -> anyhow::Result<()> {
&storage_issuer,
&fragment_issuer,
&JwsSignatureOptions::default(),
None,
)
.await?;

Expand Down
1 change: 1 addition & 0 deletions examples/0_basic/7_revoke_vc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ async fn main() -> anyhow::Result<()> {
&storage_issuer,
&fragment_issuer,
&JwsSignatureOptions::default(),
None,
)
.await?;

Expand Down
1 change: 1 addition & 0 deletions examples/1_advanced/6_domain_linkage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ async fn main() -> anyhow::Result<()> {
&storage,
&fragment,
&JwsSignatureOptions::default(),
None,
)
.await?;

Expand Down
4 changes: 2 additions & 2 deletions identity_credential/src/credential/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,11 @@ impl<T> Credential<T> {
/// in accordance with [VC Data Model v1.1](https://www.w3.org/TR/vc-data-model/#json-web-token).
///
/// The resulting string can be used as the payload of a JWS when issuing the credential.
pub fn serialize_jwt(&self) -> Result<String>
pub fn serialize_jwt(&self, custom_claims: Option<Object>) -> Result<String>
where
T: ToOwned<Owned = T> + serde::Serialize + serde::de::DeserializeOwned,
{
let jwt_representation: CredentialJwtClaims<'_, T> = CredentialJwtClaims::new(self)?;
let jwt_representation: CredentialJwtClaims<'_, T> = CredentialJwtClaims::new(self, custom_claims)?;
jwt_representation
.to_json()
.map_err(|err| Error::JwtClaimsSetSerializationError(err.into()))
Expand Down
9 changes: 7 additions & 2 deletions identity_credential/src/credential/jwt_serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,16 @@ where
sub: Option<Cow<'credential, Url>>,

vc: InnerCredential<'credential, T>,

#[serde(flatten, skip_serializing_if = "Option::is_none")]
pub(crate) custom: Option<Object>,
}

impl<'credential, T> CredentialJwtClaims<'credential, T>
where
T: ToOwned<Owned = T> + Serialize + DeserializeOwned,
{
pub(super) fn new(credential: &'credential Credential<T>) -> Result<Self> {
pub(super) fn new(credential: &'credential Credential<T>, custom: Option<Object>) -> Result<Self> {
let Credential {
context,
id,
Expand Down Expand Up @@ -107,6 +110,7 @@ where
properties: Cow::Borrowed(properties),
proof: proof.as_ref().map(Cow::Borrowed),
},
custom,
})
}
}
Expand Down Expand Up @@ -194,6 +198,7 @@ where
jti,
sub,
vc,
custom: _,
} = self;

let InnerCredential {
Expand Down Expand Up @@ -409,7 +414,7 @@ mod tests {
}"#;

let credential: Credential = Credential::from_json(credential_json).unwrap();
let jwt_credential_claims: CredentialJwtClaims<'_> = CredentialJwtClaims::new(&credential).unwrap();
let jwt_credential_claims: CredentialJwtClaims<'_> = CredentialJwtClaims::new(&credential, None).unwrap();
let jwt_credential_claims_serialized: String = jwt_credential_claims.to_json().unwrap();
// Compare JSON representations
assert_eq!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ mod tests {
fragment: &str,
secret_key: &SecretKey,
) -> Jwt {
let payload: String = credential.serialize_jwt().unwrap();
let payload: String = credential.serialize_jwt(None).unwrap();
Jwt::new(sign_bytes(document, fragment, payload.as_ref(), secret_key).into())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ mod tests {
.build()
.unwrap();

let credential_jwt = Jwt::new(credential.serialize_jwt().unwrap());
let credential_jwt = Jwt::new(credential.serialize_jwt(None).unwrap());

let presentation: Presentation<Jwt> = PresentationBuilder::new(Url::parse("did:test:abc1").unwrap(), Object::new())
.type_("ExamplePresentation")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,8 @@ where
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()
Expand All @@ -313,6 +315,7 @@ where
Ok(DecodedJwtCredential {
credential,
header: Box::new(protected),
custom_claims,
})
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ pub struct DecodedJwtCredential<T = Object> {
pub credential: Credential<T>,
/// The protected header parsed from the JWS.
pub header: Box<JwsHeader>,
/// The custom claims parsed from the JWT.
pub custom_claims: Option<Object>,
}
11 changes: 9 additions & 2 deletions identity_storage/src/storage/jwk_document_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use super::JwsSignatureOptions;
use super::Storage;

use async_trait::async_trait;
use identity_core::common::Object;
use identity_credential::credential::Credential;
use identity_credential::credential::Jws;
use identity_credential::credential::Jwt;
Expand Down Expand Up @@ -99,12 +100,14 @@ pub trait JwkDocumentExt: private::Sealed {
///
/// The `kid` in the protected header is the `id` of the method identified by `fragment` and the JWS signature will be
/// produced by the corresponding private key backed by the `storage` in accordance with the passed `options`.
/// The `custom_claims` can be used to set additional claims on the resulting JWT.
async fn create_credential_jwt<K, I, T>(
&self,
credential: &Credential<T>,
storage: &Storage<K, I>,
fragment: &str,
options: &JwsSignatureOptions,
custom_claims: Option<Object>,
) -> StorageResult<Jwt>
where
K: JwkStorage,
Expand Down Expand Up @@ -423,6 +426,7 @@ impl JwkDocumentExt for CoreDocument {
storage: &Storage<K, I>,
fragment: &str,
options: &JwsSignatureOptions,
custom_claims: Option<Object>,
) -> StorageResult<Jwt>
where
K: JwkStorage,
Expand All @@ -442,7 +446,9 @@ impl JwkDocumentExt for CoreDocument {
)));
}

let payload = credential.serialize_jwt().map_err(Error::ClaimsSerializationError)?;
let payload = credential
.serialize_jwt(custom_claims)
.map_err(Error::ClaimsSerializationError)?;
self
.create_jws(storage, fragment, payload.as_bytes(), options)
.await
Expand Down Expand Up @@ -566,6 +572,7 @@ mod iota_document {
storage: &Storage<K, I>,
fragment: &str,
options: &JwsSignatureOptions,
custom_claims: Option<Object>,
) -> StorageResult<Jwt>
where
K: JwkStorage,
Expand All @@ -574,7 +581,7 @@ mod iota_document {
{
self
.core_document()
.create_credential_jwt(credential, storage, fragment, options)
.create_credential_jwt(credential, storage, fragment, options, custom_claims)
.await
}
async fn create_presentation_jwt<K, I, CRED, T>(
Expand Down
8 changes: 7 additions & 1 deletion identity_storage/src/storage/tests/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,13 @@ async fn signing_credential() {

let credential: Credential = Credential::from_json(credential_json).unwrap();
let jws = document
.create_credential_jwt(&credential, &storage, &method_fragment, &JwsSignatureOptions::default())
.create_credential_jwt(
&credential,
&storage,
&method_fragment,
&JwsSignatureOptions::default(),
None,
)
.await
.unwrap();
// Verify the credential
Expand Down
Loading

0 comments on commit e429809

Please sign in to comment.