test(36-04): add Go unit and integration tests for token scopes and pier boot warnings
This commit is contained in:
@@ -123,6 +123,38 @@ func TestAccountTokens(t *testing.T) {
|
||||
t.Fatalf("* entry %#v", s)
|
||||
}
|
||||
}
|
||||
// Verify raw JSON wire keys "plugin_id" and "group" are always present on /account/tokens.
|
||||
var rawListed struct {
|
||||
Data []struct {
|
||||
Name string `json:"name"`
|
||||
Scopes []map[string]any `json:"scopes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(list.Body.Bytes(), &rawListed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tok := range rawListed.Data {
|
||||
for _, rawScope := range tok.Scopes {
|
||||
name, _ := rawScope["name"].(string)
|
||||
pidVal, hasPID := rawScope["plugin_id"]
|
||||
grpVal, hasGrp := rawScope["group"]
|
||||
if !hasPID || !hasGrp {
|
||||
t.Fatalf("token %q scope %q missing plugin_id/group keys: %#v", tok.Name, name, rawScope)
|
||||
}
|
||||
pid, _ := pidVal.(string)
|
||||
grp, _ := grpVal.(string)
|
||||
switch name {
|
||||
case "demo":
|
||||
if pid != "acme.demo" || grp != "acme.demo" {
|
||||
t.Fatalf("token %q scope demo: plugin_id=%q group=%q, want acme.demo/acme.demo", tok.Name, pid, grp)
|
||||
}
|
||||
case "*", "admin:read", "ghost":
|
||||
if pid != "" || grp != "" {
|
||||
t.Fatalf("token %q scope %q: plugin_id=%q group=%q, want empty strings", tok.Name, name, pid, grp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Revoked filter.
|
||||
revokedID := listed.Data[0].ID
|
||||
@@ -240,5 +272,32 @@ func TestAccountTokens(t *testing.T) {
|
||||
if !superNames["*"] || !superNames["admin:read"] {
|
||||
t.Fatalf("superuser scopes %#v", superNames)
|
||||
}
|
||||
// Verify raw JSON wire keys "plugin_id" and "group" on /account/tokens/scopes.
|
||||
var rawScopes struct {
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(superScopes.Body.Bytes(), &rawScopes); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, rawScope := range rawScopes.Data {
|
||||
name, _ := rawScope["name"].(string)
|
||||
pidVal, hasPID := rawScope["plugin_id"]
|
||||
grpVal, hasGrp := rawScope["group"]
|
||||
if !hasPID || !hasGrp {
|
||||
t.Fatalf("/account/tokens/scopes entry %q missing plugin_id/group keys: %#v", name, rawScope)
|
||||
}
|
||||
pid, _ := pidVal.(string)
|
||||
grp, _ := grpVal.(string)
|
||||
switch name {
|
||||
case "*", "admin:read":
|
||||
if pid != "" || grp != "" {
|
||||
t.Fatalf("framework scope %q: plugin_id=%q group=%q, want empty strings", name, pid, grp)
|
||||
}
|
||||
case "demo", "demo:reports":
|
||||
if pid != "acme.demo" || grp != "acme.demo" {
|
||||
t.Fatalf("plugin scope %q: plugin_id=%q group=%q, want acme.demo/acme.demo", name, pid, grp)
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = otherJWT
|
||||
}
|
||||
|
||||
@@ -293,6 +293,41 @@ func TestMCPAdminConsent(t *testing.T) {
|
||||
t.Fatalf("scope %+v: read_only must be set for admin:read only and the label filled", sc)
|
||||
}
|
||||
}
|
||||
// Verify raw JSON wire keys "plugin_id" and "group" on GET /mcp/consent/{request}.
|
||||
writerRec := show("req1", writerP)
|
||||
if writerRec.Code != http.StatusOK {
|
||||
t.Fatalf("writer show = %d %s", writerRec.Code, writerRec.Body.String())
|
||||
}
|
||||
var rawConsent struct {
|
||||
Data struct {
|
||||
Scopes []map[string]any `json:"scopes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(writerRec.Body.Bytes(), &rawConsent); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, rawScope := range rawConsent.Data.Scopes {
|
||||
name, _ := rawScope["name"].(string)
|
||||
pidVal, hasPID := rawScope["plugin_id"]
|
||||
grpVal, hasGrp := rawScope["group"]
|
||||
if !hasPID || !hasGrp {
|
||||
t.Fatalf("consent scope %q missing plugin_id/group keys: %#v", name, rawScope)
|
||||
}
|
||||
pid, _ := pidVal.(string)
|
||||
grp, _ := grpVal.(string)
|
||||
switch name {
|
||||
case "*", "admin:read":
|
||||
if pid != "" || grp != "" {
|
||||
t.Fatalf("consent framework scope %q: plugin_id=%q group=%q, want empty strings", name, pid, grp)
|
||||
}
|
||||
case "acme:write":
|
||||
if pid != "acme.items" || grp != "Items" {
|
||||
t.Fatalf("consent plugin scope acme:write: plugin_id=%q group=%q, want acme.items/Items", pid, grp)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Keep last Show call assertion targeting readerP below.
|
||||
_ = show("req1", readerP)
|
||||
provider.mu.Lock()
|
||||
last := provider.shows[len(provider.shows)-1]
|
||||
provider.mu.Unlock()
|
||||
|
||||
@@ -122,3 +122,150 @@ func TestTokenScopeNames(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type multiPermPlugin struct {
|
||||
id string
|
||||
perms []pact.Permission
|
||||
scopes []pact.TokenScope
|
||||
}
|
||||
|
||||
func (p multiPermPlugin) ID() string { return p.id }
|
||||
func (multiPermPlugin) Requires() []string { return nil }
|
||||
func (multiPermPlugin) Register(*backpack.App) error { return nil }
|
||||
func (multiPermPlugin) Boot(*backpack.App) error { return nil }
|
||||
func (p multiPermPlugin) Permissions() []pact.Permission { return p.perms }
|
||||
func (p multiPermPlugin) TokenScopes() []pact.TokenScope { return p.scopes }
|
||||
|
||||
func TestTokenScopeCovers(t *testing.T) {
|
||||
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
readOnly := []string{"GET", "HEAD"}
|
||||
|
||||
noScopes := multiPermPlugin{
|
||||
id: "acme.bare",
|
||||
perms: []pact.Permission{{Code: "acme.bare.write", Tab: "Bare", Label: "Write"}},
|
||||
}
|
||||
blog := multiPermPlugin{
|
||||
id: "acme.blog",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.blog.posts", Tab: "Blog", Label: "Posts"},
|
||||
{Code: "acme.blog.tags", Tab: "Blog", Label: "Tags"},
|
||||
},
|
||||
scopes: []pact.TokenScope{
|
||||
{
|
||||
Name: "blog:read", Label: "Blog read", Description: "Read blog",
|
||||
Permissions: []string{"acme.blog.*"}, Methods: readOnly,
|
||||
},
|
||||
{
|
||||
Name: "blog:posts", Label: "Blog posts", Description: "Write posts",
|
||||
Permissions: []string{"acme.blog.posts"}, Methods: all,
|
||||
},
|
||||
{
|
||||
Name: "blog:tags", Label: "Blog tags", Description: "Write tags",
|
||||
Permissions: []string{"acme.blog.tags"}, Methods: all,
|
||||
},
|
||||
},
|
||||
}
|
||||
blogAll := multiPermPlugin{
|
||||
id: "acme.blog",
|
||||
perms: blog.perms,
|
||||
scopes: []pact.TokenScope{
|
||||
{
|
||||
Name: "blog", Label: "Blog", Description: "Full blog",
|
||||
Permissions: []string{"acme.blog.*"}, Methods: all,
|
||||
},
|
||||
},
|
||||
}
|
||||
companion := multiPermPlugin{
|
||||
id: "acme.companion",
|
||||
scopes: []pact.TokenScope{
|
||||
{
|
||||
Name: "bare:companion", Label: "Bare companion", Description: "Covers acme.bare",
|
||||
Permissions: []string{"acme.bare.*"}, Methods: all,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("wildcard * alone does not cover writes; GET and HEAD covered via admin:read", func(t *testing.T) {
|
||||
plugins := []party.Plugin{noScopes}
|
||||
for _, method := range []string{"POST", "PUT", "PATCH", "DELETE"} {
|
||||
if TokenScopeCovers(nil, plugins, method, []string{"acme.bare.write"}) {
|
||||
t.Fatalf("method %s should not be covered by * alone", method)
|
||||
}
|
||||
}
|
||||
for _, method := range []string{"GET", "HEAD", " get "} {
|
||||
if !TokenScopeCovers(nil, plugins, method, []string{"acme.bare.write"}) {
|
||||
t.Fatalf("method %q should be covered via admin:read", method)
|
||||
}
|
||||
if !TokenScopeCovers(nil, plugins, method, nil) {
|
||||
t.Fatalf("method %q with empty permissions should be covered via admin:read", method)
|
||||
}
|
||||
}
|
||||
if TokenScopeCovers(nil, plugins, "", []string{"acme.bare.write"}) {
|
||||
t.Fatal("empty method must return false")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("read-only scope fails POST; split scopes fail multi-perm; single scope covering all passes", func(t *testing.T) {
|
||||
plugins := []party.Plugin{blog}
|
||||
if !TokenScopeCovers(nil, plugins, "POST", []string{"acme.blog.posts"}) {
|
||||
t.Fatal("blog:posts should cover POST acme.blog.posts")
|
||||
}
|
||||
if TokenScopeCovers(nil, plugins, "POST", []string{"acme.blog.posts", "acme.blog.tags"}) {
|
||||
t.Fatal("multi-permission requirement split across two scopes must return false")
|
||||
}
|
||||
// Only read-only scope plugin.
|
||||
roOnly := multiPermPlugin{
|
||||
id: "acme.blog",
|
||||
perms: blog.perms,
|
||||
scopes: blog.scopes[:1],
|
||||
}
|
||||
if TokenScopeCovers(nil, []party.Plugin{roOnly}, "POST", []string{"acme.blog.posts"}) {
|
||||
t.Fatal("read-only plugin scope must not cover POST")
|
||||
}
|
||||
// Single scope covering both permissions.
|
||||
if !TokenScopeCovers(nil, []party.Plugin{blogAll}, "POST", []string{"acme.blog.posts", "acme.blog.tags"}) {
|
||||
t.Fatal("blog wildcard scope should cover both permissions on POST")
|
||||
}
|
||||
// Empty permissions on POST must return false (matching runtime allowsUnderScope).
|
||||
if TokenScopeCovers(nil, []party.Plugin{blogAll}, "POST", nil) {
|
||||
t.Fatal("empty permissions on POST must return false")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("companion plugin scope covers first plugin write tool", func(t *testing.T) {
|
||||
plugins := []party.Plugin{noScopes, companion}
|
||||
if !TokenScopeCovers(nil, plugins, "DELETE", []string{"acme.bare.write"}) {
|
||||
t.Fatal("companion plugin scope should cover acme.bare.write")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("activated cabana guard path and party.Activated fallback", func(t *testing.T) {
|
||||
// Activated cabana guard path takes precedence even when plugins slice is nil.
|
||||
reg, err := compileTokenCatalog([]party.Plugin{blogAll})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
activatedApp := backpack.New(nil)
|
||||
if err := activatedApp.Publish(&backendResolver{guard: &compositeGuard{reg: reg}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !TokenScopeCovers(activatedApp, nil, "POST", []string{"acme.blog.posts", "acme.blog.tags"}) {
|
||||
t.Fatal("activated guard path should cover blog write permissions")
|
||||
}
|
||||
if TokenScopeCovers(activatedApp, nil, "POST", []string{"acme.bare.write"}) {
|
||||
t.Fatal("activated guard path should not cover unrelated permission")
|
||||
}
|
||||
|
||||
// party.Activated fallback when cabana is not activated and plugins slice is nil.
|
||||
bootApp := backpack.New(nil)
|
||||
if err := bootApp.Publish(party.Activated([]party.Plugin{blogAll})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !TokenScopeCovers(bootApp, nil, "PUT", []string{"acme.blog.posts"}) {
|
||||
t.Fatal("party.Activated fallback should cover acme.blog.posts")
|
||||
}
|
||||
if TokenScopeCovers(bootApp, nil, "PUT", []string{"acme.bare.write"}) {
|
||||
t.Fatal("party.Activated fallback should not cover unrelated permission")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
package cabana
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
)
|
||||
|
||||
func TestScopeMatch(t *testing.T) {
|
||||
@@ -352,3 +355,306 @@ func stringSlicesEqual(a, b []string) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func testTranslator(t *testing.T, namespaces map[string]map[string]string) *phrasebook.Translator {
|
||||
t.Helper()
|
||||
cat := phrasebook.NewCatalog()
|
||||
for ns, files := range namespaces {
|
||||
fsys := fstest.MapFS{}
|
||||
for p, body := range files {
|
||||
fsys[p] = &fstest.MapFile{Data: []byte(body)}
|
||||
}
|
||||
if err := cat.Load(ns, fsys); err != nil {
|
||||
t.Fatalf("load phrasebook %s: %v", ns, err)
|
||||
}
|
||||
}
|
||||
return phrasebook.NewTranslator(cat, phrasebook.Options{Locale: "en", Fallback: "en"})
|
||||
}
|
||||
|
||||
func TestTokenScopeGroupValidation(t *testing.T) {
|
||||
shopPerms := []pact.Permission{{Code: "acme.shop.orders", Roles: []string{"developer"}}}
|
||||
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
|
||||
tr := testTranslator(t, map[string]map[string]string{
|
||||
"backend": {
|
||||
"lang/en/lang.yaml": "api_tokens:\n scope_all: Full access\n scope_all_description: Everything\n scope_admin_read: Read-only\n scope_admin_read_description: Read everything\n",
|
||||
},
|
||||
"acme.shop": {
|
||||
"lang/en/lang.yaml": "groups:\n sales: Sales\n",
|
||||
},
|
||||
})
|
||||
|
||||
t.Run("literal group passes compilation and message key validation", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{scopePlugin{
|
||||
id: "acme.shop",
|
||||
perms: shopPerms,
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "shop", Label: "Shop", Description: "Manage shop", Group: " Commerce ",
|
||||
Permissions: []string{"acme.shop.orders"}, Methods: all,
|
||||
}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("compileTokenCatalog: %v", err)
|
||||
}
|
||||
if got := reg.tokenScopes.byName["shop"].Group; got != "Commerce" {
|
||||
t.Fatalf("compiled Group = %q, want %q", got, "Commerce")
|
||||
}
|
||||
if err := validateTokenScopeMessageKeys(reg, tr); err != nil {
|
||||
t.Fatalf("validateTokenScopeMessageKeys: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("valid phrase key group passes", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{scopePlugin{
|
||||
id: "acme.shop",
|
||||
perms: shopPerms,
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "shop", Label: "Shop", Description: "Manage shop", Group: "acme.shop::lang.groups.sales",
|
||||
Permissions: []string{"acme.shop.orders"}, Methods: all,
|
||||
}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("compileTokenCatalog: %v", err)
|
||||
}
|
||||
if err := validateTokenScopeMessageKeys(reg, tr); err != nil {
|
||||
t.Fatalf("validateTokenScopeMessageKeys: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing phrase key group fails boot validation naming scope plugin and key", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{scopePlugin{
|
||||
id: "acme.shop",
|
||||
perms: shopPerms,
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "shop", Label: "Shop", Description: "Manage shop", Group: "acme.shop::lang.groups.missing",
|
||||
Permissions: []string{"acme.shop.orders"}, Methods: all,
|
||||
}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("compileTokenCatalog: %v", err)
|
||||
}
|
||||
err = validateTokenScopeMessageKeys(reg, tr)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing :: phrase key in Group")
|
||||
}
|
||||
for _, want := range []string{"shop", "acme.shop", "acme.shop::lang.groups.missing"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("err = %q, want substring %q", err.Error(), want)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty group passes validation", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{scopePlugin{
|
||||
id: "acme.shop",
|
||||
perms: shopPerms,
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "shop", Label: "Shop", Description: "Manage shop", Group: "",
|
||||
Permissions: []string{"acme.shop.orders"}, Methods: all,
|
||||
}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("compileTokenCatalog: %v", err)
|
||||
}
|
||||
if err := validateTokenScopeMessageKeys(reg, tr); err != nil {
|
||||
t.Fatalf("validateTokenScopeMessageKeys: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestScopeGroupFallbackResolution(t *testing.T) {
|
||||
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
tr := testTranslator(t, map[string]map[string]string{
|
||||
"acme.shop": {
|
||||
"lang/en/lang.yaml": "plugin:\n name: Shop Plugin\ngroups:\n sales: Sales\n",
|
||||
"lang/pl/lang.yaml": "plugin:\n name: Wtyczka Sklep\ngroups:\n sales: Sprzedaż\n",
|
||||
},
|
||||
"acme.orders": {
|
||||
"lang/en/lang.yaml": "tabs:\n orders: Orders\n",
|
||||
"lang/pl/lang.yaml": "tabs:\n orders: Zamówienia\n",
|
||||
},
|
||||
})
|
||||
enCtx := towel.WithLocale(context.Background(), "en")
|
||||
plCtx := towel.WithLocale(context.Background(), "pl")
|
||||
|
||||
t.Run("explicit literal and phrase key group win over plugin.name and Tab", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{scopePlugin{
|
||||
id: "acme.shop",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.shop.orders", Tab: "Ignored Tab", Roles: []string{"developer"}},
|
||||
},
|
||||
scopes: []pact.TokenScope{
|
||||
{
|
||||
Name: "shop:lit", Label: "Literal", Description: "D", Group: "Commerce",
|
||||
Permissions: []string{"acme.shop.orders"}, Methods: all,
|
||||
},
|
||||
{
|
||||
Name: "shop:key", Label: "Keyed", Description: "D", Group: "acme.shop::lang.groups.sales",
|
||||
Permissions: []string{"acme.shop.orders"}, Methods: all,
|
||||
},
|
||||
},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lit := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["shop:lit"])
|
||||
if lit.PluginID != "acme.shop" || lit.Group != "Commerce" {
|
||||
t.Fatalf("literal = %+v, want plugin_id=acme.shop group=Commerce", lit)
|
||||
}
|
||||
keyEN := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["shop:key"])
|
||||
if keyEN.PluginID != "acme.shop" || keyEN.Group != "Sales" {
|
||||
t.Fatalf("keyed en = %+v, want group=Sales", keyEN)
|
||||
}
|
||||
keyPL := mapCompiledScope(plCtx, tr, reg, reg.tokenScopes.byName["shop:key"])
|
||||
if keyPL.PluginID != "acme.shop" || keyPL.Group != "Sprzedaż" {
|
||||
t.Fatalf("keyed pl = %+v, want group=Sprzedaż", keyPL)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fallback 1 resolves plugin.name in requested locale", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{scopePlugin{
|
||||
id: "acme.shop",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.shop.orders", Tab: "Orders Tab", Roles: []string{"developer"}},
|
||||
},
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "shop", Label: "Shop", Description: "D",
|
||||
Permissions: []string{"acme.shop.orders"}, Methods: all,
|
||||
}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
en := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["shop"])
|
||||
if en.PluginID != "acme.shop" || en.Group != "Shop Plugin" {
|
||||
t.Fatalf("en = %+v, want group=Shop Plugin", en)
|
||||
}
|
||||
pl := mapCompiledScope(plCtx, tr, reg, reg.tokenScopes.byName["shop"])
|
||||
if pl.PluginID != "acme.shop" || pl.Group != "Wtyczka Sklep" {
|
||||
t.Fatalf("pl = %+v, want group=Wtyczka Sklep", pl)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fallback 2 resolves unanimous literal and translated permission Tab", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{
|
||||
scopePlugin{
|
||||
id: "acme.billing",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.billing.read", Tab: "Billing", Roles: []string{"developer"}},
|
||||
{Code: "acme.billing.write", Tab: "Billing", Roles: []string{"developer"}},
|
||||
},
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "billing", Label: "Billing", Description: "D",
|
||||
Permissions: []string{"acme.billing.*"}, Methods: all,
|
||||
}},
|
||||
},
|
||||
scopePlugin{
|
||||
id: "acme.orders",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.orders.read", Tab: "acme.orders::lang.tabs.orders", Roles: []string{"developer"}},
|
||||
{Code: "acme.orders.write", Tab: "acme.orders::lang.tabs.orders", Roles: []string{"developer"}},
|
||||
},
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "orders", Label: "Orders", Description: "D",
|
||||
Permissions: []string{"acme.orders.*"}, Methods: all,
|
||||
}},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
billing := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["billing"])
|
||||
if billing.PluginID != "acme.billing" || billing.Group != "Billing" {
|
||||
t.Fatalf("billing = %+v, want group=Billing", billing)
|
||||
}
|
||||
ordersEN := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["orders"])
|
||||
if ordersEN.PluginID != "acme.orders" || ordersEN.Group != "Orders" {
|
||||
t.Fatalf("orders en = %+v, want group=Orders", ordersEN)
|
||||
}
|
||||
ordersPL := mapCompiledScope(plCtx, tr, reg, reg.tokenScopes.byName["orders"])
|
||||
if ordersPL.PluginID != "acme.orders" || ordersPL.Group != "Zamówienia" {
|
||||
t.Fatalf("orders pl = %+v, want group=Zamówienia", ordersPL)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fallback 2 non-unanimous or partially empty Tab falls through to plugin_id", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{
|
||||
scopePlugin{
|
||||
id: "acme.mixed",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.mixed.a", Tab: "Alpha", Roles: []string{"developer"}},
|
||||
{Code: "acme.mixed.b", Tab: "Beta", Roles: []string{"developer"}},
|
||||
},
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "mixed", Label: "Mixed", Description: "D",
|
||||
Permissions: []string{"acme.mixed.*"}, Methods: all,
|
||||
}},
|
||||
},
|
||||
scopePlugin{
|
||||
id: "acme.partial",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.partial.a", Tab: "Alpha", Roles: []string{"developer"}},
|
||||
{Code: "acme.partial.b", Tab: "", Roles: []string{"developer"}},
|
||||
},
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "partial", Label: "Partial", Description: "D",
|
||||
Permissions: []string{"acme.partial.*"}, Methods: all,
|
||||
}},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mixed := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["mixed"])
|
||||
if mixed.PluginID != "acme.mixed" || mixed.Group != "acme.mixed" {
|
||||
t.Fatalf("mixed = %+v, want group=acme.mixed", mixed)
|
||||
}
|
||||
partial := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["partial"])
|
||||
if partial.PluginID != "acme.partial" || partial.Group != "acme.partial" {
|
||||
t.Fatalf("partial = %+v, want group=acme.partial", partial)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fallback 3 returns raw plugin_id when no group plugin.name or tab exists", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog([]party.Plugin{scopePlugin{
|
||||
id: "acme.bare",
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.bare.use", Roles: []string{"developer"}},
|
||||
},
|
||||
scopes: []pact.TokenScope{{
|
||||
Name: "bare", Label: "Bare", Description: "D",
|
||||
Permissions: []string{"acme.bare.use"}, Methods: all,
|
||||
}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Empty Tab case.
|
||||
bare := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName["bare"])
|
||||
if bare.PluginID != "acme.bare" || bare.Group != "acme.bare" {
|
||||
t.Fatalf("bare = %+v, want group=acme.bare", bare)
|
||||
}
|
||||
// Zero matched permissions case (nil registry passed to mapCompiledScope).
|
||||
noReg := mapCompiledScope(enCtx, tr, nil, reg.tokenScopes.byName["bare"])
|
||||
if noReg.PluginID != "acme.bare" || noReg.Group != "acme.bare" {
|
||||
t.Fatalf("noReg = %+v, want group=acme.bare", noReg)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("framework and unknown stored scopes emit empty plugin_id and group", func(t *testing.T) {
|
||||
reg, err := compileTokenCatalog(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"*", "admin:read"} {
|
||||
got := mapCompiledScope(enCtx, tr, reg, reg.tokenScopes.byName[name])
|
||||
if got.PluginID != "" || got.Group != "" {
|
||||
t.Fatalf("framework scope %q = %+v, want empty plugin_id and group", name, got)
|
||||
}
|
||||
}
|
||||
unknown := mapStoredScope(enCtx, tr, reg, "removed:scope")
|
||||
if unknown.Known || unknown.PluginID != "" || unknown.Group != "" {
|
||||
t.Fatalf("unknown stored scope = %+v, want known=false and empty plugin_id/group", unknown)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
322
modules/pier/uncovered_scopes_warning_test.go
Normal file
322
modules/pier/uncovered_scopes_warning_test.go
Normal file
@@ -0,0 +1,322 @@
|
||||
package pier_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
)
|
||||
|
||||
type warningTestInput struct {
|
||||
ID int `json:"id" path:"id" jsonschema:"item id"`
|
||||
}
|
||||
|
||||
// warningBackendPlugin registers a backend-guarded route set and MCP tools
|
||||
// without implementing pact.HasTokenScopes.
|
||||
type warningBackendPlugin struct {
|
||||
id string
|
||||
mwName string
|
||||
mountMW bool
|
||||
perms []pact.Permission
|
||||
tools []pact.MCPTool
|
||||
registerMW bool
|
||||
}
|
||||
|
||||
func (p warningBackendPlugin) ID() string { return p.id }
|
||||
func (p warningBackendPlugin) Requires() []string { return nil }
|
||||
func (p warningBackendPlugin) Register(*backpack.App) error { return nil }
|
||||
func (p warningBackendPlugin) Boot(*backpack.App) error { return nil }
|
||||
func (p warningBackendPlugin) Permissions() []pact.Permission {
|
||||
return p.perms
|
||||
}
|
||||
|
||||
func (p warningBackendPlugin) Middlewares() map[string]pact.Middleware {
|
||||
if !p.registerMW {
|
||||
return nil
|
||||
}
|
||||
name := p.mwName
|
||||
if name == "" {
|
||||
name = "backend"
|
||||
}
|
||||
return map[string]pact.Middleware{
|
||||
name: func(next http.Handler) http.Handler { return next },
|
||||
}
|
||||
}
|
||||
|
||||
func (p warningBackendPlugin) Routes(r pact.Router) error {
|
||||
if !p.mountMW {
|
||||
return nil
|
||||
}
|
||||
mw := p.mwName
|
||||
if mw == "" {
|
||||
mw = "backend"
|
||||
}
|
||||
noop := func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"ok":true}`))
|
||||
}
|
||||
r.Group("/"+strings.ReplaceAll(p.id, ".", "-"), []string{mw}, func(g pact.Router) {
|
||||
g.Get("/items/{id}", noop)
|
||||
g.Post("/items/{id}", noop)
|
||||
g.Delete("/items/{id}", noop)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p warningBackendPlugin) MCP() pact.MCP {
|
||||
return pact.MCP{Tools: p.tools}
|
||||
}
|
||||
|
||||
// warningScopedPlugin extends warningBackendPlugin with pact.HasTokenScopes.
|
||||
type warningScopedPlugin struct {
|
||||
warningBackendPlugin
|
||||
scopes []pact.TokenScope
|
||||
}
|
||||
|
||||
func (p warningScopedPlugin) TokenScopes() []pact.TokenScope { return p.scopes }
|
||||
|
||||
// warningUserGuard is a minimal non-backend ("user") MCP guard provider.
|
||||
type warningUserGuard struct{}
|
||||
|
||||
func (warningUserGuard) MCPGuardName() string { return "user" }
|
||||
func (warningUserGuard) MCPTokenGuarded(mw []string) bool {
|
||||
for _, m := range mw {
|
||||
if m == "user.auth" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (warningUserGuard) MCPRequirements([]string) (pact.MCPRequirements, error) {
|
||||
return pact.MCPRequirements{}, nil
|
||||
}
|
||||
func (warningUserGuard) MCPAllows(context.Context, pact.MCPSubject, pact.MCPRequirements, []string) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
func (warningUserGuard) MCPDispatch(_ context.Context, subject pact.MCPSubject, _ string) (pact.MCPDispatch, error) {
|
||||
return pact.MCPDispatch{Principal: &bouncer.Principal{ID: subject.UserID}, Guards: []string{"user"}}, nil
|
||||
}
|
||||
|
||||
func countWarningLines(logs string) int {
|
||||
n := 0
|
||||
for _, line := range strings.Split(logs, "\n") {
|
||||
if strings.Contains(line, "level=WARN") && strings.Contains(line, "not covered by any non-* TokenScope") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestUncoveredBackendWriteToolsWarning(t *testing.T) {
|
||||
allMethods := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
|
||||
t.Run("warns_once_per_plugin_for_uncovered_backend_writes", func(t *testing.T) {
|
||||
buf := captureLogs(t)
|
||||
app := pierAppWith(t, map[string]string{"mcp.yaml": "enabled: false\n"}, &acmeGuard{})
|
||||
plugin := warningBackendPlugin{
|
||||
id: "acme.blog",
|
||||
mountMW: true,
|
||||
registerMW: true,
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.blog.manage", Tab: "Blog", Label: "Manage"},
|
||||
},
|
||||
tools: []pact.MCPTool{
|
||||
{
|
||||
Name: "blog_get_item", Title: "Get item", Description: "Read item.",
|
||||
Method: http.MethodGet, Path: "/acme-blog/items/{id}", Input: warningTestInput{},
|
||||
Permissions: []string{"acme.blog.manage"},
|
||||
},
|
||||
{
|
||||
Name: "blog_delete_item", Title: "Delete item", Description: "Delete item.",
|
||||
Method: http.MethodDelete, Path: "/acme-blog/items/{id}", Input: warningTestInput{},
|
||||
Permissions: []string{"acme.blog.manage"},
|
||||
},
|
||||
{
|
||||
Name: "blog_create_item", Title: "Create item", Description: "Create item.",
|
||||
Method: http.MethodPost, Path: "/acme-blog/items/{id}", Input: warningTestInput{},
|
||||
Permissions: []string{"acme.blog.manage"},
|
||||
},
|
||||
},
|
||||
}
|
||||
host, err := mountPier(t, app, []party.Plugin{plugin})
|
||||
if err != nil {
|
||||
t.Fatalf("mountPier must not fail boot on uncovered write tools: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = host.pier.Close() })
|
||||
|
||||
logs := buf.String()
|
||||
if got := countWarningLines(logs); got != 1 {
|
||||
t.Fatalf("warning lines = %d, want 1; logs:\n%s", got, logs)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"plugin=acme.blog",
|
||||
"pact.HasTokenScopes",
|
||||
"blog_create_item",
|
||||
"blog_delete_item",
|
||||
} {
|
||||
if !strings.Contains(logs, want) {
|
||||
t.Fatalf("logs missing %q:\n%s", want, logs)
|
||||
}
|
||||
}
|
||||
if strings.Index(logs, "blog_create_item") > strings.Index(logs, "blog_delete_item") {
|
||||
t.Fatalf("expected sorted tool names in warning log:\n%s", logs)
|
||||
}
|
||||
if strings.Contains(logs, "blog_get_item") {
|
||||
t.Fatalf("GET tool must not appear in uncovered write warning:\n%s", logs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("silent_when_covered_by_token_scope", 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.shop",
|
||||
mountMW: true,
|
||||
registerMW: true,
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.shop.manage", Tab: "Shop", Label: "Manage"},
|
||||
},
|
||||
tools: []pact.MCPTool{
|
||||
{
|
||||
Name: "shop_create_item", Title: "Create item", Description: "Create item.",
|
||||
Method: http.MethodPost, Path: "/acme-shop/items/{id}", Input: warningTestInput{},
|
||||
Permissions: []string{"acme.shop.manage"},
|
||||
},
|
||||
},
|
||||
},
|
||||
scopes: []pact.TokenScope{
|
||||
{
|
||||
Name: "shop", Label: "Shop", Description: "Manage shop",
|
||||
Permissions: []string{"acme.shop.*"}, Methods: allMethods,
|
||||
},
|
||||
},
|
||||
}
|
||||
host, err := mountPier(t, app, []party.Plugin{plugin})
|
||||
if err != nil {
|
||||
t.Fatalf("mountPier: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = host.pier.Close() })
|
||||
|
||||
if got := countWarningLines(buf.String()); got != 0 {
|
||||
t.Fatalf("expected 0 warning lines, got %d:\n%s", got, buf.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("silent_when_covered_by_companion_plugin_scope", func(t *testing.T) {
|
||||
buf := captureLogs(t)
|
||||
app := pierAppWith(t, map[string]string{"mcp.yaml": "enabled: false\n"}, &acmeGuard{})
|
||||
core := warningBackendPlugin{
|
||||
id: "acme.core",
|
||||
mountMW: true,
|
||||
registerMW: true,
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.core.write", Tab: "Core", Label: "Write"},
|
||||
},
|
||||
tools: []pact.MCPTool{
|
||||
{
|
||||
Name: "core_create_item", Title: "Create item", Description: "Create item.",
|
||||
Method: http.MethodPost, Path: "/acme-core/items/{id}", Input: warningTestInput{},
|
||||
Permissions: []string{"acme.core.write"},
|
||||
},
|
||||
},
|
||||
}
|
||||
companion := warningScopedPlugin{
|
||||
warningBackendPlugin: warningBackendPlugin{id: "acme.companion"},
|
||||
scopes: []pact.TokenScope{
|
||||
{
|
||||
Name: "core:write", Label: "Core write", Description: "Write core items",
|
||||
Permissions: []string{"acme.core.*"}, Methods: allMethods,
|
||||
},
|
||||
},
|
||||
}
|
||||
host, err := mountPier(t, app, []party.Plugin{core, companion})
|
||||
if err != nil {
|
||||
t.Fatalf("mountPier: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = host.pier.Close() })
|
||||
|
||||
if got := countWarningLines(buf.String()); got != 0 {
|
||||
t.Fatalf("expected 0 warning lines when companion covers write tool, got %d:\n%s", got, buf.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("warns_when_write_tool_has_empty_permissions", 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.emptyperm",
|
||||
mountMW: true,
|
||||
registerMW: true,
|
||||
perms: []pact.Permission{
|
||||
{Code: "acme.emptyperm.manage", Tab: "Empty", Label: "Manage"},
|
||||
},
|
||||
tools: []pact.MCPTool{
|
||||
{
|
||||
Name: "emptyperm_create_item", Title: "Create item", Description: "Create item.",
|
||||
Method: http.MethodPost, Path: "/acme-emptyperm/items/{id}", Input: warningTestInput{},
|
||||
Permissions: nil,
|
||||
},
|
||||
},
|
||||
},
|
||||
scopes: []pact.TokenScope{
|
||||
{
|
||||
Name: "emptyperm", Label: "Emptyperm", Description: "Manage emptyperm",
|
||||
Permissions: []string{"acme.emptyperm.*"}, Methods: allMethods,
|
||||
},
|
||||
},
|
||||
}
|
||||
host, err := mountPier(t, app, []party.Plugin{plugin})
|
||||
if err != nil {
|
||||
t.Fatalf("mountPier: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = host.pier.Close() })
|
||||
|
||||
logs := buf.String()
|
||||
if got := countWarningLines(logs); got != 1 {
|
||||
t.Fatalf("warning lines = %d, want 1; logs:\n%s", got, logs)
|
||||
}
|
||||
if !strings.Contains(logs, "emptyperm_create_item") || !strings.Contains(logs, "plugin=acme.emptyperm") {
|
||||
t.Fatalf("expected warning naming emptyperm_create_item and acme.emptyperm:\n%s", logs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("skips_user_guarded_write_tools", func(t *testing.T) {
|
||||
buf := captureLogs(t)
|
||||
app := pierAppWith(t, map[string]string{"mcp.yaml": "enabled: false\n"}, nil)
|
||||
reg := pact.NewMCPGuards()
|
||||
if err := reg.Register(warningUserGuard{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := app.Publish(reg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plugin := warningBackendPlugin{
|
||||
id: "acme.portal",
|
||||
mwName: "user.auth",
|
||||
mountMW: true,
|
||||
registerMW: true,
|
||||
tools: []pact.MCPTool{
|
||||
{
|
||||
Name: "portal_create_item", Title: "Create item", Description: "Create user item.",
|
||||
Method: http.MethodPost, Path: "/acme-portal/items/{id}", Input: warningTestInput{},
|
||||
},
|
||||
},
|
||||
}
|
||||
host, err := mountPier(t, app, []party.Plugin{plugin})
|
||||
if err != nil {
|
||||
t.Fatalf("mountPier: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = host.pier.Close() })
|
||||
|
||||
if got := countWarningLines(buf.String()); got != 0 {
|
||||
t.Fatalf("expected 0 warning lines for user-guarded write tool, got %d:\n%s", got, buf.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user