#[cfg(not(feature = "std"))]
use alloc::{format, string::String, string::ToString, vec::Vec};
use ed25519_dalek::{Signature as EdSignature, Signer as _, SigningKey, Verifier, VerifyingKey};
use fips204::ml_dsa_65;
use fips204::traits::{SerDes, Signer as MlSigner, Verifier as MlVerifier};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use crate::canonical::{
encode_bytes_b64, encode_constraints, encode_hybrid_pub_key, encode_i32, encode_i64,
encode_str, encode_str_array,
};
use crate::resource_path::{validate_constraint_params, validate_resource_constraints};
use crate::types::{
DelegationCert, HybridPrivateKey, HybridPublicKey, HybridSignature, KeyRotationStatement,
ProofBundle, ReceiptPartySignature, RevocationList, RevocationPush, SessionToken,
TransactionReceipt, VerifyResult, WitnessEntry, MAX_CONSTRAINTS_PER_CERT, MAX_SCOPES_PER_CERT,
MAX_SCOPE_LENGTH_BYTES,
};
#[cfg(feature = "std")]
use crate::types::{AgentIdentity, HumanRoot, MAX_AGENT_NAME_LENGTH_BYTES};
type HmacSha256 = Hmac<Sha256>;
pub fn derive_id(pub_key: &HybridPublicKey) -> String {
let mut hasher = Sha256::new();
hasher.update(&pub_key.ed25519);
hasher.update(&pub_key.ml_dsa_65);
let digest = hasher.finalize();
hex::encode(&digest[..16])
}
pub fn generate_hybrid_keypair() -> (HybridPublicKey, HybridPrivateKey) {
use rand_core::OsRng;
let mut seed = [0u8; 32];
use rand_core::RngCore;
OsRng.fill_bytes(&mut seed);
let ed_sk = SigningKey::from_bytes(&seed);
let ed_pk = ed_sk.verifying_key();
let (ml_pk, ml_sk) = ml_dsa_65::try_keygen().expect("ML-DSA-65 keygen");
(
HybridPublicKey {
ed25519: ed_pk.to_bytes().to_vec(),
ml_dsa_65: ml_pk.into_bytes().to_vec(),
},
HybridPrivateKey {
ed25519: seed.to_vec(),
ml_dsa_65: ml_sk.into_bytes().to_vec(),
},
)
}
pub fn hybrid_keypair_from_seeds(
ed_seed: &[u8; 32],
ml_seed: &[u8; 32],
) -> (HybridPublicKey, HybridPrivateKey) {
let ed_sk = SigningKey::from_bytes(ed_seed);
let ed_pk = ed_sk.verifying_key();
let mut rng = SeedOnceRng::new(ml_seed);
let (ml_pk, ml_sk) =
ml_dsa_65::try_keygen_with_rng(&mut rng).expect("ML-DSA-65 keygen from seed");
(
HybridPublicKey {
ed25519: ed_pk.to_bytes().to_vec(),
ml_dsa_65: ml_pk.into_bytes().to_vec(),
},
HybridPrivateKey {
ed25519: ed_seed.to_vec(),
ml_dsa_65: ml_sk.into_bytes().to_vec(),
},
)
}
struct SeedOnceRng {
seed: [u8; 32],
used: bool,
}
impl SeedOnceRng {
fn new(seed: &[u8; 32]) -> Self {
Self { seed: *seed, used: false }
}
}
impl rand_core::RngCore for SeedOnceRng {
fn next_u32(&mut self) -> u32 {
rand_core::impls::next_u32_via_fill(self)
}
fn next_u64(&mut self) -> u64 {
rand_core::impls::next_u64_via_fill(self)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
self.try_fill_bytes(dest).expect("SeedOnceRng exhausted")
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
if self.used || dest.len() != 32 {
return Err(rand_core::Error::from(
core::num::NonZeroU32::new(rand_core::Error::CUSTOM_START)
.expect("CUSTOM_START is non-zero"),
));
}
dest.copy_from_slice(&self.seed);
self.used = true;
Ok(())
}
}
impl rand_core::CryptoRng for SeedOnceRng {}
#[cfg(feature = "std")]
pub fn generate_human_root() -> (HumanRoot, HybridPrivateKey) {
let (pub_key, priv_key) = generate_hybrid_keypair();
let id = derive_id(&pub_key);
(
HumanRoot {
id,
public_key: pub_key,
created_at: now_unix(),
anchors: None,
},
priv_key,
)
}
#[cfg(feature = "std")]
pub fn generate_agent(
name: &str,
agent_type: &str,
) -> Result<(AgentIdentity, HybridPrivateKey), String> {
if name.len() > MAX_AGENT_NAME_LENGTH_BYTES {
return Err(format!(
"agent name is {} bytes, exceeding MAX_AGENT_NAME_LENGTH_BYTES ({})",
name.len(),
MAX_AGENT_NAME_LENGTH_BYTES
));
}
let (pub_key, priv_key) = generate_hybrid_keypair();
let id = derive_id(&pub_key);
Ok((
AgentIdentity {
id,
public_key: pub_key,
name: name.to_string(),
agent_type: agent_type.to_string(),
created_at: now_unix(),
},
priv_key,
))
}
#[cfg(feature = "std")]
fn now_unix() -> i64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
pub fn delegation_sign_bytes(cert: &DelegationCert) -> Vec<u8> {
let mut out = String::new();
out.push('{');
out.push_str("\"cert_id\":"); encode_str(&cert.cert_id, &mut out);
out.push_str(",\"constraints\":"); encode_constraints(&cert.constraints, &mut out);
out.push_str(",\"expires_at\":"); encode_i64(cert.expires_at, &mut out);
out.push_str(",\"issued_at\":"); encode_i64(cert.issued_at, &mut out);
out.push_str(",\"issuer_id\":"); encode_str(&cert.issuer_id, &mut out);
out.push_str(",\"issuer_pub_key\":"); encode_hybrid_pub_key(&cert.issuer_pub_key, &mut out);
out.push_str(",\"scope\":"); encode_str_array(&cert.scope, &mut out);
out.push_str(",\"subject_id\":"); encode_str(&cert.subject_id, &mut out);
out.push_str(",\"subject_pub_key\":"); encode_hybrid_pub_key(&cert.subject_pub_key, &mut out);
out.push_str(",\"version\":"); encode_i32(cert.version, &mut out);
out.push('}');
out.into_bytes()
}
pub fn challenge_sign_bytes(challenge: &[u8], ts: i64) -> Vec<u8> {
challenge_sign_bytes_with_stream(challenge, ts, &[], &[], 0)
}
pub fn challenge_sign_bytes_with_session_context(
challenge: &[u8],
ts: i64,
session_context: &[u8],
) -> Vec<u8> {
challenge_sign_bytes_with_stream(challenge, ts, session_context, &[], 0)
}
pub fn challenge_sign_bytes_with_stream(
challenge: &[u8],
ts: i64,
session_context: &[u8],
stream_id: &[u8],
stream_seq: i64,
) -> Vec<u8> {
let stream_len = if stream_id.is_empty() {
0
} else {
stream_id.len() + 8
};
let mut out = Vec::with_capacity(challenge.len() + 8 + session_context.len() + stream_len);
out.extend_from_slice(challenge);
out.extend_from_slice(&(ts as u64).to_be_bytes());
out.extend_from_slice(session_context);
if !stream_id.is_empty() {
out.extend_from_slice(stream_id);
out.extend_from_slice(&(stream_seq as u64).to_be_bytes());
}
out
}
pub fn revocation_sign_bytes(list: &RevocationList) -> Vec<u8> {
let mut out = String::new();
out.push('{');
out.push_str("\"issuer_id\":"); encode_str(&list.issuer_id, &mut out);
out.push_str(",\"revoked_certs\":"); encode_str_array(&list.revoked_certs, &mut out);
out.push_str(",\"updated_at\":"); encode_i64(list.updated_at, &mut out);
out.push('}');
out.into_bytes()
}
pub fn key_rotation_sign_bytes(stmt: &KeyRotationStatement) -> Vec<u8> {
let mut out = String::new();
out.push('{');
out.push_str("\"new_id\":"); encode_str(&stmt.new_id, &mut out);
out.push_str(",\"new_pub_key\":"); encode_hybrid_pub_key(&stmt.new_pub_key, &mut out);
out.push_str(",\"old_id\":"); encode_str(&stmt.old_id, &mut out);
out.push_str(",\"old_pub_key\":"); encode_hybrid_pub_key(&stmt.old_pub_key, &mut out);
out.push_str(",\"reason\":"); encode_str(&stmt.reason, &mut out);
out.push_str(",\"rotated_at\":"); encode_i64(stmt.rotated_at, &mut out);
out.push_str(",\"version\":"); encode_i32(stmt.version, &mut out);
out.push('}');
out.into_bytes()
}
pub fn sign_both(msg: &[u8], priv_key: &HybridPrivateKey) -> HybridSignature {
let mut ed_seed = [0u8; 32];
ed_seed.copy_from_slice(&priv_key.ed25519[..32]);
let ed_sk = SigningKey::from_bytes(&ed_seed);
let ed_sig = ed_sk.sign(msg);
let mut ml_sk_bytes = [0u8; ml_dsa_65::SK_LEN];
ml_sk_bytes.copy_from_slice(&priv_key.ml_dsa_65);
let ml_sk = ml_dsa_65::PrivateKey::try_from_bytes(ml_sk_bytes)
.expect("ML-DSA-65 secret key malformed");
let ml_sig = ml_sk.try_sign(msg, &[]).expect("ML-DSA-65 sign");
HybridSignature {
ed25519: ed_sig.to_bytes().to_vec(),
ml_dsa_65: ml_sig.to_vec(),
}
}
pub fn verify_both(
msg: &[u8],
sig: &HybridSignature,
pub_key: &HybridPublicKey,
) -> Result<(), String> {
if pub_key.ed25519.len() != 32 {
return Err(format!(
"Ed25519 public key wrong length: {}",
pub_key.ed25519.len()
));
}
if pub_key.ml_dsa_65.len() != 1952 {
return Err(format!(
"ML-DSA-65 public key wrong length: {}",
pub_key.ml_dsa_65.len()
));
}
if sig.ed25519.len() != 64 {
return Err(format!(
"Ed25519 signature wrong length: {}",
sig.ed25519.len()
));
}
if sig.ml_dsa_65.len() != 3309 {
return Err(format!(
"ML-DSA-65 signature wrong length: {}",
sig.ml_dsa_65.len()
));
}
let mut ed_pk_bytes = [0u8; 32];
ed_pk_bytes.copy_from_slice(&pub_key.ed25519);
let ed_pk = VerifyingKey::from_bytes(&ed_pk_bytes)
.map_err(|_| "Ed25519 public key invalid".to_string())?;
let ed_sig = EdSignature::from_slice(&sig.ed25519)
.map_err(|_| "Ed25519 signature invalid".to_string())?;
ed_pk
.verify(msg, &ed_sig)
.map_err(|_| "Ed25519 signature invalid".to_string())?;
let mut ml_pk_bytes = [0u8; ml_dsa_65::PK_LEN];
ml_pk_bytes.copy_from_slice(&pub_key.ml_dsa_65);
let ml_pk = ml_dsa_65::PublicKey::try_from_bytes(ml_pk_bytes)
.map_err(|_| "ML-DSA-65 public key malformed".to_string())?;
let mut ml_sig_bytes = [0u8; ml_dsa_65::SIG_LEN];
ml_sig_bytes.copy_from_slice(&sig.ml_dsa_65);
if !ml_pk.verify(msg, &ml_sig_bytes, &[]) {
return Err("ML-DSA-65 signature invalid".to_string());
}
Ok(())
}
pub fn issue_delegation(
cert: &mut DelegationCert,
issuer_priv: &HybridPrivateKey,
) -> Result<(), String> {
validate_resource_constraints(&cert.constraints)
.map_err(|e| format!("issuing delegation: {}", e))?;
for (i, c) in cert.constraints.iter().enumerate() {
validate_constraint_params(c)
.map_err(|e| format!("issuing delegation: constraint[{}]: {}", i, e))?;
}
if cert.scope.len() > MAX_SCOPES_PER_CERT {
return Err(format!(
"issuing delegation: {} scopes exceeds MAX_SCOPES_PER_CERT ({})",
cert.scope.len(),
MAX_SCOPES_PER_CERT
));
}
if cert.constraints.len() > MAX_CONSTRAINTS_PER_CERT {
return Err(format!(
"issuing delegation: {} constraints exceeds MAX_CONSTRAINTS_PER_CERT ({})",
cert.constraints.len(),
MAX_CONSTRAINTS_PER_CERT
));
}
for s in &cert.scope {
if s.len() > MAX_SCOPE_LENGTH_BYTES {
return Err(format!(
"issuing delegation: scope \"{}\" is {} bytes, exceeding MAX_SCOPE_LENGTH_BYTES ({})",
s,
s.len(),
MAX_SCOPE_LENGTH_BYTES
));
}
}
cert.signature = sign_both(&delegation_sign_bytes(cert), issuer_priv);
Ok(())
}
pub fn verify_delegation_signature(cert: &DelegationCert) -> bool {
verify_delegation_signature_e(cert).is_ok()
}
pub fn verify_delegation_signature_e(cert: &DelegationCert) -> Result<(), String> {
verify_both(
&delegation_sign_bytes(cert),
&cert.signature,
&cert.issuer_pub_key,
)
}
pub fn sign_challenge(challenge: &[u8], ts: i64, agent_priv: &HybridPrivateKey) -> HybridSignature {
sign_challenge_with_session_context(challenge, ts, &[], agent_priv)
}
pub fn sign_challenge_with_session_context(
challenge: &[u8],
ts: i64,
session_context: &[u8],
agent_priv: &HybridPrivateKey,
) -> HybridSignature {
assert!(
session_context.is_empty() || session_context.len() == 32,
"session_context must be 32 bytes"
);
sign_both(
&challenge_sign_bytes_with_session_context(challenge, ts, session_context),
agent_priv,
)
}
pub fn sign_challenge_with_stream(
challenge: &[u8],
ts: i64,
session_context: &[u8],
stream_id: &[u8],
stream_seq: i64,
agent_priv: &HybridPrivateKey,
) -> HybridSignature {
assert!(
session_context.is_empty() || session_context.len() == 32,
"session_context must be 32 bytes"
);
assert_eq!(stream_id.len(), 32, "stream_id must be 32 bytes");
assert!(stream_seq >= 1, "stream_seq must be >=1");
sign_both(
&challenge_sign_bytes_with_stream(challenge, ts, session_context, stream_id, stream_seq),
agent_priv,
)
}
pub fn verify_challenge_signature(
challenge: &[u8],
ts: i64,
sig: &HybridSignature,
agent_pub: &HybridPublicKey,
) -> Result<(), String> {
verify_challenge_signature_with_stream(challenge, ts, &[], &[], 0, sig, agent_pub)
}
pub fn verify_challenge_signature_with_session_context(
challenge: &[u8],
ts: i64,
session_context: &[u8],
sig: &HybridSignature,
agent_pub: &HybridPublicKey,
) -> Result<(), String> {
verify_challenge_signature_with_stream(challenge, ts, session_context, &[], 0, sig, agent_pub)
}
pub fn verify_challenge_signature_with_stream(
challenge: &[u8],
ts: i64,
session_context: &[u8],
stream_id: &[u8],
stream_seq: i64,
sig: &HybridSignature,
agent_pub: &HybridPublicKey,
) -> Result<(), String> {
if !session_context.is_empty() && session_context.len() != 32 {
return Err(format!(
"session_context must be 32 bytes, got {}",
session_context.len()
));
}
if !stream_id.is_empty() && stream_id.len() != 32 {
return Err(format!(
"stream_id must be 32 bytes, got {}",
stream_id.len()
));
}
if !stream_id.is_empty() && stream_seq < 1 {
return Err(format!("stream_seq must be >=1, got {}", stream_seq));
}
verify_both(
&challenge_sign_bytes_with_stream(challenge, ts, session_context, stream_id, stream_seq),
sig,
agent_pub,
)
}
pub fn issue_revocation_list(list: &mut RevocationList, issuer_priv: &HybridPrivateKey) {
list.signature = sign_both(&revocation_sign_bytes(list), issuer_priv);
}
pub fn verify_revocation_list(list: &RevocationList, issuer_pub: &HybridPublicKey) -> bool {
verify_both(&revocation_sign_bytes(list), &list.signature, issuer_pub).is_ok()
}
pub fn revocation_push_sign_bytes(push: &RevocationPush) -> Vec<u8> {
let mut out = String::new();
out.push('{');
out.push_str("\"entries\":"); encode_str_array(&push.entries, &mut out);
out.push_str(",\"issuer_id\":"); encode_str(&push.issuer_id, &mut out);
out.push_str(",\"pushed_at\":"); encode_i64(push.pushed_at, &mut out);
out.push_str(",\"seq_no\":"); encode_i64(push.seq_no, &mut out);
out.push('}');
out.into_bytes()
}
pub fn issue_revocation_push(push: &mut RevocationPush, issuer_priv: &HybridPrivateKey) {
push.signature = sign_both(&revocation_push_sign_bytes(push), issuer_priv);
}
pub fn verify_revocation_push(push: &RevocationPush, issuer_pub: &HybridPublicKey) -> bool {
verify_both(
&revocation_push_sign_bytes(push),
&push.signature,
issuer_pub,
)
.is_ok()
}
pub fn witness_entry_sign_bytes(entry: &WitnessEntry) -> Vec<u8> {
let mut out = String::new();
out.push('{');
out.push_str("\"entry_data\":"); encode_bytes_b64(&entry.entry_data, &mut out);
out.push_str(",\"prev_hash\":"); encode_bytes_b64(&entry.prev_hash, &mut out);
out.push_str(",\"timestamp\":"); encode_i64(entry.timestamp, &mut out);
out.push_str(",\"witness_id\":"); encode_str(&entry.witness_id, &mut out);
out.push('}');
out.into_bytes()
}
pub fn issue_witness_entry(entry: &mut WitnessEntry, witness_priv: &HybridPrivateKey) {
entry.signature = sign_both(&witness_entry_sign_bytes(entry), witness_priv);
}
pub fn verify_witness_entry(entry: &WitnessEntry, witness_pub: &HybridPublicKey) -> bool {
verify_both(
&witness_entry_sign_bytes(entry),
&entry.signature,
witness_pub,
)
.is_ok()
}
pub fn issue_key_rotation_statement(
stmt: &mut KeyRotationStatement,
old_priv: &HybridPrivateKey,
new_priv: &HybridPrivateKey,
) {
let bytes = key_rotation_sign_bytes(stmt);
stmt.signature_old = sign_both(&bytes, old_priv);
stmt.signature_new = sign_both(&bytes, new_priv);
}
pub fn verify_key_rotation_statement(stmt: &KeyRotationStatement) -> Result<(), String> {
if stmt.version != 1 {
return Err(format!(
"version_mismatch: unsupported version {}",
stmt.version
));
}
if stmt.old_id != derive_id(&stmt.old_pub_key) {
return Err("old_id does not match old_pub_key".to_string());
}
if stmt.new_id != derive_id(&stmt.new_pub_key) {
return Err("new_id does not match new_pub_key".to_string());
}
if stmt.old_id == stmt.new_id {
return Err("old_id and new_id must differ".to_string());
}
if !is_key_rotation_reason_known(&stmt.reason) {
return Err(format!("unknown key rotation reason: {}", stmt.reason));
}
let bytes = key_rotation_sign_bytes(stmt);
verify_both(&bytes, &stmt.signature_old, &stmt.old_pub_key)
.map_err(|e| format!("old signature invalid: {}", e))?;
verify_both(&bytes, &stmt.signature_new, &stmt.new_pub_key)
.map_err(|e| format!("new signature invalid: {}", e))?;
Ok(())
}
fn is_key_rotation_reason_known(reason: &str) -> bool {
matches!(
reason,
"routine" | "compromise_suspected" | "device_lost" | "recovery" | "other"
)
}
pub fn generate_challenge() -> Vec<u8> {
use rand_core::{OsRng, RngCore};
let mut b = [0u8; 32];
OsRng.fill_bytes(&mut b);
b.to_vec()
}
pub fn transaction_receipt_sign_bytes(receipt: &TransactionReceipt) -> Vec<u8> {
let mut sorted_parties: Vec<&crate::types::ReceiptParty> = receipt.parties.iter().collect();
sorted_parties.sort_by(|a, b| a.party_id.cmp(&b.party_id));
let mut out = String::new();
out.push('{');
out.push_str("\"created_at\":"); encode_i64(receipt.created_at, &mut out);
out.push_str(",\"parties\":[");
for (i, p) in sorted_parties.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push('{');
out.push_str("\"agent_id\":"); encode_str(&p.agent_id, &mut out);
out.push_str(",\"agent_pub_key\":"); encode_hybrid_pub_key(&p.agent_pub_key, &mut out);
out.push_str(",\"party_id\":"); encode_str(&p.party_id, &mut out);
out.push_str(",\"role\":"); encode_str(&p.role, &mut out);
out.push('}');
}
out.push(']');
out.push_str(",\"terms_canonical_json\":"); encode_bytes_b64(&receipt.terms_canonical_json, &mut out);
out.push_str(",\"terms_schema_uri\":"); encode_str(&receipt.terms_schema_uri, &mut out);
out.push_str(",\"transaction_id\":"); encode_str(&receipt.transaction_id, &mut out);
out.push_str(",\"version\":"); encode_i32(receipt.version, &mut out);
out.push('}');
out.into_bytes()
}
pub fn sign_transaction_receipt_party(
receipt: &TransactionReceipt,
party_id: &str,
agent_priv: &HybridPrivateKey,
) -> ReceiptPartySignature {
let data = transaction_receipt_sign_bytes(receipt);
let sig = sign_both(&data, agent_priv);
ReceiptPartySignature {
party_id: party_id.to_string(),
signature: sig,
}
}
pub fn chain_hash(chain: &[DelegationCert]) -> Vec<u8> {
let mut hasher = Sha256::new();
for cert in chain {
hasher.update(delegation_sign_bytes(cert));
}
hasher.finalize().to_vec()
}
pub fn session_token_sign_bytes(token: &SessionToken) -> Vec<u8> {
let mut scope = token.granted_scope.clone();
scope.sort();
let mut out = String::new();
out.push('{');
out.push_str("\"agent_id\":"); encode_str(&token.agent_id, &mut out);
out.push_str(",\"agent_pub_key\":"); encode_hybrid_pub_key(&token.agent_pub_key, &mut out);
out.push_str(",\"chain_hash\":"); encode_bytes_b64(&token.chain_hash, &mut out);
out.push_str(",\"granted_scope\":"); encode_str_array(&scope, &mut out);
out.push_str(",\"human_id\":"); encode_str(&token.human_id, &mut out);
out.push_str(",\"issued_at\":"); encode_i64(token.issued_at, &mut out);
out.push_str(",\"session_id\":"); encode_str(&token.session_id, &mut out);
out.push_str(",\"valid_until\":"); encode_i64(token.valid_until, &mut out);
out.push_str(",\"version\":"); encode_i32(token.version, &mut out);
out.push('}');
out.into_bytes()
}
pub fn issue_session_token(
bundle: &ProofBundle,
result: &VerifyResult,
session_id: &str,
issued_at: i64,
valid_until: i64,
session_secret: &[u8],
) -> Result<SessionToken, String> {
if session_secret.is_empty() {
return Err("session_secret must not be empty".to_string());
}
if session_id.is_empty() {
return Err("session_id must not be empty".to_string());
}
if valid_until <= issued_at {
return Err("valid_until must be strictly after issued_at".to_string());
}
let mut scope = result.granted_scope.clone();
scope.sort();
let mut token = SessionToken {
version: 1,
session_id: session_id.to_string(),
agent_id: result.agent_id.clone(),
agent_pub_key: bundle.agent_pub_key.clone(),
human_id: result.human_id.clone(),
granted_scope: scope,
issued_at,
valid_until,
chain_hash: chain_hash(&bundle.delegations),
mac: Vec::new(),
};
let signable = session_token_sign_bytes(&token);
let mut mac =
HmacSha256::new_from_slice(session_secret).map_err(|e| format!("init HMAC: {}", e))?;
mac.update(&signable);
token.mac = mac.finalize().into_bytes().to_vec();
Ok(token)
}
pub fn verify_session_token_e(
token: &SessionToken,
session_secret: &[u8],
now: i64,
) -> Result<(), String> {
if session_secret.is_empty() {
return Err("session_secret must not be empty".to_string());
}
if token.version != 1 {
return Err(format!(
"version_mismatch: unsupported version {}",
token.version
));
}
if token.chain_hash.len() != 32 {
return Err(format!(
"chain_hash must be 32 bytes, got {}",
token.chain_hash.len()
));
}
if token.mac.len() != 32 {
return Err(format!("mac must be 32 bytes, got {}", token.mac.len()));
}
let mut mac =
HmacSha256::new_from_slice(session_secret).map_err(|e| format!("init HMAC: {}", e))?;
mac.update(&session_token_sign_bytes(token));
mac.verify_slice(&token.mac)
.map_err(|_| "session_token MAC invalid".to_string())?;
if now < token.issued_at {
return Err("session_token not yet valid".to_string());
}
if now > token.valid_until {
return Err("session_token expired".to_string());
}
Ok(())
}
pub fn verify_session_token(token: &SessionToken, session_secret: &[u8], now: i64) -> bool {
verify_session_token_e(token, session_secret, now).is_ok()
}