generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6e8cc22
commit b4d0a75
Showing
5 changed files
with
244 additions
and
35 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
use crate::lib_v2::{Claims, JwtError}; | ||
use dids::{bearer::BearerDid, document::KeySelector}; | ||
use jws::v2::JwsHeader; | ||
|
||
// A JWT can be implemented as either a JWS or JWE, this module is the implementation of a JWT as a JWE | ||
|
||
// TODO implement https://github.com/TBD54566975/web5-rs/issues/174 | ||
|
||
pub struct JwtDecoded<T: Claims> { | ||
// TODO other properties for JWE | ||
pub claims: T, | ||
pub parts: Vec<String>, | ||
} | ||
|
||
pub struct Jwt; | ||
|
||
impl Jwt { | ||
pub fn sign<T: Claims>( | ||
_bearer_did: &BearerDid, | ||
_key_selector: &KeySelector, | ||
_header: Option<JwsHeader>, | ||
_claims: &T, | ||
) -> Result<String, JwtError> { | ||
unimplemented!() | ||
} | ||
|
||
pub fn decode<T: Claims>(_jwt: &str) -> Result<JwtDecoded<T>, JwtError> { | ||
unimplemented!() | ||
} | ||
|
||
pub async fn verify<T: Claims>(_jwt: &str) -> Result<JwtDecoded<T>, JwtError> { | ||
unimplemented!() | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
// use super::*; | ||
// TODO tests | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
use crate::lib_v2::{Claims, JwtError}; | ||
use dids::{bearer::BearerDid, document::KeySelector}; | ||
use jws::v2::{CompactJws, JwsHeader}; | ||
|
||
// A JWT can be implemented as either a JWS or JWE, this module is the implementation of a JWT as a JWS | ||
|
||
pub struct JwtDecoded<T: Claims> { | ||
pub header: JwsHeader, | ||
pub claims: T, | ||
pub signature: String, | ||
pub parts: Vec<String>, | ||
} | ||
|
||
pub struct Jwt; | ||
|
||
impl Jwt { | ||
pub fn sign<T: Claims>( | ||
bearer_did: &BearerDid, | ||
key_selector: &KeySelector, | ||
header: Option<JwsHeader>, | ||
claims: &T, | ||
) -> Result<String, JwtError> { | ||
let jws_header = match header { | ||
Some(h) => h, | ||
None => { | ||
let verification_method = | ||
bearer_did.document.get_verification_method(key_selector)?; | ||
|
||
JwsHeader { | ||
alg: verification_method.public_key_jwk.alg.clone(), | ||
kid: verification_method.id.clone(), | ||
typ: "JWT".to_string(), | ||
} | ||
} | ||
}; | ||
|
||
let serialized_claims = serde_json::to_string(claims)?.into_bytes(); | ||
|
||
let jwt = CompactJws::sign(bearer_did, key_selector, &jws_header, &serialized_claims)?; | ||
Ok(jwt) | ||
} | ||
|
||
pub fn decode<T: Claims>(jwt: &str) -> Result<JwtDecoded<T>, JwtError> { | ||
let jws_decoded = CompactJws::decode(jwt)?; | ||
|
||
let claims = serde_json::from_slice::<T>(&jws_decoded.payload)?; | ||
|
||
Ok(JwtDecoded { | ||
header: jws_decoded.header, | ||
claims, | ||
signature: jws_decoded.signature, | ||
parts: jws_decoded.parts, | ||
}) | ||
} | ||
|
||
pub async fn verify<T: Claims>(jwt: &str) -> Result<JwtDecoded<T>, JwtError> { | ||
let jws_decoded = CompactJws::verify(jwt).await?; | ||
|
||
let claims = serde_json::from_slice::<T>(&jws_decoded.payload)?; | ||
|
||
Ok(JwtDecoded { | ||
header: jws_decoded.header, | ||
claims, | ||
signature: jws_decoded.signature, | ||
parts: jws_decoded.parts, | ||
}) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::lib_v2::RegisteredClaims; | ||
use crypto::Curve; | ||
use dids::{ | ||
document::KeySelector, | ||
method::{ | ||
jwk::{DidJwk, DidJwkCreateOptions}, | ||
Method, | ||
}, | ||
}; | ||
use keys::key_manager::local_key_manager::LocalKeyManager; | ||
use std::sync::Arc; | ||
|
||
#[tokio::test] | ||
async fn test_sign_and_verify() { | ||
let key_manager = LocalKeyManager::new_in_memory(); | ||
let bearer_did = DidJwk::create( | ||
Arc::new(key_manager), | ||
DidJwkCreateOptions { | ||
curve: Curve::Ed25519, | ||
}, | ||
) | ||
.expect("failed to create bearer did"); | ||
|
||
let claims = RegisteredClaims { | ||
issuer: Some(bearer_did.identifier.uri.clone()), | ||
..Default::default() | ||
}; | ||
|
||
let key_id = bearer_did.document.verification_method[0].id.clone(); | ||
let jwt = Jwt::sign( | ||
&bearer_did, | ||
&KeySelector::KeyId { | ||
key_id: key_id.clone(), | ||
}, | ||
None, | ||
&claims, | ||
) | ||
.unwrap(); | ||
|
||
let jwt_decoded = Jwt::verify::<RegisteredClaims>(&jwt).await.unwrap(); | ||
|
||
// default JwsHeader | ||
assert_eq!("JWT".to_string(), jwt_decoded.header.typ); | ||
assert_eq!(key_id, jwt_decoded.header.kid); | ||
assert_eq!( | ||
bearer_did.document.verification_method[0] | ||
.public_key_jwk | ||
.alg, | ||
jwt_decoded.header.alg | ||
); | ||
|
||
// claims | ||
assert_eq!(claims.issuer, jwt_decoded.claims.issuer); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
use dids::document::DocumentError; | ||
use jws::v2::JwsError; | ||
use serde::{de::DeserializeOwned, Deserialize, Serialize}; | ||
use serde_json::Error as SerdeJsonError; | ||
|
||
#[derive(thiserror::Error, Debug, Clone, PartialEq)] | ||
pub enum JwtError { | ||
#[error(transparent)] | ||
JwsError(#[from] JwsError), | ||
#[error(transparent)] | ||
DocumentError(#[from] DocumentError), | ||
#[error("serde json error {0}")] | ||
SerdeJsonError(String), | ||
} | ||
|
||
impl From<SerdeJsonError> for JwtError { | ||
fn from(err: SerdeJsonError) -> Self { | ||
JwtError::SerdeJsonError(err.to_string()) | ||
} | ||
} | ||
|
||
pub trait Claims: Serialize + DeserializeOwned {} | ||
|
||
#[derive(Serialize, Deserialize, Debug, Default)] | ||
pub struct RegisteredClaims { | ||
#[serde(rename = "iss", skip_serializing_if = "Option::is_none")] | ||
pub issuer: Option<String>, | ||
#[serde(rename = "sub", skip_serializing_if = "Option::is_none")] | ||
pub subject: Option<String>, | ||
#[serde(rename = "aud", skip_serializing_if = "Option::is_none")] | ||
pub audience: Option<String>, | ||
#[serde(rename = "exp", skip_serializing_if = "Option::is_none")] | ||
pub expiration: Option<i64>, | ||
#[serde(rename = "nbf", skip_serializing_if = "Option::is_none")] | ||
pub not_before: Option<i64>, | ||
#[serde(rename = "iat", skip_serializing_if = "Option::is_none")] | ||
pub issued_at: Option<i64>, | ||
#[serde(rename = "jti", skip_serializing_if = "Option::is_none")] | ||
pub jti: Option<String>, | ||
} | ||
|
||
impl Claims for RegisteredClaims {} |