feat(36-03): implement pact.HasTokenScopes (sitemap, sitemap:read)
This commit is contained in:
292
token_scopes_test.go
Normal file
292
token_scopes_test.go
Normal file
@@ -0,0 +1,292 @@
|
||||
package sitemap_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
sitemap "git.golem15.com/golem15/sm-sitemap-plugin"
|
||||
apicontrollers "git.golem15.com/golem15/sm-sitemap-plugin/controllers/api"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"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/pier"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"github.com/goccy/go-yaml"
|
||||
)
|
||||
|
||||
func TestTokenScopes(t *testing.T) {
|
||||
p := &sitemap.Plugin{}
|
||||
scopes := p.TokenScopes()
|
||||
if len(scopes) != 2 {
|
||||
t.Fatalf("TokenScopes len = %d, want 2", len(scopes))
|
||||
}
|
||||
byName := map[string]pact.TokenScope{}
|
||||
for _, s := range scopes {
|
||||
byName[s.Name] = s
|
||||
}
|
||||
|
||||
fullScope, ok := byName["sitemap"]
|
||||
if !ok {
|
||||
t.Fatal("missing sitemap scope")
|
||||
}
|
||||
readScope, ok := byName["sitemap:read"]
|
||||
if !ok {
|
||||
t.Fatal("missing sitemap:read scope")
|
||||
}
|
||||
|
||||
if fullScope.Group != "" || readScope.Group != "" {
|
||||
t.Fatalf("expected empty Group for D-16 plugin.name fallback, got full=%q read=%q", fullScope.Group, readScope.Group)
|
||||
}
|
||||
if !slices.Equal(fullScope.Permissions, []string{"golem15.sitemap.*"}) {
|
||||
t.Fatalf("sitemap permissions = %#v, want [golem15.sitemap.*]", fullScope.Permissions)
|
||||
}
|
||||
if !slices.Equal(readScope.Permissions, []string{"golem15.sitemap.*"}) {
|
||||
t.Fatalf("sitemap:read permissions = %#v, want [golem15.sitemap.*]", readScope.Permissions)
|
||||
}
|
||||
wantAll := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
if !slices.Equal(fullScope.Methods, wantAll) {
|
||||
t.Fatalf("sitemap methods = %#v, want %#v", fullScope.Methods, wantAll)
|
||||
}
|
||||
wantRead := []string{"GET", "HEAD"}
|
||||
if !slices.Equal(readScope.Methods, wantRead) {
|
||||
t.Fatalf("sitemap:read methods = %#v, want %#v", readScope.Methods, wantRead)
|
||||
}
|
||||
for _, writeMethod := range []string{"POST", "PUT", "PATCH", "DELETE"} {
|
||||
if slices.Contains(readScope.Methods, writeMethod) {
|
||||
t.Fatalf("sitemap:read must not allow write method %s", writeMethod)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify every declared Label, Description, and plugin.name phrase key exists in EN and PL.
|
||||
keys := []string{
|
||||
"golem15.sitemap::lang.plugin.name",
|
||||
fullScope.Label, fullScope.Description,
|
||||
readScope.Label, readScope.Description,
|
||||
}
|
||||
for _, lang := range []string{"en", "pl"} {
|
||||
path := filepath.Join("lang", lang, "lang.yaml")
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
}
|
||||
var root map[string]any
|
||||
if err := yaml.Unmarshal(raw, &root); err != nil {
|
||||
t.Fatalf("yaml %s: %v", path, err)
|
||||
}
|
||||
for _, key := range keys {
|
||||
if !sitemapPhraseExists(root, key) {
|
||||
t.Fatalf("%s missing or empty phrase key %s", path, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify cabana.TokenScopeNames advertises sitemap and sitemap:read.
|
||||
app := backpack.New(nil)
|
||||
if err := app.Publish(party.Activated([]party.Plugin{p})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
names, err := cabana.TokenScopeNames(app)
|
||||
if err != nil {
|
||||
t.Fatalf("cabana.TokenScopeNames: %v", err)
|
||||
}
|
||||
for _, want := range []string{"sitemap", "sitemap:read"} {
|
||||
if !slices.Contains(names, want) {
|
||||
t.Fatalf("cabana.TokenScopeNames = %v, missing %q", names, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenScopesCoverMCPTools(t *testing.T) {
|
||||
p := &sitemap.Plugin{}
|
||||
plugins := []party.Plugin{p}
|
||||
|
||||
tools := p.MCP().Tools
|
||||
writeTools := 0
|
||||
for _, tool := range tools {
|
||||
if tool.Guard != "backend" {
|
||||
continue
|
||||
}
|
||||
if tool.Method == http.MethodGet || tool.Method == http.MethodHead {
|
||||
continue
|
||||
}
|
||||
writeTools++
|
||||
if !cabana.TokenScopeCovers(nil, plugins, tool.Method, tool.Permissions) {
|
||||
t.Errorf("write MCP tool %s (%s %s) is not covered by any non-* TokenScope", tool.Name, tool.Method, tool.Path)
|
||||
}
|
||||
}
|
||||
if writeTools != 2 {
|
||||
t.Fatalf("write MCP tool count = %d, want 2 (update_settings, rebuild)", writeTools)
|
||||
}
|
||||
if cabana.TokenScopeCovers(nil, plugins, http.MethodPut, []string{"golem15.other.manage"}) {
|
||||
t.Fatal("sitemap scopes must not cover unrelated plugin permissions")
|
||||
}
|
||||
|
||||
// Boot cabana + pier without Docker and confirm zero uncovered-tool warnings.
|
||||
app := newTokenScopeTestApp(t, plugins)
|
||||
router, err := surf.BuildRouter(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatalf("surf.BuildRouter: %v", err)
|
||||
}
|
||||
if err := app.Config.Set(pier.EnabledKey, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
logs := captureSlogBuffer(t)
|
||||
if err := pier.Mount(mountHost{r: router}, app, plugins); err != nil {
|
||||
t.Fatalf("pier.Mount: %v", err)
|
||||
}
|
||||
pr, ok := app.Lookup[*pier.Pier]()
|
||||
if !ok {
|
||||
t.Fatal("pier was not mounted")
|
||||
}
|
||||
if got := pr.ToolNames(); strings.Join(got, " ") != "sitemap_get_settings sitemap_rebuild sitemap_update_settings" {
|
||||
t.Fatalf("compiled tools = %v", got)
|
||||
}
|
||||
if out := logs.String(); strings.Contains(out, "not covered by any non-* TokenScope") {
|
||||
t.Fatalf("pier.Mount emitted uncovered-tool warning:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenScopesReadWriteEnforcement(t *testing.T) {
|
||||
p := &sitemap.Plugin{}
|
||||
app := newTokenScopeTestApp(t, []party.Plugin{p})
|
||||
|
||||
newPrincipal := func(limit *bouncer.ScopeLimit, super bool) *bouncer.Principal {
|
||||
return &bouncer.Principal{
|
||||
ID: 1,
|
||||
Backend: true,
|
||||
IsSuperuser: super,
|
||||
PermissionGrants: map[string]bool{apicontrollers.PermissionManage: true},
|
||||
Scope: limit,
|
||||
}
|
||||
}
|
||||
|
||||
// Full "sitemap" scope allows GET, PUT, and POST within golem15.sitemap.*,
|
||||
// and never grants permissions outside golem15.sitemap.*.
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPost, http.MethodPatch, http.MethodDelete} {
|
||||
limit, known, methodOK := cabana.ScopeLimitFor(app, []string{"sitemap"}, method)
|
||||
if known != 1 || methodOK != 1 || limit == nil {
|
||||
t.Fatalf("sitemap %s: limit=%v known=%d methodOK=%d, want non-nil/1/1", method, limit, known, methodOK)
|
||||
}
|
||||
if !cabana.Allows(newPrincipal(limit, false), []string{apicontrollers.PermissionManage}) {
|
||||
t.Fatalf("sitemap %s should allow %s", method, apicontrollers.PermissionManage)
|
||||
}
|
||||
if cabana.Allows(newPrincipal(limit, true), []string{"golem15.other.manage"}) {
|
||||
t.Fatalf("sitemap %s must not allow unrelated permission even for superuser", method)
|
||||
}
|
||||
}
|
||||
|
||||
// Read-only "sitemap:read" scope allows GET/HEAD and denies PUT/POST/PATCH/DELETE.
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
limit, known, methodOK := cabana.ScopeLimitFor(app, []string{"sitemap:read"}, method)
|
||||
if known != 1 || methodOK != 1 || limit == nil {
|
||||
t.Fatalf("sitemap:read %s: limit=%v known=%d methodOK=%d, want non-nil/1/1", method, limit, known, methodOK)
|
||||
}
|
||||
if !cabana.Allows(newPrincipal(limit, false), []string{apicontrollers.PermissionManage}) {
|
||||
t.Fatalf("sitemap:read %s should allow %s", method, apicontrollers.PermissionManage)
|
||||
}
|
||||
if cabana.Allows(newPrincipal(limit, true), []string{"golem15.other.manage"}) {
|
||||
t.Fatalf("sitemap:read %s must not allow unrelated permission", method)
|
||||
}
|
||||
}
|
||||
for _, method := range []string{http.MethodPut, http.MethodPost, http.MethodPatch, http.MethodDelete} {
|
||||
limit, known, methodOK := cabana.ScopeLimitFor(app, []string{"sitemap:read"}, method)
|
||||
if known != 1 || methodOK != 0 || limit != nil {
|
||||
t.Fatalf("sitemap:read %s: limit=%v known=%d methodOK=%d, want nil/1/0", method, limit, known, methodOK)
|
||||
}
|
||||
if cabana.Allows(newPrincipal(&bouncer.ScopeLimit{}, true), []string{apicontrollers.PermissionManage}) {
|
||||
t.Fatalf("empty scope limit on %s must deny %s", method, apicontrollers.PermissionManage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newTokenScopeTestApp(t *testing.T, plugins []party.Plugin) *backpack.App {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: sitemap-scopes-test\nlocale: en\nfallback_locale: en\nurl: https://api.example.test\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{
|
||||
Dir: dir,
|
||||
Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=sitemap-scopes-test-only-hs256-secret"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for k, v := range map[string]any{
|
||||
"http.body_limits.default_bytes": 1048576,
|
||||
"http.body_limits.upload_bytes": 8388608,
|
||||
} {
|
||||
if err := cfg.Set(k, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
app := backpack.New(cfg)
|
||||
if err := app.Publish(party.Activated(plugins)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := phrasebook.Activate(app, plugins); err != nil {
|
||||
t.Fatalf("phrasebook.Activate: %v", err)
|
||||
}
|
||||
if _, err := cabana.Activate(app, plugins); err != nil {
|
||||
t.Fatalf("cabana.Activate: %v", err)
|
||||
}
|
||||
return app
|
||||
}
|
||||
|
||||
type syncLogBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *syncLogBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
func (b *syncLogBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()
|
||||
}
|
||||
|
||||
func captureSlogBuffer(t *testing.T) *syncLogBuffer {
|
||||
t.Helper()
|
||||
buf := &syncLogBuffer{}
|
||||
prev := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug})))
|
||||
t.Cleanup(func() { slog.SetDefault(prev) })
|
||||
return buf
|
||||
}
|
||||
|
||||
func sitemapPhraseExists(root map[string]any, key string) bool {
|
||||
const prefix = "golem15.sitemap::lang."
|
||||
if !strings.HasPrefix(key, prefix) {
|
||||
return false
|
||||
}
|
||||
var cur any = root
|
||||
for _, part := range strings.Split(strings.TrimPrefix(key, prefix), ".") {
|
||||
m, ok := cur.(map[string]any)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
cur, ok = m[part]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
s, ok := cur.(string)
|
||||
return ok && strings.TrimSpace(s) != ""
|
||||
}
|
||||
Reference in New Issue
Block a user