Access control
The PHP version declares it with attributes: #[RequiresAuth], #[RequiresVerified], #[Authorize]. Rust has none of these. The framework only guarantees a login; everything else is written in call.
What the framework already does
| Check | Where | On failure |
|---|---|---|
| Login | The endpoint itself: request.user::<U>() is None | 401 policy "請先登入。" (please log in) |
| CSRF | Laravel's web middleware | 419 → the browser treats it as expired |
| The instance belongs to this user | The cache key contains the user id | 409 expired |
| The Stateless URL belongs to this user | The signed user | 403 policy |
| The method is exposed | METHODS | policy "不支援的操作。" (unsupported operation) |
| The source page | ALLOWS_REFERER_URLS | policy "這個請求不是從允許的頁面發出的。" (not sent from an allowed page) |
A login is always required. Linker has no anonymous mode; the User in runtime::routes::<User> is what looks up the current user.
Email verification
use cg_component::runtime::linker::messages;
async fn call(&mut self, ctx: &LinkerContext, method: &str, args: Args) -> laravel::Result<LinkerResponse> {
let user = User::find_or_fail(ctx.user.parse::<i64>()?).await?;
if user.email_verified_at.is_none() {
return Ok(LinkerResponse::policy(messages::UNVERIFIED));
}
// …
}Permissions: policies
use crate::models::{Invoice, InvoicePolicy, User};
"show" => {
let id = args.get("id").and_then(Value::as_i64).ok_or_else(|| laravel::Error::msg("missing id"))?;
let invoice = Invoice::find_or_fail(id).await?; // not found → 404 → service "找不到這筆資料。"
user.authorize(InvoicePolicy::view, &invoice).await?; // denied → 403 → policy
// …
}authorize returns a 403 error and find_or_fail a 404 error; call just propagates them with ?, and the framework translates them into kinds the browser understands (see Errors). To branch yourself instead of returning an error, use user.can(...):
if !user.can(InvoicePolicy::view, &invoice).await? {
return Ok(LinkerResponse::policy("This invoice isn't yours."));
}Applying to every method: booted or a shared function
PHP's class-level attributes become "the first lines of call" in Rust:
async fn call(&mut self, ctx: &LinkerContext, method: &str, args: Args) -> laravel::Result<LinkerResponse> {
let user = current_user(ctx).await?;
if !may_manage_warehouse(&user).await? { // the whole component: every method must pass
return Ok(LinkerResponse::policy(messages::POLICY));
}
match method {
"adjust" => {
let stock = WarehouseStock::find_or_fail(id_of(&args)?).await?;
user.authorize(WarehouseStockPolicy::adjust, &stock).await?; // and one more check for this method
// …
}
// …
}
}booted(&mut self, ctx) is synchronous, which suits checks on the struct's own state; checks that query the database go at the start of call. For policies that don't need a model, see Laravel for Rust's authorization.md ("Abilities without a record").
Rules
- Permissions first, then arguments. Someone without permission shouldn't learn the field rules from validation messages. PHP's fixed order is "login → email → permission → argument validation"; write Rust in the same order.
- Every arm of the
matchmust answer "who may call this". When you add a method toMETHODS, the permission check should be visible in the same diff. - Use server state for flow guards.
if self.step != 3 { return policy }: the browser can't changeself.step.
Page route middleware doesn't count
All components share the Linker endpoints. Authenticated<User> and policy checks on page routes only apply to page requests; permissions for Linker calls must be checked in the component.
Restricting which pages can call
const ALLOWS_REFERER_URLS: &'static [&'static str] = &["/tickets", "/tickets/*"];- It matches the path of the
Referer(without query and fragment);*is a wildcard. - An empty array = no restriction.
- Requests without a
Refererare allowed (PHP's default too, unlessrequire_refereris on; Rust has no such switch). - PHP also supports route names (
ticket.index); Rust supports only paths.
This isn't an authorization mechanism. It stops "another site embedding your endpoint", but curl can send any Referer it likes. Use it to narrow the exposure.
Auditing
PHP has php artisan linker:list --methods. The Rust equivalent is two places:
grep -n "register::<" src/cg/mod.rsgrep -rn "const METHODS" src/cgThose two outputs are the whole answer to "the most the browser can make the server do".