Something went wrong. Try again.
An OIDC provider for AT Protocol OAuth. Rust port of apenwarr/atlogin.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402use 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<Self, Self::Err> { 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<String>, encoding: EncodingKey, jwk: Jwk,}
impl SigningKey { pub fn generate(algorithm: SigningAlgorithm) -> Result<Self, KeyError> { 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<Self, KeyError> { 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<Self, KeyError> { 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<Self, KeyError> { 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<T: Serialize>(&self, claims: &T) -> Result<String, KeyError> { 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<SigningKey>,}
impl KeyPair { fn ensure(state_dir: &Path, algorithm: SigningAlgorithm) -> Result<Self, KeyError> { 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<Option<SigningKey>, KeyError> { if path.exists() { Ok(Some(SigningKey::load(path, algorithm)?)) } else { Ok(None) } }
fn rotate(state_dir: &Path, algorithm: SigningAlgorithm) -> Result<Self, KeyError> { 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<Item = &Jwk> { 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<Self, KeyError> { 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<Self, KeyError> { 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<T: Serialize>( &self, claims: &T, algorithm: SigningAlgorithm, ) -> Result<String, KeyError> { 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<Claims> { let decoding = DecodingKey::from_jwk(jwk).expect("jwk"); let mut validation = Validation::new(algorithm); validation.validate_aud = false; jsonwebtoken::decode::<Claims>(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); }}