Skip to content

存取控制 ​

PHP 版用屬性宣告:#[RequiresAuth]、#[RequiresVerified]、#[Authorize]。Rust 版沒有這些屬性,框架只保證登入,其餘寫在 call 裡。

框架已經做的 ​

檢查在哪失敗
登入端點本身:request.user::<U>() 為 None401 policy「請先登入。」
CSRFLaravel 的 web 中介層419 → 前端當成 expired
實例屬於這個使用者cache key 含 user id409 expired
Stateless 網址屬於這個使用者簽章裡的 user403 policy
方法有公開METHODSpolicy「不支援的操作。」
來源頁面ALLOWS_REFERER_URLSpolicy「這個請求不是從允許的頁面發出的。」

登入一定要有。 Linker 沒有匿名模式;runtime::routes::<User> 的 User 就是用來查目前的使用者。

信箱驗證 ​

rust
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));
    }
    // …
}

權限:policy ​

rust
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?;          // 找不到 → 404 → service「找不到這筆資料。」
    user.authorize(InvoicePolicy::view, &invoice).await?;     // 不通過 → 403 → policy
    // …
}

authorize 回 403 錯誤,find_or_fail 回 404 錯誤;call 直接 ? 往上丟,框架會翻成前端認得的 kind(見錯誤處理)。不想丟錯誤就用 user.can(...) 自己分支:

rust
if !user.can(InvoicePolicy::view, &invoice).await? {
    return Ok(LinkerResponse::policy("這張發票不是你的。"));
}

每支方法都套用:booted 或共用函式 ​

PHP 的類別層屬性在 Rust 寫成「call 的第一段」:

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? {               // 整個元件:每一支都要過
        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?;   // 這一支再加
            // …
        }
        // …
    }
}

booted(&mut self, ctx) 是同步的,適合檢查 struct 自己的狀態;需要查資料庫的檢查放在 call 開頭。policy 不需要 model 時怎麼寫,見 Laravel for Rust 的 authorization.md(「Abilities without a record」)。

規則 ​

  • 先權限、後參數。 沒權限的人不該從驗證訊息看出欄位規則。PHP 的固定順序是「登入 → 信箱 → 權限 → 參數驗證」,Rust 版照這個順序寫。
  • match 的每一臂都要回答「誰可以呼叫」。 新增方法時把它加進 METHODS 的同一個 diff 裡就要看到權限檢查。
  • 用伺服器狀態做流程 guard。 if self.step != 3 { return policy },前端改不到 self.step。

頁面路由的中介層不算數

Linker 的端點由所有元件共用。頁面路由上的 Authenticated<User>、policy 檢查只作用在頁面請求 —— Linker 呼叫的權限要在元件裡做。

限制從哪幾頁被呼叫 ​

rust
const ALLOWS_REFERER_URLS: &'static [&'static str] = &["/tickets", "/tickets/*"];
  • 比對 Referer 的路徑(去掉 query 與 fragment),* 是萬用字元。
  • 空陣列 = 不設限。
  • 沒有 Referer 的請求放行(PHP 預設也是,除非開 require_referer;Rust 版沒有這個開關)。
  • PHP 還支援路由名稱(ticket.index),Rust 版只支援路徑。

這不是授權機制。 它擋得住「別的網站嵌你的端點」,但 curl 想寫什麼 Referer 就寫什麼。當成縮小暴露面用。

稽核 ​

PHP 有 php artisan linker:list --methods。Rust 版的等價物是兩個地方:

bash
grep -n "register::<" src/cg/mod.rs
bash
grep -rn "const METHODS" src/cg

想知道「前端最多能叫伺服器做什麼」,這兩份輸出就是全部。