use std::fs; use std::os::unix::fs::OpenOptionsExt; use std::path::Path; use jacquard_oauth::keyset::Keyset; use serde_json::{Value, json}; use zeroize::Zeroizing; use crate::database::random_token; use crate::keys::KeyError; pub const FILE_NAME: &str = "client-key.json"; pub const PREVIOUS_FILE_NAME: &str = "client-key.previous.json"; const STAGED_FILE_NAME: &str = "client-key.staged.json"; #[derive(Clone)] pub struct ClientKey { current: Keyset, previous: Option, } impl ClientKey { pub fn generate() -> Result { Ok(Self { current: fresh()?, previous: None, }) } pub fn ensure(state_dir: &Path) -> Result { let current_path = state_dir.join(FILE_NAME); let current = if current_path.exists() { read(¤t_path)? } else { let keyset = fresh()?; write(¤t_path, &keyset)?; keyset }; Ok(Self { current, previous: previous(state_dir)?, }) } pub fn rotate(state_dir: &Path) -> Result { let current_path = state_dir.join(FILE_NAME); let previous_path = state_dir.join(PREVIOUS_FILE_NAME); let staged = state_dir.join(STAGED_FILE_NAME); let retiring = read(¤t_path)?; let keyset = fresh()?; let _ = fs::remove_file(&staged); write(&staged, &keyset)?; fs::rename(¤t_path, &previous_path)?; fs::rename(&staged, ¤t_path)?; Ok(Self { current: keyset, previous: Some(retiring), }) } pub fn keyset(&self) -> Keyset { self.current.clone() } pub fn kid(&self) -> String { public_keys(&self.current) .first() .and_then(|key| key["kid"].as_str()) .unwrap_or_default() .to_owned() } pub fn public_jwks(&self) -> Value { let keys: Vec = std::iter::once(&self.current) .chain(self.previous.iter()) .flat_map(public_keys) .collect(); json!({ "keys": keys }) } } fn fresh() -> Result { Keyset::generate_es256(&random_token()[..16]) .map_err(|error| KeyError::Client(error.to_string())) } fn public_keys(keyset: &Keyset) -> Vec { serde_json::to_value(keyset.public_jwks()) .ok() .and_then(|mut value| value.get_mut("keys").map(Value::take)) .and_then(|keys| keys.as_array().cloned()) .unwrap_or_default() } fn previous(state_dir: &Path) -> Result, KeyError> { let path = state_dir.join(PREVIOUS_FILE_NAME); if path.exists() { Ok(Some(read(&path)?)) } else { Ok(None) } } fn read(path: &Path) -> Result { let json = Zeroizing::new(fs::read_to_string(path)?); serde_json::from_str(&json).map_err(|error| KeyError::Client(error.to_string())) } fn write(path: &Path, keyset: &Keyset) -> Result<(), KeyError> { let mut file = fs::OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(path)?; let json = serde_json::to_string(keyset).map_err(|error| KeyError::Client(error.to_string()))?; std::io::Write::write_all(&mut file, json.as_bytes())?; Ok(()) } #[cfg(test)] mod tests { use super::*; use std::os::unix::fs::PermissionsExt; #[test] fn the_client_key_persists_rotates_and_publishes_only_public_halves() { let dir = tempfile::tempdir().expect("tempdir"); let first = ClientKey::ensure(dir.path()).expect("ensure"); let again = ClientKey::ensure(dir.path()).expect("ensure again"); assert_eq!(first.kid(), again.kid()); assert!(!first.kid().is_empty()); let mode = fs::metadata(dir.path().join(FILE_NAME)) .expect("metadata") .permissions() .mode(); assert_eq!(mode & 0o777, 0o600); let published = first.public_jwks(); let keys = published["keys"].as_array().expect("keys"); assert_eq!(keys.len(), 1); assert_eq!(keys[0]["kty"], "EC"); assert_eq!(keys[0]["crv"], "P-256"); assert_eq!(keys[0]["kid"], first.kid()); assert!(keys[0].get("d").is_none(), "{published}"); let rotated = ClientKey::rotate(dir.path()).expect("rotate"); assert_ne!(rotated.kid(), first.kid()); let keys = rotated.public_jwks(); let kids: Vec<&str> = keys["keys"] .as_array() .expect("keys") .iter() .filter_map(|key| key["kid"].as_str()) .collect(); assert_eq!(kids, [rotated.kid().as_str(), first.kid().as_str()]); let reloaded = ClientKey::ensure(dir.path()).expect("reopen"); assert_eq!(reloaded.public_jwks(), keys); assert!(!dir.path().join(STAGED_FILE_NAME).exists()); } }