docs(32.2): add code review reports

This commit is contained in:
Jakub Zych
2026-11-21 02:41:41 +01:00
parent 75f45933b8
commit 7a2b4954be
2 changed files with 572 additions and 0 deletions

View File

@@ -0,0 +1,338 @@
---
phase: 32.2-mcp-oauth-with-administrator-subjects
reviewed: 2026-11-21T12:00:00Z
depth: standard
scope: sibling repos ../sm-oauthserver-plugin (7b9899f..HEAD) and ../sm-grzybyfunkcjonalne-app (c06a2d8..HEAD)
files_reviewed: 51
files_reviewed_list:
- ../sm-oauthserver-plugin/README.md
- ../sm-oauthserver-plugin/account.go
- ../sm-oauthserver-plugin/admin.go
- ../sm-oauthserver-plugin/admin_navigation.go
- ../sm-oauthserver-plugin/admin_permissions.go
- ../sm-oauthserver-plugin/admin_smoke_test.go
- ../sm-oauthserver-plugin/backend_account_smoke_test.go
- ../sm-oauthserver-plugin/backend_consent_test.go
- ../sm-oauthserver-plugin/backend_grant_rows_test.go
- ../sm-oauthserver-plugin/backend_mode_smoke_test.go
- ../sm-oauthserver-plugin/backend_mode_test.go
- ../sm-oauthserver-plugin/backend_revocation_smoke_test.go
- ../sm-oauthserver-plugin/backend_revoke_test.go
- ../sm-oauthserver-plugin/backend_subject_migration_test.go
- ../sm-oauthserver-plugin/backend_tools_test.go
- ../sm-oauthserver-plugin/classes/backend_cascade.go
- ../sm-oauthserver-plugin/classes/lazy.go
- ../sm-oauthserver-plugin/classes/mcp_backend_subject.go
- ../sm-oauthserver-plugin/classes/mcp_store.go
- ../sm-oauthserver-plugin/classes/mcp_verifier.go
- ../sm-oauthserver-plugin/config/config.yaml
- ../sm-oauthserver-plugin/controllers/mcp_admin_consent.go
- ../sm-oauthserver-plugin/controllers/mcp_connections.go
- ../sm-oauthserver-plugin/controllers/mcpconnections/config_list.yaml
- ../sm-oauthserver-plugin/harness_test.go
- ../sm-oauthserver-plugin/jwt_only_test.go
- ../sm-oauthserver-plugin/lang/en/lang.yaml
- ../sm-oauthserver-plugin/lang/pl/lang.yaml
- ../sm-oauthserver-plugin/models/consent.go
- ../sm-oauthserver-plugin/models/mcp_connection.go
- ../sm-oauthserver-plugin/models/mcpconnection/columns.yaml
- ../sm-oauthserver-plugin/plugin.go
- ../sm-oauthserver-plugin/routes.go
- ../sm-oauthserver-plugin/servers.go
- ../sm-oauthserver-plugin/updates/202611200001_add_golem15_oauthserver_backend_subjects.go
- ../sm-grzybyfunkcjonalne-app/.gitmodules
- ../sm-grzybyfunkcjonalne-app/DEPLOY.md
- ../sm-grzybyfunkcjonalne-app/README.md
- ../sm-grzybyfunkcjonalne-app/boot_test.go
- ../sm-grzybyfunkcjonalne-app/config/golem15.oauthserver.yaml
- ../sm-grzybyfunkcjonalne-app/config/mcp.yaml
- ../sm-grzybyfunkcjonalne-app/deploy/env.example
- ../sm-grzybyfunkcjonalne-app/deploy/nginx/grzybyfunkcjonalne-production.conf
- ../sm-grzybyfunkcjonalne-app/deploy/nginx/grzybyfunkcjonalne-staging.conf
- ../sm-grzybyfunkcjonalne-app/go.mod
- ../sm-grzybyfunkcjonalne-app/go.work
- ../sm-grzybyfunkcjonalne-app/plugins/golem15/oauthserver
- ../sm-grzybyfunkcjonalne-app/scripts/build.sh
- ../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh
- ../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh
- ../sm-grzybyfunkcjonalne-app/summer.yaml
findings:
critical: 1
warning: 9
info: 8
total: 18
status: issues_found
---
# Phase 32.2: Code Review Report (sm-oauthserver-plugin and sm-grzybyfunkcjonalne-app)
**Reviewed:** 2026-11-21T12:00:00Z
**Depth:** standard
**Files Reviewed:** 51
**Status:** issues_found
## Summary
Reviewed the backend-subject mode of sm-oauthserver-plugin (7b9899f..HEAD: 6996ffe, 9b97466, 4c209c1, bae8222, 793eadd, 1124fd1) and the first consumer wiring in sm-grzybyfunkcjonalne-app (c06a2d8..HEAD: 2953bf8, f2dc85d, df554d5). Framework code (cabana, wristband, pier) was read only where the plugin calls into it. A sibling reviewer covers the framework itself.
**User mode stays unchanged by default.** That holds for routes, scopes, admin surface, account contributions and listeners. Every new surface is gated on `cfg.BackendMode()`. Every user-mode query filters on `user_id`, so it never sees the `user_id IS NULL` rows. There are three global changes:
- the NOT VALID CHECK constraints, which every app gets;
- the verifier's new backend branch, which is not gated on mode (WR-05);
- the consents column, which needs `migrate` to run before the new binary.
**Lock design.** The design is sound:
- shared `golem15_oauthserver_backend_grants:<id>` on code exchange and refresh;
- exclusive on revocation, consent issue and bulk revoke;
- ascending id order.
The weak points are elsewhere:
- the refresh path asks for a second pool connection while it holds a transaction (WR-01);
- transient errors are turned into terminal `invalid_grant`/401 (WR-02);
- the consent decision does not re-validate the administrator inside the lock, and the exchange never validates it, so a race can mint a grant past a password-change cutoff (WR-03);
- the per-admin lock does not serialize two administrators deciding the same request (WR-04).
**App.** The committed app state is not deployable. The gitlink, go.mod and plugins.gen.go are still pinned to v0.1.7, which predates backend mode and ignores the new keys, and check-deploy.sh cannot detect it (CR-01). The nginx locations are correct: exact or prefix matches, method limits, a 64k body cap, `auth_basic off` on staging, and no `add_header`, which is enforced globally. The smoke script never prints a secret. It does put the passwords and the authorization code on jq's argv, which contradicts its stated guarantee (WR-08). The DEPLOY.md rollback boots, but it leaves administrators' grants alive for a later re-enable (WR-07).
## Critical Issues
### CR-01: App master pins oauthserver v0.1.7, which ignores `mcp.subject`/`oidc.enabled`, and check-deploy cannot tell
**File:** `../sm-grzybyfunkcjonalne-app/plugins/golem15/oauthserver` (gitlink 7b9899f), `../sm-grzybyfunkcjonalne-app/go.mod:12`, `../sm-grzybyfunkcjonalne-app/plugins.gen.go:42`, `../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh:372-395`
**Issue:**
- **The pin.** At app HEAD (df554d5) the committed gitlink is `7b9899f`, which is v0.1.7. go.mod requires `v0.1.7`, and plugins.gen.go records `Version: "v0.1.7"`.
- **What v0.1.7 does with this config.** DEPLOY.md:428 says it: "v0.1.7 and older ignore these keys and would serve a user-mode OAuth server with OpenID Connect". A fresh clone with `git submodule update --init` therefore builds a binary that:
- mounts the OIDC provider;
- runs MCP OAuth in **user** mode, with authorize handing off to Nuxt `/connect` instead of `/gfadmin/connect`;
- mounts the frontend-user consent JSON `/oauth/mcp/requests/{request}` (jwt.auth).
- **nginx exposes it.** The new `location ^~ /oauth/mcp/` in both vhosts sends that consent JSON to Go. A frontend user session could then finish MCP requests with the user-mode scopes (`read`, `write`, `backend`).
- **Nothing catches it.**
- `TestBootUserTranslateJournal` fails at these commits (32.2-04-SUMMARY, "Notes on the plan text").
- `check-deploy.sh` passes: it only greps `config/golem15.oauthserver.yaml` and summer.yaml, and never checks that the compiled plugin understands those keys.
- **Why it blocks.** This intermediate state is known and documented, and the release is on hold, but nothing stops it from shipping. A push of app master, or a deploy from it, runs the wrong security model with no error.
**Fix:** Do not push app master until the plan 05 pointer bump (gitlink, go.mod require and plugins.gen.go moved to the plugin release that contains 4c209c1). Also make check-deploy refuse a plugin without backend mode, for example:
```bash
# The compiled oauthserver must know mcp.subject backend (v0.1.8+).
grep -qF 'SubjectModeBackend = "backend"' "$ROOT/plugins/golem15/oauthserver/classes/mcp_backend_subject.go" 2>/dev/null ||
fail "plugins/golem15/oauthserver predates mcp.subject backend; bump the submodule"
grep -Eq 'golem15\.oauthserver.*Version: "v0\.1\.[0-7]"' "$ROOT/plugins.gen.go" &&
fail "plugins.gen.go pins golem15.oauthserver to a release without backend mode"
```
## Warnings
### WR-01: Administrator refresh asks the pool for a second connection while holding the rotation transaction
**File:** `../sm-oauthserver-plugin/classes/mcp_store.go:432-438`
**Issue:**
- **What happens.** `refreshUserUsable` runs inside wristband's `WithinTx`, which holds one pooled connection plus the shared advisory lock. For a backend row it calls `cabana.BackendPrincipal(ctx, t.app, …)`. That resolves to `lazyBackendUsers.FindByID`, which takes the app's `*gorm.DB` and runs `First(&user, id)` on a **different** pool connection (cabana/http.go:304-312, auth.go:44).
- **Why it hangs.** With N concurrent refresh rotations and a pool of N, every connection is held by a transaction waiting for a second connection. The pool deadlocks until the context times out. Postgres cannot detect this.
- **Inconsistency.** The user-mode branch right below it uses the transaction (`userclasses.PrincipalByID(ctx, t.db…)`).
**Fix:** Load the administrator through the transaction. Either query `backend_users` with `t.db`, or add a cabana helper that takes a `*gorm.DB`:
```go
if backendRefreshRow(m) {
principal, err := cabana.BackendPrincipalTx(ctx, t.app, t.db, *m.BackendUserID) // reads with t.db
...
}
```
Alternatively, resolve the principal before `WithinTx`. That is harder here, because the row is only known after the lookup.
### WR-02: A transient failure in the administrator lookup becomes a terminal `invalid_grant` or 401
**File:** `../sm-oauthserver-plugin/classes/mcp_store.go:434-437`, `../sm-oauthserver-plugin/classes/mcp_verifier.go:165-168`
**Issue:**
- **Refresh.** `err != nil || principal == nil` → `return false, nil`, and wristband answers `invalid_grant`.
- **Verifier.** The same condition answers `pact.ErrMCPTokenInvalid`, a 401.
- **Effect of a DB blip.** The access token gets a 401, so the client refreshes. The refresh gets `invalid_grant`, so the client (Claude, for example) drops the connection and the administrator has to sign in and consent again. A transient DB error, a context cancel or a pool timeout is enough.
- **User mode is different.** It returns `err` on lookup errors (mcp_store.go:445-447, mcp_verifier.go:124-127), which fails closed with a retryable 5xx.
- **Not a security fix.** Failing closed does not need the error to be terminal: a 500 also denies access.
**Fix:** Keep "nil principal" as unusable, and propagate real errors:
```go
principal, err := cabana.BackendPrincipal(ctx, t.app, *m.BackendUserID)
if err != nil {
return false, err
}
if principal == nil {
return false, nil
}
```
In `verifyBackend`, map `ErrUnauthenticated` (cabana not activated) to invalid and return other errors as they are.
### WR-03: The consent decision and the code exchange never re-validate the administrator under the lock
**File:** `../sm-oauthserver-plugin/controllers/mcp_admin_consent.go:129-144`, `../sm-oauthserver-plugin/classes/mcp_store.go:208-248`
**Issue:**
- **Where the check happens.** cabana authenticates the administrator and applies its scope policy before `MCPAdminConsentDecide` runs. The provider then takes the exclusive backend grants lock, but it never re-reads the administrator.
- **The race.** A password change, a password set or a deactivation runs in cabana's save transaction. It moves `tokens_valid_after` and takes the same exclusive lock in `RevokeBackendGrants`. A decision that passed cabana's check just before that save waits on the lock. After the save commits, it issues a fresh code and writes a consent.
- **The exchange does not check either.** `ByCodeHashForUpdate` only locks, so the exchange mints tokens whose `created_at` is **after** the new cutoff:
- after a password change (for example, to evict a stolen session), the attacker's in-flight consent leaves a fully valid OAuth grant, refresh included;
- after a deactivation, the minted grant is dormant and becomes valid again when the account is re-activated.
- **Leftover rows.** A consent row for the deactivated administrator also stays behind, and the admin list shows it.
**Fix:** Inside `WithinBackendGrantsLock`, after the lock, read the administrator with `tx` and refuse when they are inactive or deleted, or when their `tokens_valid_after` is later than the start of the request (pass the session's issued-at or the request time from cabana). Do the same check in `ByCodeHashForUpdate` for backend codes, as `refreshUserUsable` already does for refresh tokens:
```go
case owner.BackendUserID != nil:
if err := lockBackendGrantsShared(ctx, t.db, *owner.BackendUserID); err != nil { return nil, err }
// after taking the row: refuse when the administrator no longer loads or
// the code was issued before tokens_valid_after
```
### WR-04: Two administrators deciding the same pending request are not serialized, and the last writer silently wins
**File:** `../sm-oauthserver-plugin/classes/mcp_store.go:193-198` (ByRequestID, no row lock), `../sm-oauthserver-plugin/classes/mcp_store.go:321-322` (MarkIssued `WHERE id = ?`), `../sm-oauthserver-plugin/controllers/mcp_admin_consent.go:129`
**Issue:**
- **No serialization.** `WithinBackendGrantsLock(… []uint{adminID} …)` serializes only one administrator's own operations. A backend pending row keeps `user_id` NULL, so every administrator "owns" it (`lookupOwnedPending`).
- **The race.** `ByRequestID` reads without `FOR UPDATE`, and `MarkIssued` updates by id without any condition. When admins A and B both POST a decision for the same request, both read the unissued row. B's `UPDATE` waits on A's row lock, then overwrites `code_hash`, `scopes` and `backend_user_id`.
- **The result.** A's redirect carries a dead code. The client ends up with **B's** grant. B's consent row is written as well.
- **Scope.** The same unconditional `MarkIssued` exists in user mode. In backend mode it lets one administrator's approval silently become another administrator's grant.
**Fix:** Make the issue conditional and check the affected rows:
```go
res := t.db.WithContext(ctx).Model(&models.MCPCode{}).
Where("id = ? AND code_hash IS NULL AND request_id IS NOT NULL AND used_at IS NULL", id).
UpdateColumns(cols)
if res.Error != nil { return res.Error }
if res.RowsAffected != 1 { return wristband.ErrPendingNotFound }
```
Alternatively, row-lock the pending row in `ByRequestID` when it is called inside the decision transaction.
### WR-05: The verifier accepts administrator grants whatever the configured mode
**File:** `../sm-oauthserver-plugin/classes/mcp_verifier.go:121-123`, `../sm-oauthserver-plugin/classes/mcp_store.go:433-438`, `../sm-oauthserver-plugin/plugin.go:119-124`
**Issue:**
- **The ungated branch.** `token.UserID == 0 && token.BackendUserID != nil` routes to `verifyBackend` in user mode too. Refresh does the same through `backendRefreshRow`.
- **What survives a switch.** If an app switches `mcp.subject` from `backend` to `user` with `mcp.enabled` still true, every administrator grant keeps verifying and refreshing. At the same time:
- `BackendCascade` is no longer registered, so role, permission and superuser changes revoke nothing;
- the My account section is gone;
- the MCP connections screen and its permission are gone.
- **Consequence.** Nobody can see or revoke those grants from the UI. Only the `tokens_valid_after` and deactivated checks remain.
- **Docs.** The README states "One subject per application", but the code does not enforce it.
**Fix:** Give the verifier and the store the configured mode. In user mode, refuse backend-subject rows (`ErrMCPTokenInvalid`, refresh unusable). Alternatively, revoke all `user_id IS NULL` grants at boot when the mode is `user`.
### WR-06: The BackendCascade fallback without a transaction makes the revocation non-atomic and the lock a no-op
**File:** `../sm-oauthserver-plugin/classes/backend_cascade.go:36-44`, `../sm-oauthserver-plugin/classes/backend_cascade.go:48-53`
**Issue:**
- **The fallback.** When `ev.Tx` is nil, `txOf` returns the pool handle and `RevokeBackendGrants` runs on it.
- **What goes wrong.** `pg_advisory_xact_lock` then runs in autocommit, so the lock is released as soon as that statement ends. The SELECT, UPDATE and DELETE statements after it are separate transactions:
- a refresh rotation can mint a successor between the SELECT and the UPDATE, and the successor stays live;
- a failure part-way leaves the grants half revoked.
- **Today.** cabana passes a transaction at every site today, so this is latent. It is still the documented contract of `OnBackendAccessRevoked`.
**Fix:**
```go
if ev.Tx == nil {
db, err := lookupDB(c.App)
if err != nil { return err }
return lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
refs, err := RevokeBackendGrants(ctx, tx, ev.AdminIDs, "")
if err != nil { return err }
FireBackendRevokedAfterCommit(ctx, c.App, tx, refs)
return nil
})
}
```
### WR-07: The DEPLOY.md rollback leaves administrators' grants alive for a later re-enable
**File:** `../sm-grzybyfunkcjonalne-app/DEPLOY.md:440`
**Issue:**
- **What the rollback does.** `MCP__ENABLED=false` plus `MCP__SUBJECT=user` unmounts the routes and the verifier. The access tokens, refresh tokens and consents stay in the database.
- **Changes during the rollback are not applied.** `BackendCascade` is registered only in backend mode, so role, own-permission and superuser changes made during the rollback window revoke nothing. Password changes and deactivations are still caught by the cutoff check.
- **Re-enabling revives them.** Rolling forward again brings back every refresh token issued before the rollback, including grants an operator would expect to be gone after "rolling back OAuth".
- **Mode switch.** Combined with WR-05, `SUBJECT=user` with `ENABLED=true` (a plausible partial rollback) would keep them verifying.
**Fix:** Add a step that ends the grants. For example, run in psql:
`UPDATE golem15_oauthserver_access_tokens SET revoked_at = now() WHERE user_id IS NULL AND revoked_at IS NULL;`
Do the same for `golem15_oauthserver_refresh_tokens`, and `DELETE FROM golem15_oauthserver_consents WHERE user_id IS NULL;`. Alternatively, state plainly that re-enabling restores existing connections.
### WR-08: smoke-mcp-oauth.sh puts passwords, the authorization code and the PKCE verifier on process argv
**File:** `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh:344`, `:372`, `:391`, `:420-421`
**Issue:**
- **The claim.** The script header (lines 35-36) and 32.2-04-SUMMARY ("Access, refresh and personal tokens, the code and the passwords never reach a command line") promise that no secret reaches a command line.
- **What actually reaches argv:**
- `jq -n --arg l … --arg p "$ADMIN_PASSWORD"` (344);
- `jq -n … --arg c "$ADMIN_PASSWORD" --arg p "$NEW_PASSWORD"` (420-421);
- `jq -rn --arg u "$CALLBACK"`, where the callback URL holds the authorization code (372);
- `curl --data-urlencode "code_verifier=$VERIFIER"` (391).
- **Who can read it.** Every one of these is visible to other local users through `/proc/<pid>/cmdline` or `ps`.
- **Why it matters.** The values are throwaway, but the guarantee is false (T-32.2-24), and the script is the template the next app will copy.
**Fix:** Pass the values through the environment or files instead of argv:
```bash
login="$(L="$ADMIN_LOGIN" P="$ADMIN_PASSWORD" jq -n '{login: env.L, password: env.P}')"
raw="$(U="$CALLBACK" K="$1" jq -rn 'env.U | split("?")[1] | ...')"
printf 'code_verifier=%s' "$VERIFIER" >"$TMP/verifier"; curl ... --data-urlencode "code_verifier@$TMP/verifier"
```
Note that `VAR=x cmd` puts the value in the environment, not in argv.
### WR-09: The committed `mcp.resource` is loopback, and a missing env override fails silently
**File:** `../sm-grzybyfunkcjonalne-app/config/golem15.oauthserver.yaml:26`
**Issue:**
- **The default.** `resource: http://127.0.0.1:8096/mcp` is the committed value for every environment. Production and UAT depend on `SUMMER_GOLEM15__OAUTHSERVER__MCP__RESOURCE` in `go/.env`.
- **When the key is missing.** pier only logs a warning (DEPLOY.md:426). The AS advertises and accepts the loopback resource, and Claude's request for `https://grzybyfunkcjonalne.pl/mcp` fails.
- **Nothing guards it.** check-deploy, the boot test and the release steps do not check it.
- **The pieces already exist.** `mcp.yaml` derives its resource from `app.url`, so the two can drift.
**Fix:** Leave `resource` empty and have the plugin default it to `<app.url>/mcp` in backend mode. Alternatively, make a mismatch between pier's resource and the verifier's resource fail boot when both are configured. At minimum, add a post-deploy check that `/.well-known/oauth-protected-resource/mcp` `.resource` equals the authorization server's `resource`.
## Info
### IN-01: Migration rollback keeps administrators' MCP codes
**File:** `../sm-oauthserver-plugin/updates/202611200001_add_golem15_oauthserver_backend_subjects.go:46-48`
**Issue:** The rollback deletes `user_id IS NULL` access tokens, refresh tokens and consents. It does not delete issued but unexchanged MCP codes that have `user_id IS NULL AND backend_user_id IS NOT NULL`. Those rows survive the down migration as orphans that the older code cannot interpret. They expire quickly, but the README's "rollback deletes every administrator's grant" is not quite true.
**Fix:** Add `DELETE FROM golem15_oauthserver_mcp_codes WHERE user_id IS NULL AND backend_user_id IS NOT NULL AND code_hash IS NOT NULL`.
### IN-02: The Clients screen's authorizations partial silently drops administrators' consents
**File:** `../sm-oauthserver-plugin/controllers/clients.go:251-290`
**Issue:** The partial loads every consent for the client and looks up `consent.UserID` among frontend users. Backend consents (UserID 0) are skipped with `continue`, so an operator who inspects an MCP client sees no administrator connections.
**Fix:** Filter with `user_id IS NOT NULL` explicitly. Optionally, show the administrators' rows, or link to the MCP connections screen.
### IN-03: check-deploy's OpenID Connect location regex misses broader routes
**File:** `../sm-grzybyfunkcjonalne-app/scripts/check-deploy.sh:336`
**Issue:** The regex only finds the literal paths. `location ^~ /oauth/`, `location /oauth` or a regex such as `~ ^/oauth/(token|jwks)` would route the OIDC paths to Go and pass the check.
**Fix:** Refuse any `location` that matches `/oauth` other than the exact `^~ /oauth/mcp/`, the same way the `/_seo` check works.
### IN-04: The advisory lock keys are 32-bit `hashtext` values shared with the user-grants namespace
**File:** `../sm-oauthserver-plugin/classes/mcp_backend_subject.go:56-58`, `:70`, `:84`
**Issue:** `hashtext("golem15_oauthserver_backend_grants:N")` and the user-grants keys share one int4 space. A collision is unlikely but possible. It would make unrelated transactions contend, and transactions that take both kinds of lock (a cabana save firing both user-link and backend events) could deadlock.
**Fix:** Use the two-key form, `pg_advisory_xact_lock(<namespace const>, id)`.
### IN-05: Smoke step 12 does not prove the cascade or the refresh
**File:** `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh:417-432`
**Issue:** The 401 after the password change also follows from the `tokens_valid_after` check alone. If `BackendCascade` were not registered, the step would still pass. The refresh token obtained in step 9 is never used, so neither rotation nor refusal after revocation is covered end to end.
**Fix:** After the password change, also POST `grant_type=refresh_token`, with the token passed from a file, and expect 400 `invalid_grant`.
### IN-06: The refresh-token CHECK allows `user_id = 0`, unlike the access-token CHECK
**File:** `../sm-oauthserver-plugin/updates/202611200001_add_golem15_oauthserver_backend_subjects.go:38-39`
**Issue:** The comment says the CHECK refuses the zero `user_id` a GORM create of a zero uint writes. Only the access-token CHECK has `user_id > 0`. The refresh-token and consent CHECKs accept `user_id = 0` with `backend_user_id` NULL.
**Fix:** Use the same `(user_id IS NOT NULL AND user_id > 0) OR backend_user_id IS NOT NULL` on all three tables.
### IN-07: A wall-clock sleep in a Docker test
**File:** `../sm-oauthserver-plugin/backend_revoke_test.go:298-321`
**Issue:** The test sets the cutoff to `time.Now()+1s` and then sleeps 2.1 s, relying on the verifier's one-second margin and on the app and DB clocks matching. On a loaded CI host this is a source of flakiness, and it adds 2 s to every run.
**Fix:** Write a cutoff in the past relative to a controllable clock (the verifier has `clock()`), or set `tokens_valid_after` to `now - 1s` and create the fresh grant after it.
### IN-08: nginx `limit_except` refuses CORS preflight on the authorization server endpoints
**File:** `../sm-grzybyfunkcjonalne-app/deploy/nginx/grzybyfunkcjonalne-production.conf:229-261` (same in staging)
**Issue:** `limit_except GET HEAD` and `limit_except GET POST` return 403 for `OPTIONS`. Browser-based MCP clients, such as the MCP Inspector, preflight the metadata and token endpoints, so they cannot connect. Claude's server-side connector is not affected.
**Fix:** If browser clients are in scope, allow `OPTIONS` and let the plugin answer CORS. Otherwise, document that only server-side connectors are supported.
---
_Reviewed: 2026-11-21T12:00:00Z_
_Reviewer: Claude (msd-code-reviewer)_
_Depth: standard_

View File

@@ -0,0 +1,234 @@
---
phase: 32.2-mcp-oauth-with-administrator-subjects
reviewed: 2026-11-21T12:00:00Z
depth: standard
scope: framework (summercms.go) half; sm-oauthserver-plugin and sm-grzybyfunkcjonalne-app reviewed separately
diff_base: 45eb34e5
files_reviewed: 56
files_reviewed_list:
- admin/src/api/types.ts
- admin/src/app/pageTitle.ts
- admin/src/app/router.ts
- admin/src/components/account/AccountContributions.vue
- admin/src/views/ConnectView.vue
- admin/src/views/LoginView.vue
- admin/tests/account/AccountContributions.test.ts
- admin/tests/app/router.test.ts
- admin/tests/smoke/account-items.smoke.test.ts
- admin/tests/smoke/connect.smoke.test.ts
- admin/tests/views/ConnectView.test.ts
- admin/tests/views/LoginView.test.ts
- docs/backend/admin-spa.md
- docs/backend/users-and-permissions.md
- docs/plugins/registration.md
- docs/services/events.md
- docs/services/mcp.md
- docs/services/oauth-server.md
- modules/cabana/README.md
- modules/cabana/account.go
- modules/cabana/account_contributions.go
- modules/cabana/account_items_smoke_test.go
- modules/cabana/account_items_test.go
- modules/cabana/admin_events.go
- modules/cabana/admin_openapi.go
- modules/cabana/backend_access_revoked_smoke_test.go
- modules/cabana/backend_access_revoked_test.go
- modules/cabana/backend_roles_admin.go
- modules/cabana/backend_users_admin.go
- modules/cabana/commands.go
- modules/cabana/contracts.go
- modules/cabana/export_test.go
- modules/cabana/http.go
- modules/cabana/mcp_admin_consent_test.go
- modules/cabana/mcp_consent.go
- modules/cabana/mcp_consent_smoke_test.go
- modules/cabana/openapi_conformance_test.go
- modules/cabana/phase10_coverage_test.go
- modules/cabana/phase10_csrf_test.go
- modules/cabana/security_coverage_test.go
- modules/cabana/token_routes_test.go
- modules/cabana/token_scope_names_test.go
- modules/cabana/token_scopes_export.go
- modules/pact/README.md
- modules/pact/capabilities.go
- modules/pact/mcp.go
- modules/phrasebook/backend/lang/en/lang.yaml
- modules/phrasebook/backend/lang/pl/lang.yaml
- modules/pier/README.md
- modules/pier/backend_guard.go
- modules/pier/backend_only_grant_test.go
- modules/pier/backend_subject_smoke_test.go
- modules/pier/identity.go
- modules/wristband/README.md
- modules/wristband/authorize.go
- modules/wristband/consent_path_smoke_test.go
- modules/wristband/consent_path_test.go
- modules/wristband/server.go
findings:
critical: 0
warning: 6
info: 5
total: 11
status: issues_found
---
# Phase 32.2: Code Review Report
**Reviewed:** 2026-11-21T12:00:00Z
**Depth:** standard
**Files Reviewed:** 56 (framework repository only; the generated `modules/boardwalk/dist`, `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` were excluded)
**Status:** issues_found
## Summary
This review covers the framework half of phase 32.2: the cabana admin consent endpoints (`GET`/`POST {api}/mcp/consent/{request}`), the My account item action route, `BackendAccessRevokedEvent` at the D-13 sites, the pact contract additions, pier's administrator-only grant branch, wristband's `ConsentPath`/`DefaultScopes`, and the SPA `ConnectView`, `LoginView` hint and `AccountContributions` item rows. I traced the diff from `45eb34e5..HEAD` together with the helpers it calls: `scopeOverlaps`, `validateTokenScopes`, `accountPrincipal`, `interactiveOnly`, `requireAjax`, `lagoon.Transaction`/`AfterCommit`, `festival.Bus.Fire`, the crud save order (Fill, FormBeforeUpdate, applyPermissionValues, Save, FormAfterUpdate), `actionDB` and the boardwalk security headers.
The checks the caller asked for came out as follows:
- **CSRF on the consent POST.** It is wrapped in `interactiveOnly(requireAjax(...))`, the admin cookie is `SameSite=Strict`, and boardwalk sends `frame-ancestors 'none'` and `X-Frame-Options: DENY`. No CSRF or clickjacking path found. The GET has no side effects in cabana.
- **Scope escalation.** `grantableConsentScopes` keeps only requested catalog scopes that pass `scopeOverlaps`. The decision is filtered against that set and then runs through `validateTokenScopes`. An unrequested `*` is dropped, and a requested `*` collapses to `["*"]`. Offline access is the AND of requested and asked. The pier backend guard caps `ScopeLimited` subjects with `ScopeLimitFor` and refuses all-unknown scopes. I could not inject an unrequested or ungrantable scope.
- **Item-action authorization.** The route checks, in order: section exists, action exists, permission (403), the item ID is in the caller's own `Items` (read inside the transaction), then `Run`. No cross-admin path found.
- **In-transaction revocation event.** It fires at delete, deactivate, password set, own password change, `admin:reset-password` (now a lagoon transaction), user role/permission/superuser change and role permission change. The hook order means the `prior*` captures are correct. Problems remain in what Tx handle the listener gets (WR-04, WR-05).
- **ConnectView redirect handling.** It leaves through `window.location.assign` after a scheme deny-list. The redirect URI itself is never checked by the framework against the request it belongs to (WR-06).
No blockers were found in the framework half. The warnings are about fail-open edges and contract inconsistencies that a plugin (the sibling oauthserver plugin, or a future one) can trip over.
## Narrative Findings (AI reviewer)
## Warnings
### WR-01: `DefaultScopes` never applies to an `offline_access`-only authorize request, which ends in a consent screen with nothing to grant
**File:** `modules/wristband/authorize.go:270-283` (with `151-160`), `modules/wristband/server.go:102-107`
**Issue:** The `Options.DefaultScopes` doc says it applies when a request "names no data scope". `parseAuthorizeScopes` only falls back when `kept` is empty after dropping the identity scopes. `scope=offline_access` (or `openid offline_access`) leaves `kept = ["offline_access"]`, so the fallback is skipped. Lines 151-160 then remove `offline_access` into the boolean, and the pending request is stored with **zero data scopes**. In backend mode this request reaches cabana's consent with `scopes: []`, and the admin gets the "none grantable" dead end even though the operator configured `DefaultScopes` for exactly this case. MCP clients that ask only for a refresh token do this.
A related case: when `DefaultScopes` is empty, or nothing survives its filter, the fallback is `["read"]` without checking `allowed`. On a backend-mode server `read` is not in `scopes_supported`, so the stored request carries a scope the server does not advertise.
**Fix:** Apply the fallback on the data scopes, not on all kept scopes:
```go
data := 0
for _, p := range kept {
if p != "offline_access" {
data++
}
}
if data == 0 {
out := append([]string(nil), fallback...)
if stringSliceContains(kept, "offline_access") {
out = append(out, "offline_access")
}
return out, ""
}
```
Keep PHP parity by doing this only when `len(s.opts.DefaultScopes) > 0`, for example with a flag passed in. Add a test for `scope=offline_access` with `DefaultScopes` set.
### WR-02: `ConsentPath` is concatenated onto `Issuer` without validation and can send the browser off-origin
**File:** `modules/wristband/authorize.go:189, 198-205`, `modules/wristband/server.go:94-100`
**Issue:** `spa := s.opts.Issuer + s.consentPath() + "?request=" + ...` uses the option exactly as given. Neither wristband nor its only caller validates it (the sibling `sm-oauthserver-plugin/servers.go:149,216-229` passes the trimmed `mcp.consent_path` straight through). Some example values:
- `@evil.example/connect` produces `https://app.example@evil.example/connect`, an off-origin 302 carrying the pending request id.
- `backend/connect` (missing slash) produces `https://app.examplebackend/connect`.
- A value containing `?` gives a malformed `...?x=1?request=`.
The option is described as "elsewhere on the same origin", but nothing enforces that. This is public API (D-04, reversibility costly).
**Fix:** Validate in `wristband.New` (or the options constructor) and refuse at boot:
```go
if p := opts.ConsentPath; p != "" {
if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "?#\\@") {
return nil, fmt.Errorf("wristband: ConsentPath %q must be a same-origin absolute path", p)
}
}
```
### WR-03: pier treats an unknown `MCPGrant.Subject` as a frontend-user grant (fail-open)
**File:** `modules/pier/identity.go:218-223`
**Issue:** `resolveOAuth` branches only on `grant.Subject == pact.MCPGrantSubjectBackend`. Any other non-empty value, such as a future `"member"` kind, a typo in a verifier, or a value from a newer plugin running against an older framework, falls through to the legacy path. That path treats `UserID` as the frontend user and also runs `consentedBackendSubject` to attach a linked administrator. pact documents `Subject` as an enum whose only meanings are empty and `"backend"`, so an unrecognized value should be refused, not reinterpreted.
**Fix:**
```go
switch grant.Subject {
case pact.MCPGrantSubjectBackend:
return resolveBackendGrant(grant)
case "":
// legacy user grant, below
default:
return Identity{}, ErrUnauthorized
}
```
### WR-04: The Administrators and Roles hooks fire `BackendAccessRevokedEvent` with a possibly nil `Tx`, and the listener then revokes outside the save's transaction
**File:** `modules/cabana/backend_users_admin.go:854-863`, `modules/cabana/backend_roles_admin.go:200-203`
**Issue:** Both hooks use `tx, _ := TxFromContext(ctx)` and pass whatever they got to `fireBackendAccessRevoked`. The event's documented contract (`admin_events.go:18-24`) is "inside the transaction of the save ... with that transaction in Tx ... commit together or not at all". If either hook ever runs without a carried transaction (another crud entry point, a test harness, a future refactor), the event fires with `Tx == nil`. The only listener today (`sm-oauthserver-plugin` `BackendCascade.txOf`) then falls back to the application pool. It revokes grants on a second connection that commits on its own while the save may still roll back, and it can wait on row or advisory locks held by the open save. `FormAfterDelete` (`backend_users_admin.go:225-228`) and `actionDB` already fail closed in this situation; these two do not.
**Fix:** Fail closed, as the delete hook does:
```go
tx, ok := TxFromContext(ctx)
if !ok {
return errors.New("cabana: administrators: an update needs its transaction")
}
```
In the roles hook, `writeDB(ctx)` already requires the transaction, so reuse that handle instead of reading the context a second time. Optionally, make `fireBackendAccessRevoked` refuse a nil `tx` when listeners exist.
### WR-05: The deactivate site hands listeners an `Unscoped` session as `Tx`, unlike every other site
**File:** `modules/cabana/backend_users_admin.go:291` (compare `235`, `856-861`, `account.go:399`, `commands.go:169`)
**Issue:** In the deactivate lifecycle, `db` comes from `actionDB(ctx)`, which is `tx.Session(NewDB).WithContext(ctx).Unscoped().Session(&gorm.Session{})`. GORM keeps `Statement.Unscoped` across that last `Session`. So listeners get a handle on which `Delete` is a **hard delete** and queries include soft-deleted rows, but only when the reason is `deactivated`. The other reasons get the plain transaction. A listener that writes through `ev.Tx` with a model that has `gorm.DeletedAt` behaves differently depending on the reason. The oauthserver models currently have no `DeletedAt`, so nothing is hit today, but the event is public API meant for any plugin.
**Fix:** Pass the raw transaction at this site:
```go
tx, _ := TxFromContext(ctx) // actionDB already proved it exists
if err := fireBackendAccessRevoked(ctx, c.application(), tx, BackendAccessDeactivated, user.ID); err != nil {
```
Alternatively, document that `Tx` is a fresh session and pass `tx.Session(&gorm.Session{NewDB: true})` at every site.
### WR-06: The framework never checks the provider's redirect against the request's redirect URI, and the SPA guard is only a scheme deny-list
**File:** `modules/cabana/mcp_consent.go:218-232`, `admin/src/views/ConnectView.vue:192-203, 232-240`
**Issue:** `mcpConsentDecide` returns whatever string `MCPAdminConsentDecide` gives back as `redirect_uri`. ConnectView then navigates the top-level window to it after refusing only `javascript:`, `data:` and `vbscript:`. pact says the framework "owns the scope policy", but the open-redirect safety of the consent screen rests entirely on the provider. The framework already has the request's `RedirectURI` from the Show call on the allow path. Nothing confirms the returned URI is that redirect plus `code`/`state`/`error`. If a provider builds the URI from anything other than the registered redirect (a bug, or a future provider), the admin's browser is sent to an arbitrary scheme or host straight after consent, with an authorization code in the URL. The deny path does not even load the request.
**Fix:** In cabana, load the request on both paths, then refuse (500 and log) a redirect that does not match the registered one:
```go
want, _ := url.Parse(req.RedirectURI)
got, err := url.Parse(redirect)
if err != nil || got.Scheme != want.Scheme || got.Host != want.Host || got.Path != want.Path {
moduleLog.ErrorContext(ctx, "cabana: mcp consent provider answered a foreign redirect", "admin_id", principal.ID)
WriteError(w, http.StatusInternalServerError, "error", msgServerError)
return
}
```
In the SPA, also refuse `blob:`, `file:`, `about:` and `filesystem:`. Better, compare the destination's scheme and host with `consent.client.redirect_host` before calling `assign`.
## Info
### IN-01: A requested `*` is offered to administrators who hold no permission, so the "none grantable" state never shows for them
**File:** `modules/cabana/token_scopes.go:337-339` (used by `modules/cabana/mcp_consent.go:61-63`)
**Issue:** `scopeOverlaps` always answers true for `*`. A client that requests `* admin:read` shown to an administrator with no permissions lists `*` as grantable instead of the `none_grantable` explanation. The administrator can then allow a grant that can do nothing. This is consistent with g15_ token creation (documented in the 32.2-01 summary), but on consent it is misleading.
**Fix:** On the consent path, offer `*` only when the administrator is a superuser or holds at least one registered permission, the same test `admin:read` uses.
### IN-02: The session binding namespaces can collide
**File:** `modules/pier/identity.go:227, 262`
**Issue:** A user grant binds to `oauth:<client>:<user>` and an administrator grant to `oauth:backend:<client>:<admin>`. A user-mode client whose ID starts with `backend:` produces the same key as an administrator grant. Today this is prevented only by server-generated client IDs and the one-mode-per-app rule (D-07), which the CONTEXT plans to relax.
**Fix:** Use an unambiguous prefix such as `oauth-backend:<client>:<admin>`, or escape the `:` in client IDs.
### IN-03: Item actions can answer 409, but the OpenAPI annotation does not document it
**File:** `modules/cabana/admin_openapi.go:503-518`, `modules/cabana/account_contributions.go:349-355`
**Issue:** `writeCRUDError` maps an `actionConflict` from `Run` to 409, and `AccountContributions.vue` handles 409. `AdminAccountContributionItemAction` lists 401/403/404/422 only, and it also does not mention the `X-Requested-With` requirement that the decide annotation does mention.
**Fix:** Add `@Failure 409 {object} ErrorEnvelope` and "Needs X-Requested-With" to the description, then regenerate.
### IN-04: The new literal admin API routes shadow controller routes of a vendor named `mcp` or `account`
**File:** `modules/cabana/http.go:351-355`
**Issue:** `GET/POST /mcp/consent/{request}` is more specific than `/{vendor}/{plugin}/{controller}`, so a plugin `mcp.consent` loses its list and create routes without any boot error. The same goes for `account/contribution-items/...` against record actions of an `account.contribution-items` controller. This is unlikely, but nothing refuses it.
**Fix:** Refuse the vendor/plugin pairs `mcp/consent` and `account/contribution-items` when compiling controllers, or document them as reserved.
### IN-05: Dispatched calls of administrator OAuth grants carry no credential, so `interactiveOnly` cannot tell them from a cookie session
**File:** `modules/pier/identity.go:248-274`, `modules/pier/dispatch.go:207-216`, `modules/cabana/token_guard.go:154-171`
**Issue:** `resolveBackendGrant` sets no `credential`, so `bouncer.Dispatch.Credential` is nil for these calls. `interactiveOnly` only refuses `*BackendAPIToken` credentials and `g15_` bearers. Tools are limited to the plugin's own token-guarded routes, so this is not reachable today. But an OAuth agent is treated as "interactive" wherever a plugin route relies on that wrapper.
**Fix:** Attach a marker credential (for example an `*MCPGrantCredential{ClientID, TokenID}`) for administrator grants, and have `interactiveOnly` refuse it too.
---
_Reviewed: 2026-11-21T12:00:00Z_
_Reviewer: Claude (msd-code-reviewer)_
_Depth: standard_