Files
co-lite/openspec/changes/add-admin-auth-users-roles/design.md
T
ngqileandClaude Opus 5.5 92c8ad3b25 docs(openspec): close admin self-escalation found in review
A non-super admin cannot change their own roles or the grants of a role they hold,
hidden roles cannot be assigned, and the direct set-password endpoint goes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 22:22:49 +08:00

86 lines
8.4 KiB
Markdown

# Design
## Context
- The admin portal in `solvway-admin-portal` is babyboo's full back office. Its kept screens call portal route handlers (`app/api/**`), which call `mobile-api` `/api/admin/**` through `callMobileApi` with the `api-key` header and the JWT as a Bearer token. The session is a sealed cookie (`bb_admin` by default).
- Co-Lite's `mobile-api` has no `/api/admin/**` controllers. `AppAccessAspect` checks the api-key and JWT signature and expiry only, so any valid token (member or admin) passes.
- Babyboo's `mobile-api` already solves this: `AdminAuthController`, `AdminUserController`, `AdminRoleController`, their services, `@AdminModule`, `AdminModuleAccess`, `AdminSessionGuard` and the admin checks in its `AppAccessAspect`, with unit tests. Babyboo and Co-Lite share the Solvway base, and Co-Lite's `services-system` and `services-auth` already expose every downstream endpoint those services call except the module-management and group endpoints we drop.
- `services-auth` `POST /auth/authenticate` issues admin (type A) tokens and answers 200 with an empty body on failure. `/auth/findUserByToken/BO/{token}` returns the admin user with roles and ACL menu, and returns nothing for a token stored as logged out by `/auth/logoutToken/{token}` (Redis).
- `services-system` `/user/resetAdminPassword` takes username and email, checks they match an admin, sets a random 8-character password with login status N (change required), and emails it.
- Tastefully's module rows use area `A`; babyboo's portal reads area `BO` with names like `BO_USERS`.
## Goals / Non-Goals
**Goals:**
- Port, not rewrite: take babyboo's admin classes and tests, then cut what depends on dropped features.
- Every rule in the specs is pinned by a test before it is implemented (porting rule in `CLAUDE.md`).
**Non-Goals:**
- Login throttling or lockout, session-policy timeouts, Google sign-in, user groups, module management, audit log, country scope.
- Changing member (customer-portal) auth.
## Decisions
### 1. Port babyboo's admin layer into `mobile-api`, trimmed
Copy `AdminAuthController`, `AdminUserController`, `AdminRoleController`, their services and DTOs, `AdminModule`, `AdminModuleAccess`, `AdminSessionGuard`, and the admin branch of babyboo's `AppAccessAspect` (`isAdminPath`, `isAdminToken`, revocation, session guard, `requireAdminModule`). Remove country scope, audit annotations, login-security and lockout handling, and anything that calls a dropped endpoint. Port the matching babyboo unit tests and adapt them; a dropped feature's tests go with it.
Alternative: write admin controllers fresh against Tastefully's backoffice controllers. Rejected: the portal already speaks babyboo's contract, and babyboo's version has the guard and tests we need.
### 2. Admin token check uses `findUserByToken/BO`
On an `/api/admin/**` path the aspect first reads the token's `USERTYPE` claim: anything but `A` is a 403. It then loads the user with `/auth/findUserByToken/BO/{token}`; no user (unknown or logged out) is a 401. `findUserByToken` did not check the logout list, so this change makes it return no user for a logged-out token, and adds `BO` to the `Area` enums in core-libs and services-system. `findUserByToken` also adds `ROLE_ADMIN` (id 2) to every admin, so the module check ignores role 2. The pending-reset 403 carries `code: PASSWORD_RESET_REQUIRED`, which the portal uses to redirect. The same lookup gives the roles for the module check and the enabled and login-status flags for the session guard (deactivated means 401; pending password change allows only first-login and logout, otherwise 403). This is one downstream call per admin request.
`ponytail:` no cache on this lookup; add a short-TTL cache keyed by token if admin latency matters.
Alternative: a JWT claim for user type. Rejected: needs a `services-auth` change and still needs the lookup for revocation and deactivation.
### 3. Wrong password becomes 401 in `mobile-api`
`AdminAuthController.login` maps an empty token from `/auth/authenticate` to 401. `services-auth` stays as is, so other callers (customer portal) are unaffected.
### 4. Forgot password reuses `/user/resetAdminPassword`
New public endpoint `POST /api/admin/auth/forgot-password` (`@AppAuth(skipValidate=true)`) with `{username, email}`. It calls `/user/resetAdminPassword` and always answers 200 with no body detail. The admin-triggered reset (`POST /api/admin/users/{id}/resetPassword`) looks up the user and calls the same endpoint with that user's username and email. The portal gets a `/forgot-password` page (added to `PUBLIC_PATHS`) linked from the login page.
The emailed password is plain text in the email body. That is Tastefully's existing behaviour, accepted for phase 1 because the user must change it at next login.
### 5. Company
`service-system` gets `company (id, name, create_date)` and `user.company_id BIGINT NULL` (nullable because member rows share the table). `services-system` `User` gains `companyId`. `AdminUserService.create` sets `companyId` from the logged-in admin, ignoring any value in the request. The seed sets company 1 on the dev admin.
### 6. Co-Lite back-office modules
Area `BO`, babyboo's id scheme: `40000000 BO_ROOT` (type R), `40700000 BO_USERS` (`/users`), `40800000 BO_ROLES` (`/roles`). Tastefully's area-`A` rows stay in the table and never show, because the portal reads area `BO`. The portal's `FIXED_PROTECTED_MODULE_NAMES` and `routeModules` are cut to the names that exist.
### 7. Roles shown
The role list hides `ROLE_MEMBER` and `ROLE_ADMIN` (id 2, attached to every admin by `findUserByToken` and ignored by the module check). The local seed drops Tastefully's business roles (KYC, merchant, staff and the rest) and keeps `ROLE_SUPER_ADMIN` (1), `ROLE_ADMIN` (2) and `ROLE_MEMBER` (3).
### 8. Portal cut-down
Delete by directory: every `app/` route, `app/api/` family, `app/components/` folder and test not used by the kept screens (list in proposal). Then remove `package.json` dependencies with no remaining import. Rename the cookie default to `colite_admin` and replace babyboo branding strings. The kept-screen tests and the shell and middleware tests must stay green; i18n keys for removed screens go with them.
### 9. Smoke check
`local/smoke.sh` logs in through `POST :8080/api/admin/auth/login` and then calls `GET :8080/api/admin/me` and `GET :8080/api/admin/users`, replacing the gateway login. The service-counter read and the public call stay.
## Risks / Trade-offs
- [Anyone who knows a username and its email can reset that password, locking the user out until they read the email] → Accepted for phase 1 (staff-only, small team). The response never reveals a match. Throttling comes back with babyboo's login-security later.
- [The ported aspect is security code copied across codebases] → Each guard rule has a ported or new test, and the reviewer reads the whole aspect diff.
- [Deleting most of the portal breaks shared imports in ways tests miss] → `npm run build` and `npm run lint` must pass, not only `vitest`.
- [Forgot-password takes longer when the details match (bcrypt plus an email), so timing can hint at a match] → Accepted for phase 1; the body is identical either way.
- [services-auth issues a token to a deactivated admin] → The admin login checks `enabled` and revokes that token before answering 401; `/user/resetAdminPassword` now refuses deactivated users.
- [A non-super admin with `BO_USERS` or `BO_ROLES` could use one module to gain the other] → A non-super admin cannot change their own roles or the grants of a role they hold, and nobody can assign `ROLE_ADMIN` or `ROLE_MEMBER`. They can still give a colleague any visible role; a subset rule (assign only what you hold) is deferred.
- [The gateway token bypass for `/user/resetAdminPassword` returns the updated-row count (1 or 0) to anyone with a gateway api-key allowed on `/user/`] → Gateway keys stay internal (mobile-api only); the public endpoint in mobile-api always answers the same.
- [Plain-text temporary password in email] → Forced change at next login; revisit with real SMTP in change 5.
## Migration Plan
Additive SQL in `sql/` of this change, run against `service-system`:
1. `01-company.sql`: create `company`, add `user.company_id`, insert company 1.
2. `02-bo-modules.sql`: insert the three BO module rows.
Nothing is deployed, so there is no live data. The same statements are mirrored into `local/seed/`. Rollback: drop the column, the table and the rows (`sql/99-rollback.sql`).