伺服器端把關
一次 Stateful Linker 呼叫經過的關卡
flowchart TD
A["POST /{prefix}/linker"] --> T{"每分鐘 120 次"}
T -->|超過| E0["429"]
T --> B{"CSRF"}
B -->|失敗| E1["419"]
B --> P{"前綴相符?"}
P -->|否| E7["404"]
P --> L{"已登入?"}
L -->|否| E8["401 policy"]
L --> F{"欄位格式"}
F -->|否| E6["422 validation"]
F --> C{"別名已註冊、模式是 Stateful?"}
C -->|否| E2["404 policy"]
C --> K{"實例鎖(等 3 秒)"}
K -->|逾時| E9["service"]
K --> D{"實例屬於這個使用者、rev 相符"}
D -->|找不到| E3["expired"]
D -->|rev 不符| E4["conflict"]
D --> R{"Referer 白名單"}
R -->|否| E5["policy"]
R --> M{"方法在 METHODS?"}
M -->|否| E5
M --> X["call:你的登入細節 → 授權 → 驗證 → 業務"]
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:#fffStateless 呼叫走 /{prefix}/linker/stateless/{alias}/call:先驗簽章(過期 → expired,竄改 → 403 policy),再確認登入的人就是 URL 裡的 user,其餘相同,但沒有實例鎖與 rev。
實例的 cache key 是 linker:{user}:{uuid}:別人的 uuid 在你的 key 底下找不到,回 expired,不會洩漏實例存在與否。
實踐
每支方法都要回答「誰可以呼叫」
runtime 只保證「有登入」。這是誰的資料、他能不能做,要在 call 裡回答:
"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", "缺少 id。")]));
};
let invoice = Invoice::find_or_fail(id).await?; // 找不到 → 404 → not_found
user.authorize(InvoicePolicy::view, &invoice).await?; // 不行 → 403 → policy
Ok(LinkerResponse::ok().data("total", invoice.total))
}- 每個方法都要有這段;共用的部分抽成
async fn load_user(context) -> laravel::Result<User>之類的 helper。 - 頁面路由上的 middleware(登入、權限)不作用在 Linker 呼叫,因為 Linker 端點是共用的。頁面要登入,不代表 Linker 方法有檢查權限。
- 需要 Email 驗證的方法自己檢查,失敗回
LinkerResponse::policy(messages::UNVERIFIED)。
權限在參數驗證之前
先 authorize 再驗其他欄位:沒權限的人不該看到欄位規則。上面的例子裡只有 id 在授權前驗,因為授權需要它。
不要相信「前端已經檢查過了」
// ❌ 前端送來的 total 不可信
create!(Order { user_id: user.id, total: args["total"].as_i64().unwrap_or(0) }).await?;
// ✅ 伺服器自己算
let total = Cart::total_for(&user).await?;
create!(Order { user_id: user.id, total: total }).await?;用伺服器狀態做流程 guard
"submit" => {
if self.step != 3 { // 前端改不到這個欄位
return Ok(LinkerResponse::policy(messages::POLICY));
}
// …
}失敗時狀態不會存
Stateful 只有在 call 回成功時才寫回 struct 並遞增 rev。驗證失敗只續期,其他失敗什麼都不動。所以「先改 self.step 再發現要失敗」不會留下半套狀態 —— 但資料庫寫入不會被還原,多步寫入請用 transaction。
Stateless 的寫入要自己保證冪等
Stateless 沒有實例鎖,同一個 URL 可以並行。寫入請用 DB transaction、unique constraint 或 idempotency key。
片段函式的 params 要挑
render::register("orders.list", |input: RenderInput| async move {
// ✅ 白名單 + 型別
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);
// ❌ 不要整包丟進查詢或樣板
// view("orders.list", input.params)
…
});片段函式看不到使用者
RenderInput 只有 method、params、target、url,沒有 request、沒有登入的使用者。渲染端點也不要求登入(只要求有效的渲染 token 與 CSRF)。
所以:
- 片段只畫不分使用者的內容(公開目錄、靜態說明、只依 params 決定的畫面)。
- 每個人看到的不一樣的東西,用 Linker 方法(有
context.user)回data或dom.repeat,像可搜尋清單教學那樣。 - 不要把 user id 放進 params 再「信任」它 —— params 是使用者輸入。
這是跟 PHP 版最大的安全差異:PHP 的 renderCallSafely() 可以呼叫 auth()->user()。
快取要含使用者
Rust 版沒有 #[Computable(cache: true)]。自己用 cache 時 key 一定要混入 user id 與參數,否則就是跨使用者洩漏:
let key = format!("orders:summary:{}:{}", context.user, month);業務程式碼裡的錯誤
call 回 Err 時,runtime 依 HTTP 狀態翻成前端認得的 kind:
| 錯誤 | kind |
|---|---|
401(例如 laravel::abort(401)) | policy,訊息「請先登入。」 |
403(authorize 失敗) | policy |
404(find_or_fail 找不到) | service,訊息「找不到這筆資料。」 |
| 409 | conflict |
| 422 | validation(沒有欄位錯誤;要欄位錯誤請回 LinkerResponse::validation) |
| 其他任何錯誤 | fatal,並輸出到 stderr(linker: …) |
APP_DEBUG=false 時 fatal 只給固定訊息「系統發生錯誤,已記錄。」;APP_DEBUG=true 時錯誤內容會放進 message 回給瀏覽器,方便開發。正式環境務必 APP_DEBUG=false。
限流
| 端點 | 限制 |
|---|---|
/{prefix}/linker、/{prefix}/linker/stateless/… | 每分鐘 120 次 |
/{prefix}/render/token | 每分鐘 60 次 |
/{prefix}/render | 不限流,但每次要消耗一個一次性 token(池最多 16 個) |
另外前端有最低送出間隔 0.8 秒(MIN_DELAY_MS),擋連點;這只是體驗,不是防護。