Skip to main content

tablo_jobs/
mail.rs

1//! Auth mail made durable: [`AuthMailQueue`] queues each letter a panel's auth sends, sealed,
2//! inside the transaction that records the letter's token, and a worker sends it.
3
4use aes_gcm::{
5    Aes256Gcm, KeyInit, Nonce,
6    aead::{Aead, Payload},
7};
8use data_encoding::BASE64URL_NOPAD;
9use hkdf::Hkdf;
10use jiff::Timestamp;
11use serde::{Deserialize, Serialize};
12use sha2::Sha256;
13use tablo_core::{AuthLetter, AuthMailDelivery};
14use topcoat::{
15    context::{Cx, context},
16    cookie::Key,
17};
18
19use crate::{Job, enqueue};
20
21/// What the derivation binds the seal's key to: no other use of the cookie key derives this one.
22const PURPOSE: &[u8] = b"tablo-jobs auth mail v1";
23
24/// The bytes of a GCM nonce, at the head of a sealed letter.
25const NONCE_BYTES: usize = 12;
26
27/// Queues the letters a panel's auth sends, for a [`Worker`](crate::Worker) with
28/// [`auth_mail`](crate::Worker::auth_mail) to send.
29///
30/// ```rust,no_run
31/// # use tablo_core::{Auth, AuthMail, PanelHandle};
32/// # use tablo_jobs::{AuthMailQueue, Worker};
33/// # use topcoat::{cookie::Key, mail::Mailbox};
34/// # fn build(key: &Key, panel: &PanelHandle, from: Mailbox) -> topcoat::Result<()> {
35/// let queue = AuthMailQueue::new(key);
36/// let mail = AuthMail::new(from, "https://app.example.com").delivery(queue.clone());
37/// let worker = Worker::new(panel)?.auth_mail(&queue);
38/// # let _ = (mail, worker);
39/// # Ok(())
40/// # }
41/// ```
42///
43/// - A letter commits with its token or not at all, and the worker retries it like any job: an
44///   outage of the mail server delays it instead of losing it.
45/// - A letter carries a live link or code, so the queue stores it sealed: AES-256-GCM under a key
46///   derived from the router's cookie [`Key`]. A reader of the database or its backups without that
47///   key reads no link.
48/// - The web process and the worker build the queue from the same key. A key rotated while mail
49///   waits leaves that mail unopenable: it dies after its attempts, and the person asks again.
50/// - A letter past its [`expires_at`](AuthLetter::expires_at) is dropped, not sent: a link that
51///   arrives dead reads as broken. Six attempts span about a quarter of an hour of backoff.
52#[derive(Clone)]
53pub struct AuthMailQueue {
54    cipher: Aes256Gcm,
55}
56
57impl AuthMailQueue {
58    /// A queue sealing letters under a key derived from `key`, the router's cookie key.
59    #[must_use]
60    pub fn new(key: &Key) -> Self {
61        let mut derived = [0; 32];
62        Hkdf::<Sha256>::new(None, key.master())
63            .expand(PURPOSE, &mut derived)
64            .expect("32 bytes is a valid HKDF-SHA256 output length");
65        Self {
66            cipher: Aes256Gcm::new(&derived.into()),
67        }
68    }
69
70    fn seal(&self, plain: &[u8]) -> topcoat::Result<String> {
71        let mut nonce = [0; NONCE_BYTES];
72        getrandom::fill(&mut nonce)
73            .map_err(|error| topcoat::Error::msg(format!("no randomness for a nonce: {error}")))?;
74        let sealed = self
75            .cipher
76            .encrypt(
77                &Nonce::from(nonce),
78                Payload {
79                    msg: plain,
80                    aad: SendAuthMail::KIND.as_bytes(),
81                },
82            )
83            .map_err(|_| topcoat::Error::msg("sealing an auth letter failed"))?;
84        let mut stored = nonce.to_vec();
85        stored.extend(sealed);
86        Ok(BASE64URL_NOPAD.encode(&stored))
87    }
88
89    fn open(&self, stored: &str) -> topcoat::Result<Vec<u8>> {
90        let refused = || {
91            topcoat::Error::msg("a queued auth letter does not open: was the cookie key changed?")
92        };
93        let stored = BASE64URL_NOPAD
94            .decode(stored.as_bytes())
95            .map_err(|_| refused())?;
96        if stored.len() < NONCE_BYTES {
97            return Err(refused());
98        }
99        let (nonce, sealed) = stored.split_at(NONCE_BYTES);
100        self.cipher
101            .decrypt(
102                &Nonce::try_from(nonce).map_err(|_| refused())?,
103                Payload {
104                    msg: sealed,
105                    aad: SendAuthMail::KIND.as_bytes(),
106                },
107            )
108            .map_err(|_| refused())
109    }
110}
111
112impl AuthMailDelivery for AuthMailQueue {
113    async fn deliver(
114        &self,
115        _cx: &Cx,
116        ex: &mut dyn toasty::Executor,
117        letter: AuthLetter,
118    ) -> topcoat::Result<()> {
119        let sealed = self.seal(&serde_json::to_vec(&letter)?)?;
120        enqueue(&SendAuthMail { sealed }).exec(ex).await
121    }
122}
123
124/// Sends a letter an [`AuthMailQueue`] queued.
125#[derive(Serialize, Deserialize)]
126pub(crate) struct SendAuthMail {
127    /// An [`AuthLetter`] as JSON, sealed.
128    sealed: String,
129}
130
131impl Job for SendAuthMail {
132    const KIND: &'static str = "tablo-auth-mail";
133    const MAX_ATTEMPTS: u32 = 6;
134
135    async fn run(self, cx: &Cx) -> topcoat::Result<()> {
136        let queue: &AuthMailQueue = context(cx);
137        let letter: AuthLetter = serde_json::from_slice(&queue.open(&self.sealed)?)?;
138        if letter.expires_at().is_some_and(|at| at <= Timestamp::now()) {
139            tracing::warn!(kind = ?letter.kind(), "an auth letter expired in the queue: dropped");
140            return Ok(());
141        }
142        topcoat::mail::send(cx, letter.mail()?).await?;
143        Ok(())
144    }
145}
146
147#[cfg(test)]
148mod tests;