use std::fs; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use jsonwebtoken::jwk::{ AlgorithmParameters, CommonParameters, EllipticCurve, EllipticCurveKeyParameters, EllipticCurveKeyType, Jwk, JwkSet, KeyAlgorithm, PublicKeyUse, RSAKeyParameters, RSAKeyType, }; use jsonwebtoken::{Algorithm, EncodingKey, Header}; use p256::elliptic_curve::sec1::ToEncodedPoint; use rsa::RsaPrivateKey; use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, LineEnding}; use rsa::traits::PublicKeyParts; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use zeroize::Zeroizing; pub const KEY_BITS: usize = 2048; pub const FILE_NAME: &str = "signing-key.pem"; pub const PREVIOUS_FILE_NAME: &str = "signing-key.previous.pem"; pub const EC_FILE_NAME: &str = "signing-key-es256.pem"; pub const EC_PREVIOUS_FILE_NAME: &str = "signing-key-es256.previous.pem"; #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub enum SigningAlgorithm { #[default] Rs256, Es256, } impl std::str::FromStr for SigningAlgorithm { type Err = UnknownSigningAlgorithm; fn from_str(value: &str) -> Result { match value.to_ascii_uppercase().as_str() { "RS256" => Ok(Self::Rs256), "ES256" => Ok(Self::Es256), _ => Err(UnknownSigningAlgorithm(value.to_owned())), } } } #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] #[error("signing algorithm must be RS256 or ES256, not {0:?}")] pub struct UnknownSigningAlgorithm(pub String); impl SigningAlgorithm { pub const ALL: [Self; 2] = [Self::Rs256, Self::Es256]; pub fn as_str(self) -> &'static str { match self { Self::Rs256 => "RS256", Self::Es256 => "ES256", } } fn jwt(self) -> Algorithm { match self { Self::Rs256 => Algorithm::RS256, Self::Es256 => Algorithm::ES256, } } fn files(self, state_dir: &Path) -> (PathBuf, PathBuf, PathBuf) { let (current, previous, staged) = match self { Self::Rs256 => (FILE_NAME, PREVIOUS_FILE_NAME, "signing-key.next.pem"), Self::Es256 => ( EC_FILE_NAME, EC_PREVIOUS_FILE_NAME, "signing-key-es256.next.pem", ), }; ( state_dir.join(current), state_dir.join(previous), state_dir.join(staged), ) } } #[derive(Clone)] pub struct SigningKey { algorithm: SigningAlgorithm, kid: String, pem: Zeroizing, encoding: EncodingKey, jwk: Jwk, } impl SigningKey { pub fn generate(algorithm: SigningAlgorithm) -> Result { let mut rng = rand::rngs::OsRng; match algorithm { SigningAlgorithm::Rs256 => Self::from_rsa(RsaPrivateKey::new(&mut rng, KEY_BITS)?), SigningAlgorithm::Es256 => Self::from_ec(p256::SecretKey::random(&mut rng)), } } pub fn load(path: &Path, algorithm: SigningAlgorithm) -> Result { let pem = Zeroizing::new(fs::read_to_string(path)?); match algorithm { SigningAlgorithm::Rs256 => Self::from_rsa(RsaPrivateKey::from_pkcs8_pem(&pem)?), SigningAlgorithm::Es256 => Self::from_ec(p256::SecretKey::from_pkcs8_pem(&pem)?), } } pub fn save(&self, path: &Path) -> Result<(), KeyError> { let mut file = fs::OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(path)?; std::io::Write::write_all(&mut file, self.pem.as_bytes())?; Ok(()) } fn from_rsa(private: RsaPrivateKey) -> Result { let pem = private.to_pkcs8_pem(LineEnding::LF)?; let encoding = EncodingKey::from_rsa_pem(pem.as_bytes())?; let modulus = private.n().to_bytes_be(); let exponent = private.e().to_bytes_be(); let kid = key_id(&modulus, &exponent); let jwk = Jwk { common: common(KeyAlgorithm::RS256, &kid), algorithm: AlgorithmParameters::RSA(RSAKeyParameters { key_type: RSAKeyType::RSA, n: URL_SAFE_NO_PAD.encode(&modulus), e: URL_SAFE_NO_PAD.encode(&exponent), }), }; Ok(Self { algorithm: SigningAlgorithm::Rs256, kid, pem, encoding, jwk, }) } fn from_ec(secret: p256::SecretKey) -> Result { let pem = secret.to_pkcs8_pem(LineEnding::LF)?; let encoding = EncodingKey::from_ec_pem(pem.as_bytes())?; let point = secret.public_key().to_encoded_point(false); let (x, y) = point.as_bytes()[1..].split_at(32); let kid = key_id(x, y); let jwk = Jwk { common: common(KeyAlgorithm::ES256, &kid), algorithm: AlgorithmParameters::EllipticCurve(EllipticCurveKeyParameters { key_type: EllipticCurveKeyType::EC, curve: EllipticCurve::P256, x: URL_SAFE_NO_PAD.encode(x), y: URL_SAFE_NO_PAD.encode(y), }), }; Ok(Self { algorithm: SigningAlgorithm::Es256, kid, pem, encoding, jwk, }) } pub fn algorithm(&self) -> SigningAlgorithm { self.algorithm } pub fn kid(&self) -> &str { &self.kid } pub fn sign(&self, claims: &T) -> Result { let mut header = Header::new(self.algorithm.jwt()); header.typ = Some("JWT".to_owned()); header.kid = Some(self.kid.clone()); Ok(jsonwebtoken::encode(&header, claims, &self.encoding)?) } } fn common(algorithm: KeyAlgorithm, kid: &str) -> CommonParameters { CommonParameters { public_key_use: Some(PublicKeyUse::Signature), key_operations: None, key_algorithm: Some(algorithm), key_id: Some(kid.to_owned()), x509_url: None, x509_chain: None, x509_sha1_fingerprint: None, x509_sha256_fingerprint: None, } } fn key_id(first: &[u8], second: &[u8]) -> String { let mut hasher = Sha256::new(); hasher.update(first); hasher.update(second); URL_SAFE_NO_PAD.encode(&hasher.finalize()[..16]) } #[derive(Clone)] pub struct KeyPair { current: SigningKey, previous: Option, } impl KeyPair { fn ensure(state_dir: &Path, algorithm: SigningAlgorithm) -> Result { let (current_path, previous_path, _) = algorithm.files(state_dir); let current = if current_path.exists() { SigningKey::load(¤t_path, algorithm)? } else { let key = SigningKey::generate(algorithm)?; key.save(¤t_path)?; key }; Ok(Self { current, previous: Self::previous(&previous_path, algorithm)?, }) } fn previous(path: &Path, algorithm: SigningAlgorithm) -> Result, KeyError> { if path.exists() { Ok(Some(SigningKey::load(path, algorithm)?)) } else { Ok(None) } } fn rotate(state_dir: &Path, algorithm: SigningAlgorithm) -> Result { let (current_path, previous_path, staged) = algorithm.files(state_dir); let retiring = SigningKey::load(¤t_path, algorithm)?; let fresh = SigningKey::generate(algorithm)?; let _ = fs::remove_file(&staged); fresh.save(&staged)?; fs::rename(¤t_path, &previous_path)?; fs::rename(&staged, ¤t_path)?; Ok(Self { current: fresh, previous: Some(retiring), }) } fn keys(&self) -> impl Iterator { std::iter::once(&self.current.jwk).chain(self.previous.iter().map(|key| &key.jwk)) } } #[derive(Clone)] pub struct SigningKeys { rsa: KeyPair, ec: KeyPair, } impl SigningKeys { pub fn new(rsa: SigningKey, ec: SigningKey) -> Self { Self { rsa: KeyPair { current: rsa, previous: None, }, ec: KeyPair { current: ec, previous: None, }, } } pub fn ensure(state_dir: &Path) -> Result { fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(state_dir)?; Ok(Self { rsa: KeyPair::ensure(state_dir, SigningAlgorithm::Rs256)?, ec: KeyPair::ensure(state_dir, SigningAlgorithm::Es256)?, }) } pub fn rotate(state_dir: &Path) -> Result { Ok(Self { rsa: KeyPair::rotate(state_dir, SigningAlgorithm::Rs256)?, ec: KeyPair::rotate(state_dir, SigningAlgorithm::Es256)?, }) } fn pair(&self, algorithm: SigningAlgorithm) -> &KeyPair { match algorithm { SigningAlgorithm::Rs256 => &self.rsa, SigningAlgorithm::Es256 => &self.ec, } } pub fn current(&self, algorithm: SigningAlgorithm) -> &SigningKey { &self.pair(algorithm).current } pub fn jwks(&self) -> JwkSet { JwkSet { keys: self.rsa.keys().chain(self.ec.keys()).cloned().collect(), } } pub fn sign( &self, claims: &T, algorithm: SigningAlgorithm, ) -> Result { self.current(algorithm).sign(claims) } } #[derive(Debug, thiserror::Error)] pub enum KeyError { #[error("cannot generate signing key: {0}")] Generate(#[from] rsa::Error), #[error("invalid signing key encoding: {0}")] Encoding(#[from] rsa::pkcs8::Error), #[error("cannot sign token: {0}")] Sign(#[from] jsonwebtoken::errors::Error), #[error("signing key file: {0}")] Io(#[from] std::io::Error), #[error("client key: {0}")] Client(String), } #[cfg(test)] mod tests { use jsonwebtoken::{DecodingKey, Validation}; use serde::Deserialize; use super::*; #[derive(Serialize, Deserialize)] struct Claims { sub: String, exp: u64, } fn claims() -> Claims { Claims { sub: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa".to_owned(), exp: jsonwebtoken::get_current_timestamp() + 60, } } fn verify(token: &str, jwk: &Jwk, algorithm: Algorithm) -> jsonwebtoken::TokenData { let decoding = DecodingKey::from_jwk(jwk).expect("jwk"); let mut validation = Validation::new(algorithm); validation.validate_aud = false; jsonwebtoken::decode::(token, &decoding, &validation).expect("decode") } fn published<'a>(keys: &'a JwkSet, kid: &str) -> &'a Jwk { keys.keys .iter() .find(|key| key.common.key_id.as_deref() == Some(kid)) .expect("published key") } #[test] fn keys_persist_verify_against_the_published_set_and_rotate_together() { let dir = tempfile::tempdir().expect("tempdir"); let first = SigningKeys::ensure(dir.path()).expect("ensure"); assert_eq!(first.jwks().keys.len(), 2); let again = SigningKeys::ensure(dir.path()).expect("ensure again"); let rotated = SigningKeys::rotate(dir.path()).expect("rotate"); let jwks = rotated.jwks(); assert_eq!(jwks.keys.len(), 4); for (algorithm, jwt) in [ (SigningAlgorithm::Rs256, Algorithm::RS256), (SigningAlgorithm::Es256, Algorithm::ES256), ] { let old = first.current(algorithm); assert_eq!(again.current(algorithm).kid(), old.kid()); assert_eq!(old.algorithm(), algorithm); let (current_path, _, _) = algorithm.files(dir.path()); assert!( old.save(¤t_path).is_err(), "keys are never overwritten" ); let new = rotated.current(algorithm); assert_ne!(new.kid(), old.kid()); let claims = claims(); for keys in [&first, &rotated] { let token = keys.sign(&claims, algorithm).expect("sign"); let kid = keys.current(algorithm).kid(); let decoded = verify(&token, published(&jwks, kid), jwt); assert_eq!(decoded.claims.sub, claims.sub); assert_eq!(decoded.header.kid.as_deref(), Some(kid)); assert_eq!(decoded.header.alg, jwt); } } let reopened = SigningKeys::ensure(dir.path()).expect("reopen"); assert_eq!(reopened.jwks(), jwks); } }