Something went wrong. Try again.
An OIDC provider for AT Protocol OAuth. Rust port of apenwarr/atlogin.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162use 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<Keyset>,}
impl ClientKey { pub fn generate() -> Result<Self, KeyError> { Ok(Self { current: fresh()?, previous: None, }) }
pub fn ensure(state_dir: &Path) -> Result<Self, KeyError> { 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<Self, KeyError> { 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<Value> = std::iter::once(&self.current) .chain(self.previous.iter()) .flat_map(public_keys) .collect(); json!({ "keys": keys }) }}
fn fresh() -> Result<Keyset, KeyError> { Keyset::generate_es256(&random_token()[..16]) .map_err(|error| KeyError::Client(error.to_string()))}
fn public_keys(keyset: &Keyset) -> Vec<Value> { 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<Option<Keyset>, KeyError> { let path = state_dir.join(PREVIOUS_FILE_NAME); if path.exists() { Ok(Some(read(&path)?)) } else { Ok(None) }}
fn read(path: &Path) -> Result<Keyset, KeyError> { 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()); }}