laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::time::Duration;

use laravel::Application;
use laravel::config::Env;
use laravel::config::session::Driver;
use laravel::crypt::{Cipher, Encrypter};
use laravel::http::Request;
use laravel::http::middleware::ValidateSignature;
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use laravel::url::InvalidSignature;

async fn unsubscribe(request: Request) -> String {
    format!("Unsubscribed {}", request.route("user").unwrap_or_default())
}

async fn home() -> &'static str {
    "Home"
}

async fn check(request: Request) -> &'static str {
    if request.has_valid_signature() {
        "valid"
    } else {
        "invalid"
    }
}

fn app() -> Application {
    app_with_key(Some(Encrypter::generate_key(Cipher::Aes256Cbc)))
}

fn app_with_key(key: Option<String>) -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            config.app.key = key;
            config.session.driver = Driver::Memory;
        })
        .with_errors(|errors, _| {
            errors.render(|invalid: &InvalidSignature, _request, status| {
                (*invalid == InvalidSignature::Expired)
                    .then_some((status, "This link has expired: we've sent you a new one."))
            });
        })
        .with_routing(|routing, _| {
            routing.web(|route: &mut Router| {
                route
                    .get("/unsubscribe/{user}", unsubscribe)
                    .middleware(ValidateSignature::ignore(["utm_source"]));
                route.get("/check", check);
                route.get("/", home).middleware(ValidateSignature);
            });
        })
        .create()
}

fn path(url: &str) -> &str {
    url.strip_prefix("http://localhost").unwrap()
}

#[tokio::test]
async fn signed_urls_open_their_route() {
    let app = app();
    let url = app
        .scope(async || laravel::url::signed_route(unsubscribe, 1))
        .await
        .unwrap();

    assert!(url.starts_with("http://localhost/unsubscribe/1?signature="), "{url}");
    app.get(path(&url)).await.assert_ok().assert_see("Unsubscribed 1");
}

#[tokio::test]
async fn signed_urls_to_the_root_route_are_shaped_like_its_url() {
    let app = app();
    let (url, signed) = app
        .scope(async || (laravel::url::route(home, ()), laravel::url::signed_route(home, ())))
        .await;
    let signed = signed.unwrap();

    assert!(signed.starts_with(&format!("{}?signature=", url.unwrap())), "{signed}");
    app.get(format!("/{}", path(&signed))).await.assert_ok();
}

#[tokio::test]
async fn changed_urls_are_forbidden() {
    let app = app();
    let url = app
        .scope(async || laravel::url::signed_route(unsubscribe, 1))
        .await
        .unwrap();

    app.get(path(&url).replace("/1?", "/2?"))
        .await
        .assert_forbidden()
        .assert_see("Invalid signature.");
    app.get("/unsubscribe/1").await.assert_forbidden();
}

#[tokio::test]
async fn temporary_urls_expire() {
    let app = app();
    let (fresh, stale) = app
        .scope(async || {
            (
                laravel::url::temporary_signed_route(unsubscribe, Duration::from_secs(60), 1).unwrap(),
                laravel::url::temporary_signed_route(unsubscribe, laravel::now() - Duration::from_secs(60), 1).unwrap(),
            )
        })
        .await;

    assert!(fresh.contains("?expires="), "{fresh}");
    app.get(path(&fresh)).await.assert_ok();
    app.get(path(&stale))
        .await
        .assert_forbidden()
        .assert_see("we've sent you a new one");
}

#[tokio::test]
async fn temporary_urls_valid_for_the_longest_duration_do_not_overflow() {
    let app = app();
    let url = app
        .scope(async || laravel::url::temporary_signed_route(unsubscribe, Duration::MAX, 1))
        .await
        .unwrap();

    app.get(path(&url)).await.assert_ok();
}

#[tokio::test]
async fn temporary_urls_expire_after_a_span_or_at_a_date() {
    use laravel::time::ToSpan;

    let app = app();
    app.travel_to("2026-10-05T09:00:00Z".parse::<laravel::time::Timestamp>().unwrap());
    let (in_an_hour, at_midnight) = app
        .scope(async || {
            (
                laravel::url::temporary_signed_route(unsubscribe, 1.hour(), 1).unwrap(),
                laravel::url::temporary_signed_route(unsubscribe, laravel::now().end_of_day().unwrap(), 2).unwrap(),
            )
        })
        .await;

    app.travel(59.minutes());
    app.get(path(&in_an_hour)).await.assert_ok();
    app.travel(2.minutes());
    app.get(path(&in_an_hour)).await.assert_forbidden();

    app.get(path(&at_midnight)).await.assert_ok();
    app.travel(1.day());
    app.get(path(&at_midnight)).await.assert_forbidden();
}

#[tokio::test]
async fn ignored_parameters_may_be_added() {
    let app = app();
    let url = app
        .scope(async || laravel::url::signed_route(unsubscribe, 1))
        .await
        .unwrap();

    app.get(format!("{}&utm_source=newsletter", path(&url)))
        .await
        .assert_ok();
    app.get(format!("{}&utm_medium=email", path(&url)))
        .await
        .assert_forbidden();
}

#[tokio::test]
async fn named_parameters_are_signed_too() {
    let app = app();
    let url = app
        .scope(async || laravel::url::signed_route(unsubscribe, [("user", "1"), ("list", "news")]))
        .await
        .unwrap();

    app.get(path(&url)).await.assert_ok();
    app.get(path(&url).replace("list=news", "list=offers"))
        .await
        .assert_forbidden();
}

#[tokio::test]
async fn handlers_can_check_signatures_themselves() {
    let app = app();
    let url = app.scope(async || laravel::url::signed_route(check, ())).await.unwrap();

    app.get(path(&url)).await.assert_see("valid");
    app.get("/check").await.assert_see("invalid");
}

#[tokio::test]
async fn signatures_and_expiries_are_reserved_parameters() {
    let app = app();
    let error = app
        .scope(async || laravel::url::signed_route(unsubscribe, [("user", "1"), ("expires", "never")]))
        .await
        .unwrap_err();

    assert!(error.to_string().contains("`expires` is reserved"), "{error}");
}

#[tokio::test]
async fn temporary_signed_routes_keep_expires_in_the_query_even_when_a_route_parameter_is_named_expires() {
    use laravel::time::ToSpan;

    async fn optional_param() -> &'static str {
        "optional"
    }

    async fn required_param(laravel::routing::Params(value): laravel::routing::Params<String>) -> String {
        value
    }

    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
        })
        .with_routing(|routing, _| {
            routing.routes(|route| {
                route
                    .get("/links/{expires?}", optional_param)
                    .middleware(ValidateSignature);
                route
                    .get("/tokens/{expires}", required_param)
                    .middleware(ValidateSignature);
            });
        })
        .create();

    app.travel_to("2026-10-05T09:00:00Z".parse::<laravel::time::Timestamp>().unwrap());

    let (optional_url, required_url) = app
        .scope(async || {
            (
                laravel::url::temporary_signed_route(optional_param, 1.hour(), ()).unwrap(),
                laravel::url::temporary_signed_route(required_param, 1.hour(), "soon").unwrap(),
            )
        })
        .await;

    assert!(
        optional_url.starts_with("http://localhost/links?expires="),
        "{optional_url}"
    );
    assert!(
        required_url.starts_with("http://localhost/tokens/soon?expires="),
        "{required_url}"
    );
    app.get(path(&optional_url)).await.assert_ok().assert_see("optional");
    app.get(path(&required_url)).await.assert_ok().assert_see("soon");

    app.travel(2.hours());
    app.get(path(&optional_url)).await.assert_forbidden();
    app.get(path(&required_url)).await.assert_forbidden();
}

#[tokio::test]
async fn urls_cant_be_signed_without_a_key() {
    let error = app_with_key(None)
        .scope(async || laravel::url::signed_route(unsubscribe, 1))
        .await
        .unwrap_err();

    assert!(error.to_string().contains("without an `APP_KEY`"), "{error}");
}