laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use crate::session::SessionInternals as _;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, UNIX_EPOCH};

use axum::extract::FromRequestParts;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use http::request::Parts;
use serde::{Deserialize, Serialize};

use super::{Authenticatable, Provider, Registry};
use crate::cache::{CacheManager, Repository};
use crate::crypt::{Encrypter, hmac};
use crate::error::{Error, Result};
use crate::hash::{self, Password};
use crate::mail::{self, Address, Mailable, Message};
use crate::routing::HandlerId;
use crate::routing::url::route_to;
use crate::session::Session;
use crate::validation::InvalidInput;
use crate::view::{data, view};

/// How long a reset link works.
const LIFETIME: Duration = Duration::from_secs(60 * 60);

/// How long after a link is sent that another request for a link does nothing.
const RESEND_WINDOW: Duration = Duration::from_secs(60);

/// The number of random bytes in a token.
const TOKEN_BYTES: usize = 32;

/// The message a failed [`Passwords::reset`] gives the `email` field.
const INVALID: &str = "This password reset token is invalid.";

/// Password resets for users of type `U`. It sends reset links and resets passwords with the
/// tokens in those links.
///
/// Take `Passwords` as a handler argument on routes in the `web` group. It uses the
/// [`UserProvider`](super::UserProvider) of the session guard for `U`, which
/// [`with_auth`](crate::foundation::ApplicationBuilder::with_auth) registers:
///
/// ```no_run
/// # mod app {
/// # use laravel::auth::Authenticatable;
/// # use laravel::hash::PasswordHash;
/// # use laravel::mail::Address;
/// # #[derive(Clone)] pub struct User { pub email: String }
/// # impl Authenticatable for User {
/// #     type Id = u64;
/// #     fn auth_id(&self) -> u64 { 1 }
/// #     fn auth_password(&self) -> Option<&PasswordHash> { None }
/// #     fn remember_token(&self) -> Option<&str> { None }
/// # }
/// # impl From<&User> for Address { fn from(user: &User) -> Self { Address::new(&user.email) } }
/// # }
/// # use app::*;
/// use laravel::auth::Passwords;
/// use laravel::prelude::*;
///
/// #[laravel::input]
/// #[validate(anyone)]
/// struct ForgotPassword {
///     #[validate(required)]
///     email: String,
/// }
///
/// async fn send_reset_link(passwords: Passwords<User>, Valid(form): Valid<ForgotPassword>) -> laravel::Result<Redirect> {
///     passwords.send_reset_link(&form.email).await?;
///
///     Ok(Redirect::back().with("status", "If that email has an account, we've sent it a reset link."))
/// }
/// ```
///
/// The cache's default store keeps the tokens as keyed hashes. A link works once, for up to 60
/// minutes, and a new link replaces the old one. Every server must share the store, so the
/// `memory` store doesn't work behind a load balancer, and the `discard` store doesn't work at
/// all. Clearing the cache deletes every outstanding token.
///
/// The hashes are keyed with `APP_KEY`. Tokens created before you rotate the key keep working
/// while the old key is in `APP_PREVIOUS_KEYS`. The reset page's path holds the token, so the
/// request log records a token that works until it's used or expires.
pub struct Passwords<U: Authenticatable> {
    provider: Arc<dyn Provider<U>>,
    cache: Repository,
    encrypter: Encrypter,
    session: Option<Session>,
    /// The handler marked `#[laravel::auth::page(reset_password)]`, which reset links open.
    reset_page: Option<HandlerId>,
}

/// A token's cache entry, which expires after [`LIFETIME`].
#[derive(Serialize, Deserialize)]
struct Entry {
    /// The token's HMAC, keyed with the application key, in hex.
    hash: String,
    /// When the token was made, in milliseconds since the Unix epoch, for the resend window.
    created: u128,
}

impl<U: Authenticatable> fmt::Debug for Passwords<U> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Passwords").finish_non_exhaustive()
    }
}

impl<U: Authenticatable, S: Send + Sync> FromRequestParts<S> for Passwords<U> {
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self> {
        let services = super::services(&parts.extensions)?.clone();
        let registry = services.resolve::<Registry>().await?;
        let definition = registry.definition::<U>()?;
        let provider = (definition.provider)(services.clone()).await?;
        let cache = services.resolve::<CacheManager>().await?.default_store()?;
        let encrypter = crate::crypt::of_request(&parts.extensions)?.clone();

        Ok(Self {
            provider,
            cache,
            encrypter,
            session: parts.extensions.get::<Session>().cloned(),
            reset_page: registry.pages.reset_password.map(|page| page.handler),
        })
    }
}

impl<U: Authenticatable> Passwords<U> {
    /// Emails a reset link to the user who logs in as `email`, if that user exists.
    ///
    /// The link opens the handler marked
    /// [`#[laravel::auth::page(reset_password)]`](macro@super::page), with the token as the
    /// route's `{token}` parameter and `email` in the query string. `send_reset_link` queues a
    /// [`ResetPasswordEmail`] to `mail::to(&user)`, so `&U` must convert into an [`Address`]. The
    /// queue keeps the email encrypted, and the response doesn't wait for the mail provider.
    ///
    /// It does nothing when the provider's [`find_for_login`](super::UserProvider::find_for_login)
    /// doesn't find the user, or when the user was sent a link in the last 60 seconds. It returns
    /// the same result in every case, so the response doesn't reveal who has an account. A new
    /// link replaces the user's previous link, so only the newest link works.
    ///
    /// To build the link or the email yourself, use
    /// [`send_reset_link_with`](Self::send_reset_link_with).
    ///
    /// # Errors
    ///
    /// Fails when no handler is marked `#[laravel::auth::page(reset_password)]`, when the provider
    /// or the cache fails, or when rendering or queueing the email fails. If the email fails, this
    /// method deletes the token, so the user can ask for a new link right away.
    pub async fn send_reset_link(&self, email: &str) -> Result<()>
    where
        for<'a> &'a U: Into<Address>,
    {
        let page = self.reset_page.ok_or_else(|| {
            crate::error::fail(
                "reset links need a page to open: mark the reset page's handler \
                 `#[laravel::auth::page(reset_password)]`",
            )
        })?;

        self.send_reset_link_with(email, async |user, token| {
            let url = route_to(page, [("token", token.as_str()), ("email", email)])?;

            mail::to(&user).queue(ResetPasswordEmail { url, token }).await
        })
        .await
    }

    /// Creates a reset token for the user who logs in as `email`, and passes the user and the
    /// token to `send`, which emails the user a link containing the token and `email`. Use it
    /// instead of [`send_reset_link`](Self::send_reset_link) to build the link yourself or to send
    /// an email of your own.
    ///
    /// The token works only with this `email`, so put `email` in the link exactly as it was given
    /// here. A link stops working when the user's email changes. `send` isn't called in the cases
    /// where [`send_reset_link`](Self::send_reset_link) sends nothing.
    ///
    /// The token is the secret that resets the password. Queue the email with
    /// `mail::to(&user).queue(..)`, which keeps the email encrypted in the queue, so the response
    /// doesn't wait for the mail provider. Don't put the token in a job of your own, because the
    /// queue stores other jobs' payloads unencrypted.
    ///
    /// # Errors
    ///
    /// Fails when the provider or the cache fails, or with `send`'s error. If `send` fails, this
    /// method deletes the token, so the user can ask for a new link right away.
    pub async fn send_reset_link_with<F, Fut>(&self, email: &str, send: F) -> Result<()>
    where
        F: FnOnce(U, String) -> Fut + Send,
        Fut: Future<Output = Result<()>> + Send,
    {
        let Some(user) = self.provider.find_for_login(email).await? else {
            return Ok(());
        };
        let key = self.key(&user)?;
        let now = now();

        if let Some(entry) = self.cache.get::<Entry>(&key).await?
            && now.saturating_sub(entry.created) < RESEND_WINDOW.as_millis()
        {
            return Ok(());
        }

        let token = token()?;
        let entry = Entry {
            hash: hmac::sign(self.encrypter.key(), [signed_value(&token, email)]),
            created: now,
        };
        self.cache.put(&key, entry, LIFETIME).await?;

        if let Err(error) = send(user, token).await {
            if let Err(forget) = self.cache.forget(&key).await {
                crate::foundation::telemetry::logging(
                    &forget,
                    || tracing::warn!(error = %forget, "deleting the unsent password reset token failed"),
                );
            }
            return Err(error);
        }

        Ok(())
    }

    /// Returns the user who logs in as `email`, if `token` is their current reset token and was
    /// sent for `email`. Returns `None` when the provider doesn't find the user, or when the token
    /// is wrong, used, replaced, older than 60 minutes, or was sent for another email.
    ///
    /// `validate` doesn't use up the token. Use it when you want to decide what a failed reset
    /// does yourself, such as showing an expired-link page before the user types a new password.
    ///
    /// # Errors
    ///
    /// Fails when the provider or the cache fails.
    pub async fn validate(&self, email: &str, token: &str) -> Result<Option<U>> {
        let Some(user) = self.provider.find_for_login(email).await? else {
            return Ok(None);
        };
        let Some(entry) = self.cache.get::<Entry>(&self.key(&user)?).await? else {
            return Ok(None);
        };

        Ok(super::signed(&self.encrypter, &signed_value(token, email), &entry.hash).then_some(user))
    }

    /// Resets the password of the user who logs in as `email`, if `token` is their current reset
    /// token as [`validate`](Self::validate) checks it, and returns the user.
    ///
    /// `reset` hashes the password and deletes the token, so the link works once. It then stores
    /// the hash with the provider's [`update_password`](super::UserProvider::update_password). The
    /// new hash logs the user out of every session and remember cookie. The `database` and
    /// `memory` session drivers also delete the user's stored sessions.
    ///
    /// `reset` doesn't log the user in. To log them in, pass the returned user to
    /// [`Auth::login`](super::Auth::login).
    ///
    /// # Errors
    ///
    /// When the token is invalid, fails with a validation error that puts "This password reset
    /// token is invalid." on the `email` field. The token stays in place, so a wrong guess doesn't
    /// cancel the user's link. A browser is redirected back to the form with the error and its
    /// input, and a JSON client gets a `422`.
    ///
    /// Also fails when the password can't be hashed, such as a password over
    /// [`MAX_PASSWORD_BYTES`](crate::hash::MAX_PASSWORD_BYTES), or when the provider or the cache
    /// fails. The token is deleted before the provider stores the hash, so if storing fails, the
    /// user needs a new link.
    pub async fn reset(&self, email: &str, token: &str, password: &Password) -> Result<U> {
        let Some(user) = self.validate(email, token).await? else {
            return Err(invalid());
        };
        let hash = hash::make(password).await?;

        // Of the requests that checked the token, only the one that deletes it goes on...
        if !self.cache.forget(&self.key(&user)?).await? {
            return Err(invalid());
        }

        self.provider.update_password(&user, &hash).await?;
        let user = self.provider.find(&user.auth_id()).await?.ok_or_else(invalid)?;

        if let Some(session) = &self.session {
            session.destroy_other_sessions(serde_json::to_value(user.auth_id())?);
        }

        Ok(user)
    }

    /// The cache key of the user's reset token.
    fn key(&self, user: &U) -> Result<String> {
        Ok(format!("password_reset:web:{}", super::id_string(&user.auth_id())?))
    }
}

/// The email that [`Passwords::send_reset_link`] queues. It shows a button that opens `url`, and
/// says how long the link works.
///
/// Its view is `laravel::auth.reset-password`. To change it, copy the framework's
/// `resources/views/auth/reset-password.html` to
/// `resources/views/vendor/laravel/auth/reset-password.html` and edit the copy. To send it with a
/// link of your own, use it in [`Passwords::send_reset_link_with`].
#[derive(Debug, Clone)]
pub struct ResetPasswordEmail {
    /// The link to the reset page, with the token and the email in it.
    pub url: String,
    /// The single-use reset token embedded in [`url`](Self::url).
    pub token: String,
}

impl Mailable for ResetPasswordEmail {
    fn build(&self) -> Result<Message> {
        let minutes = LIFETIME.as_secs() / 60;

        Ok(Message::new()
            .subject("Reset your password")
            .view(view("laravel::auth.reset-password", data! { url => self.url, minutes })))
    }
}

/// The value that a token's HMAC covers: the token and the email it was sent for, so that a link
/// stops working once the user's email changes. Tokens are URL-safe Base64, so the newline
/// separator can't appear in a token.
fn signed_value(token: &str, email: &str) -> Vec<u8> {
    format!("{token}\n{email}").into_bytes()
}

/// A new reset token: random bytes, as URL-safe Base64.
fn token() -> Result<String> {
    let mut bytes = [0; TOKEN_BYTES];
    getrandom::fill(&mut bytes)?;

    Ok(URL_SAFE_NO_PAD.encode(bytes))
}

fn now() -> u128 {
    crate::clock::system_now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
}

fn invalid() -> Error {
    InvalidInput::new().with("email", INVALID).into()
}