feat(36-03): implement pact.HasTokenScopes (sitemap, sitemap:read)

This commit is contained in:
Jakub Zych
2026-11-24 19:57:29 +01:00
parent fdbe593802
commit bd0c813299
5 changed files with 331 additions and 2 deletions

View File

@@ -155,7 +155,7 @@ The site's HTML sitemap page (vue-seo-layer) reads two public JSON routes; both
### Management API and MCP
Each management route resolves the backend administrator from a backend JWT, a personal API token covering `golem15.sitemap.*`, or the MCP dispatch, and requires `golem15.sitemap.access_definitions` (401 without an administrator, 403 without the permission):
Each management route resolves the backend administrator from a backend JWT, a personal API token covering `golem15.sitemap.*` (registered via `TokenScopes` as `sitemap` for full read/write access and `sitemap:read` for `GET`/`HEAD` only), or the MCP dispatch, and requires `golem15.sitemap.access_definitions` (401 without an administrator, 403 without the permission):
| Route | MCP tool | Effect |
|-------|----------|--------|
@@ -230,6 +230,7 @@ The files table lists the image and News files too. A save refuses an invalid si
| `sitemap.Plugin.Buckets`, `sitemap.BucketSitemap`, `sitemap.BucketHTML`, `sitemap.BucketAPI` | The throttle buckets `sitemap-xml` (60 a minute), `sitemap-html` and `sitemap-api` (300 a minute) per client IP. |
| `sitemap.Plugin.Jobs` | The rebuild job (`classes.RebuildKind`, three attempts) and the IndexNow job (`classes.IndexNowKind`, five). |
| `sitemap.Plugin.MCP` | The tools `get_settings`, `update_settings` and `rebuild` (exposed with the prefix `sitemap_`). |
| `sitemap.Plugin.TokenScopes` | Personal API token scopes `sitemap` (read/write) and `sitemap:read` (`GET`/`HEAD` only), limited to `golem15.sitemap.*`. |
| `sitemap.Plugin.Schedule` | `sitemap:rebuild` daily at 03:00. |
| `sitemap.Plugin.Commands` | `sitemap:rebuild`, `sitemap:import`, `sitemap:import-winter`. |
| `sitemap.Plugin.ConfigFS` | The default `config/config.yaml`. |
@@ -321,6 +322,6 @@ go test -short ./... # unit tests, no Docker
go test ./... # also the Postgres tests
```
Docker-free: `TestAssignSlots` and `TestRealChanges` (`classes`), `TestAllowedFrontendURL` and `TestSettingsValidate` (`models`), `TestWinterSettingsFrontendURL` (`console`), `TestSiteURLPrecedence`, `TestFileNames`, `TestScheduleAndJobs`, `TestCommandsDocumented` and `TestPluginManifest` (root).
Docker-free: `TestAssignSlots` and `TestRealChanges` (`classes`), `TestAllowedFrontendURL` and `TestSettingsValidate` (`models`), `TestWinterSettingsFrontendURL` (`console`), `TestSiteURLPrecedence`, `TestFileNames`, `TestScheduleAndJobs`, `TestCommandsDocumented`, `TestPluginManifest`, `TestTokenScopes`, `TestTokenScopesCoverMCPTools` and `TestTokenScopesReadWriteEnforcement` (root).
The Postgres tests boot the plugin with a fake content plugin (two content types over an in-memory store), a fake blog plugin (an article type and a collection type) and, for the Filter, a fake plugin that publishes one: `TestSitemapIndex` (the index and files after a rebuild job, drafts absent, escaping, 404s), `TestStableNumbering`, `TestLastmod`, `TestDebouncedRebuild`, `TestHreflangAlternates`, `TestFilterExcludes`, `TestNoFilter`, `TestListing`, `TestSettingsSingleton` (the admin API, its refusals and the files partial), `TestMigrateDefinitions`, `TestImportWinter`, `TestImportFile`, `TestRebuildCommand`, `TestImageSitemap`, `TestNewsSitemap`, `TestIndexNow` (in production, against a fake engine through `fetchguard.WithTransport`), `TestIndexNowStaging`, `TestHTMLGroups` and `TestSitemapTools` (the management API, an MCP dispatch and pier compiling the tools).

View File

@@ -90,3 +90,8 @@ indexnow:
err_rate: 'Too many notifications; the next attempt is at :time.'
jobs:
rebuild: Rebuild the sitemaps
scopes:
sitemap: Sitemaps
sitemap_description: Read and update sitemap settings and trigger sitemap rebuilds as you, within your sitemap permissions.
sitemap_read: Sitemaps, read-only
sitemap_read_description: View sitemap settings, generated files, excluded addresses and IndexNow status without making changes.

View File

@@ -90,3 +90,8 @@ indexnow:
err_rate: 'Zbyt wiele powiadomień; następna próba: :time.'
jobs:
rebuild: Odbudowa map witryny
scopes:
sitemap: Mapy witryny
sitemap_description: Odczytuj i zmieniaj ustawienia map witryny oraz uruchamiaj ich odbudowę w ramach swoich uprawnień.
sitemap_read: Mapy witryny, tylko odczyt
sitemap_read_description: Przeglądaj ustawienia map witryny, wygenerowane pliki, pominięte adresy i stan IndexNow bez wprowadzania zmian.

26
token_scopes.go Normal file
View File

@@ -0,0 +1,26 @@
package sitemap
import "git.golem15.com/golem15/summercms/modules/pact"
var _ pact.HasTokenScopes = (*Plugin)(nil)
// TokenScopes registers personal API token scopes for the Sitemap plugin.
func (p *Plugin) TokenScopes() []pact.TokenScope {
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
return []pact.TokenScope{
{
Name: "sitemap",
Label: "golem15.sitemap::lang.scopes.sitemap",
Description: "golem15.sitemap::lang.scopes.sitemap_description",
Permissions: []string{"golem15.sitemap.*"},
Methods: all,
},
{
Name: "sitemap:read",
Label: "golem15.sitemap::lang.scopes.sitemap_read",
Description: "golem15.sitemap::lang.scopes.sitemap_read_description",
Permissions: []string{"golem15.sitemap.*"},
Methods: []string{"GET", "HEAD"},
},
}
}

292
token_scopes_test.go Normal file
View 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) != ""
}