---
id: spay4-authorization-menu-contract
status: accepted
audience: [backend, bo-frontend, qa]
source_documents: [backoffice-menu-catalog.md, authorization-menu-verification-matrix.md, order-workspace-contract.md]
---

# SPay4 Authorization and Menu Contract

## 結論

`SPAY4_BO_MENU_CATALOG_V2` 是同版 BO resource/action、fixed Supply profile、menu projection、endpoint guard、OpenAPI trace 與 route registry 的唯一 authority。runtime 唯一主表是 `com.sit.spay4.auth.policy.BackofficePolicyCatalog#ENTRIES`；`MenuCode` 僅提供 typed stable identity，不可複製 group、名稱、排序、visibility、action 或 B/F/R metadata。每個 target 只服務一個 catalog version；V1 不提供同 target mixed-version compatibility。

| Realm | Principal | Authority source |
| --- | --- | --- |
| `BO_USER` | `SUPERADMIN`、`PREFIX` | active user → same-owner active role → active `role_method` → active `system_method`；System Admin 使用既有 `ADMIN`。 |
| `SUPPLY_ACTOR` | `SUPPLIER`、`GATEWAY` | active `supply_account`、immutable owner chain 與 fixed `SupplyProfile`。 |

公開 wire type 使用 `GATEWAY`；資料庫的 `SUPPLY_GATEWAY` 只保留 adapter/owner mapping。Supply actor 永不讀 `RoleSet`、`system_method` 或 `role_method`，也不建立 Supply role table。

## Request authorization

每一 protected list/detail/helper/CSV/mutation 都依此順序 fail closed：

1. 驗證 formal JWT realm、expiry、identity 與 `session_epoch`。
2. fresh-read user/supply account、直接 TOTP credential、BO role 或 Supply owner chain 的 active/lifecycle 狀態。
3. 以 V2 catalog 檢查 typed `ResourceAction`；BO grant 的 `action` 必須嚴格 JSON action set，禁止 substring matching。非菜單 protected API 必須放在同一 `BackofficePolicyCatalog` 的 hidden entry，不能另建 registry。
4. 由 authenticated principal 導出 owner scope，再執行 resource-specific business/lifecycle guard。
5. 僅在前述全部成功後執行 operation。

client Agent/Supplier/Gateway selector 只能縮小 server-derived scope。Supplier/Gateway implicit-self request 不接受 owner selector；不存在與不可見 target 以同一 not-found representation fail closed，不回 empty page 或 target existence。

### 通用規則與專責契約的適用順序

本文件的 transport 與 not-found 規則是通用預設。endpoint 專責契約明列不同的 response 包裝或資料範圍語意時，以專責契約為準；本節不改任何 API。已定案的例外：

- [BO UI foundation 的 16 條既有 reads](bo-ui-foundation-contract.md#16-條既有-reads)保留既有 raw VO／PageVo，不包 `ResponseVo`；只有 `GET /bo/v2/auth/me` 使用 `ResponseVo<PrincipalSelfVo>`。
- 同文件的 Gateway list filters（`supplierId`／`currencyId`）與 server scope AND；跨 scope 或不存在的 filter target 回空頁，不做 target-existence lookup。這是 list filter 的縮小語意，不是 detail target 的 not-found。
- Access Role／User 管理（#605、#717）以下七條回 raw root，不包 `ResponseVo`：`POST /bo/v2/access/roles`（201）與 `PUT /bo/v2/access/roles/{roleId}` 回 `RoleDetail`；`POST /bo/v2/access/users`（201）回 `{user, totpSetupSecret}`；`PUT /bo/v2/access/users/{userId}` 回 `UserDetail`；`GET /bo/v2/access/permission-resources` 回 `PermissionResource` 陣列；`GET /bo/v2/access/role-assignments` 回 `PageVo<RoleAssignmentSummary>`；`GET /bo/v2/access/roles/options` 回 `RoleOption` 陣列。`POST /bo/v2/access/users/{userId}/totp/reset` 維持 `ResponseVo<{totpSetupSecret, version}>`。逐條 wire 見 [Access Role Management API](backoffice-menu-api-reference.md#access-role-management-api) 與 [Access User Management API](backoffice-menu-api-reference.md#access-user-management-api)。
- 其他 endpoint 只有在專責契約明列時才例外；沒有明列的，沿用本文件的通用規則。

## Menu projection and Agent scope

`GET /bo/v2/menu` 回 `ResponseVo<List<SystemGroupVo>>`。它只回 catalog entry 同時 B/F/R ready、principal 有 `VIEW`、且依 group/method sort 排序的 group projection；前端只可用 `method.code` 註冊 route，未回 code 不得顯示 placeholder 或直接註冊 route。

`AGENT_MANAGEMENT` 是唯一 Agent/Prefix management resource。Superadmin 有全域管理 scope；Prefix 僅可讀 own Agent 的 `GET /bo/v2/agents/me` 與 own detail。Prefix 不得取得 Agent page/list、mutation、跨 Agent target 或 allocation API；`GET /bo/v2/agents/options` 只回 own ACTIVE Agent（0 或 1 筆，#1019 推翻 #466 的 Prefix 403）。`supplyGatewayAllocations` 與 `supplyChannelAllocations`（#442）僅是 Superadmin `AGENT_MANAGEMENT` 子 API，沒有獨立 menu/grant/Prefix API。

`DEPOSIT_WORKSPACE`（Agent Deposit）自 #516 起另授權 Superadmin（ADR-0450（此參考僅供內部環境使用，公開版本未提供）），Prefix 的範圍由 authenticated Agent scope 導出並採 Agent/HOUSE-Supply masking（非 HOUSE current 單遮罩；own `AGENT_ACCOUNT` 單例外為完整唯讀投影，#992）。原 Prefix 專用的 `COMMISSION_REPORT`（Pt Snapshot）已於 #517 移除（ADR-0451（此參考僅供內部環境使用，公開版本未提供））：Prefix 不產生分潤資料，Prefix 沒有 Pt Snapshot menu 或 route；分潤報表只剩 Supply 側的 `SUPPLY_COMMISSION_REPORT`。`CHANNEL_ANALYTICS`（#529）與 `CHANNEL_DEPOSIT_REPORT`（#530）只授權 Superadmin 與 Prefix（ADR-0454（此參考僅供內部環境使用，公開版本未提供））：Superadmin 一次指定一個 Agent，Prefix 由 authenticated Agent scope 導出、只看收款路線代號；Supplier／Gateway 沒有 grant。Supply actor 永不取得 `DEPOSIT_WORKSPACE` menu；Agent Deposit 與 Deposit List 共用 `/bo/v2/depositOrders`，以 `methodCode` 選擇範圍，Supply actor 帶 `DEPOSIT_WORKSPACE` 403。`SUPPLY_TRANSACTION_WORKSPACE`（Supplier Transaction Record）自 #513 起就緒並開啟（ADR-0455（此參考僅供內部環境使用，公開版本未提供））：授權 Superadmin 與 Supplier VIEW／UPDATE，Prefix 經 catalog `prefixVia` 轉查 `HOUSE_TRANSACTION_WORKSPACE` 的 role grant，Gateway 沒有格子（403）。兩個 Transaction 選單共用 `/bo/v2/houseCardTransactions` 六條路由，page／export 以 `methodCode=HOUSE_TRANSACTION_WORKSPACE|SUPPLY_TRANSACTION_WORKSPACE` 選擇範圍（server 重驗 caller 直接持有該選單 VIEW，delegate 不算，否則 403）；資料範圍為 Prefix 只 own Agent 的 House Card 交易、Supplier 只 own Supplier 的 Supply Channel 交易、Superadmin 全部，跨 scope 與 `transactionNo` 前綴不符一律 not-found（[Transaction Records API](backoffice-menu-api-reference.md#transaction-records-api)）。

`SYSTEM_HOURLY_PROJECTION`（#457）只授權 Superadmin VIEW／UPDATE，沒有 Agent scope：parked hourly projection fact 列表與人工重排都是全域營運操作，Prefix／Supplier／Gateway 一律 403。`/bo/v2/alerts/**` 收件匣仍只需登入，但 `recipient_scope=SUPERADMIN` 的 park 告警只有 Superadmin 可見、可讀，Prefix 以同一 not-found 拒絕。

## Transport and mutation safety

除[上述專責例外](#通用規則與專責契約的適用順序)外，所有非 `void` API 使用 `ResponseVo<T>`。page 固定 `pageNumber` zero-based、`pageSize=1..500`。versioned command conflict 為 HTTP 409／`RESOURCE_VERSION_CONFLICT(40051)`；Frontend reload authoritative data 後要求重確認，不自動 retry。

Payment Account Application 與 Account command 沒有獨立 resource，沿用 `SUPPLY_CARDHOLDER_OVERVIEW`：application detail 為 `VIEW`、create 為 `INSERT`、approve/reject/cancel 與 Account status／directionAvailability／balanceAdjustments／unfreeze 為 `UPDATE`，並一律驗 owner scope（`PaymentAccountController`、`OverviewAccountReadController`）。`DELETE /bo/v2/paymentAccounts/{id}` 使用 `SUPPLY_CARDHOLDER_OVERVIEW` 的 `DELETE`，Superadmin、Supplier、Gateway 限各自 owner chain，scope 外、查無與已刪除都回 404（ADR-0462（此參考僅供內部環境使用，公開版本未提供））。House transaction raw 必須 `Cache-Control: no-store`；不進 CSV、Audit、log 或 telemetry。rotation/reset plaintext 只可在成功 response 一次回傳，前端只可保存 volatile state。

## Seed, readiness and cache

DB `system_group` 與 `system_method` 是完整 catalog metadata 的 expected-state materialization，不是 runtime catalog authority；`menu-catalog.sql` 不寫入 `role_method`。seed 使用 stable code、可重跑且 correct state no-op；partial/mismatch 必須在 DML 前 fail closed，seed 不改動 catalog 以外的 row。BO 啟動 readiness（ADR-0394，#470）以 read-only 比對 DB 與 catalog：`system_group`／`system_method` 必須與 catalog 完全一致，缺少、metadata 不符或出現 catalog 以外的 row（含 inactive）都使 BO 啟動失敗並列出差異，ID 與時間欄位不比對；ACTIVE `role_method` 必須參照存在的 role 與 catalog method、action 為嚴格 JSON action set 且不超出該 entry 的 catalog action，未授予或 inactive grant 不影響啟動，也不自動補 grant。B/F/R readiness preflight 一律 read-only；readiness mismatch 時 service 不得服務 protected API，但不阻止完整 catalog metadata 的預先 materialize。

Redis 僅可快取已通過 authority guard 的 derived projection；key 至少含 realm、principal type/id、session epoch、catalog version。Redis hit/miss/unavailable 都必須重新驗證 realm、credential、role/owner-chain、epoch、resource action 與 business guard；不得 fallback 本機 stale authorization cache。
