open-standards/smart-byte/smart-byte-rs/crates/smart-byte-vc/src/jwt.rs
Transaction Science 01d4ad9c7b Ingest batch 2: 9 new crates across openpay / smart-byte / eoc
openpay/ (+3 crates, ~8400 LOC, 162 tests)
  op-iso8583/         ISO 8583 messages for direct acquirer / card-network
                      connectivity. MTIs, primary+secondary bitmaps, full
                      DE catalogue, BCD/ASCII/EBCDIC/LLVAR/LLLVAR codecs,
                      five dialects (Visa Base I, Mastercard MDS, Amex GNS,
                      Discover, JCB), network-management messages
                      (sign-on/echo/cutover), DE 55 EMV TLV.
  op-mobile-wallets/  Apple Pay (ECDH-P256 + AES-256-GCM), Google Pay ECv2
                      (ECDH + HKDF + AES-256-CTR + HMAC), Samsung Pay. PAN
                      never leaves the decryption boundary as a String;
                      lands in VaultRef. No-PAN-leakage assertions per
                      wallet.
  op-routing/         Least-cost routing + MCC-aware routing + intelligent
                      retry / soft-decline recovery. 231-MCC catalogue.
                      Real ISO 8583 DE-39 soft/hard decline taxonomies.

smart-byte/smart-byte-rs/ (+3 crates, ~7100 LOC, 96 tests)
  smart-byte-vc/      W3C Verifiable Credentials 2.0: VCDM, presentations,
                      Data Integrity proofs (eddsa-jcs-2022), VC-JWT,
                      SD-JWT (selective disclosure), Bitstring Status
                      List 2021. Cargo-bridge maps VCs to Smart Byte
                      envelopes with SAID stability.
  smart-byte-did/     W3C DID resolution: did:key (Ed25519/P-256/secp256k1),
                      did:web (HTTPS), did:peer (numalgo 2+4), did:jwk,
                      did:ion (feature-gated stub). DID URL dereferencer.
  smart-byte-pq/      Post-quantum signatures: ML-DSA-44/65/87 (FIPS 204),
                      SLH-DSA across 12 parameter sets (FIPS 205), FN-DSA
                      (draft FIPS 206, feature-gated). Hybrid Ed25519 +
                      ML-DSA pattern for the transition. Secret-key
                      zeroize-on-drop.

eoc/eoc-rs/ (+3 crates, ~6450 LOC, 76 tests)
  eoc-vendor-api/     NeuralBackend implementations: Anthropic, OpenAI,
                      Google, Mistral, Cohere, Groq, Together, Fireworks.
                      SSE streaming. Prompt-caching where supported.
                      Joule estimates per published energy coefficient
                      (12-model curated table).
  eoc-embeddings/     21 embedding models behind one Embedder trait:
                      OpenAI v3 (3), Cohere v3 (3), Voyage (5), Mistral,
                      Jina, plus local ONNX (BGE x3, nomic, mxbai, GTE,
                      E5) behind 'local' feature. Matryoshka-style
                      dimension projection. Per-content-hash cache.
  eoc-route-learned/  RouteLLM-style matrix-factorisation router +
                      multinomial-logreg classifier + LinUCB / Thompson
                      bandits for online learning. LearnedCascade wraps
                      the rule-based cascade with a confidence-threshold
                      skip policy. Synthetic-eval accuracy: MF 0.935,
                      LogReg 0.980.

Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 334 new tests total; all passing
- #![forbid(unsafe_code)] across every new crate
- No unwrap/expect outside #[cfg(test)]

Rust 1.95.0 edition 2024 (inherited via root rust-toolchain.toml).
2026-05-23 18:12:24 -04:00

151 lines
4.9 KiB
Rust

//! VC-JWT — RFC 7519 JWT carrying a Verifiable Credential payload.
//!
//! Signing algorithm: EdDSA (Ed25519). Encoding: compact JWS
//! (`base64url(header) . base64url(payload) . base64url(signature)`).
//!
//! Per VCDM 2.0 §6.3 ("Securing Mechanism"), the payload is the
//! credential JSON itself (no `iss`/`sub`/`iat` shoehorning) — the
//! VC fields are authoritative.
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ed25519_dalek::{
Signature, SigningKey, Verifier, VerifyingKey, ed25519::signature::Signer,
};
use serde::{Deserialize, Serialize};
use crate::credential::VerifiableCredential;
use crate::error::VcError;
use crate::proof::JwtProof;
/// JOSE header for VC-JWT.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct JwtHeader {
/// Signing algorithm. We support `"EdDSA"`.
pub alg: String,
/// Token type. `"vc+jwt"` per VCDM 2.0; legacy issuers use `"JWT"`.
pub typ: String,
/// Verification method (key id). Typically a DID URL.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
}
impl JwtHeader {
/// Header preset for EdDSA / VC-JWT.
pub fn eddsa(kid: Option<String>) -> Self {
Self {
alg: "EdDSA".to_string(),
typ: "vc+jwt".to_string(),
kid,
}
}
}
/// Issue a VC-JWT. The compact serialisation is returned both as a raw
/// string and wrapped in a [`JwtProof`] for ergonomic insertion into a
/// credential's `proof` array (when in-band binding is desired).
pub fn issue_vc_jwt(
vc: &VerifiableCredential,
signing_key: &SigningKey,
kid: Option<String>,
) -> Result<(String, JwtProof), VcError> {
let header = JwtHeader::eddsa(kid);
let header_bytes = serde_json::to_vec(&header)?;
let payload_bytes = serde_jcs::to_vec(vc).map_err(|e| VcError::Jcs(e.to_string()))?;
let h = URL_SAFE_NO_PAD.encode(&header_bytes);
let p = URL_SAFE_NO_PAD.encode(&payload_bytes);
let signing_input = format!("{h}.{p}");
let sig: Signature = signing_key.sign(signing_input.as_bytes());
let s = URL_SAFE_NO_PAD.encode(sig.to_bytes());
let jwt = format!("{signing_input}.{s}");
let proof = JwtProof {
type_: "JwtProof2020".to_string(),
jwt: jwt.clone(),
};
Ok((jwt, proof))
}
/// Verify a VC-JWT compact string with `verifying_key`. Returns the
/// decoded credential on success.
pub fn verify_vc_jwt(
jwt: &str,
verifying_key: &VerifyingKey,
) -> Result<VerifiableCredential, VcError> {
let parts: Vec<&str> = jwt.split('.').collect();
if parts.len() != 3 {
return Err(VcError::Jwt(format!(
"expected 3 compact JWS parts, got {}",
parts.len()
)));
}
let header_bytes = URL_SAFE_NO_PAD.decode(parts[0])?;
let header: JwtHeader = serde_json::from_slice(&header_bytes)?;
if header.alg != "EdDSA" {
return Err(VcError::Jwt(format!(
"unsupported alg: {}",
header.alg
)));
}
let payload_bytes = URL_SAFE_NO_PAD.decode(parts[1])?;
let sig_bytes = URL_SAFE_NO_PAD.decode(parts[2])?;
if sig_bytes.len() != 64 {
return Err(VcError::Jwt(format!(
"expected 64-byte Ed25519 signature, got {}",
sig_bytes.len()
)));
}
let mut s = [0u8; 64];
s.copy_from_slice(&sig_bytes);
let signature = Signature::from_bytes(&s);
let signing_input = format!("{}.{}", parts[0], parts[1]);
verifying_key
.verify(signing_input.as_bytes(), &signature)
.map_err(|e| VcError::Signature(e.to_string()))?;
let vc: VerifiableCredential = serde_json::from_slice(&payload_bytes)?;
Ok(vc)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::credential::{CredentialSubject, VcBuilder};
use crate::issuer::Issuer;
use ed25519_dalek::SigningKey;
use rand::rngs::OsRng;
fn fixture_vc() -> VerifiableCredential {
let subj = CredentialSubject {
id: Some("did:example:alice".parse().unwrap()),
claims: serde_json::Map::new(),
};
VcBuilder::new()
.issuer(Issuer::Uri("did:example:issuer".parse().unwrap()))
.subject(subj)
.build()
.unwrap()
}
#[test]
fn jwt_roundtrip() {
let sk = SigningKey::generate(&mut OsRng);
let vk = sk.verifying_key();
let vc = fixture_vc();
let (jwt, _proof) = issue_vc_jwt(
&vc,
&sk,
Some("did:example:issuer#keys-1".into()),
)
.unwrap();
let back = verify_vc_jwt(&jwt, &vk).unwrap();
assert_eq!(back.issuer.id().as_str(), "did:example:issuer");
}
#[test]
fn jwt_rejects_wrong_key() {
let sk = SigningKey::generate(&mut OsRng);
let other = SigningKey::generate(&mut OsRng);
let vc = fixture_vc();
let (jwt, _) = issue_vc_jwt(&vc, &sk, None).unwrap();
assert!(verify_vc_jwt(&jwt, &other.verifying_key()).is_err());
}
}