Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: VC/VP signing #62

Merged
merged 1 commit into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ categories = ["cryptography", "wasm"]

[workspace.dependencies]
ssi-claims = { git = "https://github.com/vaultie/ssi", default-features = false, features = ["ed25519", "w3c"] }
ssi-claims-core = { git = "https://github.com/vaultie/ssi", default-features = false }
ssi-crypto = { git = "https://github.com/vaultie/ssi", default-features = false }
ssi-dids-core = { git = "https://github.com/vaultie/ssi", default-features = false }
ssi-json-ld = { git = "https://github.com/vaultie/ssi", default-features = false }
ssi-jwk = { git = "https://github.com/vaultie/ssi", default-features = false, features = ["ed25519"] }
Expand Down
3 changes: 2 additions & 1 deletion crates/teddybear-crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ repository.workspace = true
categories.workspace = true

[dependencies]
ssi-claims = { workspace = true }
ssi-claims-core = { workspace = true }
ssi-crypto = { workspace = true }
ssi-dids-core = { workspace = true }
ssi-jwk = { workspace = true }
ssi-jws = { workspace = true }
Expand Down
150 changes: 101 additions & 49 deletions crates/teddybear-crypto/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::{borrow::Cow, sync::Arc};

use ed25519_dalek::SigningKey;
use ed25519_dalek::{SigningKey, VerifyingKey};
use ssi_dids_core::{
document::DIDVerificationMethod, method_resolver::VerificationMethodDIDResolver,
resolution::Options, DIDResolver, Document, Unexpected, DID,
resolution::Options, DIDResolver, DIDURLBuf, Document, Unexpected, DID, DIDURL,
};
use ssi_jwk::{Algorithm, Base64urlUInt, OctetParams, Params};
use ssi_jws::{
Expand Down Expand Up @@ -41,11 +41,23 @@ pub enum Error {

#[derive(Clone, Debug)]
pub struct KeyInfo {
id: DIDURLBuf,
jwk: JWK,
}

impl KeyInfo {
pub fn id(&self) -> &DIDURL {
self.id.as_did_url()
}
}

#[derive(Clone, Debug)]
pub struct Public;
pub struct Public {
// verifying_key here in not necessary at the moment, but it might be useful later.
// FIXME: Remove the #[allow(dead_code)] as soon as the field starts being used.
#[allow(dead_code)]
verifying_key: VerifyingKey,
}

#[derive(Clone, Debug)]
pub struct Private {
Expand Down Expand Up @@ -143,48 +155,27 @@ impl Ed25519<Private> {

impl Ed25519<Public> {
pub async fn from_jwk(jwk: JWK) -> Result<Self, Error> {
let (document, ed25519, x25519) = Ed25519::<()>::parts_from_jwk(jwk).await?;
let did = DidKey.generate(&jwk).ok_or(Error::MissingPrivateKey)?;
let (document, ed25519, x25519, verifying_key) =
Ed25519::<()>::parts_from_did(&did).await?;

Ok(Self {
document,
ed25519,
x25519,
raw: Public,
raw: Public { verifying_key },
})
}

pub async fn from_did(did: &str) -> Result<Self, Error> {
let did = DID::new(did).map_err(|e| e.1)?;

let document = VerificationMethodDIDResolver::<_, Ed25519VerificationKey2020>::new(DidKey)
.resolve_with(did, Options::default())
.await?
.document
.into_document();

let ed25519 = extract_key_info(
String::from("Ed25519"),
document
.verification_method
.first()
.expect("teddybear-did-key should provide at least one ed25519 key"),
)?;

let x25519 = extract_key_info(
String::from("X25519"),
document
.verification_relationships
.key_agreement
.first()
.and_then(|val| val.as_value())
.expect("teddybear-did-key should provide at least one x25519 key"),
)?;
let (document, ed25519, x25519, verifying_key) = Self::parts_from_did(did).await?;

Ok(Self {
document,
ed25519,
x25519,
raw: Public,
raw: Public { verifying_key },
})
}
}
Expand Down Expand Up @@ -229,28 +220,55 @@ impl<T> Ed25519<T> {
}

async fn parts_from_jwk(mut jwk: JWK) -> Result<(Document, KeyInfo, KeyInfo), Error> {
let did = DidKey
.generate(&jwk)
.expect("ed25519 key should produce a correct did document");
let did = DidKey.generate(&jwk).ok_or(Error::MissingPrivateKey)?;

let document = VerificationMethodDIDResolver::<_, Ed25519VerificationKey2020>::new(DidKey)
.resolve_with(did.as_did(), Options::default())
.await?
.document
.into_document();

jwk.key_id = Some(
let id = document
.verification_method
.first()
.expect("at least one key is expected")
.id
.clone();

// JWK structure is preserved as much as possible, so we can't use
// extract_key_info for acquiring Ed25519 key from DID.
jwk.key_id = Some(id.to_string());
jwk.algorithm = Some(Algorithm::EdDSA);

let (x25519, _) = extract_key_info::<X25519KeyInfo>(
document
.verification_relationships
.key_agreement
.first()
.and_then(|val| val.as_value())
.expect("teddybear-did-key should provide at least one x25519 key"),
)?;

Ok((document, KeyInfo { id, jwk }, x25519))
}

async fn parts_from_did(
did: &DID,
) -> Result<(Document, KeyInfo, KeyInfo, VerifyingKey), Error> {
let document = VerificationMethodDIDResolver::<_, Ed25519VerificationKey2020>::new(DidKey)
.resolve_with(did, Options::default())
.await?
.document
.into_document();

let (ed25519, verifying_key) = extract_key_info::<Ed25519KeyInfo>(
document
.verification_method
.first()
.expect("at least one key is expected")
.id
.to_string(),
);
jwk.algorithm = Some(Algorithm::EdDSA);
.expect("teddybear-did-key should provide at least one ed25519 key"),
)?;

let x25519 = extract_key_info(
String::from("X25519"),
let (x25519, _) = extract_key_info::<X25519KeyInfo>(
document
.verification_relationships
.key_agreement
Expand All @@ -259,7 +277,7 @@ impl<T> Ed25519<T> {
.expect("teddybear-did-key should provide at least one x25519 key"),
)?;

Ok((document, KeyInfo { jwk }, x25519))
Ok((document, ed25519, x25519, verifying_key))
}
}

Expand All @@ -281,7 +299,7 @@ impl Signer<Ed25519VerificationKey2020> for Ed25519<Private> {
async fn for_method(
&self,
method: Cow<'_, Ed25519VerificationKey2020>,
) -> Result<Option<Self::MessageSigner>, ssi_claims::SignatureError> {
) -> Result<Option<Self::MessageSigner>, ssi_claims_core::SignatureError> {
if method.id.as_str() != self.ed25519_did() {
return Ok(None);
}
Expand Down Expand Up @@ -312,11 +330,41 @@ pub fn verify_jws_with_embedded_jwk(jws: &str) -> Result<(JWK, Vec<u8>), Error>
Ok((key, jws.payload))
}

struct Ed25519KeyInfo;
struct X25519KeyInfo;

trait RawExtract {
type Output;

const CURVE: &'static str;

fn extract(value: &[u8]) -> Result<Self::Output, Error>;
}

impl RawExtract for Ed25519KeyInfo {
type Output = VerifyingKey;

const CURVE: &'static str = "Ed25519";

fn extract(value: &[u8]) -> Result<Self::Output, Error> {
Ok(VerifyingKey::try_from(value)?)
}
}

impl RawExtract for X25519KeyInfo {
type Output = ();

const CURVE: &'static str = "X25519";

fn extract(_: &[u8]) -> Result<Self::Output, Error> {
Ok(())
}
}

#[inline]
fn extract_key_info(
curve: String,
fn extract_key_info<T: RawExtract>(
verification_method: &DIDVerificationMethod,
) -> Result<KeyInfo, Error> {
) -> Result<(KeyInfo, T::Output), Error> {
let public_key_multibase = verification_method
.properties
.get("publicKeyMultibase")
Expand All @@ -325,14 +373,18 @@ fn extract_key_info(

let public_key = multibase::decode(public_key_multibase)?.1;

let raw_output = T::extract(&public_key[2..])?;

let mut jwk = JWK::from(Params::OKP(OctetParams {
curve,
curve: T::CURVE.to_string(),
public_key: Base64urlUInt(public_key[2..].to_owned()),
private_key: None,
}));

jwk.key_id = Some(verification_method.id.to_string());
let id = verification_method.id.clone();

jwk.key_id = Some(id.to_string());
jwk.algorithm = Some(Algorithm::EdDSA);

Ok(KeyInfo { jwk })
Ok((KeyInfo { id, jwk }, raw_output))
}
1 change: 1 addition & 0 deletions crates/teddybear-vc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ categories.workspace = true

[dependencies]
ssi-claims = { workspace = true }
ssi-crypto = { workspace = true }
ssi-dids-core = { workspace = true }
ssi-json-ld = { workspace = true }
ssi-vc = { workspace = true }
Expand Down
15 changes: 14 additions & 1 deletion crates/teddybear-vc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ pub async fn issue_vc<'a>(

credential.validate_credential(&params)?;

let verification_method = Ed25519VerificationKey2020::from_public_key(
key.ed25519.id().as_iri().to_owned(),
key.document().id.as_uri().to_owned(),
key.raw_signing_key().verifying_key(),
);

Ok(Ed25519Signature2020
.sign_with(
SignatureEnvironment {
Expand All @@ -67,7 +73,7 @@ pub async fn issue_vc<'a>(
CredentialRef(credential),
resolver,
key,
ProofOptions::default(),
ProofOptions::from_method(ReferenceOrOwned::Owned(verification_method)),
(),
)
.await?)
Expand All @@ -94,6 +100,12 @@ pub async fn present_vp<'a>(

let resolver = CustomResolver::new(DidKey);

let verification_method = Ed25519VerificationKey2020::from_public_key(
key.ed25519.id().as_iri().to_owned(),
key.document().id.as_uri().to_owned(),
key.raw_signing_key().verifying_key(),
);

Ok(Ed25519Signature2020
.sign_with(
SignatureEnvironment {
Expand All @@ -106,6 +118,7 @@ pub async fn present_vp<'a>(
ProofOptions {
proof_purpose: ProofPurpose::Authentication,
domains: domain.map(|val| vec![val]).unwrap_or_default(),
verification_method: Some(ReferenceOrOwned::Owned(verification_method)),
challenge,
..Default::default()
},
Expand Down
13 changes: 13 additions & 0 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@
owner = "numtide";
repo = "flake-utils";
};

identity-context = {
url = "https://w3c.credential.nexus/identity.jsonld";
flake = false;
};
};

outputs = {
Expand All @@ -41,6 +46,7 @@
fenix,
nix-filter,
flake-utils,
identity-context,
...
}:
flake-utils.lib.eachDefaultSystem (
Expand Down Expand Up @@ -168,10 +174,10 @@
inherit cjs esm uni;

e2e-test = pkgs.callPackage ./nix/node-testing.nix {
inherit uni;
inherit identity-context uni;

src = ./tests;
yarnLockHash = "sha256-KdtWLlP0jHiQXyWcUuE3sKjrgfHnGRlObg7u4g4FBNE=";
yarnLockHash = "sha256-Zcm5jr6hHq34vmRBq8ATLaqzg9svBIjL41OKcH5Enf4=";
};

unit-test = craneLib.cargoTest (nativeArgs
Expand Down
Loading