use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};
use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Nonce};
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use hmac::{Hmac, Mac};
use rand::TryRng;
use serde::{Serialize, de::DeserializeOwned};
use sha2::Sha256;
const NONCE_LEN: usize = 12;
#[derive(Debug, thiserror::Error)]
pub enum CryptError {
#[error("APP_KEY is not set; generate one with Crypt::generate_key()")]
MissingKey,
#[error("invalid key: {0}")]
InvalidKey(&'static str),
#[error("the payload could not be decrypted")]
Decrypt,
#[error("the value could not be encrypted")]
Encrypt,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum SignatureError {
#[error("signature is missing")]
Missing,
#[error("signature is invalid")]
Invalid,
#[error("signed url has expired")]
Expired,
}
#[derive(Clone)]
pub struct Crypt {
keys: Vec<[u8; 32]>,
}
impl fmt::Debug for Crypt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Crypt({} keys, redacted)", self.keys.len())
}
}
fn parse_key(s: &str) -> Result<[u8; 32], CryptError> {
let b64 = s
.trim()
.strip_prefix("base64:")
.ok_or(CryptError::InvalidKey(
"expected the form base64:<32 bytes>",
))?;
let bytes = STANDARD
.decode(b64)
.map_err(|_| CryptError::InvalidKey("not valid base64"))?;
bytes
.try_into()
.map_err(|_| CryptError::InvalidKey("must decode to exactly 32 bytes"))
}
fn random_bytes<const N: usize>() -> [u8; N] {
let mut b = [0u8; N];
rand::rngs::SysRng
.try_fill_bytes(&mut b)
.expect("OS random number generator failed");
b
}
impl Crypt {
pub fn new(key: &str) -> Result<Self, CryptError> {
Self::with_previous(key, &[])
}
pub fn with_previous(key: &str, previous: &[&str]) -> Result<Self, CryptError> {
let mut keys = vec![parse_key(key)?];
for p in previous {
keys.push(parse_key(p)?);
}
Ok(Self { keys })
}
pub fn from_env() -> Result<Self, CryptError> {
let key = std::env::var("APP_KEY").map_err(|_| CryptError::MissingKey)?;
if key.trim().is_empty() {
return Err(CryptError::MissingKey);
}
let prev = std::env::var("APP_PREVIOUS_KEYS").unwrap_or_default();
let prev: Vec<&str> = prev
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect();
Self::with_previous(&key, &prev)
}
pub fn generate_key() -> String {
format!("base64:{}", STANDARD.encode(random_bytes::<32>()))
}
pub fn encrypt<T: Serialize>(&self, value: &T) -> Result<String, CryptError> {
let plain = serde_json::to_vec(value).map_err(|_| CryptError::Encrypt)?;
let nonce_bytes = random_bytes::<NONCE_LEN>();
let cipher = Aes256Gcm::new_from_slice(&self.keys[0]).map_err(|_| CryptError::Encrypt)?;
let ct = cipher
.encrypt(&Nonce::from(nonce_bytes), plain.as_slice())
.map_err(|_| CryptError::Encrypt)?;
let mut out = nonce_bytes.to_vec();
out.extend_from_slice(&ct);
Ok(URL_SAFE_NO_PAD.encode(out))
}
pub fn decrypt<T: DeserializeOwned>(&self, payload: &str) -> Result<T, CryptError> {
let raw = URL_SAFE_NO_PAD
.decode(payload)
.map_err(|_| CryptError::Decrypt)?;
if raw.len() < NONCE_LEN + 16 {
return Err(CryptError::Decrypt);
}
let (nonce, ct) = raw.split_at(NONCE_LEN);
for key in &self.keys {
let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| CryptError::Decrypt)?;
if let Ok(plain) = Nonce::try_from(nonce)
.map_err(|_| ())
.and_then(|n| cipher.decrypt(&n, ct).map_err(|_| ()))
{
return serde_json::from_slice(&plain).map_err(|_| CryptError::Decrypt);
}
}
Err(CryptError::Decrypt)
}
}
#[derive(Clone, Debug)]
pub struct UrlSigner {
keys: Vec<[u8; 32]>,
}
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
fn split(url: &str) -> (&str, Vec<&str>, &str) {
let (rest, frag) = url.find('#').map_or((url, ""), |i| url.split_at(i));
let (base, q) = rest.split_once('?').unwrap_or((rest, ""));
(base, q.split('&').filter(|s| !s.is_empty()).collect(), frag)
}
fn key_of(pair: &str) -> &str {
pair.split_once('=').map_or(pair, |(k, _)| k)
}
fn mac_for(key: &[u8; 32], base: &str, pairs: &[&str]) -> Hmac<Sha256> {
let mut sorted = pairs.to_vec();
sorted.sort_by(|a, b| key_of(a).cmp(key_of(b)));
let mut mac =
<Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key).expect("hmac accepts any key length");
mac.update(b"ryuk-url-v1\n");
mac.update(base.as_bytes());
mac.update(b"?");
mac.update(sorted.join("&").as_bytes());
mac
}
impl UrlSigner {
pub fn new(crypt: &Crypt) -> Self {
Self {
keys: crypt.keys.clone(),
}
}
pub fn from_env() -> Result<Self, CryptError> {
Ok(Self::new(&Crypt::from_env()?))
}
pub fn sign(&self, url: &str, expires_at: Option<SystemTime>) -> String {
let (base, pairs, frag) = split(url);
let mut pairs: Vec<String> = pairs
.into_iter()
.filter(|p| !matches!(key_of(p), "signature" | "expires"))
.map(String::from)
.collect();
if let Some(t) = expires_at {
let secs = t.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
pairs.push(format!("expires={secs}"));
}
let refs: Vec<&str> = pairs.iter().map(String::as_str).collect();
let sig = mac_for(&self.keys[0], base, &refs).finalize().into_bytes();
pairs.push(format!("signature={}", URL_SAFE_NO_PAD.encode(sig)));
format!("{base}?{}{frag}", pairs.join("&"))
}
pub fn verify(&self, url: &str) -> Result<(), SignatureError> {
self.verify_at(url, now_secs())
}
fn verify_at(&self, url: &str, now: u64) -> Result<(), SignatureError> {
let (base, pairs, _) = split(url);
let sigs: Vec<&str> = pairs
.iter()
.filter(|p| key_of(p) == "signature")
.copied()
.collect();
let [sig] = sigs.as_slice() else {
return Err(if sigs.is_empty() {
SignatureError::Missing
} else {
SignatureError::Invalid
});
};
let sig = sig.split_once('=').map_or("", |(_, v)| v);
let sig = URL_SAFE_NO_PAD
.decode(sig)
.map_err(|_| SignatureError::Invalid)?;
let rest: Vec<&str> = pairs
.into_iter()
.filter(|p| key_of(p) != "signature")
.collect();
if !self
.keys
.iter()
.any(|k| mac_for(k, base, &rest).verify_slice(&sig).is_ok())
{
return Err(SignatureError::Invalid);
}
let exp: Vec<&str> = rest
.iter()
.filter(|p| key_of(p) == "expires")
.copied()
.collect();
match exp.as_slice() {
[] => Ok(()),
[e] => {
let at: u64 = e
.split_once('=')
.and_then(|(_, v)| v.parse().ok())
.ok_or(SignatureError::Invalid)?;
if now > at {
Err(SignatureError::Expired)
} else {
Ok(())
}
}
_ => Err(SignatureError::Invalid),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
fn crypt() -> Crypt {
Crypt::new(&Crypt::generate_key()).unwrap()
}
#[test]
fn roundtrip_and_random_nonce() {
let c = crypt();
let a = c.encrypt(&"secret").unwrap();
let b = c.encrypt(&"secret").unwrap();
assert_ne!(a, b);
assert!(!a.contains('+') && !a.contains('/') && !a.contains('='));
assert_eq!(c.decrypt::<String>(&a).unwrap(), "secret");
}
#[test]
fn tamper_fails_closed() {
let c = crypt();
let p = c.encrypt(&"secret").unwrap();
let mut raw = URL_SAFE_NO_PAD.decode(&p).unwrap();
for i in [0, NONCE_LEN, raw.len() - 1] {
raw[i] ^= 1;
assert!(c.decrypt::<String>(&URL_SAFE_NO_PAD.encode(&raw)).is_err());
raw[i] ^= 1;
}
assert!(c.decrypt::<String>(&p[..p.len() - 4]).is_err());
assert!(c.decrypt::<String>("").is_err());
assert!(c.decrypt::<String>("!!!").is_err());
}
#[test]
fn wrong_key_and_wrong_type() {
let p = crypt().encrypt(&"x").unwrap();
assert!(crypt().decrypt::<String>(&p).is_err());
let c = crypt();
let p = c.encrypt(&"x").unwrap();
assert!(c.decrypt::<u32>(&p).is_err());
}
#[test]
fn rotation() {
let (old, new) = (Crypt::generate_key(), Crypt::generate_key());
let p = Crypt::new(&old).unwrap().encrypt(&7u32).unwrap();
assert!(Crypt::new(&new).unwrap().decrypt::<u32>(&p).is_err());
let rotated = Crypt::with_previous(&new, &[&old]).unwrap();
assert_eq!(rotated.decrypt::<u32>(&p).unwrap(), 7);
let q = rotated.encrypt(&8u32).unwrap();
assert!(Crypt::new(&old).unwrap().decrypt::<u32>(&q).is_err());
}
#[test]
fn key_validation() {
let k = Crypt::generate_key();
assert!(k.starts_with("base64:"));
assert!(matches!(
Crypt::new("short"),
Err(CryptError::InvalidKey(_))
));
assert!(Crypt::new("base64:AAAA").is_err());
assert!(Crypt::new("base64:!!!").is_err());
let msg = Crypt::new(&format!("{k}x")).unwrap_err().to_string();
assert!(!msg.contains(&k));
assert!(!format!("{:?}", Crypt::new(&k).unwrap()).contains(&k[7..]));
}
fn signer() -> UrlSigner {
UrlSigner::new(&crypt())
}
#[test]
fn sign_verify_and_param_order() {
let s = signer();
let u = s.sign("https://a.test/p/1?b=2&a=1#top", None);
assert!(u.ends_with("#top"));
assert_eq!(s.verify(&u), Ok(()));
let (base, q) = u.split_once('?').unwrap();
let q = q.split('#').next().unwrap();
let mut parts: Vec<&str> = q.split('&').collect();
parts.reverse();
assert_eq!(s.verify(&format!("{base}?{}", parts.join("&"))), Ok(()));
}
#[test]
fn repeated_parameters_keep_their_order() {
let s = signer();
let u = s.sign("https://a.test/p?x=1&x=2", None);
assert_eq!(s.verify(&u), Ok(()));
let swapped = u.replace("x=1&x=2", "x=2&x=1");
assert_eq!(s.verify(&swapped), Err(SignatureError::Invalid));
}
#[test]
fn tamper_path_query_signature() {
let s = signer();
let u = s.sign("https://a.test/p/1?a=1", None);
assert_eq!(
s.verify(&u.replace("/p/1", "/p/2")),
Err(SignatureError::Invalid)
);
assert_eq!(
s.verify(&u.replace("a=1", "a=2")),
Err(SignatureError::Invalid)
);
assert_eq!(s.verify(&format!("{u}&a=1")), Err(SignatureError::Invalid));
assert_eq!(
s.verify(&u.replace("a=1&", "")),
Err(SignatureError::Invalid)
);
assert_eq!(
s.verify(&u.replace("a.test", "b.test")),
Err(SignatureError::Invalid)
);
assert_eq!(
s.verify(&format!("{u}&signature={}", "AAAA")),
Err(SignatureError::Invalid)
);
let (head, _) = u.rsplit_once("signature=").unwrap();
assert_eq!(s.verify(head), Err(SignatureError::Missing));
assert_eq!(s.verify("https://a.test/p/1"), Err(SignatureError::Missing));
assert_eq!(
s.verify(&format!("{head}signature=")),
Err(SignatureError::Invalid)
);
assert_eq!(
s.verify(&format!("{head}signature=%%%")),
Err(SignatureError::Invalid)
);
assert_eq!(signer().verify(&u), Err(SignatureError::Invalid)); }
#[test]
fn expiry() {
let s = signer();
let t = SystemTime::now() + Duration::from_secs(60);
let u = s.sign("/dl?f=1", Some(t));
assert_eq!(s.verify(&u), Ok(()));
let at = t.duration_since(UNIX_EPOCH).unwrap().as_secs();
assert_eq!(s.verify_at(&u, at), Ok(()));
assert_eq!(s.verify_at(&u, at + 1), Err(SignatureError::Expired));
let longer = u.replace(&format!("expires={at}"), &format!("expires={}", at + 999));
assert_eq!(s.verify(&longer), Err(SignatureError::Invalid));
let dropped = u.replace(&format!("&expires={at}"), "");
assert_eq!(s.verify(&dropped), Err(SignatureError::Invalid));
}
#[test]
fn resign_replaces_and_rotation_verifies() {
let (old, new) = (Crypt::generate_key(), Crypt::generate_key());
let old_s = UrlSigner::new(&Crypt::new(&old).unwrap());
let u = old_s.sign("/x?a=1", None);
assert_eq!(old_s.sign(&u, None), u);
let new_s = UrlSigner::new(&Crypt::with_previous(&new, &[&old]).unwrap());
assert_eq!(new_s.verify(&u), Ok(()));
assert_eq!(new_s.verify(&new_s.sign(&u, None)), Ok(()));
}
}