320 lines
10 KiB
Go
320 lines
10 KiB
Go
package seo_test
|
|
|
|
import (
|
|
"bytes"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
seo "git.golem15.com/golem15/sm-seo-plugin"
|
|
apicontrollers "git.golem15.com/golem15/sm-seo-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 := &seo.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["seo"]
|
|
if !ok {
|
|
t.Fatal("missing seo scope")
|
|
}
|
|
readScope, ok := byName["seo:read"]
|
|
if !ok {
|
|
t.Fatal("missing seo: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.seo.*"}) {
|
|
t.Fatalf("seo permissions = %#v, want [golem15.seo.*]", fullScope.Permissions)
|
|
}
|
|
if !slices.Equal(readScope.Permissions, []string{"golem15.seo.*"}) {
|
|
t.Fatalf("seo:read permissions = %#v, want [golem15.seo.*]", readScope.Permissions)
|
|
}
|
|
wantAll := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
|
if !slices.Equal(fullScope.Methods, wantAll) {
|
|
t.Fatalf("seo methods = %#v, want %#v", fullScope.Methods, wantAll)
|
|
}
|
|
wantRead := []string{"GET", "HEAD"}
|
|
if !slices.Equal(readScope.Methods, wantRead) {
|
|
t.Fatalf("seo:read methods = %#v, want %#v", readScope.Methods, wantRead)
|
|
}
|
|
for _, writeMethod := range []string{"POST", "PUT", "PATCH", "DELETE"} {
|
|
if slices.Contains(readScope.Methods, writeMethod) {
|
|
t.Fatalf("seo: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.seo::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 !seoPhraseExists(root, key) {
|
|
t.Fatalf("%s missing or empty phrase key %s", path, key)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Verify cabana.TokenScopeNames advertises seo and seo: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{"seo", "seo:read"} {
|
|
if !slices.Contains(names, want) {
|
|
t.Fatalf("cabana.TokenScopeNames = %v, missing %q", names, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestTokenScopesCoverMCPTools(t *testing.T) {
|
|
p := &seo.Plugin{}
|
|
plugins := []party.Plugin{p}
|
|
|
|
tools := p.MCP().Tools
|
|
if len(tools) < 41 {
|
|
t.Fatalf("MCP tool count = %d, want >= 41", len(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 < 26 {
|
|
t.Fatalf("write MCP tool count = %d, want >= 26", writeTools)
|
|
}
|
|
t.Logf("verified %d write MCP tools out of %d total tools covered", writeTools, len(tools))
|
|
if cabana.TokenScopeCovers(nil, plugins, http.MethodPut, []string{"golem15.other.manage"}) {
|
|
t.Fatal("seo scopes must not cover unrelated plugin permissions")
|
|
}
|
|
|
|
// Boot cabana + pier without Docker and confirm zero uncovered-tool warnings.
|
|
app := newSEOTokenScopeTestApp(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 := captureSEOSlogBuffer(t)
|
|
if err := pier.Mount(seoMountHost{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 := len(pr.ToolNames()); got != len(tools) {
|
|
t.Fatalf("compiled tool count = %d, want %d", got, len(tools))
|
|
}
|
|
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 := &seo.Plugin{}
|
|
app := newSEOTokenScopeTestApp(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 "seo" scope allows GET/POST/PUT/PATCH/DELETE within golem15.seo.*,
|
|
// and never grants permissions outside golem15.seo.*.
|
|
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} {
|
|
limit, known, methodOK := cabana.ScopeLimitFor(app, []string{"seo"}, method)
|
|
if known != 1 || methodOK != 1 || limit == nil {
|
|
t.Fatalf("seo %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("seo %s should allow %s", method, apicontrollers.PermissionManage)
|
|
}
|
|
if cabana.Allows(newPrincipal(limit, true), []string{"golem15.other.manage"}) {
|
|
t.Fatalf("seo %s must not allow unrelated permission even for superuser", method)
|
|
}
|
|
}
|
|
|
|
// Read-only "seo:read" scope allows GET/HEAD and denies POST/PUT/PATCH/DELETE.
|
|
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
|
limit, known, methodOK := cabana.ScopeLimitFor(app, []string{"seo:read"}, method)
|
|
if known != 1 || methodOK != 1 || limit == nil {
|
|
t.Fatalf("seo: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("seo:read %s should allow %s", method, apicontrollers.PermissionManage)
|
|
}
|
|
if cabana.Allows(newPrincipal(limit, true), []string{"golem15.other.manage"}) {
|
|
t.Fatalf("seo:read %s must not allow unrelated permission", method)
|
|
}
|
|
}
|
|
for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} {
|
|
limit, known, methodOK := cabana.ScopeLimitFor(app, []string{"seo:read"}, method)
|
|
if known != 1 || methodOK != 0 || limit != nil {
|
|
t.Fatalf("seo: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 newSEOTokenScopeTestApp(t *testing.T, plugins []party.Plugin) *backpack.App {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: seo-scopes-test\nlocale: en\nfallback_locale: en\nurl: https://app.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=" + adminJWTSecret},
|
|
})
|
|
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 seoMountHost struct{ r *surf.Router }
|
|
|
|
func (h seoMountHost) Routes() []pier.RouteInfo {
|
|
var out []pier.RouteInfo
|
|
for _, ri := range h.r.Routes() {
|
|
out = append(out, pier.RouteInfo{Method: ri.Method, Pattern: ri.Pattern, PluginID: ri.PluginID, Middleware: ri.Middleware})
|
|
}
|
|
return out
|
|
}
|
|
func (h seoMountHost) Handler(method, pattern string) (http.Handler, bool) {
|
|
return h.r.Handler(method, pattern)
|
|
}
|
|
func (seoMountHost) MountStream(string, string, http.Handler, ...string) error { return nil }
|
|
func (seoMountHost) MountJSON(string, string, http.Handler) error { return nil }
|
|
func (h seoMountHost) Owner(method, path string) (string, bool) {
|
|
for _, ri := range h.r.Routes() {
|
|
if ri.Method == method && ri.Pattern == path {
|
|
return ri.PluginID, true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
type seoSyncLogBuffer struct {
|
|
mu sync.Mutex
|
|
buf bytes.Buffer
|
|
}
|
|
|
|
func (b *seoSyncLogBuffer) Write(p []byte) (int, error) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.buf.Write(p)
|
|
}
|
|
|
|
func (b *seoSyncLogBuffer) String() string {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return b.buf.String()
|
|
}
|
|
|
|
func captureSEOSlogBuffer(t *testing.T) *seoSyncLogBuffer {
|
|
t.Helper()
|
|
buf := &seoSyncLogBuffer{}
|
|
prev := slog.Default()
|
|
slog.SetDefault(slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug})))
|
|
t.Cleanup(func() { slog.SetDefault(prev) })
|
|
return buf
|
|
}
|
|
|
|
func seoPhraseExists(root map[string]any, key string) bool {
|
|
const prefix = "golem15.seo::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) != ""
|
|
}
|