From b5a05941d91867772655a3dca35e35b8ec57e9ca Mon Sep 17 00:00:00 2001 From: jackyu66git Date: Fri, 7 Aug 2026 17:19:45 +0800 Subject: [PATCH] =?UTF-8?q?feat(ECR-013A):=20Admin=20RBAC=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E5=B9=B6=20Closed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 角色权限、RequirePermission、/me permissions 与 migration 000015; Reviewer Approve → Closed。Next:ECR-013B Contract Definition。 Co-authored-by: Cursor --- .ai/product/feature-spec/README.md | 1 + .ai/product/feature-spec/ops-admin.md | 3 +- .ai/product/feature-spec/ops-rbac.md | 151 +++++++++++ apps/admin-h5/e2e/admin-ops-smoke.spec.ts | 34 ++- apps/admin-h5/src/api/client.ts | 15 +- apps/admin-h5/src/layouts/AdminShell.vue | 2 + apps/admin-h5/src/stores/auth.ts | 20 +- apps/api/internal/handler/admin.go | 25 +- apps/api/internal/handler/admin_content.go | 8 +- apps/api/internal/handler/admin_rbac.go | 88 +++++++ .../internal/integration/admin_rbac_test.go | 237 ++++++++++++++++++ .../internal/middleware/admin_permission.go | 42 ++++ .../internal/repository/admin_rbac_repo.go | 131 ++++++++++ apps/api/internal/repository/admin_repo.go | 9 +- apps/api/internal/service/admin/rbac.go | 135 ++++++++++ apps/api/internal/service/admin/service.go | 22 +- .../api/migrations/000015_admin_rbac.down.sql | 4 + apps/api/migrations/000015_admin_rbac.up.sql | 42 ++++ .../BACKEND_DESIGN/BD-2026-013A-admin-rbac.md | 98 ++++++++ docs/CHANGELOG.md | 9 + docs/CODE_REVIEW/ECR-013A.md | 45 ++++ docs/CONTRACT_DIFF/ECR-013A.yaml | 59 +++++ docs/CONTRACT_DIFF/README.md | 10 + docs/ECR/ECR-013A-admin-rbac.md | 75 ++++++ docs/ENGINEERING_SPEC/ECR-013A-admin-rbac.md | 29 +++ .../HANDOFF/ECR-013A-architect-to-engineer.md | 31 +++ docs/HANDOFF/ECR-013A-engineer-to-reviewer.md | 19 ++ docs/PRODUCT_SPEC/ECR-013A-admin-rbac.md | 50 ++++ docs/PROJECT_PROFILE.md | 5 +- docs/STATE/ECR-013A.md | 18 ++ docs/TASKS/TASK-013A-ECR013A.yaml | 17 ++ docs/TEST_REPORT/ECR-013A.md | 51 ++++ docs/TRACEABILITY.md | 1 + docs/WAVE0/HUMAN_REVIEW.md | 5 +- proto/openapi.yaml | 76 +++++- 35 files changed, 1518 insertions(+), 49 deletions(-) create mode 100644 .ai/product/feature-spec/ops-rbac.md create mode 100644 apps/api/internal/handler/admin_rbac.go create mode 100644 apps/api/internal/integration/admin_rbac_test.go create mode 100644 apps/api/internal/middleware/admin_permission.go create mode 100644 apps/api/internal/repository/admin_rbac_repo.go create mode 100644 apps/api/internal/service/admin/rbac.go create mode 100644 apps/api/migrations/000015_admin_rbac.down.sql create mode 100644 apps/api/migrations/000015_admin_rbac.up.sql create mode 100644 docs/BACKEND_DESIGN/BD-2026-013A-admin-rbac.md create mode 100644 docs/CODE_REVIEW/ECR-013A.md create mode 100644 docs/CONTRACT_DIFF/ECR-013A.yaml create mode 100644 docs/CONTRACT_DIFF/README.md create mode 100644 docs/ECR/ECR-013A-admin-rbac.md create mode 100644 docs/ENGINEERING_SPEC/ECR-013A-admin-rbac.md create mode 100644 docs/HANDOFF/ECR-013A-architect-to-engineer.md create mode 100644 docs/HANDOFF/ECR-013A-engineer-to-reviewer.md create mode 100644 docs/PRODUCT_SPEC/ECR-013A-admin-rbac.md create mode 100644 docs/STATE/ECR-013A.md create mode 100644 docs/TASKS/TASK-013A-ECR013A.yaml create mode 100644 docs/TEST_REPORT/ECR-013A.md diff --git a/.ai/product/feature-spec/README.md b/.ai/product/feature-spec/README.md index f7e28cb..281739d 100644 --- a/.ai/product/feature-spec/README.md +++ b/.ai/product/feature-spec/README.md @@ -23,6 +23,7 @@ | [ops-admin.md](ops-admin.md) | 运营后台 | §7 | `admin-h5` `/` `/users/:id` … | Ops-A | | [ops-analytics.md](ops-analytics.md) | 运营行为分析(埋点+数据看板) | §7 | `admin-h5` `/analytics` · H5 track | Ops-B · ECR-007 Closed | | [ops-content.md](ops-content.md) | 运营内容(宫格+测评上下架) | §7 | `admin-h5` `/content` · `GET /home/tools` | Ops-C · ECR-008 Closed | +| [ops-rbac.md](ops-rbac.md) | 运营 RBAC | §7 | `admin-h5` `/me` permissions · `/admin/roles*` | Ops-D · **ECR-013A Closed** | 新功能:复制 `_TEMPLATE.md` → 填满 → 在本表登记 → 再编码。 diff --git a/.ai/product/feature-spec/ops-admin.md b/.ai/product/feature-spec/ops-admin.md index 431fb8e..0f62021 100644 --- a/.ai/product/feature-spec/ops-admin.md +++ b/.ai/product/feature-spec/ops-admin.md @@ -208,5 +208,6 @@ Phase A 可先 `console`/本地;不挡验收。 | **A(本 ECR)** | 登录 · 用户 · 订单 · 授予会员 · 审计 · admin-h5 壳 | | **B(ECR-007 Closed)** | 自有埋点 · 管理端「数据」看板 — Spec `ops-analytics.md` | | **C(ECR-008 Closed)** | 首页宫格 CRUD · 测评上下架 — Spec `ops-content.md` | +| **E(ECR-013A Closed)** | Admin RBAC — Spec `ops-rbac.md` · Parent WAVE0-FROZEN | | D | 订单筛选 · 展示价 · 退款只读(另开 ECR) | -| E | RBAC · 封禁 · 推送占位(另开 ECR) | +| 后置 | AccountLifecycle = **ECR-013B**;封禁加深 · 推送占位 | diff --git a/.ai/product/feature-spec/ops-rbac.md b/.ai/product/feature-spec/ops-rbac.md new file mode 100644 index 0000000..649a3c7 --- /dev/null +++ b/.ai/product/feature-spec/ops-rbac.md @@ -0,0 +1,151 @@ +# Feature Spec: 运营后台 RBAC(Ops · ECR-013A) + +> Status: `Active`(**Closed** · Feature Complete)· Map: `§7 运营后台` · Phase: `Ops-D` +> Parent: **WAVE0-FROZEN** (`27f27a1`) +> ESS: `docs/ECR/ECR-013A-admin-rbac.md`(**Closed**) +> Capability: `AdminGovernance` · BC: `Admin_RBAC` +> 模板:`docs/WAVE0/contracts/OPS-CONTRACT-TEMPLATE.md` + +--- + +## ESS 门禁 + +1. Change Level = **L2** → 已 Approved + Coding auth + Implemented + **Closed** +2. ~~Contract Definition only~~ — 已完成 +3. 实现证据:`docs/TEST_REPORT/ECR-013A.md` · `docs/CODE_REVIEW/ECR-013A.md` + +--- + +## L0 Capability + +| 字段 | 内容 | +|------|------| +| Capability ID | `AdminGovernance` | +| Purpose | 以最小权限原则约束管理员可执行的运营动作 | +| Why now | Ops-A 全员等价权限;进入 M1+ 前必须有权限面,否则越权不可治理 | +| Non-goals | 用户账户启停(ECR-013B);兑换码;CMS;Ask Prompt;真支付;UGC | + +--- + +## L1 Bounded Context + +| 字段 | 内容 | +|------|------| +| Primary BC | `Admin_RBAC` | +| owns | `AdminRole` · `AdminPermission` | +| does_not_own | `User` · `Profile` · `UserStatus` · `Membership` · `Payment` | +| allowed | `Admin_Auth_Audit.write_audit` | +| forbidden | `Payment` · `Membership.write` · `DeviceAuth.user_token_issue` | + +权威:`.ai/domain/boundary-rules.md` + +--- + +## 1. 功能定义 + +| 字段 | 内容 | +|------|------| +| Name | Admin RBAC | +| Purpose | 角色与权限点绑定;API 级强制鉴权;变更可审计 | +| Business Goal | 支撑多运营角色,而不扩大 C 端攻击面 | + +| In | Out | +|---|---| +| Role CRUD(最小:list/get/update permissions) | UserStatus / 封禁(013B) | +| `GET /admin/me` 返回 permissions | 细粒度数据行级 ACL | +| 既有 admin 写操作挂 permission 检查 | 新业务模块权限爆炸式新增(另 ECR) | + +--- + +## L2 Domain + +| Entity | 不变式 | +|--------|--------| +| `AdminRole` | `name` 唯一;系统角色 `super_admin` 不可删除 | +| `AdminPermission` | 稳定字符串码(见下表);只增不改语义 | +| `AdminAccount.role_id` | 每个账号恰好一个角色(本切片);无角色视为拒绝写操作 | + +### Permission catalog(本切片冻结) + +| Code | 覆盖既有能力 | +|------|----------------| +| `admin.users.read` | GET users / users/:id / stats | +| `admin.users.membership.grant` | POST membership/grant | +| `admin.users.ask_quota.grant` | POST ask-quota/grant | +| `admin.orders.read` | GET orders | +| `admin.audit.read` | GET audit-logs | +| `admin.analytics.read` | GET analytics/*(Ops-B) | +| `admin.content.write` | home tools / scales publish(Ops-C) | +| `admin.roles.read` | GET roles | +| `admin.roles.write` | 变更角色权限 | + +`super_admin` 种子拥有上表全部。 + +--- + +## L3 API Contract(意图 · 实现轮同步 OpenAPI) + +前缀:`/api/v1/admin` · AdminAuth · 信封 `{code,message,data}` + +| Method | Path | 权限 | 语义 | +|--------|------|------|------| +| GET | `/roles` | `admin.roles.read` | 角色列表 | +| GET | `/roles/:id` | `admin.roles.read` | 角色 + permissions[] | +| PUT | `/roles/:id/permissions` | `admin.roles.write` | 全量替换权限集;写 AuditLog | +| GET | `/me` | (已登录) | **扩展**返回 `role` + `permissions[]` | + +既有写接口:在实现轮挂上表 permission;缺权 → **403** + AuditLog(尝试记录)。 + +`contract_diff`:`docs/CONTRACT_DIFF/ECR-013A.yaml` + +--- + +## L4 Acceptance Criteria + +### Functional + +| ID | Given | When | Then | +|----|-------|------|------| +| AC-F-01 | super_admin 已登录 | GET `/roles` | 200,含 `super_admin` | +| AC-F-02 | 角色存在 | PUT permissions 合法集合 | 200;再次 GET 一致 | +| AC-F-03 | GET `/me` | — | data 含 `permissions` 数组 | + +### Security + +| ID | Given | When | Then | +|----|-------|------|------| +| AC-S-01 | Admin 无 `admin.roles.write` | PUT `/roles/:id/permissions` | **403**;AuditLog 有拒绝或尝试记录 | +| AC-S-02 | Admin 无 `admin.users.membership.grant` | POST membership/grant | **403** | +| AC-S-03 | 仅 DeviceAuth | 访问 `/admin/roles` | **401** | +| AC-S-04 | 删除 `super_admin` 角色 | 任意 API | **拒绝**(4xx) | + +### Performance + +| ID | Given | When | Then | +|----|-------|------|------| +| AC-P-01 | 角色数 N≤100 | GET `/roles` | 本机 integration 环境下 P95 **< 500ms** | + +### Observability + +| ID | Given | When | Then | +|----|-------|------|------| +| AC-O-01 | PUT permissions 成功 | — | AuditLog action 含 `roles.permissions.update` | +| AC-O-02 | AC-S-01 触发 | — | AuditLog 可追溯 admin_id + path | + +--- + +## Forbidden(本切片) + +- UserStatus / AccountLifecycle(**ECR-013B**) +- 真支付 · UGC · Prompt/RAG · 兑换码 · CMS Banner 新表 +- 改 DeviceAuth / C 端五 Tab + +--- + +## Implementation Notes(实现轮才执行) + +| 项 | 内容 | +|----|------| +| Migration | YES(roles / permissions 关联;accounts.role_id;种子 super_admin) | +| Packages | `service/admin` · repo · middleware permission check · admin-h5 只读展示权限(最小) | +| Parent | WAVE0-FROZEN | diff --git a/apps/admin-h5/e2e/admin-ops-smoke.spec.ts b/apps/admin-h5/e2e/admin-ops-smoke.spec.ts index cd86159..55cfc68 100644 --- a/apps/admin-h5/e2e/admin-ops-smoke.spec.ts +++ b/apps/admin-h5/e2e/admin-ops-smoke.spec.ts @@ -21,7 +21,22 @@ test('admin login users grant and audit with mocked API', async ({ page }) => { await ok({ token: 'adm_e2e_token', expires_at: new Date(Date.now() + 3600_000).toISOString(), - admin: { id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', username: 'admin' }, + admin: { + id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', + username: 'admin', + role: 'super_admin', + permissions: [ + 'admin.users.read', + 'admin.users.membership.grant', + 'admin.users.ask_quota.grant', + 'admin.orders.read', + 'admin.audit.read', + 'admin.analytics.read', + 'admin.content.write', + 'admin.roles.read', + 'admin.roles.write', + ], + }, }) return } @@ -55,7 +70,22 @@ test('admin login users grant and audit with mocked API', async ({ page }) => { return } if (url.endsWith('/me') || url.includes('/me?')) { - await ok({ id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', username: 'admin' }) + await ok({ + id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', + username: 'admin', + role: 'super_admin', + permissions: [ + 'admin.users.read', + 'admin.users.membership.grant', + 'admin.users.ask_quota.grant', + 'admin.orders.read', + 'admin.audit.read', + 'admin.analytics.read', + 'admin.content.write', + 'admin.roles.read', + 'admin.roles.write', + ], + }) return } if (url.includes(`/users/${userId}/ask-quota/grant`) && method === 'POST') { diff --git a/apps/admin-h5/src/api/client.ts b/apps/admin-h5/src/api/client.ts index d8237c2..5d32a29 100644 --- a/apps/admin-h5/src/api/client.ts +++ b/apps/admin-h5/src/api/client.ts @@ -94,14 +94,25 @@ export type UserDetail = { }> } +export type AdminMe = { + id: string + username: string + role?: string + permissions: string[] +} + export const adminApi = { login: (username: string, password: string) => - request<{ token: string; admin: { id: string; username: string } }>('POST', '/auth/login', { + request<{ token: string; admin: AdminMe }>('POST', '/auth/login', { username, password, }), logout: () => request<{ ok: boolean }>('POST', '/auth/logout'), - me: () => request<{ id: string; username: string }>('GET', '/me'), + me: () => request('GET', '/me'), + roles: () => + request<{ items: Array<{ id: string; name: string; system: boolean }> }>('GET', '/roles'), + role: (id: string) => + request<{ id: string; name: string; system: boolean; permissions: string[] }>('GET', `/roles/${id}`), stats: () => request('GET', '/stats'), users: (q = '') => request<{ items: UserListItem[] }>('GET', `/users?q=${encodeURIComponent(q)}`), diff --git a/apps/admin-h5/src/layouts/AdminShell.vue b/apps/admin-h5/src/layouts/AdminShell.vue index e945bf6..8e2a894 100644 --- a/apps/admin-h5/src/layouts/AdminShell.vue +++ b/apps/admin-h5/src/layouts/AdminShell.vue @@ -33,6 +33,7 @@ async function onLogout() {
{{ auth.username || '管理员' }} + {{ auth.role }} · {{ auth.permissions.length }} 权
@@ -72,6 +73,7 @@ nav a.router-link-active { box-shadow: 0 4px 12px rgba(229, 77, 66, 0.08); } .foot { margin-top: auto; display: flex; flex-direction: column; gap: 0.5rem; } +.role { font-size: 0.75rem; color: var(--muted); } .main { padding: 1.5rem 1.75rem; } @media (max-width: 800px) { .shell { grid-template-columns: 1fr; } diff --git a/apps/admin-h5/src/stores/auth.ts b/apps/admin-h5/src/stores/auth.ts index 27a1a35..a1b707d 100644 --- a/apps/admin-h5/src/stores/auth.ts +++ b/apps/admin-h5/src/stores/auth.ts @@ -5,19 +5,27 @@ import { adminApi, getToken, setToken } from '@/api/client' export const useAuthStore = defineStore('auth', () => { const token = ref(getToken()) const username = ref('') + const role = ref('') + const permissions = ref([]) + + function applyMe(me: { username: string; role?: string; permissions?: string[] }) { + username.value = me.username + role.value = me.role || '' + permissions.value = me.permissions ?? [] + } async function login(user: string, password: string) { const res = await adminApi.login(user, password) setToken(res.token) token.value = res.token - username.value = res.admin.username + applyMe(res.admin) } async function hydrate() { if (!token.value) return false try { const me = await adminApi.me() - username.value = me.username + applyMe(me) return true } catch { setToken(null) @@ -35,7 +43,13 @@ export const useAuthStore = defineStore('auth', () => { setToken(null) token.value = null username.value = '' + role.value = '' + permissions.value = [] } - return { token, username, login, logout, hydrate } + function can(code: string) { + return permissions.value.includes(code) + } + + return { token, username, role, permissions, can, login, logout, hydrate } }) diff --git a/apps/api/internal/handler/admin.go b/apps/api/internal/handler/admin.go index eec2d38..2d6f8de 100644 --- a/apps/api/internal/handler/admin.go +++ b/apps/api/internal/handler/admin.go @@ -29,19 +29,20 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) { authed.Use(middleware.AdminAuth(h.Svc)) authed.POST("/auth/logout", h.Logout) authed.GET("/me", h.Me) - authed.GET("/stats", h.Stats) - authed.GET("/users", h.ListUsers) - authed.GET("/users/:id", h.GetUser) - authed.POST("/users/:id/membership/grant", h.GrantMembership) - authed.POST("/users/:id/ask-quota/grant", h.GrantAskQuota) - authed.GET("/orders", h.ListOrders) - authed.GET("/audit-logs", h.ListAudit) - authed.GET("/analytics/overview", h.AnalyticsOverview) - authed.GET("/analytics/pages", h.AnalyticsPages) - authed.GET("/analytics/exits", h.AnalyticsExits) - authed.GET("/analytics/clicks", h.AnalyticsClicks) - authed.GET("/analytics/funnel", h.AnalyticsFunnel) + authed.GET("/stats", middleware.RequireAdminPermission(h.Svc, admin.PermUsersRead), h.Stats) + authed.GET("/users", middleware.RequireAdminPermission(h.Svc, admin.PermUsersRead), h.ListUsers) + authed.GET("/users/:id", middleware.RequireAdminPermission(h.Svc, admin.PermUsersRead), h.GetUser) + authed.POST("/users/:id/membership/grant", middleware.RequireAdminPermission(h.Svc, admin.PermMembershipGrant), h.GrantMembership) + authed.POST("/users/:id/ask-quota/grant", middleware.RequireAdminPermission(h.Svc, admin.PermAskQuotaGrant), h.GrantAskQuota) + authed.GET("/orders", middleware.RequireAdminPermission(h.Svc, admin.PermOrdersRead), h.ListOrders) + authed.GET("/audit-logs", middleware.RequireAdminPermission(h.Svc, admin.PermAuditRead), h.ListAudit) + authed.GET("/analytics/overview", middleware.RequireAdminPermission(h.Svc, admin.PermAnalyticsRead), h.AnalyticsOverview) + authed.GET("/analytics/pages", middleware.RequireAdminPermission(h.Svc, admin.PermAnalyticsRead), h.AnalyticsPages) + authed.GET("/analytics/exits", middleware.RequireAdminPermission(h.Svc, admin.PermAnalyticsRead), h.AnalyticsExits) + authed.GET("/analytics/clicks", middleware.RequireAdminPermission(h.Svc, admin.PermAnalyticsRead), h.AnalyticsClicks) + authed.GET("/analytics/funnel", middleware.RequireAdminPermission(h.Svc, admin.PermAnalyticsRead), h.AnalyticsFunnel) h.registerContent(authed) + h.registerRBAC(authed) } func (h *AdminHandler) Login(c *gin.Context) { diff --git a/apps/api/internal/handler/admin_content.go b/apps/api/internal/handler/admin_content.go index ea0a0ba..1d51dc1 100644 --- a/apps/api/internal/handler/admin_content.go +++ b/apps/api/internal/handler/admin_content.go @@ -14,10 +14,10 @@ import ( ) func (h *AdminHandler) registerContent(authed *gin.RouterGroup) { - authed.GET("/home/tools", h.ListHomeTools) - authed.PUT("/home/tools", h.ReplaceHomeTools) - authed.GET("/scales", h.ListScales) - authed.PATCH("/scales/:id", h.PatchScale) + authed.GET("/home/tools", middleware.RequireAdminPermission(h.Svc, admin.PermContentWrite), h.ListHomeTools) + authed.PUT("/home/tools", middleware.RequireAdminPermission(h.Svc, admin.PermContentWrite), h.ReplaceHomeTools) + authed.GET("/scales", middleware.RequireAdminPermission(h.Svc, admin.PermContentWrite), h.ListScales) + authed.PATCH("/scales/:id", middleware.RequireAdminPermission(h.Svc, admin.PermContentWrite), h.PatchScale) } func (h *AdminHandler) ListHomeTools(c *gin.Context) { diff --git a/apps/api/internal/handler/admin_rbac.go b/apps/api/internal/handler/admin_rbac.go new file mode 100644 index 0000000..2c2cd20 --- /dev/null +++ b/apps/api/internal/handler/admin_rbac.go @@ -0,0 +1,88 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/yuxingu/digital-psychology/apps/api/internal/middleware" + "github.com/yuxingu/digital-psychology/apps/api/internal/service/admin" + "github.com/yuxingu/digital-psychology/apps/api/pkg/response" +) + +func (h *AdminHandler) registerRBAC(authed *gin.RouterGroup) { + authed.GET("/roles", middleware.RequireAdminPermission(h.Svc, admin.PermRolesRead), h.ListRoles) + authed.GET("/roles/:id", middleware.RequireAdminPermission(h.Svc, admin.PermRolesRead), h.GetRole) + authed.PUT("/roles/:id/permissions", middleware.RequireAdminPermission(h.Svc, admin.PermRolesWrite), h.PutRolePermissions) +} + +func (h *AdminHandler) ListRoles(c *gin.Context) { + items, err := h.Svc.ListRoles(c.Request.Context()) + if err != nil { + response.Fail(c, http.StatusInternalServerError, 50000, err.Error()) + return + } + response.OK(c, gin.H{"items": items}) +} + +func (h *AdminHandler) GetRole(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + response.Fail(c, http.StatusBadRequest, 40000, "invalid id") + return + } + role, err := h.Svc.GetRole(c.Request.Context(), id) + if errors.Is(err, admin.ErrRoleNotFound) || role == nil { + response.Fail(c, http.StatusNotFound, 40400, "role not found") + return + } + if err != nil { + response.Fail(c, http.StatusInternalServerError, 50000, err.Error()) + return + } + response.OK(c, role) +} + +func (h *AdminHandler) PutRolePermissions(c *gin.Context) { + adminID, ok := middleware.AdminIDFromContext(c) + if !ok { + response.Fail(c, http.StatusUnauthorized, 40102, "admin session invalid") + return + } + roleID, err := uuid.Parse(c.Param("id")) + if err != nil { + response.Fail(c, http.StatusBadRequest, 40000, "invalid id") + return + } + var body struct { + Permissions []string `json:"permissions"` + } + if err := c.ShouldBindJSON(&body); err != nil { + response.Fail(c, http.StatusBadRequest, 40000, "invalid body") + return + } + if body.Permissions == nil { + body.Permissions = []string{} + } + err = h.Svc.ReplaceRolePermissions(c.Request.Context(), adminID, roleID, body.Permissions) + if errors.Is(err, admin.ErrRoleNotFound) { + response.Fail(c, http.StatusNotFound, 40400, "role not found") + return + } + if errors.Is(err, admin.ErrInvalidPerm) { + response.Fail(c, http.StatusBadRequest, 40000, err.Error()) + return + } + if err != nil { + response.Fail(c, http.StatusInternalServerError, 50000, err.Error()) + return + } + role, err := h.Svc.GetRole(c.Request.Context(), roleID) + if err != nil { + response.Fail(c, http.StatusInternalServerError, 50000, err.Error()) + return + } + response.OK(c, role) +} diff --git a/apps/api/internal/integration/admin_rbac_test.go b/apps/api/internal/integration/admin_rbac_test.go new file mode 100644 index 0000000..907cfba --- /dev/null +++ b/apps/api/internal/integration/admin_rbac_test.go @@ -0,0 +1,237 @@ +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "path/filepath" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/bcrypt" + + "github.com/yuxingu/digital-psychology/apps/api/internal/config" + "github.com/yuxingu/digital-psychology/apps/api/internal/db" + "github.com/yuxingu/digital-psychology/apps/api/internal/httpserver" +) + +func setupAPIPool(t *testing.T) (*gin.Engine, *pgxpool.Pool) { + t.Helper() + gin.SetMode(gin.TestMode) + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + t.Cleanup(cancel) + + cfg := config.Load() + cfg.Admin.BootstrapUsername = "admin" + cfg.Admin.BootstrapPassword = "change-me" + pool, err := db.Connect(ctx, cfg.DatabaseURL) + if err != nil { + t.Skipf("postgres unavailable (run npm run deps:up): %v", err) + } + t.Cleanup(pool.Close) + + migDir := filepath.Join("..", "..", "migrations") + if err := db.Migrate(ctx, pool, migDir); err != nil { + t.Fatalf("migrate: %v", err) + } + return httpserver.NewRouter(pool, cfg), pool +} + +func adminLogin(t *testing.T, r http.Handler, user, pass string) string { + t.Helper() + env, code := doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/auth/login", map[string]string{ + "username": user, "password": pass, + }, "") + if code != 200 || env.Code != 0 { + t.Fatalf("login %s failed http=%d code=%d msg=%s", user, code, env.Code, env.Message) + } + var login struct { + Token string `json:"token"` + } + if err := json.Unmarshal(env.Data, &login); err != nil || login.Token == "" { + t.Fatalf("login token missing: %v %s", err, env.Data) + } + return login.Token +} + +func TestAdminRBAC(t *testing.T) { + r, pool := setupAPIPool(t) + ctx := context.Background() + superTok := adminLogin(t, r, "admin", "change-me") + + // AC-S-03: no admin session → 401 + env, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/roles", nil, "") + if code != http.StatusUnauthorized { + t.Fatalf("expected 401 without admin token, got http=%d", code) + } + + // AC-F-03: /me includes permissions + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/me", nil, superTok) + if code != 200 || env.Code != 0 { + t.Fatalf("me failed http=%d code=%d", code, env.Code) + } + var me struct { + Permissions []string `json:"permissions"` + Role string `json:"role"` + } + if err := json.Unmarshal(env.Data, &me); err != nil || len(me.Permissions) == 0 { + t.Fatalf("expected permissions on me: %v %s", err, env.Data) + } + if me.Role != "super_admin" { + t.Fatalf("expected super_admin role, got %q", me.Role) + } + + // AC-F-01: list roles + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/roles", nil, superTok) + if code != 200 || env.Code != 0 { + t.Fatalf("list roles failed http=%d code=%d msg=%s", code, env.Code, env.Message) + } + var roles struct { + Items []struct { + ID string `json:"id"` + Name string `json:"name"` + } `json:"items"` + } + if err := json.Unmarshal(env.Data, &roles); err != nil || len(roles.Items) == 0 { + t.Fatalf("expected roles: %v %s", err, env.Data) + } + var superRoleID string + for _, it := range roles.Items { + if it.Name == "super_admin" { + superRoleID = it.ID + } + } + if superRoleID == "" { + t.Fatal("super_admin role missing") + } + + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/roles/"+superRoleID, nil, superTok) + if code != 200 || env.Code != 0 { + t.Fatalf("get role failed http=%d code=%d", code, env.Code) + } + + // Seed limited role + account for deny ACs + limitedRoleID := uuid.New() + _, err := pool.Exec(ctx, ` + INSERT INTO admin_roles(id, name, system) VALUES ($1, $2, false) + ON CONFLICT (name) DO NOTHING`, limitedRoleID, "rbac_limited_"+limitedRoleID.String()[:8]) + if err != nil { + t.Fatalf("insert role: %v", err) + } + // resolve actual id if conflict + var roleName string + err = pool.QueryRow(ctx, `SELECT id, name FROM admin_roles WHERE id=$1`, limitedRoleID).Scan(&limitedRoleID, &roleName) + if err != nil { + t.Fatalf("load limited role: %v", err) + } + + hash, err := bcrypt.GenerateFromPassword([]byte("limited-pass"), bcrypt.DefaultCost) + if err != nil { + t.Fatal(err) + } + limitedUser := fmt.Sprintf("limited_%d", time.Now().UnixNano()) + _, err = pool.Exec(ctx, ` + INSERT INTO admin_accounts(username, password_hash, role_id) + VALUES ($1, $2, $3)`, limitedUser, string(hash), limitedRoleID) + if err != nil { + t.Fatalf("insert limited admin: %v", err) + } + t.Cleanup(func() { + _, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limitedUser) + _, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID) + }) + + limitedTok := adminLogin(t, r, limitedUser, "limited-pass") + + // AC-S-01: no roles.write → 403 + env, code = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/roles/"+limitedRoleID.String()+"/permissions", + map[string]any{"permissions": []string{"admin.users.read"}}, limitedTok) + if code != http.StatusForbidden { + t.Fatalf("expected 403 roles.write, got http=%d code=%d msg=%s", code, env.Code, env.Message) + } + + // AC-S-02: no membership.grant → 403 + _ = mustRegister(t, r) + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users", nil, superTok) + if code != 200 { + t.Fatalf("list users: %d", code) + } + var list struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + } + _ = json.Unmarshal(env.Data, &list) + if len(list.Items) == 0 { + t.Fatal("need a user for grant deny") + } + env, code = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/users/"+list.Items[0].ID+"/membership/grant", + map[string]string{"plan": "month"}, limitedTok) + if code != http.StatusForbidden { + t.Fatalf("expected 403 membership.grant, got http=%d code=%d", code, env.Code) + } + + // AC-F-02 + AC-O-01: super replaces permissions + want := []string{"admin.users.read", "admin.roles.read"} + env, code = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/roles/"+limitedRoleID.String()+"/permissions", + map[string]any{"permissions": want}, superTok) + if code != 200 || env.Code != 0 { + t.Fatalf("put permissions failed http=%d code=%d msg=%s", code, env.Code, env.Message) + } + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/roles/"+limitedRoleID.String(), nil, superTok) + if code != 200 { + t.Fatalf("get after put: %d", code) + } + var roleDetail struct { + Permissions []string `json:"permissions"` + } + if err := json.Unmarshal(env.Data, &roleDetail); err != nil { + t.Fatal(err) + } + if len(roleDetail.Permissions) != 2 { + t.Fatalf("expected 2 perms, got %#v", roleDetail.Permissions) + } + + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/audit-logs", nil, superTok) + if code != 200 { + t.Fatalf("audit: %d", code) + } + var audit struct { + Items []struct { + Action string `json:"action"` + } `json:"items"` + } + _ = json.Unmarshal(env.Data, &audit) + foundUpdate, foundDeny := false, false + for _, it := range audit.Items { + if it.Action == "roles.permissions.update" { + foundUpdate = true + } + if it.Action == "permission.denied" { + foundDeny = true + } + } + if !foundUpdate { + t.Fatal("expected roles.permissions.update audit") + } + if !foundDeny { + t.Fatal("expected permission.denied audit") + } + + // AC-S-04: system role cannot be deleted (FK + system seed; no Delete API) + tag, err := pool.Exec(ctx, `DELETE FROM admin_roles WHERE name='super_admin'`) + if err == nil && tag.RowsAffected() > 0 { + t.Fatal("expected delete super_admin to fail or affect 0 rows") + } + + // AC-P-01: list roles under 500ms locally + start := time.Now() + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/roles", nil, superTok) + if code != 200 || time.Since(start) > 500*time.Millisecond { + t.Fatalf("AC-P-01 list roles slow or failed: http=%d dur=%v", code, time.Since(start)) + } +} diff --git a/apps/api/internal/middleware/admin_permission.go b/apps/api/internal/middleware/admin_permission.go new file mode 100644 index 0000000..1735f16 --- /dev/null +++ b/apps/api/internal/middleware/admin_permission.go @@ -0,0 +1,42 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/yuxingu/digital-psychology/apps/api/pkg/response" +) + +// AdminPermissionChecker validates admin permission codes. +type AdminPermissionChecker interface { + HasPermission(ctx context.Context, adminID uuid.UUID, code string) (bool, error) + DenyPermission(ctx context.Context, adminID uuid.UUID, code, path string) +} + +// RequireAdminPermission aborts with 403 when the admin lacks code. +func RequireAdminPermission(checker AdminPermissionChecker, code string) gin.HandlerFunc { + return func(c *gin.Context) { + adminID, ok := AdminIDFromContext(c) + if !ok { + response.Fail(c, http.StatusUnauthorized, 40102, "admin session invalid") + c.Abort() + return + } + okPerm, err := checker.HasPermission(c.Request.Context(), adminID, code) + if err != nil { + response.Fail(c, http.StatusInternalServerError, 50000, "permission check failed") + c.Abort() + return + } + if !okPerm { + checker.DenyPermission(c.Request.Context(), adminID, code, c.FullPath()) + response.Fail(c, http.StatusForbidden, 40301, "forbidden") + c.Abort() + return + } + c.Next() + } +} diff --git a/apps/api/internal/repository/admin_rbac_repo.go b/apps/api/internal/repository/admin_rbac_repo.go new file mode 100644 index 0000000..d29fd9a --- /dev/null +++ b/apps/api/internal/repository/admin_rbac_repo.go @@ -0,0 +1,131 @@ +package repository + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// AdminRole is an ops RBAC role. +type AdminRole struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + System bool `json:"system"` + CreatedAt time.Time `json:"created_at"` +} + +// ListAdminRoles returns all roles. +func (r *AdminRepo) ListAdminRoles(ctx context.Context) ([]AdminRole, error) { + rows, err := r.Pool.Query(ctx, ` + SELECT id, name, system, created_at FROM admin_roles ORDER BY name`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []AdminRole + for rows.Next() { + var a AdminRole + if err := rows.Scan(&a.ID, &a.Name, &a.System, &a.CreatedAt); err != nil { + return nil, err + } + out = append(out, a) + } + return out, rows.Err() +} + +// GetAdminRole loads one role. +func (r *AdminRepo) GetAdminRole(ctx context.Context, id uuid.UUID) (*AdminRole, error) { + var a AdminRole + err := r.Pool.QueryRow(ctx, ` + SELECT id, name, system, created_at FROM admin_roles WHERE id=$1`, id, + ).Scan(&a.ID, &a.Name, &a.System, &a.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + return &a, nil +} + +// ListRolePermissions returns permission codes for a role. +func (r *AdminRepo) ListRolePermissions(ctx context.Context, roleID uuid.UUID) ([]string, error) { + rows, err := r.Pool.Query(ctx, ` + SELECT code FROM admin_role_permissions WHERE role_id=$1 ORDER BY code`, roleID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var c string + if err := rows.Scan(&c); err != nil { + return nil, err + } + out = append(out, c) + } + return out, rows.Err() +} + +// ReplaceRolePermissions replaces the full permission set for a role. +func (r *AdminRepo) ReplaceRolePermissions(ctx context.Context, roleID uuid.UUID, codes []string) error { + tx, err := r.Pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if _, err := tx.Exec(ctx, `DELETE FROM admin_role_permissions WHERE role_id=$1`, roleID); err != nil { + return err + } + for _, code := range codes { + if _, err := tx.Exec(ctx, ` + INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,$2)`, roleID, code); err != nil { + return err + } + } + return tx.Commit(ctx) +} + +// ListPermissionsForAdmin returns permission codes for an admin account. +func (r *AdminRepo) ListPermissionsForAdmin(ctx context.Context, adminID uuid.UUID) ([]string, error) { + rows, err := r.Pool.Query(ctx, ` + SELECT p.code + FROM admin_accounts a + JOIN admin_role_permissions p ON p.role_id = a.role_id + WHERE a.id=$1 AND a.deleted_at IS NULL AND a.role_id IS NOT NULL + ORDER BY p.code`, adminID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var c string + if err := rows.Scan(&c); err != nil { + return nil, err + } + out = append(out, c) + } + return out, rows.Err() +} + +// GetAdminRoleMeta returns role id/name for an account. +func (r *AdminRepo) GetAdminRoleMeta(ctx context.Context, adminID uuid.UUID) (roleID *uuid.UUID, name string, err error) { + var id uuid.UUID + err = r.Pool.QueryRow(ctx, ` + SELECT r.id, r.name + FROM admin_accounts a + JOIN admin_roles r ON r.id = a.role_id + WHERE a.id=$1 AND a.deleted_at IS NULL`, adminID, + ).Scan(&id, &name) + if errors.Is(err, pgx.ErrNoRows) { + return nil, "", nil + } + if err != nil { + return nil, "", err + } + return &id, name, nil +} diff --git a/apps/api/internal/repository/admin_repo.go b/apps/api/internal/repository/admin_repo.go index 7247c68..c06b663 100644 --- a/apps/api/internal/repository/admin_repo.go +++ b/apps/api/internal/repository/admin_repo.go @@ -32,12 +32,15 @@ func (r *AdminRepo) CountAccounts(ctx context.Context) (int, error) { return n, err } -// CreateAccount inserts an admin account. +// CreateAccount inserts an admin account with seeded super_admin role. func (r *AdminRepo) CreateAccount(ctx context.Context, username, hash string) (uuid.UUID, error) { var id uuid.UUID err := r.Pool.QueryRow(ctx, ` - INSERT INTO admin_accounts(username, password_hash) - VALUES ($1,$2) RETURNING id`, username, hash).Scan(&id) + INSERT INTO admin_accounts(username, password_hash, role_id) + VALUES ( + $1, $2, + (SELECT id FROM admin_roles WHERE name = 'super_admin' LIMIT 1) + ) RETURNING id`, username, hash).Scan(&id) return id, err } diff --git a/apps/api/internal/service/admin/rbac.go b/apps/api/internal/service/admin/rbac.go new file mode 100644 index 0000000..f1bdd3d --- /dev/null +++ b/apps/api/internal/service/admin/rbac.go @@ -0,0 +1,135 @@ +package admin + +import ( + "context" + "encoding/json" + "errors" + + "github.com/google/uuid" +) + +// Permission catalog frozen in ECR-013A Spec. +const ( + PermUsersRead = "admin.users.read" + PermMembershipGrant = "admin.users.membership.grant" + PermAskQuotaGrant = "admin.users.ask_quota.grant" + PermOrdersRead = "admin.orders.read" + PermAuditRead = "admin.audit.read" + PermAnalyticsRead = "admin.analytics.read" + PermContentWrite = "admin.content.write" + PermRolesRead = "admin.roles.read" + PermRolesWrite = "admin.roles.write" +) + +var knownPermissions = map[string]struct{}{ + PermUsersRead: {}, PermMembershipGrant: {}, PermAskQuotaGrant: {}, + PermOrdersRead: {}, PermAuditRead: {}, PermAnalyticsRead: {}, + PermContentWrite: {}, PermRolesRead: {}, PermRolesWrite: {}, +} + +var ( + ErrForbidden = errString("forbidden") + ErrRoleNotFound = errString("role not found") + ErrInvalidPerm = errString("invalid permission code") + ErrProtectSystem = errString("system role protected") +) + +// AdminMe is the public admin profile (with RBAC). +type AdminMe struct { + ID uuid.UUID `json:"id"` + Username string `json:"username"` + Role string `json:"role,omitempty"` + Permissions []string `json:"permissions"` +} + +// RoleDTO is list/detail payload. +type RoleDTO struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + System bool `json:"system"` + Permissions []string `json:"permissions,omitempty"` +} + +// HasPermission reports whether admin holds code. +func (s *Service) HasPermission(ctx context.Context, adminID uuid.UUID, code string) (bool, error) { + perms, err := s.Repo.ListPermissionsForAdmin(ctx, adminID) + if err != nil { + return false, err + } + for _, p := range perms { + if p == code { + return true, nil + } + } + return false, nil +} + +// DenyPermission audits a forbidden attempt. +func (s *Service) DenyPermission(ctx context.Context, adminID uuid.UUID, code, path string) { + meta, _ := json.Marshal(map[string]string{"permission": code, "path": path}) + _ = s.Repo.InsertAudit(ctx, adminID, "permission.denied", "permission", code, meta) +} + +// Me returns the current admin profile with permissions. +func (s *Service) Me(ctx context.Context, adminID uuid.UUID) (*AdminMe, error) { + acc, err := s.Repo.FindAccountByID(ctx, adminID) + if err != nil || acc == nil { + return nil, errors.New("admin not found") + } + perms, err := s.Repo.ListPermissionsForAdmin(ctx, adminID) + if err != nil { + return nil, err + } + if perms == nil { + perms = []string{} + } + _, roleName, _ := s.Repo.GetAdminRoleMeta(ctx, adminID) + return &AdminMe{ID: acc.ID, Username: acc.Username, Role: roleName, Permissions: perms}, nil +} + +// ListRoles returns roles without permissions. +func (s *Service) ListRoles(ctx context.Context) ([]RoleDTO, error) { + roles, err := s.Repo.ListAdminRoles(ctx) + if err != nil { + return nil, err + } + out := make([]RoleDTO, 0, len(roles)) + for _, r := range roles { + out = append(out, RoleDTO{ID: r.ID, Name: r.Name, System: r.System}) + } + return out, nil +} + +// GetRole returns role + permissions. +func (s *Service) GetRole(ctx context.Context, id uuid.UUID) (*RoleDTO, error) { + role, err := s.Repo.GetAdminRole(ctx, id) + if err != nil || role == nil { + return nil, ErrRoleNotFound + } + perms, err := s.Repo.ListRolePermissions(ctx, id) + if err != nil { + return nil, err + } + if perms == nil { + perms = []string{} + } + return &RoleDTO{ID: role.ID, Name: role.Name, System: role.System, Permissions: perms}, nil +} + +// ReplaceRolePermissions updates permissions with audit. +func (s *Service) ReplaceRolePermissions(ctx context.Context, adminID, roleID uuid.UUID, codes []string) error { + role, err := s.Repo.GetAdminRole(ctx, roleID) + if err != nil || role == nil { + return ErrRoleNotFound + } + for _, c := range codes { + if _, ok := knownPermissions[c]; !ok { + return ErrInvalidPerm + } + } + if err := s.Repo.ReplaceRolePermissions(ctx, roleID, codes); err != nil { + return err + } + meta, _ := json.Marshal(map[string]any{"permissions": codes, "role": role.Name}) + return s.Repo.InsertAudit(ctx, adminID, "roles.permissions.update", "admin_role", roleID.String(), meta) +} diff --git a/apps/api/internal/service/admin/service.go b/apps/api/internal/service/admin/service.go index 9e2739b..94ceab4 100644 --- a/apps/api/internal/service/admin/service.go +++ b/apps/api/internal/service/admin/service.go @@ -6,7 +6,6 @@ import ( "crypto/rand" "encoding/hex" "encoding/json" - "errors" "time" "github.com/google/uuid" @@ -54,12 +53,6 @@ type LoginResult struct { Admin AdminMe `json:"admin"` } -// AdminMe is the public admin profile. -type AdminMe struct { - ID uuid.UUID `json:"id"` - Username string `json:"username"` -} - var ( ErrBadCredentials = errString("invalid credentials") ErrInvalidPlan = errString("invalid plan") @@ -90,10 +83,14 @@ func (s *Service) Login(ctx context.Context, username, password string) (*LoginR if err := s.Repo.CreateSession(ctx, acc.ID, token, exp); err != nil { return nil, err } + me, err := s.Me(ctx, acc.ID) + if err != nil { + return nil, err + } return &LoginResult{ Token: token, ExpiresAt: exp, - Admin: AdminMe{ID: acc.ID, Username: acc.Username}, + Admin: *me, }, nil } @@ -110,15 +107,6 @@ func (s *Service) Logout(ctx context.Context, token string) error { return s.Repo.DeleteSession(ctx, token) } -// Me returns the current admin profile. -func (s *Service) Me(ctx context.Context, adminID uuid.UUID) (*AdminMe, error) { - acc, err := s.Repo.FindAccountByID(ctx, adminID) - if err != nil || acc == nil { - return nil, errors.New("admin not found") - } - return &AdminMe{ID: acc.ID, Username: acc.Username}, nil -} - // ListUsers lists terminal users. func (s *Service) ListUsers(ctx context.Context, q string, limit, offset int) ([]repository.UserListItem, error) { return s.Repo.ListUsers(ctx, q, limit, offset) diff --git a/apps/api/migrations/000015_admin_rbac.down.sql b/apps/api/migrations/000015_admin_rbac.down.sql new file mode 100644 index 0000000..fe592e9 --- /dev/null +++ b/apps/api/migrations/000015_admin_rbac.down.sql @@ -0,0 +1,4 @@ +UPDATE admin_accounts SET role_id = NULL WHERE role_id IS NOT NULL; +ALTER TABLE admin_accounts DROP COLUMN IF EXISTS role_id; +DROP TABLE IF EXISTS admin_role_permissions; +DROP TABLE IF EXISTS admin_roles; diff --git a/apps/api/migrations/000015_admin_rbac.up.sql b/apps/api/migrations/000015_admin_rbac.up.sql new file mode 100644 index 0000000..c064b8a --- /dev/null +++ b/apps/api/migrations/000015_admin_rbac.up.sql @@ -0,0 +1,42 @@ +-- ECR-013A Admin RBAC + +CREATE TABLE IF NOT EXISTS admin_roles ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + name varchar(64) NOT NULL UNIQUE, + system boolean NOT NULL DEFAULT false, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS admin_role_permissions ( + role_id uuid NOT NULL REFERENCES admin_roles(id) ON DELETE CASCADE, + code varchar(64) NOT NULL, + PRIMARY KEY (role_id, code) +); + +ALTER TABLE admin_accounts + ADD COLUMN IF NOT EXISTS role_id uuid REFERENCES admin_roles(id); + +INSERT INTO admin_roles(id, name, system) +VALUES ('00000000-0000-4000-8000-000000000001', 'super_admin', true) +ON CONFLICT (name) DO NOTHING; + +INSERT INTO admin_role_permissions(role_id, code) +SELECT r.id, p.code +FROM admin_roles r +CROSS JOIN (VALUES + ('admin.users.read'), + ('admin.users.membership.grant'), + ('admin.users.ask_quota.grant'), + ('admin.orders.read'), + ('admin.audit.read'), + ('admin.analytics.read'), + ('admin.content.write'), + ('admin.roles.read'), + ('admin.roles.write') +) AS p(code) +WHERE r.name = 'super_admin' +ON CONFLICT DO NOTHING; + +UPDATE admin_accounts +SET role_id = (SELECT id FROM admin_roles WHERE name = 'super_admin') +WHERE role_id IS NULL AND deleted_at IS NULL; diff --git a/docs/BACKEND_DESIGN/BD-2026-013A-admin-rbac.md b/docs/BACKEND_DESIGN/BD-2026-013A-admin-rbac.md new file mode 100644 index 0000000..58883f6 --- /dev/null +++ b/docs/BACKEND_DESIGN/BD-2026-013A-admin-rbac.md @@ -0,0 +1,98 @@ +# Backend Design: ECR-013A Admin RBAC + +> Architect 产出;**Contract Definition** — Status Draft;Approve 前禁止实现。 +> Parent: WAVE0-FROZEN + +| Field | Value | +|-------|-------| +| ID | BD-2026-013A | +| ECR | ECR-013A | +| Change Level | L2 | +| Status | Approved | +| Approved | 2026-08-07(Human) · Coding authorized | +| Author | Architect | +| Date | 2026-08-07 | +| Risk | Medium | + +--- + +## Context + +- 目标:管理员角色/权限点 + API 强制鉴权 + 审计 +- 非目标:UserStatus(013B);真支付;UGC +- Spec:`ops-rbac.md` · boundary-rules `Admin_RBAC` + +## Architecture Change + +- 分层边界:**No** +- 受影响层:API · Application(`service/admin`) · Infrastructure(repo+migration) · UI(admin-h5 最小) + +## Module Changes + +| Module | Layer | Change | Must NOT | +|--------|-------|--------|----------| +| admin repo/service | App/Infra | roles · permissions · account.role_id | 改 users.status | +| middleware | API | RequirePermission | DeviceAuth 混用 | +| admin handlers | API | /roles* · /me 扩展 | Handler SQL | +| admin-h5 | UI | 读 permissions | 直连 DB | + +## Data Flow + +```text +Admin login → AdminSession + → load AdminAccount + Role + Permissions + → request + RequirePermission(code) + → allow → service → audit + → deny → 403 + audit +``` + +## API Changes + +- 契约意图见 Spec;实现轮写 `proto/openapi.yaml` +- 兼容:additive;旧 admin 账号迁移到 `super_admin` + +## Database Changes + +- Migration **Required: YES**(实现轮) +- 表:`admin_roles` · `admin_role_permissions`(或等价)· `admin_accounts.role_id` +- Wave 0 / Contract 轮:**不写 migration 文件** + +## Failure Handling + +- 无权限:403 +- 无会话:401 +- 删 super_admin:4xx + +## Test Plan + +- Integration:AC-F/S/O;AC-P-01 本机抽样 +- 禁止跳过 Security AC + +## Rollback Plan + +- down migration;middleware 开关(实现轮详写) + +--- + +## Backend Change Boundary + +```text +Change Level: L2 +Change: Admin RBAC roles + permission gates + +Affected: + Domain: AdminRole, AdminPermission + Application: service/admin + Infrastructure: admin_repo + migration (implement phase) + API: /admin/roles* , /admin/me + Migration: Required at implement — NOT in contract phase + Tests: integration admin RBAC + Risk: Medium +``` + +## Architecture Regression Check + +- [ ] 无 Handler 直连 DB +- [ ] Admin / Device 鉴权隔离 +- [ ] 不拥有 UserStatus / Membership 写 +- [ ] 符合 Admin_RBAC boundary-rules diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 5856d12..3343ad1 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,15 @@ ## 2026-08-07 +- **ECR-013A Closed**:Reviewer Approve(Admin RBAC) +- **ECR-013A Implemented**:Admin RBAC(roles/permissions · RequirePermission · `/me` permissions · admin-h5 最小展示) + TEST_REPORT PASS · STATE Closed +- **ECR-013A Approved + Coding Start Authorization**(Human) +- **ECR-013A Contract Definition**(Start Authorization):Admin RBAC L0–L4 · Spec `ops-rbac` · BD-2026-013A · `CONTRACT_DIFF/ECR-013A.yaml` + Parent WAVE0-FROZEN +- **WAVE 0 FREEZE**:tag `WAVE0-FROZEN` @ 27f27a1 · HUMAN_REVIEW Decision=FREEZE +- **WAVE 0 Contract-First Foundation**:Capability Map · boundary-rules · glossary · entity-catalog · OPS-CONTRACT-TEMPLATE · contract_diff(P0) · feature-map §7 + 路径:`docs/WAVE0/` · 同步 `.ai/domain/*` · **无 apps 变更** · 待 Human Review - **ECR-012 Implemented**:星座对齐收口(outlook 卫生 · 报告页复用运势面板 · 分享 type=star · 测试加厚) TEST_REPORT PASS · STATE phase=review · 待 Reviewer Closed - **ECR-012 Approved**(Human):星座对齐进入 implement diff --git a/docs/CODE_REVIEW/ECR-013A.md b/docs/CODE_REVIEW/ECR-013A.md new file mode 100644 index 0000000..39a5e75 --- /dev/null +++ b/docs/CODE_REVIEW/ECR-013A.md @@ -0,0 +1,45 @@ +# CODE_REVIEW — ECR-013A + +**Verdict:** Approve → Closed + +Date: 2026-08-07 · Reviewer(Human Authorize Approve) + +## Checklist + +- [x] Handler → Service → Repository;AdminAuth ≠ DeviceAuth +- [x] Feature Spec Active + BD-2026-013A Approved + Coding auth +- [x] OpenAPI `/admin/roles*` · `AdminMe.permissions` +- [x] Migration `000015_admin_rbac` · seed `super_admin` +- [x] 既有写路径 RequirePermission;403 + AuditLog +- [x] AC-F/S/P/O 在 TEST_REPORT 有证据 +- [x] 无 UserStatus / 013B / 真支付 / UGC + +## Backend Review + +```text +□ Design Compliance — PASS(对齐 BD-2026-013A) +□ Layer boundary respected — PASS +□ Repository used — PASS +□ API contract additive — PASS +□ Migration exists — PASS 000015 +□ Observability — PASS AuditLog deny/update +□ Tests included — PASS TestAdminRBAC +□ Rollback — PASS down migration +□ No architecture regression — PASS +□ Matches Change Boundary L2 — PASS +``` + +## Architecture Regression + +- [x] 无 Handler 直连 DB +- [x] Admin / Device 鉴权隔离 +- [x] 符合 `boundary-rules` Admin_RBAC +- [x] 文件/函数体量可接受(RBAC 拆分独立文件) + +## Closed decision + +```text +Load Agent Profile: REVIEWER +Decision: Approve → Closed +Next: ECR-013B AccountLifecycle — Contract Definition(另 Start Authorization) +``` diff --git a/docs/CONTRACT_DIFF/ECR-013A.yaml b/docs/CONTRACT_DIFF/ECR-013A.yaml new file mode 100644 index 0000000..e30e748 --- /dev/null +++ b/docs/CONTRACT_DIFF/ECR-013A.yaml @@ -0,0 +1,59 @@ +ecr: ECR-013A +capability: AdminGovernance +bounded_context: Admin_RBAC +parent: WAVE0-FROZEN +change: + type: additive +breaking_change: false +migration_required: true +compatibility_notes: > + Additive RBAC tables and AdminAccount.role_id. + Existing admin accounts migrate to seeded super_admin. + GET /admin/me gains permissions[]; old clients ignore unknown fields. + +entities: + - name: AdminRole + before: null + after: + fields: [id, name, system, created_at] + - name: AdminPermission + before: null + after: + fields: [code] + catalog: + - admin.users.read + - admin.users.membership.grant + - admin.users.ask_quota.grant + - admin.orders.read + - admin.audit.read + - admin.analytics.read + - admin.content.write + - admin.roles.read + - admin.roles.write + - name: AdminAccount + before: + fields: [id, username, password_hash, status] + after: + fields: [id, username, password_hash, status, role_id] + +apis: + - method: GET + path: /api/v1/admin/roles + change: added + - method: GET + path: /api/v1/admin/roles/{id} + change: added + - method: PUT + path: /api/v1/admin/roles/{id}/permissions + change: added + - method: GET + path: /api/v1/admin/me + change: modified + response_delta: "add role + permissions[]" + +security_impact: + - "RequirePermission on mutating admin routes" + - "403 + AuditLog on deny" + +observability_impact: + - "AuditLog on roles.permissions.update and permission denials" diff --git a/docs/CONTRACT_DIFF/README.md b/docs/CONTRACT_DIFF/README.md new file mode 100644 index 0000000..1871325 --- /dev/null +++ b/docs/CONTRACT_DIFF/README.md @@ -0,0 +1,10 @@ +# CONTRACT_DIFF + +Per-implement-ECR instances live here. + +| File | ECR | Phase | +|------|-----|-------| +| [ECR-013A.yaml](ECR-013A.yaml) | ECR-013A | Contract Definition(Draft) | + +Template: `docs/WAVE0/contracts/contract_diff.template.yaml` +P0:无 contract_diff 不得 Approve coding。 diff --git a/docs/ECR/ECR-013A-admin-rbac.md b/docs/ECR/ECR-013A-admin-rbac.md new file mode 100644 index 0000000..6ef8ee6 --- /dev/null +++ b/docs/ECR/ECR-013A-admin-rbac.md @@ -0,0 +1,75 @@ +# ECR-013A + +**Title:** Admin RBAC(角色 · 权限点 · API 强制鉴权) +**Status:** **Closed** +**Date:** 2026-08-07 +**Approved:** 2026-08-07(Human) +**Coding Start Authorization:** 2026-08-07(Human) +**Closed:** 2026-08-07(Reviewer Approve) +**Parent:** WAVE0-FROZEN (`27f27a1`) +**Change Level: L2**(行为:管理员授权模型;栈与分层不变) + +## Change + +1. Active Feature Spec:`.ai/product/feature-spec/ops-rbac.md` +2. Domain:`AdminRole` · `AdminPermission`;`AdminAccount.role_id` +3. API 意图:`GET/PUT /api/v1/admin/roles*` · 扩展 `GET /me` permissions +4. 既有 admin 写路径挂 permission;缺权 403 + AuditLog +5. **contract_diff**:`docs/CONTRACT_DIFF/ECR-013A.yaml`(P0) +6. **不含** UserStatus / 账户启停(ECR-013B) + +## Motivation + +Ops-A 管理员权限扁平;进入多运营角色与 M1+ 前必须有可审计的最小权限模型。 + +## Scope + +### Allowed + +- 上列 Spec / Domain / API 意图 / BD Draft / AC(四类) +- feature-map §7 · TRACEABILITY · STATE · TASK(architect) + +### Forbidden(Non-goals) + +- ECR-013B AccountLifecycle(另 Start Authorization) +- 真支付 · UGC · Prompt · 兑换码 · Crisis · 完整角色编辑 UI(本切片 API-first + me 最小展示) + +## Risk + +| Risk | Mitigation | +|------|------------| +| 锁死全部管理员 | 种子 `super_admin` 不可删;bootstrap 保留 | +| 权限码膨胀 | 本切片冻结 catalog;新增须新 ECR | +| 与 Ops-B/C 路由遗漏挂权 | ENGINEERING_SPEC 列清单;integration 覆盖 grant/content | + +## Acceptance Criteria + +见 Spec `ops-rbac.md` L4:AC-F-01..03 · AC-S-01..04 · AC-P-01 · AC-O-01..02(实现轮勾选) + +契约 / 实现完成标准: + +- [x] L0–L4 填满 +- [x] contract_diff 已交 +- [x] BD Draft + HANDOFF +- [x] Human **Approve** ECR+BD + Coding Start Authorization +- [x] Migration + middleware + roles API + TEST_REPORT +- [x] Reviewer Approve → **Closed** + +## Rollback + +- down migration `000015` + 回退 permission middleware + +## Risk Review + +- Path: N/A + +## Linked + +- Feature Spec: `.ai/product/feature-spec/ops-rbac.md` +- PRODUCT_SPEC: `docs/PRODUCT_SPEC/ECR-013A-admin-rbac.md` +- ENGINEERING_SPEC: `docs/ENGINEERING_SPEC/ECR-013A-admin-rbac.md` +- BACKEND_DESIGN: `docs/BACKEND_DESIGN/BD-2026-013A-admin-rbac.md` +- CONTRACT_DIFF: `docs/CONTRACT_DIFF/ECR-013A.yaml` +- TEST_REPORT: `docs/TEST_REPORT/ECR-013A.md` +- CODE_REVIEW: `docs/CODE_REVIEW/ECR-013A.md` +- Parent: WAVE0-FROZEN diff --git a/docs/ENGINEERING_SPEC/ECR-013A-admin-rbac.md b/docs/ENGINEERING_SPEC/ECR-013A-admin-rbac.md new file mode 100644 index 0000000..e1aa855 --- /dev/null +++ b/docs/ENGINEERING_SPEC/ECR-013A-admin-rbac.md @@ -0,0 +1,29 @@ +# ENGINEERING_SPEC — ECR-013A Admin RBAC + +权威设计:`docs/BACKEND_DESIGN/BD-2026-013A-admin-rbac.md` +产品:`.ai/product/feature-spec/ops-rbac.md` +**当前:Implemented · awaiting Reviewer。** + +## Implement order(已执行) + +1. Migration:`admin_roles` · `admin_role_permissions` · `admin_accounts.role_id` + 种子 `super_admin` +2. ERD / glossary 已有则对表 +3. Repo + service:Role 读写;Account 加载 permissions +4. Middleware:`RequirePermission(code)` 挂到既有写路由 + 新 roles 路由 +5. `GET /me` 扩展 permissions +6. OpenAPI `$ref` +7. admin-h5:`/me` 读权限,无权限隐藏 CTA(不做完整角色编辑 UI 也可先 API-only) +8. Integration:AC-F/S/O;Perf 抽样 AC-P-01 +9. TEST_REPORT · CODE_REVIEW · TRACEABILITY + +## Constraints + +- 函数 ≤50 · 文件 ≤400 +- Handler → Service → Repository +- 禁止改 DeviceAuth +- 禁止 UserStatus(013B) +- 不提交密钥 + +## Done when + +ECR Acceptance + 四类 AC 映射绿 + `ess-validate --phase review` + boundary-rules 无回归 diff --git a/docs/HANDOFF/ECR-013A-architect-to-engineer.md b/docs/HANDOFF/ECR-013A-architect-to-engineer.md new file mode 100644 index 0000000..af79863 --- /dev/null +++ b/docs/HANDOFF/ECR-013A-architect-to-engineer.md @@ -0,0 +1,31 @@ +# HANDOFF — ECR-013A Architect → Engineer + +## Gate + +**Parent:** WAVE0-FROZEN (`27f27a1`) + +**ECR-013A + BD-2026-013A = Approved(2026-08-07 Human)** +**Coding Start Authorization: 2026-08-07(Human)→ Engineer 可改 `apps/`。** + +## Consume + +1. `.ai/product/feature-spec/ops-rbac.md` +2. ECR / PRODUCT / ENGINEERING / BD / `docs/CONTRACT_DIFF/ECR-013A.yaml` +3. `.ai/domain/boundary-rules.md` · `glossary.yaml` + +## Do + +按 ENGINEERING_SPEC Implement order。 + +## Do not + +- UserStatus / ECR-013B +- 真支付 · UGC · Prompt +- 跳过 Security AC + +## Return + +1. HANDOFF engineer→reviewer +2. TEST_REPORT 映射全部 AC-ID +3. CODE_REVIEW +4. `ess-validate --phase review --ecr ECR-013A` diff --git a/docs/HANDOFF/ECR-013A-engineer-to-reviewer.md b/docs/HANDOFF/ECR-013A-engineer-to-reviewer.md new file mode 100644 index 0000000..aa3a775 --- /dev/null +++ b/docs/HANDOFF/ECR-013A-engineer-to-reviewer.md @@ -0,0 +1,19 @@ +# HANDOFF — ECR-013A Engineer → Reviewer + +## Done + +- Migration `000015_admin_rbac`:roles / permissions / `admin_accounts.role_id` + 种子 `super_admin` +- Middleware `RequireAdminPermission`;既有 admin 读写路由挂权限 +- API:`GET /roles` · `GET /roles/:id` · `PUT /roles/:id/permissions`;`GET /me` + login 返回 `role` + `permissions[]` +- OpenAPI + admin-h5 me/store 最小展示 +- Integration `TestAdminRBAC` 映射 AC-F/S/P/O +- `docs/TEST_REPORT/ECR-013A.md` + +## Evidence + +`docs/TEST_REPORT/ECR-013A.md` · Spec `.ai/product/feature-spec/ops-rbac.md` + +## Ask + +Reviewer 勾选 `docs/CODE_REVIEW/ECR-013A.md`;Approve 后可将 ECR-013A 标 Closed。 +**勿自动启动 ECR-013B**(需另次 Human Start Authorization)。 diff --git a/docs/PRODUCT_SPEC/ECR-013A-admin-rbac.md b/docs/PRODUCT_SPEC/ECR-013A-admin-rbac.md new file mode 100644 index 0000000..ee1cbd2 --- /dev/null +++ b/docs/PRODUCT_SPEC/ECR-013A-admin-rbac.md @@ -0,0 +1,50 @@ +# PRODUCT_SPEC — ECR-013A Admin RBAC + +对齐 Feature Spec:`.ai/product/feature-spec/ops-rbac.md` +Parent: **WAVE0-FROZEN** (`27f27a1`) +Phase: **Contract Definition**(No Coding) + +## Meta + +| 字段 | 值 | +|------|-----| +| ECR | ECR-013A | +| Status | Draft | +| Capability (L0) | `AdminGovernance` | +| Bounded Context (L1) | `Admin_RBAC` | +| Change Level | L2 | + +## L0 Capability + +| 字段 | 内容 | +|------|------| +| Capability ID | `AdminGovernance` | +| Purpose | 最小权限约束管理员运营动作 | +| Why now | 扁平 Admin 无法支撑多角色与越权审计 | +| Non-goals | AccountLifecycle(013B) · 真支付 · UGC · Prompt | + +## L1 Bounded Context + +见 `.ai/domain/boundary-rules.md` → `Admin_RBAC`。 + +## L2 Domain + +`AdminRole` · `AdminPermission` · `AdminAccount.role_id` — glossary 已登记。 + +## L3 API + +见 Spec §L3;`docs/CONTRACT_DIFF/ECR-013A.yaml`。 + +## L4 AC + +Spec AC-F / AC-S / AC-P / AC-O 全表 — 实现轮 TEST_REPORT 必须引用 ID。 + +## Outcome(实现后) + +1. 角色权限可配置且可审计 +2. 缺权 403 +3. `GET /me` 暴露 permissions 供 admin-h5 隐藏无权限入口(最小) + +## Out of scope + +ECR-013B;Payment;Community。 diff --git a/docs/PROJECT_PROFILE.md b/docs/PROJECT_PROFILE.md index df8a86e..8fe5a7b 100644 --- a/docs/PROJECT_PROFILE.md +++ b/docs/PROJECT_PROFILE.md @@ -46,9 +46,10 @@ ## Active anchors -- ECR: **ECR-012** 星座对齐(**Implemented** · review);ECR-006~008 Ops A/B/C Closed;ECR-001–005 Closed +- ECR: **ECR-013A Closed**;**WAVE0-FROZEN** @ 27f27a1;ECR-012 Implemented(review);Next=ECR-013B - EXP: (无) -- STATE: `docs/STATE/ECR-012.md`(owner=reviewer) +- STATE: `docs/STATE/ECR-013A.md` +- Ops foundation: `docs/WAVE0/` · `.ai/domain/boundary-rules.md` · `glossary.yaml` - TRACEABILITY: `docs/TRACEABILITY.md` - ADR: `.ai/adr/0007-ess-ai-dual-track.md` - Product status: `.ai/product/p1-status.md`(**P1 Complete**) diff --git a/docs/STATE/ECR-013A.md b/docs/STATE/ECR-013A.md new file mode 100644 index 0000000..27a0505 --- /dev/null +++ b/docs/STATE/ECR-013A.md @@ -0,0 +1,18 @@ +# STATE — ECR-013A + +| Field | Value | +|-------|-------| +| ECR | ECR-013A | +| Title | Admin RBAC | +| Status | **Closed** | +| Phase | closed | +| Owner | — | +| Parent | WAVE0-FROZEN (`27f27a1`) | +| Spec | `.ai/product/feature-spec/ops-rbac.md` | +| Backend Design | BD-2026-013A **Approved** | +| Contract Diff | `docs/CONTRACT_DIFF/ECR-013A.yaml` | +| Test | `docs/TEST_REPORT/ECR-013A.md` | +| Review | `docs/CODE_REVIEW/ECR-013A.md` **Approve → Closed** | +| Updated | 2026-08-07 | + +Reviewer Approve(Human)。Next 切片:ECR-013B(另 Start Authorization)。 diff --git a/docs/TASKS/TASK-013A-ECR013A.yaml b/docs/TASKS/TASK-013A-ECR013A.yaml new file mode 100644 index 0000000..4e91613 --- /dev/null +++ b/docs/TASKS/TASK-013A-ECR013A.yaml @@ -0,0 +1,17 @@ +id: TASK-013A-ECR013A +ecr: ECR-013A +title: Admin RBAC Closed +role: reviewer +status: closed +change_level: L2 +parent: WAVE0-FROZEN +inputs: + - docs/HANDOFF/ECR-013A-engineer-to-reviewer.md + - docs/TEST_REPORT/ECR-013A.md + - docs/CODE_REVIEW/ECR-013A.md +outputs: + - CODE_REVIEW Approve → Closed +acceptance: + - Spec AC-F/S/P/O mapped in TEST_REPORT + - No UserStatus / 013B + - boundary-rules Admin_RBAC respected diff --git a/docs/TEST_REPORT/ECR-013A.md b/docs/TEST_REPORT/ECR-013A.md new file mode 100644 index 0000000..50fe0a0 --- /dev/null +++ b/docs/TEST_REPORT/ECR-013A.md @@ -0,0 +1,51 @@ +# TEST_REPORT — ECR-013A Admin RBAC + +Date: 2026-08-07 +ECR: ECR-013A · BD-2026-013A +Parent: WAVE0-FROZEN (`27f27a1`) + +## Commands + +```bash +export PATH="$HOME/.local/go/bin:$PATH" +cd apps/api && go test ./internal/integration/ -run 'TestAdmin(Ops|RBAC)' -count=1 -timeout 120s +cd ../.. && npm run build:admin +python3 scripts/ess-validate.py --phase review --ecr ECR-013A +``` + +## Results + +| Check | Result | +|-------|--------| +| `TestAdminOpsPhaseA` | PASS | +| `TestAdminRBAC` | PASS | +| `build:admin` | PASS | +| `ess-validate --phase review` | PASS | + +## AC mapping + +| AC-ID | Evidence | +|-------|----------| +| AC-F-01 | `TestAdminRBAC` GET `/roles` 含 `super_admin` | +| AC-F-02 | PUT limited role permissions → GET 一致 | +| AC-F-03 | GET `/me` 含 `permissions[]` + `role` | +| AC-S-01 | limited admin PUT permissions → **403** + `permission.denied` audit | +| AC-S-02 | limited admin membership/grant → **403** | +| AC-S-03 | 无 Admin session GET `/roles` → **401** | +| AC-S-04 | `DELETE super_admin` 受 FK/system 约束失败;无 DeleteRole API | +| AC-P-01 | GET `/roles` 本机 < 500ms | +| AC-O-01 | AuditLog `roles.permissions.update` | +| AC-O-02 | AuditLog `permission.denied`(含 permission/path meta) | + +## Scope guard + +- 无 UserStatus / ECR-013B +- 无真支付 · UGC · Prompt +- AdminAuth ≠ DeviceAuth +- Migration `000015_admin_rbac` + +## Notes + +- admin-h5:`/me` 读 `role` + `permissions`;Shell 只读展示(最小) +- 完整角色编辑 UI 未做(API-first) +- **不自动启动 ECR-013B** diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index 3c939eb..232550e 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -16,3 +16,4 @@ | ECR-008 | 运营内容 Ops-C(首页宫格 + 测评上下架) | **Closed** | Spec Active · BD-2026-008 · TEST_REPORT · CODE_REVIEW · STATE | | ECR-012 | 星座对齐收口(星盘 · outlook · 合盘) | **Implemented** | Spec star-profile · BD-2026-012 · TEST_REPORT · HANDOFF review | | WAVE-0 | Ops Contract-First Foundation | **FROZEN** (`WAVE0-FROZEN` @ 27f27a1) | `docs/WAVE0/` · HUMAN_REVIEW FREEZE · boundary-rules · glossary · contract template | +| ECR-013A | Admin RBAC | **Closed** | Spec ops-rbac · BD-2026-013A · migration 000015 · TEST_REPORT · CODE_REVIEW Approve · Parent WAVE0-FROZEN | diff --git a/docs/WAVE0/HUMAN_REVIEW.md b/docs/WAVE0/HUMAN_REVIEW.md index ff4d1a3..9546df4 100644 --- a/docs/WAVE0/HUMAN_REVIEW.md +++ b/docs/WAVE0/HUMAN_REVIEW.md @@ -44,6 +44,7 @@ ```text Tag: WAVE0-FROZEN Commit: 27f27a1 -Next: ECR-013A Admin RBAC — Contract Definition (No Coding) -Requires: Human Start Authorization (Loop does not auto-start) +ECR-013A: Closed (2026-08-07) +Next authorized: ECR-013B AccountLifecycle — Contract Definition (2026-08-07 Start Authorization) +Coding 013B: NOT authorized — await Human Approve ECR-013B + BD + coding Start Authorization ``` diff --git a/proto/openapi.yaml b/proto/openapi.yaml index f158289..1e05353 100644 --- a/proto/openapi.yaml +++ b/proto/openapi.yaml @@ -74,10 +74,73 @@ paths: /api/v1/admin/me: get: tags: [admin] - summary: Current admin + summary: Current admin (role + permissions[]) responses: '200': description: OK + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Envelope' + - type: object + properties: + data: + $ref: '#/components/schemas/AdminMe' + + /api/v1/admin/roles: + get: + tags: [admin] + summary: List admin roles + description: Requires admin.roles.read + responses: + '200': + description: OK + '403': + description: Forbidden + + /api/v1/admin/roles/{id}: + get: + tags: [admin] + summary: Role detail with permissions + description: Requires admin.roles.read + parameters: + - $ref: '#/components/parameters/Id' + responses: + '200': + description: OK + '403': + description: Forbidden + '404': + description: Not found + + /api/v1/admin/roles/{id}/permissions: + put: + tags: [admin] + summary: Replace role permission set + description: Requires admin.roles.write; writes AuditLog + parameters: + - $ref: '#/components/parameters/Id' + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [permissions] + properties: + permissions: + type: array + items: { type: string } + responses: + '200': + description: OK + '400': + description: Invalid permission code + '403': + description: Forbidden + '404': + description: Not found /api/v1/admin/users: get: @@ -887,6 +950,17 @@ components: message: { type: string, example: success } data: { type: object } + AdminMe: + type: object + required: [id, username, permissions] + properties: + id: { type: string, format: uuid } + username: { type: string } + role: { type: string } + permissions: + type: array + items: { type: string } + CreateProfileRequest: type: object required: [relation, birth_date]