Skip to main content

tablo_core/auth/
mail.rs

1//! The mail auth sends: the [`AuthMail`] configuration every mailed link shares, the links it
2//! builds, where its letters go, and the headers a page carrying a token answers with.
3
4mod delivery;
5
6use std::{future::Future, sync::Arc, time::Duration};
7
8use jiff::Timestamp;
9use topcoat::{
10    context::Cx,
11    mail::Mailbox,
12    router::{request::uri, response::Response},
13};
14
15use self::delivery::DynDelivery;
16pub(super) use self::delivery::send;
17pub use self::delivery::{AuthLetter, AuthLetterKind, AuthMailDelivery};
18use crate::auth::realm::{Realm, current_realm};
19
20/// Where a panel's auth mail comes from and where its links point, installed with
21/// [`Auth::mail`](super::Auth::mail): the sender, and the absolute URL every link starts with.
22///
23/// ```rust
24/// use tablo_core::{Auth, AuthMail, PasswordAuth, PasswordReset};
25/// use topcoat::mail::Mailbox;
26///
27/// # fn main() -> Result<(), topcoat::mail::AddressError> {
28/// let auth = Auth::password()
29///     .mail(AuthMail::new(
30///         Mailbox::named("Example", "no-reply@example.com")?,
31///         "https://admin.example.com",
32///     ))
33///     .password_reset(PasswordReset::new(PasswordAuth::new()));
34/// # let _ = auth;
35/// # Ok(())
36/// # }
37/// ```
38///
39/// The base URL is configuration, not the request's `Host` header, which the client chooses: a
40/// link built from it could point a victim's email at another host. Mounting refuses a base URL
41/// that is not an absolute `http` or `https` URL, or that carries a query or fragment.
42///
43/// The mail goes out through the router's [`Mailer`](topcoat::mail::Mailer), which the app adds
44/// with `.with(Mailer::new(..))` before mounting the panel and without which mounting refuses the
45/// panel, or through the [`delivery`](Self::delivery) the app installs.
46pub struct AuthMail {
47    from: Mailbox,
48    base_url: String,
49    delivery: Option<Arc<dyn DynDelivery>>,
50}
51
52impl AuthMail {
53    /// Mails from `from`, with links that start with `base_url`, such as
54    /// `https://admin.example.com`: the scheme and host the app answers on, before the panel's
55    /// prefix.
56    #[must_use]
57    pub fn new(from: Mailbox, base_url: impl Into<String>) -> Self {
58        Self {
59            from,
60            base_url: base_url.into().trim_end_matches('/').to_string(),
61            delivery: None,
62        }
63    }
64
65    /// Hands each letter to `delivery` inside the transaction that records its token, in place of
66    /// sending it through the router's `Mailer` once that commits: see [`AuthMailDelivery`].
67    /// Mounting then needs no `Mailer`.
68    #[must_use]
69    pub fn delivery(mut self, delivery: impl AuthMailDelivery) -> Self {
70        self.delivery = Some(Arc::new(delivery));
71        self
72    }
73
74    /// Whether the letters go through the router's `Mailer`.
75    fn sends_through_mailer(&self) -> bool {
76        self.delivery.is_none()
77    }
78
79    /// Whether the base URL is an absolute `http` or `https` URL without a query or fragment.
80    pub(crate) fn base_url_is_absolute(&self) -> bool {
81        self.base_url.parse::<http::Uri>().is_ok_and(|uri| {
82            matches!(uri.scheme_str(), Some("http" | "https"))
83                && uri.authority().is_some()
84                && uri.query().is_none()
85        }) && !self.base_url.contains('#')
86    }
87
88    pub(crate) fn base_url(&self) -> &str {
89        &self.base_url
90    }
91
92    /// The absolute link to `path` on this app, with `token` in its query.
93    pub(super) fn link(&self, path: &str, token: &topcoat::session::Token) -> String {
94        let query = form_urlencoded::Serializer::new(String::new())
95            .append_pair(TOKEN_FIELD, &token.encode())
96            .finish();
97        format!("{}{path}?{query}", self.base_url)
98    }
99
100    /// A letter of `kind` from this sender to `address`, titled `subject`, reading `text`, whose
101    /// link or code works for `lifetime` from now.
102    pub(super) fn letter(
103        &self,
104        kind: AuthLetterKind,
105        address: &str,
106        subject: String,
107        text: String,
108        lifetime: Option<Duration>,
109    ) -> topcoat::Result<AuthLetter> {
110        let expires_at = lifetime
111            .map(|lifetime| {
112                Timestamp::try_from(std::time::SystemTime::now() + lifetime)
113                    .map_err(topcoat::Error::from)
114            })
115            .transpose()?;
116        AuthLetter::new(kind, &self.from, address, subject, text, expires_at)
117    }
118
119    /// Hands `letter` to the installed delivery through `ex`, the transaction recording its token,
120    /// and answers `None`; without one, answers the letter, to [`send`] once `ex` commits.
121    pub(super) async fn hand(
122        &self,
123        cx: &Cx,
124        ex: &mut dyn toasty::Executor,
125        letter: AuthLetter,
126    ) -> topcoat::Result<Option<AuthLetter>> {
127        match &self.delivery {
128            Some(delivery) => {
129                delivery.deliver(cx, ex, letter).await?;
130                Ok(None)
131            }
132            None => Ok(Some(letter)),
133        }
134    }
135}
136
137impl std::fmt::Debug for AuthMail {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        f.debug_struct("AuthMail")
140            .field("from", &self.from.address())
141            .field("base_url", &self.base_url)
142            .field("delivery", &self.delivery.is_some())
143            .finish()
144    }
145}
146
147/// The key a mailed link carries its token under, in its query and in the form it opens.
148pub(super) const TOKEN_FIELD: &str = "token";
149
150/// The token the request's query carries, or empty.
151pub(super) fn token_from_query(cx: &Cx) -> String {
152    uri(cx)
153        .query()
154        .and_then(|query| {
155            form_urlencoded::parse(query.as_bytes())
156                .find(|(key, _)| key == TOKEN_FIELD)
157                .map(|(_, value)| value.into_owned())
158        })
159        .unwrap_or_default()
160}
161
162/// Runs `send` after the response, with the request's panel and its [`AuthMail`], logging a
163/// failure as `what`: waiting on the database or the mail server, or answering differently,
164/// would tell the visitor whether an account exists. [`settled`](crate::settled) waits for it.
165pub(super) fn after_response<F, Fut>(cx: &Cx, what: &'static str, send: F)
166where
167    F: FnOnce(Cx, Arc<Realm>) -> Fut + Send + 'static,
168    Fut: Future<Output = topcoat::Result<()>> + Send + 'static,
169{
170    let Some(panel) = current_realm(cx).map(Arc::clone) else {
171        return;
172    };
173    let request = cx.clone();
174    crate::settle::AfterResponse::spawn(cx, async move {
175        let prefix = panel.prefix.clone();
176        if let Err(error) = send(request, panel).await {
177            tracing::error!(error = %error, panel = %prefix, "{what} not sent");
178        }
179    });
180}
181
182/// `response` with `Referrer-Policy: no-referrer`: a page whose URL or form carries a token
183/// sends no referrer at all, not even to the panel's own origin.
184pub(super) fn private(mut response: Response) -> topcoat::Result<Response> {
185    response.headers_mut().insert(
186        http::header::REFERRER_POLICY,
187        http::HeaderValue::from_static("no-referrer"),
188    );
189    Ok(response)
190}
191
192/// The mistakes in what a panel's auth mails: a feature that mails links without
193/// [`Auth::mail`](super::Auth::mail), a base URL that is not absolute, and a router that cannot
194/// send mail. `has_mail` says whether the router can.
195pub(super) fn declaration_errors(
196    auth: &super::AuthConfig,
197    has_mail: bool,
198) -> Vec<crate::DeclarationErrorKind> {
199    use crate::{AuthMailFault, DeclarationErrorKind};
200
201    let mailing = auth.mailing();
202    if auth.is_disabled() || mailing.is_empty() {
203        return Vec::new();
204    }
205    let Some(mail) = auth.mail.as_ref() else {
206        return mailing
207            .into_iter()
208            .map(|feature| DeclarationErrorKind::AuthMail(AuthMailFault::Unset { feature }))
209            .collect();
210    };
211    let mut faults = Vec::new();
212    if !mail.base_url_is_absolute() {
213        faults.push(AuthMailFault::BaseUrl(mail.base_url().to_string()));
214    }
215    if !has_mail && mail.sends_through_mailer() {
216        faults.push(AuthMailFault::MissingMail);
217    }
218    faults
219        .into_iter()
220        .map(DeclarationErrorKind::AuthMail)
221        .collect()
222}