fix(36): compile token scope catalog once in pier boot coverage warning

This commit is contained in:
Jakub Zych
2026-11-25 01:29:28 +01:00
parent 0b90f757bc
commit 51b60b94b8
4 changed files with 109 additions and 22 deletions

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)
}
})
}