//! EdDSA (Ed25519) JSON Web Tokens: signing, verification, claim checks and the public key format. //! //! The header is `{"alg":"EdDSA","typ":"JWT","kid":...}`. Verification reads the algorithm first and //! accepts only `EdDSA`, so `none` and every other algorithm fail before any key is used. The key is //! chosen by `kid` from the keys that are published; an unknown `kid` is refused. Claim checks are a //! separate call, so each caller states its own issuer and audience. use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use serde_json::{Map, Value, json}; /// The only algorithm this provider signs or accepts. pub const ALG: &str = "EdDSA"; /// How far an `iat` may lie in the future, in seconds (contracts section 2.3: five minutes). pub const MAX_FUTURE_IAT_SECS: i64 = 300; /// Why a token was refused. Only the web layer sees these; the client gets one generic answer. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum JwtError { /// The token does not have three parts, or a part is not valid base64url JSON. #[error("the token is malformed")] Malformed, /// The header names an algorithm other than EdDSA. #[error("the algorithm is not EdDSA")] Algorithm, /// The `kid` is missing or not published. #[error("the key id is not published")] UnknownKey, /// The signature does not verify with the key. #[error("the signature does not verify")] Signature, /// A claim is missing, has the wrong type or has a wrong value. #[error("the claim {0} is missing or wrong")] Claim(&'static str), } /// A public key that may verify tokens, under its `kid`. pub struct PublishedKey { kid: String, key: VerifyingKey, } impl PublishedKey { /// A verifying key from its `kid` and its 32 raw public bytes. `None` for bytes that are not a key. pub fn new(kid: String, public: &[u8]) -> Option { let raw: [u8; 32] = public.try_into().ok()?; VerifyingKey::from_bytes(&raw) .ok() .map(|key| PublishedKey { kid, key }) } } /// Signs `claims` (a JSON object) with `key`, and puts `kid` in the header. pub fn sign(key: &SigningKey, kid: &str, claims: &Value) -> String { let header = json!({"alg": ALG, "typ": "JWT", "kid": kid}); let signing_input = format!("{}.{}", encode_json(&header), encode_json(claims)); let signature: Signature = key.sign(signing_input.as_bytes()); format!( "{signing_input}.{}", BASE64_URL_SAFE_NO_PAD.encode(signature.to_bytes()) ) } /// Signs `claims` with the key whose 32-byte seed is `seed`. The seed is the sealed form of the key /// (`keys::generate`), opened for the one call. pub fn sign_with_seed(seed: &[u8; 32], kid: &str, claims: &Value) -> String { sign(&SigningKey::from_bytes(seed), kid, claims) } /// Verifies a token against the published keys and returns its claims. The algorithm, the `kid`, and /// the signature are checked; the time and the issuer are not (see [`check_claims`]). pub fn verify(keys: &[PublishedKey], token: &str) -> Result, JwtError> { let mut parts = token.split('.'); let (Some(header), Some(payload), Some(signature), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { return Err(JwtError::Malformed); }; let header = decode_object(header)?; if header.get("alg").and_then(Value::as_str) != Some(ALG) { return Err(JwtError::Algorithm); } let kid = header .get("kid") .and_then(Value::as_str) .ok_or(JwtError::UnknownKey)?; let key = keys .iter() .find(|known| known.kid == kid) .ok_or(JwtError::UnknownKey)?; let raw = BASE64_URL_SAFE_NO_PAD .decode(signature) .map_err(|_| JwtError::Malformed)?; let raw: [u8; 64] = raw.try_into().map_err(|_| JwtError::Malformed)?; let signature = Signature::from_bytes(&raw); let signing_input = format!( "{}.{}", token.split('.').next().unwrap_or_default(), payload ); key.key .verify_strict(signing_input.as_bytes(), &signature) .map_err(|_| JwtError::Signature)?; decode_object(payload) } /// Checks the registered claims: `iss` equals `issuer` exactly, `aud` is `audience` (a string, or an /// array holding only that string), `exp` is in the future, and `iat` is at most five minutes ahead. pub fn check_claims( claims: &Map, issuer: &str, audience: &str, now: i64, ) -> Result<(), JwtError> { if claims.get("iss").and_then(Value::as_str) != Some(issuer) { return Err(JwtError::Claim("iss")); } if !audience_is(claims.get("aud"), audience) { return Err(JwtError::Claim("aud")); } let exp = claims .get("exp") .and_then(Value::as_i64) .ok_or(JwtError::Claim("exp"))?; if exp <= now { return Err(JwtError::Claim("exp")); } let iat = claims .get("iat") .and_then(Value::as_i64) .ok_or(JwtError::Claim("iat"))?; if iat > now + MAX_FUTURE_IAT_SECS { return Err(JwtError::Claim("iat")); } Ok(()) } /// Checks only the issuer: `iss` equals `issuer` exactly. For a caller that checks its own expiry /// (an ID token used as a logout hint may be expired) and its own audience. pub fn check_issuer(claims: &Map, issuer: &str) -> Result<(), JwtError> { if claims.get("iss").and_then(Value::as_str) == Some(issuer) { Ok(()) } else { Err(JwtError::Claim("iss")) } } /// The audience of a token when it is a single string. `None` for an array or a missing claim. pub fn single_audience(claims: &Map) -> Option<&str> { claims.get("aud").and_then(Value::as_str) } fn audience_is(aud: Option<&Value>, expected: &str) -> bool { match aud { Some(Value::String(one)) => one == expected, Some(Value::Array(list)) => list.len() == 1 && list[0].as_str() == Some(expected), _ => false, } } /// One public key as a JWK (RFC 8037), for the JWKS document. pub fn jwk(kid: &str, public: &[u8]) -> Value { json!({ "kty": "OKP", "crv": "Ed25519", "x": BASE64_URL_SAFE_NO_PAD.encode(public), "kid": kid, "use": "sig", "alg": ALG, }) } fn encode_json(value: &Value) -> String { BASE64_URL_SAFE_NO_PAD.encode(value.to_string()) } fn decode_object(segment: &str) -> Result, JwtError> { let bytes = BASE64_URL_SAFE_NO_PAD .decode(segment) .map_err(|_| JwtError::Malformed)?; match serde_json::from_slice(&bytes) { Ok(Value::Object(map)) => Ok(map), _ => Err(JwtError::Malformed), } } #[cfg(test)] mod tests { use super::*; #[test] fn a_signed_token_verifies_and_a_tampered_one_does_not() { let key = SigningKey::from_bytes(&[9u8; 32]); let public = key.verifying_key().to_bytes(); let keys = vec![PublishedKey::new("k1".into(), &public).expect("key")]; let token = sign(&key, "k1", &json!({"iss": "https://im.test", "aud": "im"})); assert!(verify(&keys, &token).is_ok()); let forged = json!({"iss": "https://im.test", "aud": "admin"}); let mut parts: Vec<&str> = token.split('.').collect(); let forged_part = BASE64_URL_SAFE_NO_PAD.encode(forged.to_string()); parts[1] = &forged_part; assert_eq!(verify(&keys, &parts.join(".")), Err(JwtError::Signature)); let none = format!( "{}.{}.", BASE64_URL_SAFE_NO_PAD.encode(r#"{"alg":"none","kid":"k1"}"#), BASE64_URL_SAFE_NO_PAD.encode("{}") ); assert_eq!(verify(&keys, &none), Err(JwtError::Algorithm)); } }