Laravel Rust Security Guide: What the Framework Protects and What It Leaves to You
Laravel Rust went to beta on 1 December 2026. The compiler now enforces several things Laravel PHP left to discipline, but CORS, security headers, rate limiting and session encryption still ship with defaults you need to change. This guide walks through each one from the official 0.x docs.
Laravel released the first beta of Laravel Rust on 1 December 2026. It is a new framework built on Axum, Tokio and SQLx that keeps Laravel's conventions, not a port of the PHP code. That matters for security, because almost nothing you know about hardening a Laravel PHP app can be assumed to carry over. Some things are stricter. Some defaults are looser than you would expect.
This guide is written from the official 0.x documentation as it stood on 6 December 2026 (crate version 0.2.0). The framework is in beta and Laravel warns that "releases before 1.0 may include breaking changes to APIs and configuration", so check the docs for anything you rely on.
The short version
| Area | Out of the box | What you still do |
|---|---|---|
| SQL injection | Values are bound parameters | Keep user input out of AssertSqlSafe and native SQLx strings |
| XSS | {{ }} output is HTML-escaped |
Audit every safe filter; add a CSP |
| CSRF | On for the web group |
Keep exclusions narrow and verify webhooks by signature |
| Authorisation | Validation types must declare who may submit | Write the policies; scope every query |
| CORS | Any origin on api/* |
Restrict origins |
| Security headers | Two headers only | Add HSTS, CSP, Referrer-Policy, Permissions-Policy |
| Rate limiting | None by default | Throttle login, reset and API routes |
| Sessions | lax cookies, HttpOnly, 120 minutes |
Use a server-side driver; consider SESSION_ENCRYPT=true |
| Dependencies | Nothing built in | Run cargo audit and npm audit in CI |
What the compiler now enforces
Three protections that depend on discipline in Laravel PHP are compile errors in Laravel Rust.
Validation must say who may submit. Every input type declares its audience. The validation docs state that "a handler that validates a type without anyone, authenticated, or an authorize function doesn't compile". You cannot forget the authorisation decision on a form, though you can still make the wrong one. #[validate(anyone)] on an endpoint that changes another user's data compiles fine.
Password hashes cannot leak into JSON by accident. PasswordHash does not implement Serialize. A struct you serialise must mark the field #[serde(skip)] or it will not build. The Password input type prints [redacted] when debug-formatted, which keeps it out of logs.
Mass assignment is structural. An input struct fills only the columns it declares, so, in the docs' words, "extra fields sent by a client are ignored automatically". There is no $guarded = [] to get wrong. The risk moves to what you put in the input struct: add is_admin to it and a client can set it.
None of this covers business logic. IDOR, broken tenant scoping and missing policy checks are exactly as possible in Rust as in PHP.
Environment and secrets
Configuration will feel familiar, with a few differences worth knowing.
APP_ENVdefaults to production. "WhenAPP_ENVisn't set, your application runs asproduction." A missing variable fails safe.APP_DEBUGmust be off. With it on, browsers get "a detailed debug page showing the error, where it happened, its chain of causes, and the incoming request", and JSON errors include the type, file and line. With it off, messages become "Server Error". The same rule as Laravel PHP applies: never true in production.APP_KEYis still the crown jewel. It encrypts cookies and sessions, and the docs are plain that whoever holds it "can read your encrypted values, forge your cookies, and create signed URLs". Use a different key per environment. Rotate withAPP_PREVIOUS_KEYS. The default cipher is AES-256-CBC with a MAC;APP_CIPHERaccepts the GCM modes.- Required variables can fail the boot. The app refuses to start on invalid or missing required configuration, and you can mark your own with
env.require("STRIPE_KEY"). Use it for every secret, so a missing key is a failed deploy and not a runtime surprise. .envstill exists. It is read from the app root and must not be committed. Process environment variables take precedence over it.
The minimum production set from the docs is APP_ENV=production, APP_DEBUG=false, APP_KEY, an https:// APP_URL and DATABASE_URL.
SQL: safe by default, two escape hatches
The query builder and db::query! bind every value:
db::query!("SELECT * FROM users WHERE role IN ({...roles})")
The docs say the macro "never concatenates values into your SQL string" and turns each capture into a bound parameter at compile time. That closes the common injection path.
Two hatches remain open, and they are what to search for in review:
use laravel::db::sqlx::AssertSqlSafe;
db::raw!(AssertSqlSafe(format!("{function}(created_at)")))
AssertSqlSafe embeds the string "verbatim without parameter bindings". The name is an assertion by you, not a check by the framework. The second hatch is native SQLx through laravel::db::sqlx, which also skips Laravel's query listeners. Grep for both:
grep -rn "AssertSqlSafe\|db::sqlx" src/
Every hit should be buildable only from constants or an allowlist, never from request input. The reasoning is the same as for raw queries in Eloquent.
XSS and Content Security Policy
Templates use MiniJinja, and "every value output with {{ ... }} is HTML-escaped automatically". The unescaped paths are the safe filter and with_html:
{{ post.body_html|safe }}
Treat |safe like {!! !!} in Blade: acceptable only for HTML you sanitised on the way in. For data inside a script, use the js filter. The docs carry a specific warning: "Never use tojson inside a double-quoted HTML attribute. Because tojson doesn't escape double quotes, user data could break out of the attribute."
No Content-Security-Policy is sent by default. The docs show a nonce middleware you write yourself:
#[middleware]
pub async fn csp_headers(request: Request, next: Next) -> Response {
let nonce = laravel::str::random(32);
view::use_csp_nonce(&nonce);
let response = next.run(request).await;
response.with_header(
"content-security-policy",
format!("script-src 'nonce-{nonce}' 'strict-dynamic'; style-src 'nonce-{nonce}'"),
)
}
The default scaffold is Inertia with React, so most of your rendering happens in the browser. React escapes by default too, and dangerouslySetInnerHTML is the thing to grep for there. One pre-launch fix is a useful reminder that the framework itself is young: a pull request merged in November fixed an Inertia prop that could run script in the browser.
CSRF
The web group runs PreventRequestForgery on every method except GET, HEAD and OPTIONS. It works in two steps: a request the browser marks as same-origin through Sec-Fetch-Site passes; otherwise the session token must match or the response is 419. Browsers do not send Sec-Fetch-Site over plain HTTP, so the docs tell you to always send the token ({{ csrf_field() }} in forms, or the X-XSRF-TOKEN / X-CSRF-TOKEN headers).
Exclusions exist, and they are where CSRF protection usually dies:
PreventRequestForgery::new().except(["stripe/*", "webhooks/*"])
Exclude only routes that are called by other systems, and verify those by signature. API route files have no session and no CSRF check, so anything in them must authenticate by token, not by cookie.
Sessions and cookies
The defaults are reasonable: SameSite=lax, HttpOnly, a 120-minute lifetime, the session ID regenerated on login and invalidated on logout, and Secure set automatically when APP_URL is https. Four things need a decision.
- Set
SESSION_DRIVERexplicitly. New apps usedatabase, but the fallback when the variable is unset iscookie. With the cookie driver, "a copy of an old session cookie remains valid until it expires", so logout cannot revoke a stolen session. SESSION_ENCRYPTisfalsein the example config. Session rows in your database or Redis are readable by anyone with access to that store. Turn it on if sessions hold anything sensitive.- Cookies outside the
webgroup are not encrypted. "Routes outside thewebgroup ... send cookies unencrypted", and a global middleware that sets a cookie sends it in the clear as well. APP_URLdrives the Secure flag. Anhttp://APP_URLbehind a TLS-terminating proxy means session cookies withoutSecure. Check with a cookie scan after deploying.
CORS: the default to change first
By default, per the routing docs, "any origin may call routes under api/*", with any method and any header. Credentials are off, which limits the damage, but an open API is rarely what you intend. Restrict it in src/config/cors.rs:
#[config::section]
fn cors() -> Cors {
Cors {
paths: vec!["api/*".to_owned()],
methods: Allowed::Any,
origins: Allowed::only(["https://app.example.com"]),
origin_patterns: Vec::new(),
headers: Allowed::Any,
exposed_headers: Vec::new(),
max_age: Some(0.seconds().into()),
credentials: true,
}
}
Never combine credentials: true with an open origin list. The failure modes are the ones we cover in CORS misconfigurations in Laravel.
Security headers
The SecurityHeaders middleware sets exactly two: X-Frame-Options: SAMEORIGIN and X-Content-Type-Options: nosniff. There is no HSTS, CSP, Referrer-Policy or Permissions-Policy unless you add them in middleware or at your proxy. Run the deployed site through the header checker to see what is actually sent.
Authentication
- Passwords are hashed with bcrypt at cost 12 (
BCRYPT_ROUNDS). Passwords over 72 bytes are rejected, not silently truncated, and hashes are upgraded on login when the cost changes. The hashing docs list no Argon2 option. - Login takes the same time whether or not the account exists, and returns a generic error. Changing a password invalidates other sessions.
- Reset tokens are single-use and last 60 minutes.
- API tokens are yours to build. There is no Sanctum or Passport equivalent in the 0.x docs. You implement a request guard, and the docs' advice is to "store a hash of each API token". Expiry, scopes and revocation are your code, so they need tests.
- No two-factor authentication is documented yet.
Rate limiting is opt-in
Nothing is throttled until you say so, including login. Add Throttle::per_minute(60) style limits to API routes and write the login limiter the docs show:
let limit = Limit::per_minute(5);
let key = format!("login:{}|{}", login.email.to_lowercase(), login.request().ip());
rate_limit::check(&key, limit).await??;
Counters live in the default cache store, and the docs say to use the database or Redis store in production. Limits are keyed by IP "as resolved by your trusted proxies", which leads to the next section.
Proxies, hosts and the server
The app is a single binary listening on 127.0.0.1:8000. The framework does not terminate TLS; the docs assume a load balancer that does.
- Trusted proxies.
X-Forwarded-*headers are ignored unless the sender is trusted:middleware.trust_proxies(["10.0.0.0/8"]). Without it,request.ip()is your load balancer, so every user shares one rate-limit bucket. With"*"behind a CDN plus a load balancer, clients may be able to spoof their IP. - Trusted hosts. In production only the
APP_URLhost and its subdomains are answered; others get400. That blocks Host-header tricks such as password reset poisoning. It is not enforced inlocalortesting. - Request limits. 2 MB bodies, 16 MB multipart, 1,000 fields, 20 files and a 30-second handler timeout are the defaults. An open pull request claims request bodies have no read timeout; it was unmerged and unconfirmed when we checked, but a reverse proxy with its own timeouts in front is sensible either way.
Endpoints the framework adds
There is no Telescope, Horizon or Pulse equivalent to leave exposed, which removes a whole class of classic Laravel findings. What does exist:
/up, the health route. It runs before any middleware, answers on any host and does not check the database. Harmless, but public./broadcasting/auth, if you use broadcasting.- Workflow resume URLs. The docs warn that "a wait token is an identifier, not a secret. Anyone who can reach the route can resume the run". Put authentication in front of them.
- Reverb accepts WebSocket connections from any origin by default. Set
REVERB_APP_ALLOWED_ORIGINS.
Tracing deserves a note too: OpenTelemetry spans exclude bound query parameters, but Laravel "exports a request's path (like /reset-password/8f2c...) and each cache key as written". Secrets in URLs end up in your tracing backend.
File uploads
The image rule accepts JPEG, PNG, GIF, BMP and WebP and rejects SVG "because an SVG can carry scripts". mimes(...) sniffs content, while extensions(...) looks only at the filename, so do not rely on extensions alone. .store("avatars") generates a random name with an extension derived from the contents. The docs' rule is direct: "Never pass client_name to store_as".
Dependencies
The docs do not mention dependency auditing, so add it yourself. A Laravel Rust app has two dependency trees, Cargo and npm:
cargo install cargo-audit
cargo audit
npm audit --omit=dev
Run both in CI. The ecosystem around the framework is days old, which means few third-party crates to vet, and also little track record for the ones that appear. Check a new crate's age, downloads and repository before adding it.
Code written by agents
New apps ship with AGENTS.md, CLAUDE.md and a set of agent skills, and Laravel's stated premise is that people will increasingly not read application code line by line. The compile-time checks above are the framework's answer. They do not replace review of the places a compiler cannot judge: AssertSqlSafe, |safe, #[validate(anyone)], CSRF exclusions and CORS origins. Those five greps are a good pull-request checklist.
Checking from the outside
Several of these defaults are visible to anyone on the internet: missing HSTS and CSP, open CORS, cookie flags, TLS configuration, a debug page. A free StackShield scan checks the language-independent ones on a Laravel Rust app today. For the full list of what to verify before launch, use the Laravel Rust production security checklist, and see how the framework compares in Laravel PHP vs Go vs Rust security.
Is your Laravel app exposed right now?
34% of Laravel apps we scan have at least one critical issue, and most teams do not find out until something breaks. The free scan checks your live app in 60 seconds. Then StackShield re-runs every check after each deploy, so a fix you ship today does not quietly regress next week.
Frequently Asked Questions
Is Laravel Rust secure enough for production?
It is a beta. Laravel says releases before 1.0 may include breaking changes and that it plans to call the framework stable after about six to eight weeks of feedback. No security advisories had been published for it as of 6 December 2026, and it has had no public independent audit that we could find. Treat it as you would any 0.x dependency: fine for trials and low-risk services, with extra review before it handles sensitive data.
Does Rust make a Laravel application immune to SQL injection and XSS?
No. Rust removes memory-safety bugs, and Laravel Rust binds query values as parameters and escapes template output by default. But the framework still has escape hatches: AssertSqlSafe embeds a string into SQL verbatim, and the safe filter prints HTML unescaped. Both are as dangerous as their PHP equivalents when user input reaches them.
Which Laravel Rust defaults should I change before going live?
Restrict CORS, which allows any origin on api/* by default. Add HSTS, a Content-Security-Policy, Referrer-Policy and Permissions-Policy, because only X-Frame-Options and X-Content-Type-Options are set. Add rate limits, since none apply by default. Use a server-side session driver, consider SESSION_ENCRYPT=true, and configure trusted proxies for your load balancer.
Does Laravel Rust have an equivalent of Sanctum or Passport?
Not in the 0.x docs. API authentication is a request guard you write yourself. The docs advise storing a hash of each API token and show a SHA-256 example that reads the bearer token from the request.
How do I report a vulnerability in Laravel Rust?
Email security@laravel.com, as set out in the Laravel organisation security policy on GitHub. GitHub Issues are disabled on the Laravel Rust repositories, and a public pull request is not the place for an undisclosed vulnerability.
Related Security Terms
Related Articles
SQL Injection in Laravel: Where Eloquent Protects You and Where It Doesn't
Eloquent and the Query Builder bind your values through PDO prepared statements, so a plain where() is safe. The trouble starts with whereRaw, dynamic orderBy, and LIKE wildcards. Here is exactly where the gaps are.
SecurityLaravel PHP vs Go vs Rust: Which Is More Secure?
Laravel now ships in three languages. Rust enforces the most at compile time, Go relies on conventions, and PHP has fifteen years of hardening and tooling behind it. All three share the same weak defaults for CORS, headers and rate limiting. Here is the comparison, control by control.
Tools & ReviewsLaravel Rust Vulnerability Scanner: What to Scan and Which Tools to Use
There is no single vulnerability scanner for Laravel Rust yet. You need three layers: dependency audits for Cargo and npm, a code review for the framework's unsafe escape hatches, and an external scan of the deployed app. Here is what each layer finds and how to run it.
Compare StackShield
Security Checklists
Laravel Production Deployment Security Checklist
A comprehensive security checklist for deploying Laravel applications to production. Covers environment config, server hardening, access control, and monitoring.
20 itemsLaravel API Security Checklist
Secure your Laravel API endpoints against common vulnerabilities. Covers authentication, input validation, rate limiting, and response security.
Stay Updated on Laravel Security
Get actionable security tips, vulnerability alerts, and best practices for Laravel apps.