feat(36-03): implement pact.HasTokenScopes (seo, seo:read)
This commit is contained in:
@@ -265,7 +265,7 @@ A crawl is a conga job (`golem15.seo.crawl`, one attempt) started from **Start c
|
||||
|
||||
### Management API and MCP tools
|
||||
|
||||
The management routes live under `/_seo/api/v1` (bucket `seo-api`, 300 requests a minute per client IP). Each resolves the administrator from a backend JWT, a personal API token (scope `golem15.seo.*`) or pier's in-process dispatch, so an MCP call runs as the backend account linked to the MCP user; each answers `401` without one and `403` without `golem15.seo.manage`. Field refusals are `422 {"error": "validation_failed", "errors": {...}}`; a redirect that would create a loop is `422 {"error": "redirect_loop", "path": [...], "message": "..."}`, so the tool call fails; a missing row is `404`. History records these writes with via `mcp` when they come through MCP, and redirects created through MCP have origin `mcp`.
|
||||
The management routes live under `/_seo/api/v1` (bucket `seo-api`, 300 requests a minute per client IP). Each resolves the administrator from a backend JWT, a personal API token (scope `golem15.seo.*`, registered via `TokenScopes` as `seo` for full read/write access and `seo:read` for `GET`/`HEAD` only) or pier's in-process dispatch, so an MCP call runs as the backend account linked to the MCP user; each answers `401` without one and `403` without `golem15.seo.manage`. Field refusals are `422 {"error": "validation_failed", "errors": {...}}`; a redirect that would create a loop is `422 {"error": "redirect_loop", "path": [...], "message": "..."}`, so the tool call fails; a missing row is `404`. History records these writes with via `mcp` when they come through MCP, and redirects created through MCP have origin `mcp`.
|
||||
|
||||
| Tool (`seo_` + name) | Route | What it does |
|
||||
|------|-------|--------------|
|
||||
@@ -314,6 +314,7 @@ The element bundle (`assets/dist/seo.js` and `seo.css`) is built from `assets/sr
|
||||
| Identifier | Description |
|
||||
|------------|-------------|
|
||||
| `Plugin` | The `golem15.seo` plugin; `Plugin.Service` returns the booted `classes.Service`. |
|
||||
| `Plugin.TokenScopes` | Personal API token scopes `seo` (read/write) and `seo:read` (`GET`/`HEAD` only), limited to `golem15.seo.*`. |
|
||||
| `TabSEO`, `TabGeneral`, `TabRobotsFile`, `TabRobotsBots` | The SEO tab key, the settings' General tab key and the robots.txt screen's tab keys. |
|
||||
| `BucketResolve`, `BucketNotFound`, `BucketRobots`, `BucketAPI` | The throttle buckets of resolve (and the verification files), the 404 report, `/robots.txt` and the management API. |
|
||||
| `AdminOperations`, `AdminOperation`, `ContentController` | Every SEO admin operation (controller, kind) and its MCP tool; `ContentController` (`*`) stands for the form of every content type. |
|
||||
@@ -414,4 +415,4 @@ npm ci && npm run typecheck && npm test && bash scripts/check-dist.sh
|
||||
|
||||
The element tests (`tests/elements`, vitest on happy-dom) drive the widget elements through a fake of the admin's widget host (`tests/elements/host.ts`), including a host that drops an action.
|
||||
|
||||
The smoke tests boot the plugin with fake content plugins (`acme.pages`, and `acme.blog` with a category segment for strict URLs) and exercise the SEO tab, the settings tabs, the resolver precedence, history, generation, the URL rule form, redirects (engine, loops and chains, address changes from the admin and from events), the 404 log, normalisation and strict URLs, robots.txt and verification files through the admin and public APIs, and the management API as an MCP client (`TestMCPSetURLSeoTracer`, `TestManagementAPI`, `TestIssues`), batches, undo and CSV (`TestBatch`, `TestUndo`, `TestCSVTransfer`, and the `mcp` and `import` cases of `TestLoopRefused`). The sitemap, the registry and the site-level endpoints are covered by `TestSitemapFilterTracer`, `TestFilterReasons`, `TestNoindexPublishedConflict`, `TestSitemapBlockedIssue`, `TestRegistry`, `TestRouteReport`, `TestNoindexPathsTracer`, `TestSiteEndpoint`, `TestLLMSTxt`, `TestRobotsSitemapLine`, `TestSettingsLinks` and `TestPurgeAfterWrite`; the fixture boots the sitemap plugin next to the SEO plugin. The site audit is covered by `TestCrawlerTracer`, `TestCrawlerChecks` (a planted site with one page per kind and a clean control page, served to the crawler through `fetchguard.WithTransport`), `TestIssueMerge`, `TestStagingCrawl`, `TestRenderSkipped`, `TestCrawlAdmin`, `TestCrawlSchedule` and `TestCrawlTools`, with the fake content plugin `acme.crawl` naming fixing tools. Auto-links are covered by `TestAutolinksTracer` (the phrases of a page's locale in the resolve answer, never the page's own, `autolink_max` 0) and `TestAutolinks` (the screen, its refusals, Add focus keyphrases, the API and MCP); `TestLinkSuggestions` crawls a planted site and checks E10's counts and suggestions through the API and the widget action. `TestChromeRenderer` renders a page in a real headless Chrome (it runs when `SEO_TEST_CHROME` names a binary or `chromium`, `chromium-browser` or `google-chrome` is on `PATH`, and is skipped otherwise) and `TestRendererGuards` checks the refused paths and private addresses. `TestEveryAdminOperationHasTool`, `TestMCPReadToolsAreGET`, `TestIssueKindLabels` and the static parts of `TestCrawlTools` and `TestCrawlSchedule` run without Docker.
|
||||
The smoke tests boot the plugin with fake content plugins (`acme.pages`, and `acme.blog` with a category segment for strict URLs) and exercise the SEO tab, the settings tabs, the resolver precedence, history, generation, the URL rule form, redirects (engine, loops and chains, address changes from the admin and from events), the 404 log, normalisation and strict URLs, robots.txt and verification files through the admin and public APIs, and the management API as an MCP client (`TestMCPSetURLSeoTracer`, `TestManagementAPI`, `TestIssues`), batches, undo and CSV (`TestBatch`, `TestUndo`, `TestCSVTransfer`, and the `mcp` and `import` cases of `TestLoopRefused`). The sitemap, the registry and the site-level endpoints are covered by `TestSitemapFilterTracer`, `TestFilterReasons`, `TestNoindexPublishedConflict`, `TestSitemapBlockedIssue`, `TestRegistry`, `TestRouteReport`, `TestNoindexPathsTracer`, `TestSiteEndpoint`, `TestLLMSTxt`, `TestRobotsSitemapLine`, `TestSettingsLinks` and `TestPurgeAfterWrite`; the fixture boots the sitemap plugin next to the SEO plugin. The site audit is covered by `TestCrawlerTracer`, `TestCrawlerChecks` (a planted site with one page per kind and a clean control page, served to the crawler through `fetchguard.WithTransport`), `TestIssueMerge`, `TestStagingCrawl`, `TestRenderSkipped`, `TestCrawlAdmin`, `TestCrawlSchedule` and `TestCrawlTools`, with the fake content plugin `acme.crawl` naming fixing tools. Auto-links are covered by `TestAutolinksTracer` (the phrases of a page's locale in the resolve answer, never the page's own, `autolink_max` 0) and `TestAutolinks` (the screen, its refusals, Add focus keyphrases, the API and MCP); `TestLinkSuggestions` crawls a planted site and checks E10's counts and suggestions through the API and the widget action. `TestChromeRenderer` renders a page in a real headless Chrome (it runs when `SEO_TEST_CHROME` names a binary or `chromium`, `chromium-browser` or `google-chrome` is on `PATH`, and is skipped otherwise) and `TestRendererGuards` checks the refused paths and private addresses. `TestEveryAdminOperationHasTool`, `TestMCPReadToolsAreGET`, `TestIssueKindLabels`, `TestTokenScopes`, `TestTokenScopesCoverMCPTools`, `TestTokenScopesReadWriteEnforcement` and the static parts of `TestCrawlTools` and `TestCrawlSchedule` run without Docker.
|
||||
|
||||
@@ -784,3 +784,8 @@ issues:
|
||||
sum_heading_empty: "H:level"
|
||||
kind_h1_title_mismatch: "H1 does not match the title"
|
||||
sum_h1_title_mismatch: "“:h1”"
|
||||
scopes:
|
||||
seo: SEO
|
||||
seo_description: Manage SEO metadata, URL rules, redirects, robots.txt, pages, auto-links, settings and site audits as you, within your SEO permissions.
|
||||
seo_read: SEO, read-only
|
||||
seo_read_description: View SEO metadata, rules, redirects, 404 logs, robots.txt, settings, history and audit issues without making changes.
|
||||
|
||||
@@ -814,3 +814,8 @@ issues:
|
||||
sum_heading_empty: "H:level"
|
||||
kind_h1_title_mismatch: "H1 nie pasuje do tytułu"
|
||||
sum_h1_title_mismatch: "„:h1”"
|
||||
scopes:
|
||||
seo: SEO
|
||||
seo_description: Zarządzaj metadanymi SEO, regułami adresów, przekierowaniami, robots.txt, stronami, automatycznymi linkami, ustawieniami i audytem witryny w ramach swoich uprawnień SEO.
|
||||
seo_read: SEO, tylko odczyt
|
||||
seo_read_description: Przeglądaj metadane SEO, reguły, przekierowania, dziennik 404, robots.txt, ustawienia, historię i problemy z audytu bez wprowadzania zmian.
|
||||
|
||||
26
token_scopes.go
Normal file
26
token_scopes.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package seo
|
||||
|
||||
import "git.golem15.com/golem15/summercms/modules/pact"
|
||||
|
||||
var _ pact.HasTokenScopes = (*Plugin)(nil)
|
||||
|
||||
// TokenScopes registers personal API token scopes for the SEO plugin.
|
||||
func (p *Plugin) TokenScopes() []pact.TokenScope {
|
||||
all := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
return []pact.TokenScope{
|
||||
{
|
||||
Name: "seo",
|
||||
Label: "golem15.seo::lang.scopes.seo",
|
||||
Description: "golem15.seo::lang.scopes.seo_description",
|
||||
Permissions: []string{"golem15.seo.*"},
|
||||
Methods: all,
|
||||
},
|
||||
{
|
||||
Name: "seo:read",
|
||||
Label: "golem15.seo::lang.scopes.seo_read",
|
||||
Description: "golem15.seo::lang.scopes.seo_read_description",
|
||||
Permissions: []string{"golem15.seo.*"},
|
||||
Methods: []string{"GET", "HEAD"},
|
||||
},
|
||||
}
|
||||
}
|
||||
319
token_scopes_test.go
Normal file
319
token_scopes_test.go
Normal file
@@ -0,0 +1,319 @@
|
||||
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) != ""
|
||||
}
|
||||
Reference in New Issue
Block a user