use std::fmt;
use aws_lc_rs::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey};
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;
use super::message::{ComponentId, SignatureInput, signature_base};
use super::structured::{BareItem, Dictionary, ListEntry};
use super::{DIRECTORY_TAG, WebBotAuthError};
pub(crate) const RFC9421_TEST_KEY_X: &str = "JrQLj5P_89iXES9-vFgrIy29clF9CC_oPPsw3c5D0bs";
pub fn jwk_thumbprint(public_key: &[u8; 32]) -> String {
let canonical =
format!(r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#, URL_SAFE_NO_PAD.encode(public_key));
URL_SAFE_NO_PAD.encode(Sha256::digest(canonical.as_bytes()))
}
pub(crate) fn verify_ed25519(public_key: &[u8; 32], message: &[u8], signature: &[u8]) -> bool {
UnparsedPublicKey::new(&ED25519, public_key).verify(message, signature).is_ok()
}
pub struct Ed25519SigningKey {
seed: Zeroizing<[u8; 32]>,
key_pair: Ed25519KeyPair,
public_key: [u8; 32],
thumbprint: String,
}
impl fmt::Debug for Ed25519SigningKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ed25519SigningKey")
.field("thumbprint", &self.thumbprint)
.finish_non_exhaustive()
}
}
impl Ed25519SigningKey {
pub fn from_seed(seed: [u8; 32]) -> Result<Self, WebBotAuthError> {
let seed = Zeroizing::new(seed);
let key_pair = Ed25519KeyPair::from_seed_unchecked(seed.as_ref())
.map_err(|e| WebBotAuthError::InvalidKey { reason: e.to_string() })?;
let public_key: [u8; 32] = key_pair.public_key().as_ref().try_into().map_err(|_| {
WebBotAuthError::InvalidKey { reason: "public key is not 32 bytes".into() }
})?;
let thumbprint = jwk_thumbprint(&public_key);
Ok(Self { seed, key_pair, public_key, thumbprint })
}
pub fn generate() -> Result<Self, WebBotAuthError> {
let mut seed = Zeroizing::new([0u8; 32]);
aws_lc_rs::rand::fill(seed.as_mut())
.map_err(|_| WebBotAuthError::InvalidKey { reason: "no secure randomness".into() })?;
Self::from_seed(*seed)
}
pub fn from_jwk(jwk: &str) -> Result<Self, WebBotAuthError> {
#[derive(Deserialize)]
struct PrivateJwk {
kty: String,
crv: String,
x: Option<String>,
d: Option<String>,
}
let invalid = |reason: &str| WebBotAuthError::InvalidKey { reason: reason.to_string() };
let parsed: PrivateJwk =
serde_json::from_str(jwk).map_err(|_| invalid("the JWK is not an OKP JSON object"))?;
let d = Zeroizing::new(parsed.d.unwrap_or_default());
if parsed.kty != "OKP" || parsed.crv != "Ed25519" {
return Err(invalid("the JWK is not an OKP Ed25519 key"));
}
if d.is_empty() {
return Err(invalid("the JWK has no private `d` member"));
}
let seed = Zeroizing::new(
URL_SAFE_NO_PAD.decode(d.as_bytes()).map_err(|_| invalid("`d` is not base64url"))?,
);
let seed: [u8; 32] =
seed.as_slice().try_into().map_err(|_| invalid("`d` is not 32 bytes"))?;
let key = Self::from_seed(seed)?;
if parsed.x.is_some_and(|x| x != URL_SAFE_NO_PAD.encode(key.public_key)) {
return Err(invalid("`x` does not match `d`"));
}
Ok(key)
}
pub fn to_private_jwk(&self) -> Zeroizing<String> {
let d = Zeroizing::new(URL_SAFE_NO_PAD.encode(self.seed.as_ref()));
Zeroizing::new(format!(
r#"{{"kty":"OKP","crv":"Ed25519","kid":"{}","x":"{}","d":"{}"}}"#,
self.thumbprint,
URL_SAFE_NO_PAD.encode(self.public_key),
d.as_str()
))
}
pub fn public_key(&self) -> &[u8; 32] {
&self.public_key
}
pub fn thumbprint(&self) -> &str {
&self.thumbprint
}
pub fn public_jwk(&self) -> DirectoryKey {
DirectoryKey {
kty: "OKP".to_string(),
crv: "Ed25519".to_string(),
kid: Some(self.thumbprint.clone()),
x: URL_SAFE_NO_PAD.encode(self.public_key),
key_use: Some("sig".to_string()),
alg: None,
nbf: None,
exp: None,
}
}
pub fn sign(&self, message: &[u8]) -> [u8; 64] {
let mut out = [0u8; 64];
out.copy_from_slice(self.key_pair.sign(message).as_ref());
out
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectoryKey {
pub kty: String,
pub crv: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kid: Option<String>,
pub x: String,
#[serde(rename = "use", default, skip_serializing_if = "Option::is_none")]
pub key_use: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub alg: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nbf: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exp: Option<i64>,
}
impl DirectoryKey {
pub fn public_key(&self) -> Result<[u8; 32], WebBotAuthError> {
if self.kty != "OKP" || self.crv != "Ed25519" {
return Err(WebBotAuthError::InvalidKey {
reason: format!("key type {}/{} is not OKP/Ed25519", self.kty, self.crv),
});
}
let bytes = URL_SAFE_NO_PAD
.decode(&self.x)
.map_err(|_| WebBotAuthError::InvalidKey { reason: "`x` is not base64url".into() })?;
bytes
.try_into()
.map_err(|_| WebBotAuthError::InvalidKey { reason: "`x` is not 32 bytes".into() })
}
pub fn thumbprint(&self) -> Result<String, WebBotAuthError> {
self.public_key().map(|key| jwk_thumbprint(&key))
}
pub fn is_current(&self, now: i64) -> bool {
let seconds = |value: i64| if value >= 100_000_000_000 { value / 1000 } else { value };
self.nbf.is_none_or(|nbf| now >= seconds(nbf))
&& self.exp.is_none_or(|exp| now < seconds(exp))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct KeyDirectory {
pub keys: Vec<DirectoryKey>,
}
impl KeyDirectory {
pub fn from_keys<'a>(keys: impl IntoIterator<Item = &'a Ed25519SigningKey>) -> Self {
Self { keys: keys.into_iter().map(Ed25519SigningKey::public_jwk).collect() }
}
pub fn parse(bytes: &[u8], max_keys: usize) -> Result<Self, String> {
#[derive(Deserialize)]
struct Raw {
keys: Vec<serde_json::Value>,
}
let raw: Raw = serde_json::from_slice(bytes)
.map_err(|e| format!("the document is not a JWKS: {e}"))?;
if raw.keys.len() > max_keys {
return Err(format!(
"it lists {} keys, more than the limit of {max_keys}",
raw.keys.len()
));
}
let keys = raw
.keys
.into_iter()
.filter_map(|entry| {
if entry.get("d").is_some() {
tracing::warn!("key directory entry carries private key material; skipped");
return None;
}
let key: DirectoryKey = serde_json::from_value(entry).ok()?;
let usable = key.public_key().is_ok()
&& key.key_use.as_deref().is_none_or(|u| u == "sig")
&& key.alg.as_deref().is_none_or(|a| matches!(a, "ed25519" | "Ed25519" | "EdDSA"));
if !usable {
tracing::debug!(key.kty = %key.kty, "key directory entry is not a usable Ed25519 key; skipped");
}
usable.then_some(key)
})
.collect();
Ok(Self { keys })
}
pub fn find(&self, thumbprint: &str) -> Option<&DirectoryKey> {
self.keys.iter().find(|key| key.thumbprint().is_ok_and(|t| t == thumbprint))
}
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_else(|_| String::from(r#"{"keys":[]}"#))
}
pub fn signed_response(
&self,
keys: &[&Ed25519SigningKey],
authority: &str,
created: i64,
expires: i64,
) -> Result<DirectoryResponse, WebBotAuthError> {
if keys.is_empty() || expires < created {
return Err(WebBotAuthError::InvalidConfig {
reason: "a directory proof needs at least one key and expires at or after created"
.into(),
});
}
let body = self.to_json();
let content_digest =
format!("sha-256=:{}:", STANDARD.encode(Sha256::digest(body.as_bytes())));
let authority = authority.to_ascii_lowercase();
let mut inputs = Dictionary::new();
let mut signatures = Dictionary::new();
for (index, key) in keys.iter().enumerate() {
let label =
if keys.len() == 1 { "binding".to_string() } else { format!("binding{index}") };
let mut input = SignatureInput::new(vec![
ComponentId::new("@authority").with_param("req", BareItem::Boolean(true)),
ComponentId::new("content-digest"),
]);
input.params.insert("created", BareItem::Integer(created));
input.params.insert("expires", BareItem::Integer(expires));
input.params.insert("keyid", BareItem::String(key.thumbprint().to_string()));
input.params.insert("tag", BareItem::String(DIRECTORY_TAG.to_string()));
let base = signature_base(&input, |component| match component.name() {
"@authority" => Ok(authority.clone()),
_ => Ok(content_digest.clone()),
})?;
let signature = key.sign(base.as_bytes());
inputs.insert(label.clone(), ListEntry::InnerList(input.to_inner_list()));
signatures.insert(
label,
ListEntry::Item(super::structured::Item::new(BareItem::ByteSequence(
signature.to_vec(),
))),
);
}
let serialize = |dict: Dictionary| {
dict.serialize().map_err(|e| WebBotAuthError::InvalidConfig { reason: e.to_string() })
};
Ok(DirectoryResponse {
body,
content_digest,
signature_input: serialize(inputs)?,
signature: serialize(signatures)?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectoryResponse {
pub body: String,
pub content_digest: String,
pub signature_input: String,
pub signature: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn key_validity_reads_seconds_and_milliseconds() {
let mut key = Ed25519SigningKey::generate().unwrap().public_jwk();
key.nbf = Some(1_743_465_600_000);
assert!(key.is_current(1_743_465_600));
assert!(!key.is_current(1_743_465_599));
key.nbf = Some(1_700_000_000);
key.exp = Some(1_800_000_000);
assert!(key.is_current(1_750_000_000));
assert!(!key.is_current(1_800_000_000));
}
#[test]
fn parse_skips_unusable_entries() {
let good = Ed25519SigningKey::generate().unwrap();
let doc = serde_json::json!({
"keys": [
{"kty": "RSA", "n": "abc", "e": "AQAB"},
{"kty": "OKP", "crv": "Ed25519", "x": "short"},
{"kty": "OKP", "crv": "Ed25519", "x": good.public_jwk().x, "d": "secret"},
{"kty": "OKP", "crv": "Ed25519", "x": good.public_jwk().x, "use": "enc"},
{"kty": "OKP", "crv": "Ed25519", "x": good.public_jwk().x, "alg": "ES256"},
good.public_jwk(),
],
"purpose": "rag"
});
let parsed = KeyDirectory::parse(doc.to_string().as_bytes(), 16).unwrap();
assert_eq!(parsed.keys, vec![good.public_jwk()]);
assert!(KeyDirectory::parse(doc.to_string().as_bytes(), 3).is_err());
assert!(KeyDirectory::parse(b"[]", 3).is_err());
}
#[test]
fn from_jwk_rejects_mismatched_public_key() {
let a = Ed25519SigningKey::generate().unwrap();
let b = Ed25519SigningKey::generate().unwrap();
let mut jwk: serde_json::Value = serde_json::from_str(&a.to_private_jwk()).unwrap();
jwk["x"] = serde_json::Value::String(b.public_jwk().x);
assert!(Ed25519SigningKey::from_jwk(&jwk.to_string()).is_err());
assert!(Ed25519SigningKey::from_jwk(r#"{"kty":"OKP","crv":"Ed25519"}"#).is_err());
}
#[test]
fn signatures_verify() {
let key = Ed25519SigningKey::generate().unwrap();
let signature = key.sign(b"message");
assert!(verify_ed25519(key.public_key(), b"message", &signature));
assert!(!verify_ed25519(key.public_key(), b"other", &signature));
}
}