ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Authenticated encryption and signed URLs, shaped like Laravel's `Crypt`
//! and `URL::signedRoute`. Both are keyed from `APP_KEY` (`base64:` + 32 bytes,
//! the same format as Laravel; make one with [`Crypt::generate_key`]).
//!
//! ```
//! use ryuk::crypt::{Crypt, UrlSigner};
//! use std::time::{Duration, SystemTime};
//!
//! let crypt = Crypt::new(&Crypt::generate_key()).unwrap();
//! let token = crypt.encrypt(&("user", 42)).unwrap();
//! assert_eq!(crypt.decrypt::<(String, i32)>(&token).unwrap(), ("user".into(), 42));
//!
//! let signer = UrlSigner::new(&crypt);
//! let exp = SystemTime::now() + Duration::from_secs(3600);
//! let url = signer.sign("https://app.test/unsubscribe?user=7", Some(exp));
//! assert!(signer.verify(&url).is_ok());
//! assert!(signer.verify(&url.replace("user=7", "user=8")).is_err());
//! ```
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;

/// Key or crypto failure. Messages never contain key material.
#[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),
    /// Bad base64, truncated, tampered, wrong key or wrong type: deliberately indistinguishable.
    #[error("the payload could not be decrypted")]
    Decrypt,
    #[error("the value could not be encrypted")]
    Encrypt,
}

/// Why a signed URL was refused.
#[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,
}

/// AES-256-GCM encrypter. The first key encrypts; every key is tried on decrypt,
/// so rotating `APP_KEY` keeps old payloads readable via `APP_PREVIOUS_KEYS`.
#[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];
    // An unavailable OS RNG is unrecoverable; never fall back to something weaker.
    rand::rngs::SysRng
        .try_fill_bytes(&mut b)
        .expect("OS random number generator failed");
    b
}

impl Crypt {
    /// `key` is `base64:<32 bytes>`.
    pub fn new(key: &str) -> Result<Self, CryptError> {
        Self::with_previous(key, &[])
    }

    /// As [`Crypt::new`], plus older keys accepted for decryption only.
    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 })
    }

    /// Reads `APP_KEY` and the comma-separated `APP_PREVIOUS_KEYS` (optional).
    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)
    }

    /// A fresh random key in `APP_KEY` format.
    pub fn generate_key() -> String {
        format!("base64:{}", STANDARD.encode(random_bytes::<32>()))
    }

    /// Serialize to JSON, encrypt with a random nonce, return url-safe base64
    /// (`nonce || ciphertext || tag`).
    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))
    }

    /// Reverse of [`Crypt::encrypt`]. Any tampering, truncation or key mismatch is
    /// a [`CryptError::Decrypt`].
    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)
    }
}

/// Signs and verifies URLs with HMAC-SHA256 keyed from `APP_KEY`.
///
/// The signature covers path + query (sorted by name, so the order of different parameters does not matter;
/// the order of a repeated parameter does)
/// including `expires`; the fragment is not signed. Comparison is on the raw
/// (not percent-decoded) text, so re-encoding a signed URL invalidates it.
#[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())
}

/// Split into (base without query/fragment, query pairs excluding `signature`, fragment incl. `#`).
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> {
    // Stable, by name only: parameters may be reordered, but the order of repeated names is signed, because
    // an app that reads the first `x` must not see a different one after `?x=1&x=2` becomes `?x=2&x=1`.
    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 {
    /// Uses the crypt's keys (current to sign; current and previous to verify).
    pub fn new(crypt: &Crypt) -> Self {
        Self {
            keys: crypt.keys.clone(),
        }
    }

    /// `Crypt::from_env()` then [`UrlSigner::new`].
    pub fn from_env() -> Result<Self, CryptError> {
        Ok(Self::new(&Crypt::from_env()?))
    }

    /// Append `expires` (unix seconds, if given) and `signature` to `url`.
    /// Any `expires`/`signature` already on it is replaced.
    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("&"))
    }

    /// Check signature (constant time), then expiry. Fails closed on anything odd,
    /// including duplicated `signature`/`expires` parameters.
    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();
        // verify_slice compares in constant time.
        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);
        // new payloads use the new key only
        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(()));
        // reorder params: still valid
        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)); // other key
    }

    #[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));
        // extending expires, or dropping it, breaks the signature
        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(()));
    }
}