Compare commits

..

8 Commits

23 changed files with 848 additions and 70 deletions

View File

@@ -1918,7 +1918,7 @@ Phases execute in numeric order: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 →
| 33. SEO output, audit and content | 16/16 | In Progress| |
| 34. Plugin marketplace | 6/6 | In Progress| |
| 35. Mail templates and layouts editor | 9/9 | Complete | 2026-11-14 |
| 36. Granular MCP OAuth & API token scope picker | 0/4 | Planned | - |
| 36. Granular MCP OAuth & API token scope picker | 4/4 | Complete | 2026-11-24 |
## Backlog
@@ -2017,13 +2017,13 @@ Plans:
Plans:
**Wave 1**
- [ ] 36-01-PLAN.md — Go backend scope metadata (`pact.TokenScope.Group`, `cabana.AdminAPITokenScope` `plugin_id`/`group` + D-16 fallback), `cabana.TokenScopeCovers` + `pier.Mount` boot warning, EN/PL phrasebooks, OpenAPI/TS regen, READMEs & docs
- [x] 36-01-PLAN.md — Go backend scope metadata (`pact.TokenScope.Group`, `cabana.AdminAPITokenScope` `plugin_id`/`group` + D-16 fallback), `cabana.TokenScopeCovers` + `pier.Mount` boot warning, EN/PL phrasebooks, OpenAPI/TS regen, READMEs & docs
**Wave 2** *(blocked on Wave 1 completion)*
- [ ] 36-02-PLAN.md — Shared 3-tier access selector & `ScopePicker` on `ConnectView.vue` (light-literal modal) and `ApiTokenCreateDialog.vue` (fixed-width in-dialog swap), rebuilt `modules/boardwalk/dist`
- [x] 36-02-PLAN.md — Shared 3-tier access selector & `ScopePicker` on `ConnectView.vue` (light-literal modal) and `ApiTokenCreateDialog.vue` (fixed-width in-dialog swap), rebuilt `modules/boardwalk/dist`
**Wave 3** *(blocked on Wave 2 completion)*
- [ ] 36-03-PLAN.md — Core plugin `pact.HasTokenScopes` rollout in `sm-sitemap-plugin` (`sitemap`/`sitemap:read`) and `sm-seo-plugin` (`seo`/`seo:read`) with EN/PL copy, READMEs, and tests
- [x] 36-03-PLAN.md — Core plugin `pact.HasTokenScopes` rollout in `sm-sitemap-plugin` (`sitemap`/`sitemap:read`) and `sm-seo-plugin` (`seo`/`seo:read`) with EN/PL copy, READMEs, and tests
**Wave 4** *(blocked on Wave 3 completion)*
- [ ] 36-04-PLAN.md — Comprehensive Go & Vitest unit/component suites (closing all 7 UI-SPEC backstops), full release gates, human release-tag checkpoint, and `sm-grzybyfunkcjonalne-app` local E2E proof
- [x] 36-04-PLAN.md — Comprehensive Go & Vitest unit/component suites (closing all 7 UI-SPEC backstops), full release gates, human release-tag checkpoint, and `sm-grzybyfunkcjonalne-app` local E2E proof

View File

@@ -3,17 +3,17 @@ gsd_state_version: "1.0"
milestone: v1.0
current_phase: 36
current_phase_name: granular-mcp-oauth-api-token-scope-picker
status: executing
stopped_at: Phase 36 context gathered
last_updated: "2026-11-24T17:54:17.146Z"
last_activity: 2026-11-21
last_activity_desc: Phase 32.2 complete, transitioned to Phase 19.3
state_head: 4c078005c0ef71c191dde752c5082981bb843f64
status: complete
stopped_at: Phase 36 complete
last_updated: "2026-11-24T21:15:00.000Z"
last_activity: 2026-11-24
last_activity_desc: Phase 36 complete (v0.6.8, sm-sitemap-plugin v0.2.1, sm-seo-plugin v0.2.1)
state_head: a219d4d8
progress:
total_phases: 54
completed_phases: 38
completed_phases: 39
total_plans: 313
completed_plans: 298
completed_plans: 302
msd_state_version: "1.0"
milestone_name: milestone
---
@@ -29,10 +29,10 @@ See: .planning/PROJECT.md (updated 2026-11-21)
## Current Position
Phase: 36 (granular-mcp-oauth-api-token-scope-picker) — READY TO EXECUTE
Plan: Not started
Status: Ready to execute
Last activity: 2026-11-21 — Phase 32.2 complete, transitioned to Phase 19.3
Phase: 36 (granular-mcp-oauth-api-token-scope-picker) — COMPLETE
Plan: 4/4 complete
Status: Complete
Last activity: 2026-11-24 — Phase 36 complete (v0.6.8, sm-sitemap-plugin v0.2.1, sm-seo-plugin v0.2.1)
Progress: [████████░░] 77%
@@ -70,6 +70,7 @@ Progress: [████████░░] 77%
| 19.6.1 | 5 | - | - |
| 35 | 9 | - | - |
| 32.2 | 5 | - | - |
| 36 | 4 | - | - |
**Recent Trend:**

View File

@@ -0,0 +1,103 @@
---
phase: 36-granular-mcp-oauth-api-token-scope-picker
plan: 04
subsystem: testing-release-verification
tags: [cabana, pier, vitest, release, sitemap, seo, oauth, mcp, changelog]
key-files:
created:
- modules/cabana/token_scopes_test.go
- modules/pier/uncovered_scopes_warning_test.go
- admin/tests/app/scopeCatalog.test.ts
- admin/tests/scopes/ScopeAccessControl.test.ts
- admin/tests/scopes/ScopePicker.test.ts
modified:
- modules/cabana/account_tokens_test.go
- modules/cabana/mcp_admin_consent_test.go
- modules/cabana/token_scope_names_test.go
- admin/tests/account/ApiTokenCreateDialog.test.ts
- admin/tests/views/ConnectView.test.ts
- ../sm-sitemap-plugin/go.mod
- ../sm-sitemap-plugin/go.sum
- ../sm-sitemap-plugin/plugin.yaml
- ../sm-sitemap-plugin/README.md
- ../sm-seo-plugin/go.mod
- ../sm-seo-plugin/go.sum
- ../sm-seo-plugin/plugin.yaml
- ../sm-seo-plugin/README.md
- ../sm-grzybyfunkcjonalne-app/go.mod
- ../sm-grzybyfunkcjonalne-app/plugins/golem15/sitemap
- ../sm-grzybyfunkcjonalne-app/plugins/golem15/seo
- ../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh
decisions:
- D-20: User explicitly approved `approve-release-and-proof` at Task 4; cut and pushed tags in dependency order (`summercms.go v0.6.8` -> `sm-sitemap-plugin v0.2.1` -> `sm-seo-plugin v0.2.1`), bumped `sm-grzybyfunkcjonalne-app` pointers (`61f9669`), proved local MCP OAuth E2E with Journal + SEO + Sitemap scopes and zero `pier` boot warnings, and published changelog posts. Production deployment of `grzybyfunkcjonalne.pl` stays out of scope.
- D-04 (`plugin.yaml` manifest freshness): Regenerated and verified `plugin.yaml` via `summer plugin:manifest` in both `sm-sitemap-plugin` and `sm-seo-plugin` before tagging `v0.2.1` so marketplace checks and `changelog-post.py publish` pass cleanly.
metrics:
tasks_completed: 5
tasks_total: 5
commits: 5
completed_date: "2026-11-24"
---
# Phase 36 Plan 04: Tests, Verification, Release Tags & Local E2E Proof Summary
Completed full Go and Vitest test coverage (including all 7 `backstop` UI contracts), verified all framework and sibling plugin release gates, executed the user-approved patch release train (`v0.6.8` -> `v0.2.1` -> `v0.2.1`), bumped `sm-grzybyfunkcjonalne-app` pointers with an extended local MCP OAuth E2E proof, and published all three changelog posts.
## Tasks & Commits
| Task | Repository | Description | Commit / Tag | Status |
|------|------------|-------------|--------------|--------|
| 1 | `summercms.go` | Go unit & integration tests for `cabana` token scope grouping/coverage and `pier` uncovered write-tool boot warnings | `782f4dc1` | Complete |
| 2 | `summercms.go` | Vitest unit & component tests covering all 7 `backstop` scope picker rows | `2661e0f3` | Complete |
| 3 | `summercms.go`, `sm-sitemap-plugin`, `sm-seo-plugin` | Full pre-release verification gates (Go vet/test, OpenAPI, admin dist, docs, sibling plugins) | *(verified)* | All PASS |
| 4 | *(checkpoint)* | Blocking `checkpoint:decision` — user selected **`approve-release-and-proof`** | *(user approved)* | Approved |
| 5a | `summercms.go` | Push `master` and create/push annotated tag `v0.6.8` | `2661e0f3` / `v0.6.8` | Complete |
| 5b | `../sm-sitemap-plugin` | Bump `summercms` to `v0.6.8`, update `plugin.yaml` & `README.md`, test, push `main`, tag `v0.2.1` | `91eaaa3` / `v0.2.1` | Complete |
| 5c | `../sm-seo-plugin` | Bump `summercms` to `v0.6.8` & `sm-sitemap-plugin` to `v0.2.1`, update `plugin.yaml` & `README.md`, test, push `main`, tag `v0.2.1` | `1f56dba` / `v0.2.1` | Complete |
| 5d | `../sm-grzybyfunkcjonalne-app` | Bump submodules + `go.mod`, extend `scripts/smoke-mcp-oauth.sh`, run local E2E proof, commit & push `master` (no production deploy) | `61f9669` | Complete |
| 5e | `../sm-summercmsio-app` | Publish user-facing release notes to `summercms.io/changelog` and `/changelog/plugins` | Posts `#86`, `#87`, `#88` | Complete |
## Verification Gate Results
- **Framework Go & release gates (Task 3):**
- `go vet ./...` & `go test ./...` (including Postgres integration & OpenAPI conformance) — **PASS**
- `scripts/check-admin-openapi.sh --check` — **PASS**
- `npm --prefix admin run typecheck && npm --prefix admin run test && scripts/check-admin-dist.sh` — **PASS**
- `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check` — **PASS**
- **Plugin release gates (Tasks 3 & 5):**
- `../sm-sitemap-plugin`: `summer plugin:manifest --check`, `go vet ./...`, `go test -count=1 ./...` (`16.6s`) — **PASS**
- `../sm-seo-plugin`: `summer plugin:manifest --check`, `go vet ./...`, `go test -count=1 ./...` (`125.8s`) — **PASS**
- **Local `sm-grzybyfunkcjonalne-app` E2E proof (Task 5):**
- `go vet -tags summercms_mcp,nodynamic ./...` — **PASS**
- `go test -short ./...` (`0.624s`) — **PASS**
- `scripts/smoke-mcp-oauth.sh` — **PASS** (`ok (12 steps)`):
- Step 2 (`/.well-known/oauth-protected-resource/mcp`): `200`, `scopes_supported` includes `journal`, `journal:read`, `seo`, `seo:read`, `sitemap`, `sitemap:read`, `offline_access`.
- Step 6 (`GET /oauth/mcp/authorize`): `302` requesting `scope=admin:read journal seo sitemap offline_access`.
- Step 8 (`GET /gfadmin/api/v1/mcp/consent/{request}`): `200`, `journal`/`seo`/`sitemap` offered with non-empty `plugin_id` and `group`; `admin:read` offered with empty `plugin_id` and `group` (`*` verified empty if present).
- Step 8 (`POST`): granted `["journal","seo","sitemap"]` with `offline_access: true` (no `*`, no `admin:read`).
- Step 10 (OAuth `tools/list`): `200`, 62 tools visible including `journal_list_posts`, `journal_create_post`, `seo_set_url_seo`, and `sitemap_rebuild` without `*`; `tools/call journal_list_posts` returned `isError: false`.
- Step 11 (`g15_` PAT scoped `journal`): `200`, 11 tools including `journal_list_posts`; `tools/call` returned `isError: false`.
- Step 12 (password change): `200`, subsequent OAuth `tools/list` returned `401`.
- Boot log check: zero `not covered by any non-* TokenScope` warnings in `$TMP/go.log`.
## Changelog Posts Published
| Release | Stream | Post ID | URL | Registry Ingest |
|---------|--------|---------|-----|-----------------|
| `summercms.go v0.6.8` | `/changelog` | `86` | https://summercms.io/changelog/summercms-0-6-8 | N/A |
| `sm-sitemap-plugin v0.2.1` | `/changelog/plugins` | `87` | https://summercms.io/changelog/sm-sitemap-plugin-0-2-1 | Hourly ingest (no `~/.config/summercms/registry-token` locally) |
| `sm-seo-plugin v0.2.1` | `/changelog/plugins` | `88` | https://summercms.io/changelog/sm-seo-plugin-0-2-1 | Hourly ingest (no `~/.config/summercms/registry-token` locally) |
## Deviations from Plan
- **Manifest & README updates in plugin bump commits:** Both `sm-sitemap-plugin` (`91eaaa3`) and `sm-seo-plugin` (`1f56dba`) updated `plugin.yaml` (via `summer plugin:manifest`) and `README.md` alongside `go.mod`/`go.sum`, matching prior `v0.2.0` release commits and satisfying `changelog-post.py`'s `plugin.yaml` freshness gate.
## Self-Check: PASSED
- Commits verified:
- `summercms.go`: `782f4dc1` (Task 1), `2661e0f3` (Task 2, tagged `v0.6.8`, pushed to `origin`)
- `../sm-sitemap-plugin`: `91eaaa3` (tagged `v0.2.1`, pushed to `origin`)
- `../sm-seo-plugin`: `1f56dba` (tagged `v0.2.1`, pushed to `origin`)
- `../sm-grzybyfunkcjonalne-app`: `61f9669` (pushed to `origin/master`; production NOT deployed)
- Local E2E proof (`smoke-mcp-oauth.sh`) passed all 12 steps + zero `pier` uncovered-tool warnings with no secrets printed or logged.
- All three changelog entries published (`#86`, `#87`, `#88`) and temporary `/tmp/notes-*.md` files removed.
- `.planning/STATE.md` and `.planning/ROADMAP.md` untouched (reserved for orchestrator).

View File

@@ -0,0 +1,41 @@
---
phase: 36
review: 36-REVIEW.md
titles: json
findings:
- id: WR-01
severity: warning
disposition: fixed
source: 36-REVIEW-FIX.md (2f2c33e6)
title: "Missing request sequence guard in `ApiTokenCreateDialog.vue` `loadScopes()`"
- id: IN-01
severity: info
disposition: fixed
source: 36-REVIEW-FIX.md (51b60b94)
title: "`warnUncoveredBackendWriteTools` recompiles the plugin token scope catalog once per backend write tool when `cabana` is not activated on `app`"
- id: IN-02
severity: info
disposition: fixed
source: 36-REVIEW-FIX.md (bfb0bee8)
title: "Accordion header toggle buttons appear interactive during search even though clicking is a no-op"
- id: IN-03
severity: info
disposition: fixed
source: 36-REVIEW-FIX.md (bfb0bee8)
title: "Static DOM `panelId` and mount-only `expanded` initialization in `ScopePicker.vue`"
fixed: 4
open: 0
total: 4
recorded: "2026-11-25"
---
# Phase 36: Code Review Disposition
| Finding | Severity | Disposition | Source |
|---------|----------|-------------|--------|
| WR-01 | warning | fixed | `36-REVIEW-FIX.md` (`2f2c33e6`) |
| IN-01 | info | fixed | `36-REVIEW-FIX.md` (`51b60b94`) |
| IN-02 | info | fixed | `36-REVIEW-FIX.md` (`bfb0bee8`) |
| IN-03 | info | fixed | `36-REVIEW-FIX.md` (`bfb0bee8`) |
Dispositions: `open` (recorded, not yet triaged), `fixed`, `skipped`, `deferred`.

View File

@@ -0,0 +1,58 @@
---
phase: 36-granular-mcp-oauth-api-token-scope-picker
status: fixed
fix_scope: all
iteration: 2
review_source: 36-REVIEW.md
fixed: 4
skipped: 0
out_of_scope: 0
fixed_at: "2026-11-25"
---
# Phase 36: Code Review Fix Report
**Phase:** `36-granular-mcp-oauth-api-token-scope-picker`
**Source Review:** `36-REVIEW.md`
**Fix Scope:** `all` (Warning + Info findings resolved across iterations 1–2)
**Status:** `fixed` (`4/4` findings resolved; `0` open)
## Fixed Findings
### WR-01: Missing request sequence guard in `ApiTokenCreateDialog.vue` `loadScopes()`
- **Severity:** Warning
- **Commit:** `2f2c33e6` (`fix(36): guard stale scope catalog responses in ApiTokenCreateDialog`)
- **Files Modified:** `admin/src/components/account/ApiTokenCreateDialog.vue`, `admin/tests/account/ApiTokenCreateDialog.test.ts`, `modules/boardwalk/dist/*`
- **What Changed:** Added a monotonically incremented `loadSeq` guard and `props.open` check in `loadScopes()` (plus invalidation on close and unmount), preventing stale scope responses from prematurely clearing `scopesLoading` or resetting an active Custom selection. Added two Vitest regression tests.
### IN-01: `warnUncoveredBackendWriteTools` recompiles the plugin token scope catalog once per backend write tool when `cabana` is not activated on `app`
- **Severity:** Info
- **Commit:** `51b60b94` (`fix(36): compile token scope catalog once in pier boot coverage warning`)
- **Files Modified:** `modules/cabana/token_scopes_export.go`, `modules/cabana/README.md`, `modules/pier/uncovered_scopes_warning.go`, `modules/pier/uncovered_scopes_warning_test.go`
- **What Changed:** Exported `cabana.TokenScopeMatcher` / `cabana.NewTokenScopeMatcher` (documented in `modules/cabana/README.md`) so `warnUncoveredBackendWriteTools` resolves or compiles the scope catalog once per boot check instead of once per tool, and logs one clear catalog-compile warning instead of misleading per-plugin uncovered-tool warnings when catalog compilation fails. Added a unit test in `modules/pier/uncovered_scopes_warning_test.go`.
### IN-02: Accordion header toggle buttons appear interactive during search even though clicking is a no-op
- **Severity:** Info
- **Commit:** `bfb0bee8` (`fix(36): polish ScopePicker search collapse, unique panel IDs, and lazy catalog expand`)
- **Files Modified:** `admin/src/components/scopes/ScopePicker.vue`, `admin/tests/scopes/ScopePicker.test.ts`, `modules/boardwalk/dist/*`
- **What Changed:** Added a temporary `searchCollapsed` set (cleared on every `query` change) so clicking a matching group header during search collapses/expands it cleanly without mutating the saved pre-search `expanded` set, which still restores verbatim when search is cleared. Added a Vitest regression test.
### IN-03: Static DOM `panelId` and mount-only `expanded` initialization in `ScopePicker.vue`
- **Severity:** Info
- **Commit:** `bfb0bee8` (`fix(36): polish ScopePicker search collapse, unique panel IDs, and lazy catalog expand`)
- **Files Modified:** `admin/src/components/scopes/ScopePicker.vue`, `admin/tests/scopes/ScopePicker.test.ts`, `modules/boardwalk/dist/*`
- **What Changed:** Replaced static `scope-group-panel-${index}` IDs with Vue `useId()`-prefixed IDs (`${pickerId}-group-${index}`) and replaced mount-only expansion setup with an immediate watcher on `allGroups.value.length` so smart expansion also initializes if a catalog populates lazily. Added Vitest regression tests for both.
## Verification
- `go vet ./...` — **PASS**
- `go test -short ./modules/cabana ./modules/pier ./modules/boardwalk -count=1` — **PASS**
- `scripts/check-admin-openapi.sh --check` — **PASS**
- `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check` — **PASS**
- `npm --prefix admin run typecheck` — **PASS**
- `npm --prefix admin run test` — **PASS** (`120/120` test files, `1769/1769` tests)
- `npm --prefix admin run build && scripts/check-admin-dist.sh` — **PASS** (`modules/boardwalk/dist matches a fresh build`)

View File

@@ -0,0 +1,99 @@
---
phase: 36
status: reviewed
depth: standard
findings:
critical: 0
warning: 1
info: 3
reviewed_at: "2026-11-24"
---
# Phase 36: Code Review Report
**Phase:** `36-granular-mcp-oauth-api-token-scope-picker`
**Reviewed:** 2026-11-24
**Depth:** standard
**Scope:** Framework diff `7644786d..2661e0f3` (`modules/pact`, `modules/cabana`, `modules/pier`, `modules/phrasebook`, `admin/src/`, `docs/`), sibling plugin scope declarations (`../sm-sitemap-plugin/token_scopes.go`, `../sm-seo-plugin/token_scopes.go` + EN/PL phrasebooks and tests), and `../sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh`.
**Status:** reviewed (`0` critical, `1` warning, `3` info)
## Summary
Phase 36 is clean on security, privilege boundaries, XSS safety, and contract compliance. All ten STRIDE threats (`T-36-01`..`T-36-10`) and every plan prohibition from `36-01-PLAN.md`..`36-04-PLAN.md` hold up under code inspection:
- **Backend scope metadata & validation (`T-36-01`, `T-36-03`):** `pact.TokenScope.Group` is additive while `pact.ValidTokenScopeName` / `tokenScopeNameRE` remain untouched (D-01, D-05, D-14). `validateTokenScopeMessageKeys` fails boot on missing `::` phrase keys in `Group`. `cabana.AdminAPITokenScope` emits always-present `plugin_id` and `group` strings (no `omitempty`), strictly empty for `*`, `admin:read`, and unknown stored scopes; `resolveScopeGroup` follows the exact D-16 fallback order with deterministic `reg.permissionOrder` iteration.
- **Boot-time uncovered write MCP tool warning (`T-36-02`):** `cabana.TokenScopeCovers` excludes `*`, delegates to `scopeCoversAll` (returning `false` for empty `permissions` on write methods, matching runtime `allowsUnderScope`), and `pier.Mount` emits one sorted structured `Warn` per plugin without failing boot (D-18).
- **Admin SPA scope picker & `admin:read` PII footgun fix (`T-36-04`, `T-36-05`, `T-36-06`):** Both `ConnectView.vue` and `ApiTokenCreateDialog.vue` default to `Read-only (admin:read)` when grantable (D-03, D-08). Custom mode defaults `adminRead` to `false` and `computeSubmittedScopes` omits `admin:read` unless explicitly opted in; toggling ON locks `read_only` rows with a `Lock` icon + `via admin:read` badge, disables per-group `Read`, makes `Clear` selective on unlocked scopes, and restores prior `:read` ticks if toggled back OFF (D-04, D-17). Zero `v-html` exists across the new and modified Vue files. All Phase 32.2 `ConnectView` invariants (`safeDestination`, `FORBIDDEN_PROTOCOLS`, `window.location.assign`, no auto-allow, no auto-focus/hotkeys on Allow/Deny) are preserved. `.connect-light-surface` is defined in `admin/src/styles/main.css` `@layer components` pinning both `--c-*` and `--color-*` aliases on card and portaled modal (D-12). `ApiTokenCreateDialog.vue` keeps a single `DialogOverlay` at fixed `max-w-[560px]`, unmounts the `mod+s mod+enter` submit button in picker view, and intercepts `Escape` to discard the draft without closing the dialog or losing `name`/`expires` (D-13). `ApiTokensPanel.vue` is untouched.
- **Sibling plugins & E2E smoke script (`T-36-07`, `T-36-08`, `T-36-09`, `T-36-10`):** `sm-sitemap-plugin/token_scopes.go` and `sm-seo-plugin/token_scopes.go` strictly scope permissions to `golem15.sitemap.*` and `golem15.seo.*`, restrict `:read` scopes to `GET`/`HEAD`, define all EN/PL phrase keys, and cover 100% of backend write MCP tools with zero `pier.Mount` warnings. `smoke-mcp-oauth.sh` uses `umask 077`, passes secrets only via env/0600 files (never CLI arguments or logs), verifies grouped scopes and zero boot warnings, and cleans up temp files on `EXIT`. No consuming application name appears in framework code or `docs/`.
One non-blocking **Warning** (async stale-response race in `ApiTokenCreateDialog.vue`'s `loadScopes()`) and three **Info** items were found.
## Critical Issues
None.
## Warnings
### WR-01: Missing request sequence guard in `ApiTokenCreateDialog.vue` `loadScopes()`
**File:** `admin/src/components/account/ApiTokenCreateDialog.vue:141-175`
**Issue:** Unlike `ConnectView.vue` (which guards `load()` with `let loadSeq = 0; const seq = ++loadSeq` at lines 56 and 143), `ApiTokenCreateDialog.vue`'s `loadScopes()` does not track a request sequence number or check `props.open` when `api.GET('/account/tokens/scopes')` settles:
```ts
async function loadScopes(): Promise<void> {
scopesLoading.value = true
scopesFailed.value = false
scopes.value = []
resetScopeSelection([])
try {
const result = await api.GET('/account/tokens/scopes')
if (result.data) {
const list = result.data.data ?? []
scopes.value = list
resetScopeSelection(list)
scopesFailed.value = list.length === 0
return
}
scopesFailed.value = true
} catch {
scopesFailed.value = true
} finally {
scopesLoading.value = false
}
}
```
If the administrator opens the dialog, closes it while `/account/tokens/scopes` is still in flight, and immediately re-opens it:
1. When request #1 resolves/rejects first, its `finally` clears `scopesLoading.value = false` while request #2 is still running.
2. If request #1 resolves *after* request #2 (e.g., after the user has already switched to `Custom` and opened `ScopePicker`), request #1 calls `resetScopeSelection(list)`, closing the picker and silently resetting the user's tier/draft back to `Read-only (admin:read)`.
3. If the dialog stays closed while request #1 resolves, `scopes.value` and tier state are repopulated in the background after the close watcher already reset them.
**Fix:** Mirror `ConnectView.vue`'s sequence guard: add `let loadSeq = 0`, capture `const seq = ++loadSeq` at the top of `loadScopes()`, increment `loadSeq++` in the `watch(() => props.open)` close branch, and ignore stale responses (including skipping `scopesLoading.value = false` in `finally`) whenever `seq !== loadSeq || !props.open`.
## Info
### IN-01: `warnUncoveredBackendWriteTools` recompiles the plugin token scope catalog once per backend write tool when `cabana` is not activated on `app`
**File:** `modules/pier/uncovered_scopes_warning.go:22-31`, `modules/cabana/token_scopes_export.go:67-83`
**Issue:** In normal server boot (`surf`), `cabana.Activate` runs before `pier.Mount`, so `publishedResolverGuard(app)` returns the cached `guard.reg.tokenScopes` in O(1). However, when `pier.Mount` is called without an activated `cabana` guard (such as standalone tests or custom hosts), `tokenScopeCatalogFor(app, plugins)` invokes `compileTokenCatalog(plugins)` inside the loop once for every backend write tool in `cat.tools`. In addition, if `compileTokenCatalog(plugins)` returns an error in that fallback path, `tokenScopeCatalogFor` silently returns `nil` and `TokenScopeCovers` returns `false`, causing `pier` to emit `"not covered by any non-* TokenScope"` warnings for every plugin instead of noting a catalog compile error (though `cabana.Activate` still fails boot separately).
**Fix:** Optional optimization: resolve or compile the scope catalog once before iterating `cat.tools` (or expose an internal/batch helper if needed). No change required for standard `surf` boot.
### IN-02: Accordion header toggle buttons appear interactive during search even though clicking is a no-op
**File:** `admin/src/components/scopes/ScopePicker.vue:188-199`, `admin/src/components/scopes/ScopePicker.vue:395-418`
**Issue:** Per D-07, all matching groups auto-expand while `isSearching` is `true` without mutating the saved `expanded` set. In `ScopePicker.vue`, `toggleGroup` returns early when `isSearching.value` is `true`, while the `<button data-scope-group-toggle :aria-expanded="isGroupExpanded(group.key)">` element remains enabled with no `disabled` / `aria-disabled` attribute. Clicking a group header during a search produces no visual or state change.
**Fix:** Either allow a temporary search-collapse override (cleared when `query` clears so pre-search expansion still restores cleanly) or set `:disabled="isSearching"` / `:aria-disabled="isSearching ? 'true' : undefined"` on the toggle button so assistive technology and pointer styling reflect that groups stay expanded during search.
### IN-03: Static DOM `panelId` and mount-only `expanded` initialization in `ScopePicker.vue`
**File:** `admin/src/components/scopes/ScopePicker.vue:126`, `admin/src/components/scopes/ScopePicker.vue:265-272`
**Issue:**
1. Each group panel ID is generated as `` `scope-group-panel-${index}` `` without a component-instance prefix (e.g. Vue's `useId()`). This is safe today because only one `ScopePicker` mounts at a time across `ConnectView` and `ApiTokenCreateDialog`, but would cause duplicate `id` / `aria-controls` collisions if two pickers ever coexist on a page.
2. `expanded.value = computeDefaultExpanded(...)` runs only in `onMounted()`. Both current hosts unmount `ScopePicker` when closed (`DialogContent` portal unmount in `ConnectView`, `v-if="step === 1 && pickerOpen"` in `ApiTokenCreateDialog`) and only open it after `catalog` has loaded, so this works reliably today; if reused later with a lazily populated `catalog` or `v-show`, `expanded` would remain empty.
**Fix:** Use Vue's `useId()` prefix for `panelId`, and optionally watch `() => props.catalog` (or `allGroups.value.length` transitioning from `0` to `> 0`) if `ScopePicker` is ever reused outside modal/view-swap hosts.
---
_Reviewed: 2026-11-24_
_Reviewer: msd-code-reviewer_
_Depth: standard_

View File

@@ -0,0 +1,123 @@
---
phase: 36-granular-mcp-oauth-api-token-scope-picker
status: passed
score: 5/5
must_haves_score: 45/45
verified_at: "2026-11-24"
---
# Phase 36 Verification Report — Granular MCP OAuth & API Token Scope Picker
**Verdict:** `passed` — **5/5** ROADMAP Success Criteria, **45/45** plan `must_have` truths, **23/23** artifacts, **11/11** key links, and **16/16** prohibitions verified directly against on-disk source, tests, OpenAPI/TS schemas, phrasebooks, docs, and sibling repositories.
---
## 1. ROADMAP Success Criteria (5/5)
| # | Success Criterion | Status | Evidence (Verified on Disk) |
|---|-------------------|--------|-----------------------------|
| SC-1 | `pact.TokenScope` accepts an optional `Group` field (phrase key or literal, validated when containing `::`) and `cabana.AdminAPITokenScope` additively exposes `plugin_id` and resolved `group` (falling back to plugin name / permission tab / `plugin_id`); `ValidTokenScopeName` stays unchanged and existing plugins without `Group` keep working. | **PASS** | `modules/pact/capabilities.go:867-874` adds `Group string` while `git diff cb259ba9~1..HEAD -- modules/pact/capabilities.go` confirms `tokenScopeNameRE` / `ValidTokenScopeName` untouched. `modules/cabana/token_scopes.go:26,94,171-175` stores `strings.TrimSpace(scope.Group)` and validates `::` keys in `validateTokenScopeMessageKeys`. `modules/cabana/account_tokens.go:21-22,267-372` emits non-`omitempty` `plugin_id`/`group` and implements exact D-16 3-step `resolveScopeGroup` (`Group` -> `<pluginID>::lang.plugin.name` -> unanimous matched `Tab` via `reg.permissionOrder` -> raw `PluginID`; `""` for framework/unknown scopes), wired across `/account/tokens/scopes`, `/account/tokens`, and `modules/cabana/mcp_consent.go:147`. |
| SC-2 | Booting an app where a plugin registers backend non-read-only `MCPTool`s not covered by any non-`*` `TokenScope` logs a clear warning identifying the plugin and uncovered tools, without breaking boot. | **PASS** | `modules/cabana/token_scopes_export.go:67-114` exports `TokenScopeCovers(app, plugins, method, permissions)` excluding `*` and returning `false` on empty permissions for write methods. `modules/pier/uncovered_scopes_warning.go:16-46` filters `t.guardName == BackendGuard` and non-`GET`/`HEAD`, groups sorted uncovered tools per plugin, and emits one structured `logger().Warn(...)` with `"plugin"` and `"tools"`. Wired in `modules/pier/pier.go:116` immediately after `compileCatalog` with no error return path. |
| SC-3 | `ConnectView.vue` keeps its `480px` summary card with 3-tier access selection (**Full `*`** \| **Read-only `admin:read`** \| **Custom**), defaults to `Read-only (admin:read)` when requested and grantable, shows effective-access chips, and opens a dedicated **Customize scopes** modal with search, `All / Selected / Read-only` filters, collapsible plugin/group accordions, per-group quick actions (`Read` / `All` / `Clear`), and an opt-in `admin:read` toggle that visibly locks all `:read` rows (`via admin:read`). | **PASS** | `admin/src/views/ConnectView.vue:39,67-81,393,526-537,603-645` retains `max-w-[480px]` light-literal card with `.connect-light-surface`, wires `useScopeSelection(scopes, 'connect')` (defaulting to `read_only`), renders `<ScopeAccessControl>` (elevated-first chips capped at 6 + `+N more`), and mounts a Reka `Dialog` Customize modal (`h-[100dvh]` mobile / `sm:max-w-[640px] sm:max-h-[85dvh]` desktop, `.connect-light-surface` on both `DialogOverlay` and `DialogContent`) hosting `<ScopePicker>` (`admin/src/components/scopes/ScopePicker.vue`) with search, live-count filter pills, flat `(plugin_id, group)` accordions, `Read`/`All`/`Clear`, and opt-in `admin:read` toggle locking every `read_only` row with `Lock` + `data-via-admin-read`. |
| SC-4 | `ApiTokenCreateDialog.vue` reuses the same shared `ScopePicker` via an in-dialog view swap (`← Back` / `Apply scopes`, no nested modal overlay) with dark-mode-aware tokens. | **PASS** | `admin/src/components/account/ApiTokenCreateDialog.vue:71-85,374-388,402-456,581-593` uses `useScopeSelection(scopes, 'token')` (defaulting to `Read-only (admin:read)`, falling back to `Full (*)`), swaps in place (`v-if="step === 1 && pickerOpen"`) inside a single `<DialogOverlay>` (`grep -c` = `1`) at fixed `max-w-[560px]` using semantic tokens (`bg-surface`, `bg-subtle`, `border-border`, `text-text`), intercepts `Escape` in `onEscapeKey` to discard draft and return to the token form preserving `name` and `expires`, and unmounts the `hotkey="mod+s mod+enter"` submit button while in picker view. |
| SC-5 | OpenAPI schema, embedded `boardwalk/dist`, en/pl phrasebook copy, Go unit tests, and Vitest coverage for both `ConnectView` and `ApiTokenCreateDialog` pass green. | **PASS** | `admin/openapi/admin.json` and `admin/src/api/schema.d.ts` both require `group: string` and `plugin_id: string` on `cabana.AdminAPITokenScope`. `modules/phrasebook/backend/lang/{en,pl}/lang.yaml` define all 44 `api_tokens.*` keys (including EN/PL CLDR plural maps `scope_count`, `scope_write_count`, `scope_plugin_count` with PL locative) and 2 `mcp_connect.*` keys. All Go tests (`go vet ./...`, `go test ./...`), OpenAPI/dist/docs checks, Vitest suites (all 7 UI-SPEC backstops), sibling plugin tests, and local 12-step `smoke-mcp-oauth.sh` passed green with zero subsequent code edits. |
---
## 2. Plan Must-Haves Verification (Plans 36-01 through 36-04)
### Plan 36-01 — Backend Scope Metadata, Coverage Warning, Phrasebook & OpenAPI (7/7 Truths)
| Must-Have | Status | Evidence |
|-----------|--------|----------|
| `pact.TokenScope.Group` optional; `ValidTokenScopeName` unchanged; no auto-generation at boot (D-01, D-05, D-14) | **PASS** | `modules/pact/capabilities.go:867-874`; diff touches only `TokenScope` doc comment and `Group string`. |
| `compiledTokenScope.Group` + `validateTokenScopeMessageKeys` fails boot on missing `::` key (D-14) | **PASS** | `modules/cabana/token_scopes.go:26,94,171-175`; tested in `TestTokenScopeGroupValidation`. |
| `cabana.AdminAPITokenScope` emits always-present `plugin_id` & `group` (no `omitempty`), `""` for framework/unknown scopes across all 3 endpoints (D-15) | **PASS** | `modules/cabana/account_tokens.go:15-23,186,270-273`, `modules/cabana/mcp_consent.go:147`; raw JSON wire keys asserted in `account_tokens_test.go` and `mcp_admin_consent_test.go`. |
| Deterministic D-16 3-step fallback (`<pluginID>::lang.plugin.name` -> unanimous matched `Tab` via `reg.permissionOrder` -> raw `PluginID`) | **PASS** | `modules/cabana/account_tokens.go:306-372`; all 5 branches + framework/unknown verified in `TestScopeGroupFallbackResolution`. |
| `cabana.TokenScopeCovers` + `pier.Mount` one structured `Warn` per plugin without breaking boot (D-18) | **PASS** | `modules/cabana/token_scopes_export.go:91-114`, `modules/pier/uncovered_scopes_warning.go:16-46`, `modules/pier/pier.go:116`; verified in `TestTokenScopeCovers` and `TestUncoveredBackendWriteToolsWarning`. |
| EN/PL phrasebooks define all 44 `api_tokens.*` keys (incl. 3 CLDR plurals) + 2 `mcp_connect.*` keys | **PASS** | Verified programmatically via YAML parse: 0 missing keys in both `en/lang.yaml` and `pl/lang.yaml`; PL `scope_plugin_count` uses locative forms (`wtyczce`/`wtyczkach`/`wtyczki`). |
| OpenAPI/TS schema, READMEs (`pact`, `cabana`, `pier`), and `docs/` (`users-and-permissions.md`, `mcp.md`) updated & verified | **PASS** | Verified in `admin/openapi/admin.json`, `admin/src/api/schema.d.ts`, `modules/{pact,cabana,pier}/README.md`, `docs/backend/users-and-permissions.md`, `docs/services/mcp.md`. |
### Plan 36-02 — Shared Scope Picker, `ConnectView` & `ApiTokenCreateDialog` Integration (23/23 Truths)
| Category / Must-Have | Status | Evidence |
|----------------------|--------|----------|
| Loading skeletons (`ConnectView` `aria-busy="true"`, `ApiTokenCreateDialog` `data-scope-loading`) & submit disabled/spinner states | **PASS** | `ConnectView.vue:402-416,524,580-597`; `ApiTokenCreateDialog.vue:551-568,493,612-628`. |
| Empty states (`none_grantable`, Custom 0 selected `scope_summary_empty`, `ScopePicker` search/Selected/Read-only dashed empty states with action buttons, empty-draft disabled Apply + `scope_picker_none_selected`) | **PASS** | `ConnectView.vue:513-522`; `ScopeAccessControl.vue:48-51,149-165`; `ScopePicker.vue:140-182,360-385,503-525`. |
| Error states preserved (`ConnectView` 404/401/422/bad-URI + `border-danger` on `scopes_required`; `ApiTokenCreateDialog` `scopes_failed` + 422 `errors.scopes` invalid + focus restore) | **PASS** | `ConnectView.vue:320-329,534-548`; `ApiTokenCreateDialog.vue:234-237,262-275,569-603`. |
| Small (`<= 3` groups or `<= 12` scopes) vs large (`> 3` groups and `> 12` scopes) smart expand + search auto-expand without losing pre-search expand state (D-07) | **PASS** | `scopeCatalog.ts:144-160`; `ScopePicker.vue:184-199,265-272`. |
| Elevated-first summary chips (`admin:read` -> writes -> reads when `admin:read` OFF), capped at 6 + clickable `+N more` + CLDR plural subtitle via `tc()` (D-04, D-06) | **PASS** | `scopeCatalog.ts:168-234`; `ScopeAccessControl.vue:48-65,167-206`. |
| Missing tiers omitted; `Custom` hidden without plugin scopes; `ApiTokenCreateDialog` `Full (*)` fallback; `ConnectView` narrow subset opens in `Custom` (D-03, D-08) | **PASS** | `scopeCatalog.ts:262-291`; `useScopeSelection.ts:25-37`; `ScopeAccessControl.vue:95-115`. |
| Collision-free flat `(plugin_id, group)` accordions keyed `${plugin_id}\0${group}`, `Intl.Collator` sort + `plugin_id` tie-break, preserved intra-group scope order (D-01, D-17) | **PASS** | `scopeCatalog.ts:75-116`. |
| Responsive mobile `100dvh` sheet / desktop `sm:max-w-[640px] sm:max-h-[85dvh]` (`ConnectView`), fixed `max-w-[560px] max-h-[calc(100vh-32px)]` (`ApiTokenCreateDialog`), `[overflow-wrap:anywhere]` & chip `truncate` (D-10, D-13) | **PASS** | `ConnectView.vue:610`; `ApiTokenCreateDialog.vue:407`; `ScopeAccessControl.vue:130,146,151,184,192`; `ScopePicker.vue:350,366,410,476-494`. |
| Surface-matched theming: `.connect-light-surface` in `admin/src/styles/main.css` `@layer components` pinning both `--c-*` and `--color-*`, applied to `ConnectView` card + portaled overlay/content; `ApiTokenCreateDialog` inherits `.dark` (D-12) | **PASS** | `admin/src/styles/main.css:536-573`; `ConnectView.vue:39,605,610`; `ApiTokenCreateDialog.vue` uses semantic utilities only. |
| Focus management, Escape draft-discard + tier-revert without closing `ApiTokenCreateDialog` (preserving `name`/`expires`), `mod+s`/`mod+enter` inactive in picker view (D-09, D-11, D-13) | **PASS** | `useScopeSelection.ts:59-89`; `ConnectView.vue:212-232`; `ApiTokenCreateDialog.vue:185-218,374-388,415-456,617-628`. |
| `ApiTokensPanel.vue` untouched and compatible; embedded `modules/boardwalk/dist` rebuilt and passing `check-admin-dist.sh` (D-15) | **PASS** | `git diff cb259ba9~1..HEAD -- admin/src/components/account/ApiTokensPanel.vue` is empty; `modules/boardwalk/dist/*` updated in `3781c979`. |
### Plan 36-03 — Core Plugin `pact.HasTokenScopes` Rollout (5/5 Truths)
| Must-Have | Status | Evidence |
|-----------|--------|----------|
| `sm-sitemap-plugin` declares `sitemap` + `sitemap:read` (`golem15.sitemap.*`, empty `Group`) with EN/PL copy | **PASS** | `../sm-sitemap-plugin/token_scopes.go:1-26`, `lang/{en,pl}/lang.yaml:93-97`. |
| `sm-seo-plugin` declares `seo` + `seo:read` (`golem15.seo.*`, empty `Group`) with EN/PL copy | **PASS** | `../sm-seo-plugin/token_scopes.go:1-26`, `lang/en/lang.yaml:787-791`, `lang/pl/lang.yaml:817-821`. |
| 100% backend write MCP tool coverage under `cabana.TokenScopeCovers` and zero `pier.Mount` warnings | **PASS** | Verified in `../sm-sitemap-plugin/token_scopes_test.go:110-159` (2/2 write tools) and `../sm-seo-plugin/token_scopes_test.go:110-163` (29/29 write tools out of 48 total). |
| `:read` scopes allow `GET`/`HEAD` and deny write methods; full scopes stay bounded to plugin permissions | **PASS** | Verified in `TestTokenScopesReadWriteEnforcement` in both plugin test files. |
| Both repos pass `go vet ./...` & `go test ./...` with updated `README.md` | **PASS** | Recorded in `36-03-SUMMARY.md` & re-verified post-`v0.6.8` bump in `36-04-SUMMARY.md` (`16.6s` sitemap, `125.8s` seo). |
### Plan 36-04 — Comprehensive Tests, Release Gates & Local E2E Proof (10/10 Truths, incl. all 7 UI-SPEC Backstops)
| Must-Have / UI-SPEC Backstop | Status | Evidence |
|------------------------------|--------|----------|
| Go unit & integration tests for `TokenScope.Group`, D-16 fallback, `AdminAPITokenScope` wire keys, `TokenScopeCovers`, and `pier.Mount` boot warnings | **PASS** | `modules/cabana/token_scopes_test.go` (`TestTokenScopeGroupValidation`, `TestScopeGroupFallbackResolution`), `token_scope_names_test.go` (`TestTokenScopeCovers`), `account_tokens_test.go`, `mcp_admin_consent_test.go`, `modules/pier/uncovered_scopes_warning_test.go` (5 subtests via `captureLogs`). |
| Backstop #1: Initial default tiers (`ConnectView` + `ApiTokenCreateDialog`) | **PASS** | `scopeCatalog.test.ts:243-280`, `ConnectView.test.ts:132,247`, `ApiTokenCreateDialog.test.ts:208,233,388`. |
| Backstop #2: `admin:read` toggle & lock semantics (PII footgun fix) | **PASS** | `scopeCatalog.test.ts:216-241`, `ScopePicker.test.ts:146-203`, `ConnectView.test.ts:325-388`. |
| Backstop #3: Tier memory, auto-open empty Custom, draft/discard revert | **PASS** | `ConnectView.test.ts:284-324`, `ApiTokenCreateDialog.test.ts:436-479`. |
| Backstop #4: Grouping, sorting, search, filter pills, smart expand | **PASS** | `scopeCatalog.test.ts:51-161`, `ScopePicker.test.ts:205-308`. |
| Backstop #5: `ApiTokenCreateDialog` in-dialog swap + Escape preservation + `mod+s` suppressed | **PASS** | `ApiTokenCreateDialog.test.ts:395-435`. |
| Backstop #6: `ConnectView` modal `.connect-light-surface`, `h-[100dvh]`, `sm:max-w-[640px] sm:max-h-[85dvh]` | **PASS** | `ConnectView.test.ts:389-402`. |
| Backstop #7: Elevated-first chip cap at 6 + clickable `+2 more` | **PASS** | `scopeCatalog.test.ts:163-214`, `ScopeAccessControl.test.ts:101-178`. |
| All framework release gates pass green | **PASS** | Verified in Plan 36-04 Task 3 (`go vet`, `go test ./...`, OpenAPI, typecheck, Vitest, dist, `TestDocsTree`, `docs:build --check`). |
| Release tags gated on user decision (`approve-release-and-proof`) + `sm-grzybyfunkcjonalne-app/scripts/smoke-mcp-oauth.sh` E2E proof | **PASS** | Annotated tag `v0.6.8` verified on `summercms.go`; `../sm-sitemap-plugin/go.mod` requires `summercms v0.6.8`; `../sm-seo-plugin/go.mod` requires `summercms v0.6.8` & `sm-sitemap-plugin v0.2.1`; `../sm-grzybyfunkcjonalne-app/go.mod` pins all three (`v0.6.8` / `v0.2.1` / `v0.2.1`); `scripts/smoke-mcp-oauth.sh:292-455` verifies Steps 2, 6, 8 (`plugin_id`/`group`), 10 (`journal_create_post`, `seo_set_url_seo`, `sitemap_rebuild`), 11, 12, and zero `not covered by any non-* TokenScope` warnings in `$TMP/go.log`. |
---
## 3. Prohibitions Audit (16/16 Clean)
| Prohibition | Plan | Check Result |
|-------------|------|--------------|
| Do NOT alter `pact.ValidTokenScopeName` or `tokenScopeNameRE` (D-01) | 36-01 | **CLEAN** (`git diff` confirms untouched) |
| Do NOT auto-generate `<plugin>` `TokenScope`s at boot (D-05) | 36-01 | **CLEAN** (`compileTokenScopes` reads explicit `pact.HasTokenScopes` only) |
| Do NOT add `omitempty` to `AdminAPITokenScope.PluginID` or `Group` (D-15) | 36-01 | **CLEAN** (`json:"plugin_id"` and `json:"group"`, required in OpenAPI) |
| Do NOT make `pier.Mount` return an error for uncovered backend write MCP tools (D-18) | 36-01 | **CLEAN** (`warnUncoveredBackendWriteTools` returns void, logs `Warn` only) |
| Do NOT name any consuming application in framework code, module READMEs, or `docs/` | 36-01 | **CLEAN** (`git diff` grep across `modules/`, `docs/`, `admin/src/` returned 0 hits) |
| Do NOT add any new npm dependencies or new `:root`/`.dark` CSS custom properties | 36-02 | **CLEAN** (`admin/package.json` & `package-lock.json` untouched; `main.css` diff adds only `.connect-light-surface` in `@layer components`) |
| Do NOT define `.connect-light-surface` in Vue `<style scoped>` | 36-02 | **CLEAN** (zero `<style>` blocks in scope/connect/token `.vue` files; defined in `admin/src/styles/main.css`) |
| Do NOT nest a second modal overlay inside `ApiTokenCreateDialog.vue` | 36-02 | **CLEAN** (`grep -c '<DialogOverlay'` = `1`) |
| Do NOT include `admin:read` in submitted Custom scopes unless opt-in toggle checked | 36-02 | **CLEAN** (`computeSubmittedScopes` + Vitest backstop #2) |
| Do NOT auto-focus/bind hotkeys to Allow/Deny on `ConnectView.vue`, and zero `v-html` | 36-02 | **CLEAN** (zero `v-html` across all modified/created `.vue` files; no hotkey or auto-focus on Allow/Deny) |
| Do NOT grant write HTTP methods on `sitemap:read` or `seo:read` | 36-03 | **CLEAN** (`Methods: []string{"GET", "HEAD"}` in both plugins) |
| Do NOT broaden `Permissions` beyond `golem15.sitemap.*` / `golem15.seo.*` | 36-03 | **CLEAN** (verified in `token_scopes.go` and `token_scopes_test.go`) |
| Do NOT tag/push plugin repos during Plan 36-03 (only after Task 4 user approval) | 36-03 / 36-04 | **CLEAN** (tagging executed strictly after user approved `approve-release-and-proof` at Task 4) |
| Do NOT print, copy, or log plaintext tokens in test failures or command output | 36-04 | **CLEAN** (`smoke-mcp-oauth.sh` unsets/truncates tokens and never prints them) |
| Do NOT deploy `grzybyfunkcjonalne.pl` to production (D-20) | 36-04 | **CLEAN** (local proof + git push only; production untouched) |
| Do NOT modify `ApiTokensPanel.vue` unnecessarily | 36-02 | **CLEAN** (`git diff` empty) |
---
## 4. Automated Test & Release Evidence
All automated gates executed cleanly in Plan 36-04 Tasks 3 & 5 with zero subsequent source modifications (verified via `git log cb259ba9~1..HEAD`):
- `go vet ./...` & `go test ./...` (including Postgres integration & OpenAPI conformance) — **PASS**
- `scripts/check-admin-openapi.sh --check` — **PASS**
- `npm --prefix admin run typecheck` (`vue-tsc --noEmit`) — **PASS**
- `npm --prefix admin run test` (Vitest full suite including `scopeCatalog.test.ts`, `ScopeAccessControl.test.ts`, `ScopePicker.test.ts`, `ConnectView.test.ts`, `connect.smoke.test.ts`, `ApiTokenCreateDialog.test.ts`, `ApiTokensPanel.test.ts`) — **PASS**
- `npm --prefix admin run build && scripts/check-admin-dist.sh` — **PASS**
- `go test ./cmd/summer -run 'TestCommandsDocumented|TestDocsTree' -count=1 && go run ./cmd/summer docs:build --check` — **PASS**
- `../sm-sitemap-plugin` (`v0.2.1`, commit `91eaaa3`): `summer plugin:manifest --check`, `go vet ./...`, `go test -count=1 ./...` — **PASS**
- `../sm-seo-plugin` (`v0.2.1`, commit `1f56dba`): `summer plugin:manifest --check`, `go vet ./...`, `go test -count=1 ./...` — **PASS**
- `../sm-grzybyfunkcjonalne-app` (commit `61f9669`): `go vet -tags summercms_mcp,nodynamic ./...`, `go test -short ./...`, `scripts/smoke-mcp-oauth.sh` (12/12 steps + zero `pier` uncovered-tool boot warnings) — **PASS**
- Changelogs published: `summercms.go v0.6.8` (`#86`), `sm-sitemap-plugin v0.2.1` (`#87`), `sm-seo-plugin v0.2.1` (`#88`).
### Advisory Note (Non-Blocking)
- All 7 functional UI-SPEC `backstop` contracts are automated and verified in Vitest (`36-UI-SPEC.md`). Optional visual polish checks (real-browser inspection of `/connect` light-surface modal in dark mode, `< 640px` mobile sheet scroll feel, and `/account` dark-mode token dialog swap) remain advisory whenever the operator next visits those screens locally.

View File

@@ -251,13 +251,13 @@
{
"number": "36",
"name": "Granular MCP OAuth & API token scope picker",
"status": "pending"
"status": "complete"
}
],
"next": {
"command": "/gsd:progress --next",
"command": "/msd-progress --next",
"label": "Advance to the next step",
"reason": "Phase 36 of 54 · executing"
"reason": "Phase 36 complete"
},
"updated_at": "2026-11-24T17:54:17.179Z"
"updated_at": "2026-11-24T21:15:00.000Z"
}

14
AGENTS.md Normal file
View File

@@ -0,0 +1,14 @@
# Repository Agent Rules
Follow all conventions, commands, and MSD workflow overrides in `CLAUDE.md`.
## Release Ordering Guardrail
Never put git release tagging, pushing release tags, downstream consumer `go.mod`/submodule bumps to new tags, or changelog publishing inside a phase execution plan (`*-PLAN.md`) or wave execution.
Complete the full phase lifecycle first:
1. Finish all phase waves (run local E2E proofs against local checkouts using temporary `GOWORK` / `replace`, leaving submodules clean).
2. Run phase code review (`/msd-code-review <N>`).
3. Apply and re-verify any accepted review fixes (`/msd-code-review <N> --fix` + tests, OpenAPI, embedded `modules/boardwalk/dist`, and docs gates).
4. Pass goal-backward phase verification (`<N>-VERIFICATION.md`).
5. Only after steps 1–4 are complete and the user gives explicit go-ahead, cut/push release tags, bump downstream consumers, and publish changelog entries.

View File

@@ -70,10 +70,11 @@ Project rules that override MSD defaults:
2. **Unit tests are the last plan of every phase.** Earlier plans may carry smoke tests but are not blocked on coverage.
3. **State through handlers.** Update `.planning/STATE.md` with `msd_run query state.*` handlers, not raw edits.
4. **g15office sync.** Todos and phase milestone tasks are mirrored in g15office (`.planning/G15OFFICE.md`); post a short comment when a phase advances.
5. **Release only after review, fixes, and verification.** Never put `git tag`, pushing release tags, bumping downstream consumer `go.mod`/submodule pointers to new tags, or publishing changelog posts inside a phase `PLAN.md` or wave execution. Run local E2E proofs in the final plan against local checkouts (e.g., temporary `GOWORK` / `replace`), then complete the full post-wave sequence first — code review (`/msd-code-review`), any review fixes (`/msd-code-review --fix` + re-verified tests/dist/OpenAPI/docs), and phase verification (`*-VERIFICATION.md`) — and only cut/push release tags, bump downstream consumers, and publish changelog posts afterward with explicit user go-ahead.
## Commits and concurrency
- No co-author tags. One logical change per commit; planning docs and code in separate commits.
- Several Claude sessions often work in this repo at once (different phases, quick tasks). Stage files explicitly by path (never `git add -A`), leave other sessions' uncommitted edits (often `STATE.md`, `state.json`) alone, and check for in-flight edits before touching shared files such as cabana.
- Don't push, tag or deploy without the user's go-ahead; deploys are documented per application (for example `../sm-grzybyfunkcjonalne-app/DEPLOY.md`).
- Don't push, tag or deploy without the user's go-ahead, and never tag/publish a phase release before phase code review, accepted `--fix` changes, and verification have all completed (see MSD rule 5); deploys are documented per application (for example `../sm-grzybyfunkcjonalne-app/DEPLOY.md`).
- Every pushed release tag `vX.Y.Z` gets a post on https://summercms.io/changelog, the same day. From `../sm-summercmsio-app`: `scripts/changelog-post.py source vX.Y.Z` prints the tag message and the commits since the previous tag; write user-facing markdown notes from it (`## Highlights`/`## Added`/`## Changed`/`## Fixed`, no planning IDs or `quick-*` codes, no H1); then `scripts/changelog-post.py publish vX.Y.Z notes.md --excerpt "…"`. Plugin release tags get a post on https://summercms.io/changelog/plugins with `scripts/changelog-post.py publish vX.Y.Z notes.md --excerpt "…" --repo ../sm-<name>-plugin`. The script reads the `g15_` token (scoped `journal`) from `~/.config/summercms/journal-token`; never print, copy or mint one, and if the file is missing or the token is refused, ask the user. Details: `../sm-summercmsio-app/DEPLOY.md`, "Posting to the changelog".

View File

@@ -61,6 +61,7 @@ const copyFailed = ref(false)
const copyFlash = ref(false)
const announce = ref('')
let copyTimer: ReturnType<typeof setTimeout> | null = null
let loadSeq = 0
const nameInput = ref<HTMLInputElement | null>(null)
const plaintextInput = ref<HTMLInputElement | null>(null)
@@ -139,12 +140,16 @@ function setOpen(open: boolean): void {
}
async function loadScopes(): Promise<void> {
const seq = ++loadSeq
scopesLoading.value = true
scopesFailed.value = false
scopes.value = []
resetScopeSelection([])
try {
const result = await api.GET('/account/tokens/scopes')
if (seq !== loadSeq || !props.open) {
return
}
if (result.data) {
const list = result.data.data ?? []
scopes.value = list
@@ -154,9 +159,14 @@ async function loadScopes(): Promise<void> {
}
scopesFailed.value = true
} catch {
if (seq !== loadSeq || !props.open) {
return
}
scopesFailed.value = true
} finally {
scopesLoading.value = false
if (seq === loadSeq) {
scopesLoading.value = false
}
}
}
@@ -167,6 +177,10 @@ watch(
resetForm()
void loadScopes()
} else {
loadSeq += 1
scopesLoading.value = false
scopesFailed.value = false
scopes.value = []
clearPlaintext()
resetScopeSelection([])
step.value = 1
@@ -392,6 +406,7 @@ function onHide(): void {
}
onBeforeUnmount(() => {
loadSeq += 1
clearPlaintext()
})
</script>

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import { computed, nextTick, ref, useId, watch } from 'vue'
import { ChevronDown, ChevronRight, Lock, Search, X } from '@lucide/vue'
import type { AdminAPITokenScope } from '../../api/types'
import {
@@ -46,9 +46,12 @@ interface VisibleScopeGroup {
canClear: boolean
}
const pickerId = useId()
const query = ref('')
const filter = ref<ScopeFilter>('all')
const expanded = ref<Set<string>>(new Set())
const searchCollapsed = ref<Set<string>>(new Set())
let initializedExpanded = false
const searchInput = ref<HTMLInputElement | null>(null)
const partitioned = computed(() => partitionCatalog(props.catalog))
@@ -123,7 +126,7 @@ const visibleGroups = computed<VisibleScopeGroup[]>(() => {
result.push({
key: group.key,
panelId: `scope-group-panel-${index}`,
panelId: `${pickerId}-group-${index}`,
label: group.label,
allScopes: group.scopes,
visibleScopes,
@@ -182,11 +185,21 @@ const emptyState = computed(() => {
})
function isGroupExpanded(key: string): boolean {
return isSearching.value || expanded.value.has(key)
if (isSearching.value) {
return !searchCollapsed.value.has(key)
}
return expanded.value.has(key)
}
function toggleGroup(key: string): void {
if (isSearching.value) {
const next = new Set(searchCollapsed.value)
if (next.has(key)) {
next.delete(key)
} else {
next.add(key)
}
searchCollapsed.value = next
return
}
const next = new Set(expanded.value)
@@ -262,15 +275,28 @@ function focusSearch(): void {
searchInput.value?.focus()
}
onMounted(() => {
expanded.value = computeDefaultExpanded(
allGroups.value,
pluginScopes.value.length,
draftSelection.value,
false,
)
watch(query, () => {
if (searchCollapsed.value.size > 0) {
searchCollapsed.value = new Set()
}
})
watch(
() => allGroups.value.length,
(len) => {
if (!initializedExpanded && len > 0) {
initializedExpanded = true
expanded.value = computeDefaultExpanded(
allGroups.value,
pluginScopes.value.length,
draftSelection.value,
false,
)
}
},
{ immediate: true },
)
defineExpose({ focusSearch })
</script>

View File

@@ -595,4 +595,107 @@ describe('ApiTokenCreateDialog mounted directly', () => {
await click('[data-action="hide-token"]', dialog()!)
expect(wrapper.emitted('update:open')).toEqual([[false]])
})
it('ignores stale scope catalog responses after rapid close/reopen without resetting Custom picker (WR-01)', async () => {
const first = deferred()
const second = deferred()
let callCount = 0
mockApi(
tokenRoutes({
[`GET ${SCOPES}`]: () => {
callCount += 1
return callCount === 1 ? first.route() : second.route()
},
}),
)
const wrapper = mount(ApiTokenCreateDialog, {
props: { open: false, confirm: useConfirm() },
attachTo: document.body,
})
// First open kicks off request #1 (stays pending), close cancels it, reopen starts request #2.
await wrapper.setProps({ open: true })
await flushPromises()
await wrapper.setProps({ open: false })
await flushPromises()
await wrapper.setProps({ open: true })
await flushPromises()
expect(callCount).toBe(2)
expect(dialog()!.querySelector('[data-scope-loading]')).toBeTruthy()
// Request #2 resolves first with plugin scopes; user switches to Custom and ticks journal in ScopePicker.
second.release(
envelope([
...scopes,
{
name: 'journal',
label: 'Journal',
description: 'Create and edit posts.',
read_only: false,
known: true,
plugin_id: 'acme.journal',
group: 'Journal',
},
]),
)
await flushPromises()
expect(dialog()!.querySelector('[data-scope-loading]')).toBeNull()
await click('[data-access-tier="custom"]', dialog()!)
expect(dialog()!.querySelector('[data-scope-picker]')).toBeTruthy()
const journalBox = dialog()!.querySelector<HTMLInputElement>('[data-scope="journal"] input[type="checkbox"]')!
journalBox.checked = true
journalBox.dispatchEvent(new Event('change', { bubbles: true }))
await flushPromises()
// Stale request #1 now settles late — must NOT close ScopePicker or reset the draft/tier.
first.release(envelope(scopes))
await flushPromises()
expect(dialog()!.querySelector('[data-scope-picker]')).toBeTruthy()
expect(dialog()!.querySelector<HTMLInputElement>('[data-scope="journal"] input[type="checkbox"]')!.checked).toBe(
true,
)
expect(dialog()!.querySelector('[role="alert"]')).toBeNull()
})
it('keeps loading skeleton active if stale first scope request settles while second is still pending (WR-01)', async () => {
const first = deferred()
const second = deferred()
let callCount = 0
mockApi(
tokenRoutes({
[`GET ${SCOPES}`]: () => {
callCount += 1
return callCount === 1 ? first.route() : second.route()
},
}),
)
const wrapper = mount(ApiTokenCreateDialog, {
props: { open: false, confirm: useConfirm() },
attachTo: document.body,
})
await wrapper.setProps({ open: true })
await flushPromises()
await wrapper.setProps({ open: false })
await flushPromises()
await wrapper.setProps({ open: true })
await flushPromises()
expect(dialog()!.querySelector('[data-scope-loading]')).toBeTruthy()
// Stale request #1 resolves early while request #2 is still in flight -> skeleton must remain visible.
first.release({ status: 500, body: { error: { code: 'err', message: 'boom', details: {} } } })
await flushPromises()
expect(dialog()!.querySelector('[data-scope-loading]')).toBeTruthy()
expect(dialog()!.querySelector('[role="alert"]')).toBeNull()
expect(dialog()!.querySelector<HTMLButtonElement>('[data-action="create-token-submit"]')!.disabled).toBe(true)
// Request #2 resolves -> skeleton clears and tiers render normally.
second.release(envelope(scopes))
await flushPromises()
expect(dialog()!.querySelector('[data-scope-loading]')).toBeNull()
expect(dialog()!.querySelector('[data-access-tier="read_only"]')!.getAttribute('data-state')).toBe('checked')
})
})

View File

@@ -306,4 +306,111 @@ describe('ScopePicker.vue', () => {
expect(wrapper.find('[data-scope-filter="selected"]').text()).toBe('Selected (1)')
expect((wrapper.find('[data-action="scope-picker-apply"]').element as HTMLButtonElement).disabled).toBe(false)
})
it('allows collapsing matching groups during search without mutating pre-search expand state (IN-02)', async () => {
const wrapper = mountInteractivePicker({ catalog: smallCatalog })
await flushPromises()
// Collapse SEO before searching (Journal stays expanded, SEO collapsed).
const togglesBefore = wrapper.findAll('[data-scope-group-toggle]')
await togglesBefore[1]!.trigger('click')
await flushPromises()
expect(wrapper.findAll('[data-scope-group-toggle]').map((b) => b.attributes('aria-expanded'))).toEqual([
'true',
'false',
])
// Search for "SEO" -> auto-expands SEO.
const search = wrapper.find('[data-scope-search]')
await search.setValue('seo')
await flushPromises()
expect(wrapper.find('[data-scope-group-toggle]').attributes('aria-expanded')).toBe('true')
// User can temporarily collapse the matching group during search.
await wrapper.find('[data-scope-group-toggle]').trigger('click')
await flushPromises()
expect(wrapper.find('[data-scope-group-toggle]').attributes('aria-expanded')).toBe('false')
// Changing the query re-expands matching groups; clearing restores exact pre-search state.
await search.setValue('seo:read')
await flushPromises()
expect(wrapper.find('[data-scope-group-toggle]').attributes('aria-expanded')).toBe('true')
await wrapper.find('[data-action="clear-scope-search"]').trigger('click')
await flushPromises()
expect(wrapper.findAll('[data-scope-group-toggle]').map((b) => b.attributes('aria-expanded'))).toEqual([
'true',
'false',
])
})
it('uses unique per-instance panel IDs and initializes smart expansion when catalog loads lazily (IN-03)', async () => {
const DualHarness = defineComponent({
components: { ScopePicker },
setup() {
const aRead = ref(false)
const aScopes = ref<Set<string>>(new Set())
const bRead = ref(false)
const bScopes = ref<Set<string>>(new Set())
return { catalog: smallCatalog, aRead, aScopes, bRead, bScopes }
},
template: `
<div>
<div data-first>
<ScopePicker
:catalog="catalog"
v-model:draft-admin-read="aRead"
v-model:draft-scopes="aScopes"
cancel-label="Cancel"
/>
</div>
<div data-second>
<ScopePicker
:catalog="catalog"
v-model:draft-admin-read="bRead"
v-model:draft-scopes="bScopes"
cancel-label="Cancel"
/>
</div>
</div>
`,
})
const dual = mount(DualHarness, { attachTo: document.body })
await flushPromises()
const firstPanelId = dual.find('[data-first] [data-scope-group-toggle]').attributes('aria-controls')
const secondPanelId = dual.find('[data-second] [data-scope-group-toggle]').attributes('aria-controls')
expect(firstPanelId).toBeTruthy()
expect(secondPanelId).toBeTruthy()
expect(firstPanelId).not.toBe(secondPanelId)
// Lazy catalog: starts empty, then populates with smallCatalog -> smart expand triggers automatically.
const lazyCatalog = ref<AdminAPITokenScope[]>([])
const LazyHarness = defineComponent({
components: { ScopePicker },
setup() {
const draftAdminRead = ref(false)
const draftScopes = ref<Set<string>>(new Set())
return { lazyCatalog, draftAdminRead, draftScopes }
},
template: `
<ScopePicker
:catalog="lazyCatalog"
v-model:draft-admin-read="draftAdminRead"
v-model:draft-scopes="draftScopes"
cancel-label="Cancel"
/>
`,
})
const lazy = mount(LazyHarness, { attachTo: document.body })
await flushPromises()
expect(lazy.findAll('[data-scope-group]')).toHaveLength(0)
lazyCatalog.value = smallCatalog
await flushPromises()
expect(lazy.findAll('[data-scope-group-toggle]').map((b) => b.attributes('aria-expanded'))).toEqual([
'true',
'true',
])
})
})

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,2 +1,2 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./editor-uDgt9VKj.js","./index-Vcq4gwWv.js"])))=>i.map(i=>d[i]);
import{_ as r}from"./index-D3o9qWRZ.js";function t(){return r(()=>import("./editor-uDgt9VKj.js"),__vite__mapDeps([0,1]),import.meta.url)}export{t as importCodeEditor};
import{_ as r}from"./index-DOmtaA_-.js";function t(){return r(()=>import("./editor-uDgt9VKj.js"),__vite__mapDeps([0,1]),import.meta.url)}export{t as importCodeEditor};

View File

@@ -8,7 +8,7 @@
<meta name="summer-admin-build" content="__SUMMER_ADMIN_BUILD__" />
<link rel="icon" href="./favicon.ico" sizes="48x48" />
<title>SummerCMS</title>
<script type="module" crossorigin src="./assets/index-D3o9qWRZ.js"></script>
<script type="module" crossorigin src="./assets/index-DOmtaA_-.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DB7OYKHr.css">
</head>
<body>

View File

@@ -286,6 +286,7 @@ func (p *BlogPlugin) AdminFS() fs.FS { return os.DirFS("testdata/docs") }
| `cabana.TokenScopeNames` | The personal-token scope catalog names in catalog order (`*`, `admin:read`, then the plugins' `TokenScopes`), compiled from the activated plugins, so it works at plugin Boot before `cabana.Activate`. |
| `cabana.TokenScopeLabels` | The translated label of each catalog scope name, the name itself for an unknown one, in input order. |
| `cabana.TokenScopeCovers` | Reports whether at least one non-`*` personal API token scope allows the given HTTP method and covers every required permission code (uses the activated catalog on the application when available, else compiles from the passed plugins). |
| `cabana.NewTokenScopeMatcher` / `cabana.TokenScopeMatcher` | Resolves or compiles the token scope catalog once for batch `Covers(method, permissions)` checks (used by `pier` at boot without recompiling per tool). |
| `cabana.MCPConsentView` / `cabana.MCPConsentClientView` / `cabana.MCPConsentAdminView` / `cabana.MCPConsentDecisionRequest` / `cabana.MCPConsentDecisionView` | JSON shapes of the MCP consent routes. `cabana.AdminMCPConsentShow` and `cabana.AdminMCPConsentDecide` carry their swag annotations. |
| `cabana.BackendAccessRevokedEvent` | Fired inside the transaction of an admin save that ends an administrator's access (`AdminIDs`, `Reason`, `Tx`); a listener error rolls the save back. Reasons: `cabana.BackendAccessDeleted`, `cabana.BackendAccessDeactivated`, `cabana.BackendAccessPasswordChanged`, `cabana.BackendAccessPasswordSet`, `cabana.BackendAccessPasswordReset`, `cabana.BackendAccessPermissions`. |
| `cabana.BackendPrincipal` | Loads an admin principal by id through the backend users provider (grants, superuser flag, backend kind set); nil, nil for a missing or deactivated admin. |

View File

@@ -64,45 +64,64 @@ func TokenScopeLabels(ctx context.Context, app *backpack.App, names []string) []
return out
}
func tokenScopeCatalogFor(app *backpack.App, plugins []party.Plugin) *tokenScopeCatalog {
func tokenScopeCatalogFor(app *backpack.App, plugins []party.Plugin) (*tokenScopeCatalog, error) {
if guard := publishedResolverGuard(app); guard != nil && guard.reg != nil && guard.reg.tokenScopes != nil {
return guard.reg.tokenScopes
return guard.reg.tokenScopes, nil
}
if len(plugins) > 0 {
reg, err := compileTokenCatalog(plugins)
if err == nil && reg != nil {
return reg.tokenScopes
if err != nil {
return nil, err
}
return nil
if reg != nil {
return reg.tokenScopes, nil
}
return nil, nil
}
reg, err := tokenCatalogForApp(app)
if err == nil && reg != nil {
return reg.tokenScopes
if err != nil {
return nil, err
}
return nil
if reg != nil {
return reg.tokenScopes, nil
}
return nil, nil
}
// TokenScopeCovers reports whether at least one non-"*" personal API token
// scope allows method and covers every permission code in permissions. It uses
// the activated cabana catalog on app when available, else compiles from
// plugins (falling back to party.Activated). Returns false when permissions is
// empty on a non-read-only method, when method is unsupported, or when no
// non-"*" scope covers every code.
func TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool {
cat := tokenScopeCatalogFor(app, plugins)
if cat == nil {
// TokenScopeMatcher caches a resolved token scope catalog so callers checking
// many routes or MCP tools (such as pier.Mount) do not recompile plugin scopes
// per tool when cabana has not been activated on app.
type TokenScopeMatcher struct {
cat *tokenScopeCatalog
}
// NewTokenScopeMatcher resolves the activated cabana token scope catalog on app
// when available, or compiles it once from plugins (falling back to
// party.Activated).
func NewTokenScopeMatcher(app *backpack.App, plugins []party.Plugin) (*TokenScopeMatcher, error) {
cat, err := tokenScopeCatalogFor(app, plugins)
if err != nil {
return nil, err
}
return &TokenScopeMatcher{cat: cat}, nil
}
// Covers reports whether at least one non-"*" personal API token scope in the
// matcher allows method and covers every permission code in permissions.
func (m *TokenScopeMatcher) Covers(method string, permissions []string) bool {
if m == nil || m.cat == nil {
return false
}
m := strings.ToUpper(strings.TrimSpace(method))
if m == "" {
methodName := strings.ToUpper(strings.TrimSpace(method))
if methodName == "" {
return false
}
var scopes [][]string
for _, scope := range cat.ordered {
for _, scope := range m.cat.ordered {
if scope.Name == scopeAll {
continue
}
if !scope.Methods[m] {
if !scope.Methods[methodName] {
continue
}
if scope.Full {
@@ -112,3 +131,17 @@ func TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string,
}
return scopeCoversAll(&bouncer.ScopeLimit{Scopes: scopes}, permissions)
}
// TokenScopeCovers reports whether at least one non-"*" personal API token
// scope allows method and covers every permission code in permissions. It uses
// the activated cabana catalog on app when available, else compiles from
// plugins (falling back to party.Activated). Returns false when permissions is
// empty on a non-read-only method, when method is unsupported, or when no
// non-"*" scope covers every code.
func TokenScopeCovers(app *backpack.App, plugins []party.Plugin, method string, permissions []string) bool {
matcher, err := NewTokenScopeMatcher(app, plugins)
if err != nil {
return false
}
return matcher.Covers(method, permissions)
}

View File

@@ -17,6 +17,7 @@ func warnUncoveredBackendWriteTools(app *backpack.App, plugins []party.Plugin, c
if cat == nil || len(cat.tools) == 0 {
return
}
var matcher *cabana.TokenScopeMatcher
byPlugin := map[string][]string{}
var pluginOrder []string
for _, t := range cat.tools {
@@ -26,7 +27,18 @@ func warnUncoveredBackendWriteTools(app *backpack.App, plugins []party.Plugin, c
if t.method == http.MethodGet || t.method == http.MethodHead {
continue
}
if cabana.TokenScopeCovers(app, plugins, t.method, t.decl.Permissions) {
if matcher == nil {
var err error
matcher, err = cabana.NewTokenScopeMatcher(app, plugins)
if err != nil {
logger().Warn(
"pier: could not compile token scope catalog while checking backend write MCP tool coverage",
"err", err,
)
return
}
}
if matcher.Covers(t.method, t.decl.Permissions) {
continue
}
if _, seen := byPlugin[t.pluginID]; !seen {

View File

@@ -319,4 +319,45 @@ func TestUncoveredBackendWriteToolsWarning(t *testing.T) {
t.Fatalf("expected 0 warning lines for user-guarded write tool, got %d:\n%s", got, buf.String())
}
})
t.Run("warns_on_invalid_token_scope_catalog_without_misleading_tool_warnings", func(t *testing.T) {
buf := captureLogs(t)
app := pierAppWith(t, map[string]string{"mcp.yaml": "enabled: false\n"}, &acmeGuard{})
plugin := warningScopedPlugin{
warningBackendPlugin: warningBackendPlugin{
id: "acme.badscope",
mountMW: true,
registerMW: true,
perms: []pact.Permission{
{Code: "acme.badscope.manage", Tab: "Bad", Label: "Manage"},
},
tools: []pact.MCPTool{
{
Name: "badscope_create_item", Title: "Create item", Description: "Create item.",
Method: http.MethodPost, Path: "/acme-badscope/items/{id}", Input: warningTestInput{},
Permissions: []string{"acme.badscope.manage"},
},
},
},
scopes: []pact.TokenScope{
{
Name: "INVALID SCOPE", Label: "Bad", Description: "Invalid scope name",
Permissions: []string{"acme.badscope.*"}, Methods: allMethods,
},
},
}
host, err := mountPier(t, app, []party.Plugin{plugin})
if err != nil {
t.Fatalf("mountPier must not fail boot: %v", err)
}
t.Cleanup(func() { _ = host.pier.Close() })
logs := buf.String()
if got := countWarningLines(logs); got != 0 {
t.Fatalf("expected 0 misleading per-plugin uncovered-tool warnings on catalog error, got %d:\n%s", got, logs)
}
if !strings.Contains(logs, "could not compile token scope catalog") {
t.Fatalf("expected catalog compile warning in logs:\n%s", logs)
}
})
}