Skip to content

Server-side checks ​

The gates one Stateful Linker call passes ​

mermaid
flowchart TD
    A["POST /{prefix}/linker"] --> T{"120 per minute"}
    T -->|exceeded| E0["429"]
    T --> B{"CSRF"}
    B -->|fails| E1["419"]
    B --> P{"Prefix matches?"}
    P -->|no| E7["404"]
    P --> L{"Logged in?"}
    L -->|no| E8["401 policy"]
    L --> F{"Field format"}
    F -->|no| E6["422 validation"]
    F --> C{"Alias registered, mode Stateful?"}
    C -->|no| E2["404 policy"]
    C --> K{"Instance lock (wait 3 s)"}
    K -->|timeout| E9["service"]
    K --> D{"Instance belongs to this user, rev matches"}
    D -->|not found| E3["expired"]
    D -->|rev mismatch| E4["conflict"]
    D --> R{"Referer allow list"}
    R -->|no| E5["policy"]
    R --> M{"Method in METHODS?"}
    M -->|no| E5
    M --> X["call: your login details → authorization → validation → business"]

    style E0 fill:#b91c1c,color:#fff
    style E1 fill:#b91c1c,color:#fff
    style E2 fill:#b91c1c,color:#fff
    style E3 fill:#b91c1c,color:#fff
    style E4 fill:#b91c1c,color:#fff
    style E5 fill:#b91c1c,color:#fff
    style E6 fill:#b91c1c,color:#fff
    style E7 fill:#b91c1c,color:#fff
    style E8 fill:#b91c1c,color:#fff
    style E9 fill:#b91c1c,color:#fff
    style X fill:#15803d,color:#fff

Stateless calls go to /{prefix}/linker/stateless/{alias}/call: the signature is checked first (expired → expired, tampered → 403 policy), then the logged-in user must be the URL's user; the rest is the same, without the instance lock and rev.

The instance cache key is linker:{user}:{uuid}: someone else's uuid isn't found under your key, so it returns expired and doesn't reveal whether the instance exists.

In practice ​

Every method must answer "who may call this" ​

The runtime only guarantees "logged in". Whose data it is and whether they may act on it must be answered in call:

rust
"show" => {
    let user = User::find_or_fail(context.user.parse::<i64>()?).await?;
    let id = args.get("id").and_then(|v| v.as_str()?.parse::<i64>().ok().or(v.as_i64()));
    let Some(id) = id else {
        return Ok(LinkerResponse::validation([("id", "The id is missing.")]));
    };
    let invoice = Invoice::find_or_fail(id).await?;        // not found → 404 → not_found
    user.authorize(InvoicePolicy::view, &invoice).await?;  // denied → 403 → policy
    Ok(LinkerResponse::ok().data("total", invoice.total))
}
  • Every method needs this; move the shared parts into a helper such as async fn load_user(context) -> laravel::Result<User>.
  • Middleware on page routes (login, permissions) doesn't apply to Linker calls, because the Linker endpoints are shared. A page requiring login doesn't mean the Linker method checked permissions.
  • Methods that need email verification check it themselves and return LinkerResponse::policy(messages::UNVERIFIED) on failure.

Permissions before argument validation ​

authorize first, then validate the other fields: someone without permission shouldn't see the field rules. In the example above only id is validated before authorization, because authorization needs it.

Don't trust "the front end already checked" ​

rust
// ❌ the total from the browser can't be trusted
create!(Order { user_id: user.id, total: args["total"].as_i64().unwrap_or(0) }).await?;

// ✅ the server computes it
let total = Cart::total_for(&user).await?;
create!(Order { user_id: user.id, total: total }).await?;

Use server state for flow guards ​

rust
"submit" => {
    if self.step != 3 {                // the browser can't change this field
        return Ok(LinkerResponse::policy(messages::POLICY));
    }
    // …
}

State isn't saved on failure ​

Stateful writes the struct back and increments rev only when call succeeds. A validation failure only renews; other failures change nothing. So "change self.step, then discover it must fail" leaves no half-done state, but database writes aren't rolled back; use a transaction for multi-step writes.

Stateless writes must be idempotent ​

Stateless has no instance lock, so the same URL can run in parallel. Use DB transactions, unique constraints or idempotency keys for writes.

Pick fragment params explicitly ​

rust
render::register("orders.list", |input: RenderInput| async move {
    // ✅ allow list + types
    let mode = match input.params.get("mode").map(String::as_str) {
        Some("detail") => "detail",
        _ => "list",
    };
    let page: u32 = input.params.get("page").and_then(|p| p.parse().ok()).unwrap_or(1).clamp(1, 500);
    // ❌ don't pass the whole map into a query or template
    // view("orders.list", input.params)
    …
});

Fragment functions can't see the user ​

RenderInput has only method, params, target and url: no request, no logged-in user. The render endpoint doesn't require a login either (only a valid render token and CSRF).

So:

  • Fragments only draw content that doesn't depend on the user (public catalogs, static help, screens decided only by params).
  • For anything that differs per person, use a Linker method (it has context.user) to return data or dom.repeat, as in the searchable list tutorial.
  • Don't put a user id in params and then "trust" it; params are user input.

This is the biggest security difference from the PHP version: PHP's renderCallSafely() can call auth()->user().

Caches must include the user ​

The Rust version has no #[Computable(cache: true)]. When you use the cache yourself, the key must mix in the user id and the arguments, or it leaks across users:

rust
let key = format!("orders:summary:{}:{}", context.user, month);

Errors in business code ​

When call returns Err, the runtime translates it into a kind the browser understands, by HTTP status:

Errorkind
401 (for example laravel::abort(401))policy, message "請先登入。" (please log in)
403 (a failed authorize)policy
404 (find_or_fail didn't find it)service, message "找不到這筆資料。" (not found)
409conflict
422validation (no field errors; return LinkerResponse::validation for those)
Any other errorfatal, also written to stderr (linker: …)

With APP_DEBUG=false, fatal only gives the fixed message "系統發生錯誤,已記錄。" (an error occurred and was logged); with APP_DEBUG=true the error text is put in message and sent to the browser, for development. Always run production with APP_DEBUG=false.

Rate limits ​

EndpointLimit
/{prefix}/linker, /{prefix}/linker/stateless/…120 per minute
/{prefix}/render/token60 per minute
/{prefix}/renderNot throttled, but each request uses up a one-time token (a pool of at most 16)

The browser also has a minimum interval of 0.8 seconds between sends (MIN_DELAY_MS) to stop double clicks; that's for user experience, not protection.