- pact: MCPGrant.Subject with MCPGrantSubjectBackend, MCPSubject.ScopeLimited - pier: a backend-subject grant resolves straight to a scope-limited backend subject bound to oauth:backend:<client>:<admin>, no link lookup, no ceiling - pier: the backend guard scope-limits ScopeLimited subjects like g15_ tokens - wristband: Options.ConsentPath and Options.DefaultScopes; defaults unchanged - smoke tests TestBackendSubjectSmoke (Postgres) and TestConsentPathSmoke
239 lines
8.8 KiB
Go
239 lines
8.8 KiB
Go
package pier_test
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"io/fs"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"testing"
|
|
"testing/fstest"
|
|
"time"
|
|
|
|
"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/lagoon"
|
|
"git.golem15.com/golem15/summercms/modules/pact"
|
|
"git.golem15.com/golem15/summercms/modules/party"
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
|
)
|
|
|
|
// adminToolsController is the one admin controller cabana.Activate needs
|
|
// before it publishes the backend resolver the backend guard reads.
|
|
type adminToolsController struct{}
|
|
|
|
func (adminToolsController) ID() string { return "acme.admintools.items" }
|
|
func (adminToolsController) ModelName() string { return "Item" }
|
|
func (adminToolsController) ConfigDir() string { return "controllers/items" }
|
|
func (adminToolsController) NewRecord() any { return &adminToolsItem{} }
|
|
|
|
type adminToolsItem struct {
|
|
ID uint `gorm:"column:id;primaryKey"`
|
|
}
|
|
|
|
func (adminToolsItem) TableName() string { return "acme_admintools_items" }
|
|
|
|
// adminToolsPlugin declares two backend tools on routes behind cabana's
|
|
// "backend" middleware: a GET (read-only) and a POST (write).
|
|
type adminToolsPlugin struct{}
|
|
|
|
func (adminToolsPlugin) ID() string { return "acme.admintools" }
|
|
func (adminToolsPlugin) Requires() []string { return nil }
|
|
func (adminToolsPlugin) Register(*backpack.App) error { return nil }
|
|
func (adminToolsPlugin) Boot(*backpack.App) error { return nil }
|
|
func (adminToolsPlugin) AdminControllers() []pact.AdminController {
|
|
return []pact.AdminController{adminToolsController{}}
|
|
}
|
|
func (adminToolsPlugin) AdminFS() fs.FS {
|
|
return fstest.MapFS{
|
|
"controllers/items/config_list.yaml": {Data: []byte("list: ~/plugins/acme/admintools/models/item/columns.yaml\nmodelClass: Item\ntitle: Items\n")},
|
|
"models/item/columns.yaml": {Data: []byte("columns:\n id:\n label: ID\n")},
|
|
}
|
|
}
|
|
|
|
func (adminToolsPlugin) Routes(r pact.Router) error {
|
|
r.Group("/acme/admin", []string{"backend"}, func(g pact.Router) {
|
|
g.Get("/items", func(w http.ResponseWriter, req *http.Request) {
|
|
user, _ := bouncer.User(req.Context())
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if user == nil {
|
|
_, _ = w.Write([]byte(`{"admin":0}`))
|
|
return
|
|
}
|
|
_, _ = w.Write([]byte(`{"admin":` + strconv.FormatUint(uint64(user.ID), 10) + `}`))
|
|
})
|
|
g.Post("/items", func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"created":true}`))
|
|
})
|
|
})
|
|
return nil
|
|
}
|
|
|
|
func (adminToolsPlugin) MCP() pact.MCP {
|
|
return pact.MCP{Tools: []pact.MCPTool{
|
|
{Name: "list_items", Title: "List items", Description: "Lists the items.", Method: "GET", Path: "/acme/admin/items", Input: struct{}{}},
|
|
{Name: "create_item", Title: "Create item", Description: "Creates an item.", Method: "POST", Path: "/acme/admin/items", Input: struct{}{}},
|
|
}}
|
|
}
|
|
|
|
// backendGrantVerifier answers an administrator-only grant
|
|
// (pact.MCPGrantSubjectBackend) for oas_at_admin_read and a grant with no
|
|
// subject kind and no frontend user for oas_at_nobody.
|
|
type backendGrantVerifier struct {
|
|
admin uint
|
|
}
|
|
|
|
func (v backendGrantVerifier) MCPVerifyToken(_ context.Context, raw string) (pact.MCPGrant, error) {
|
|
switch raw {
|
|
case "oas_at_admin_read":
|
|
return pact.MCPGrant{Subject: pact.MCPGrantSubjectBackend, BackendUserID: v.admin, ClientID: "c-admin", TokenID: 11, Scopes: []string{"admin:read"}, ExpiresAt: time.Now().Add(time.Hour)}, nil
|
|
case "oas_at_nobody":
|
|
return pact.MCPGrant{BackendUserID: v.admin, ClientID: "c-admin", TokenID: 12, Scopes: []string{"admin:read"}, ExpiresAt: time.Now().Add(time.Hour)}, nil
|
|
}
|
|
return pact.MCPGrant{}, pact.ErrMCPTokenInvalid
|
|
}
|
|
|
|
func (backendGrantVerifier) MCPResource() string { return "http://acme.test/mcp" }
|
|
|
|
// backendSubjectApp starts Postgres, migrates the backend tables, seeds a
|
|
// superuser administrator and activates cabana, so the backend guard's
|
|
// BackendPrincipal and ScopeLimitFor are the real ones.
|
|
func backendSubjectApp(t *testing.T, plugins []party.Plugin) (*backpack.App, uint) {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
ctr, err := postgres.Run(ctx, "postgres:16-alpine",
|
|
postgres.WithDatabase("pier"), postgres.WithUsername("pier"), postgres.WithPassword("pier"),
|
|
postgres.BasicWaitStrategies())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = ctr.Terminate(context.Background()) })
|
|
dsn, err := ctr.ConnectionString(ctx, "sslmode=disable")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Close() })
|
|
gdb, err := lagoon.Use(ctx, db)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := lagoon.Migrate(gdb, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dir := t.TempDir()
|
|
files := map[string]string{
|
|
"app.yaml": "name: acme\nurl: http://acme.test\nlocale: en\nfallback_locale: en\n",
|
|
"http.yaml": "body_limits:\n default_bytes: 1048576\n upload_bytes: 1048576\n",
|
|
"mcp.yaml": "enabled: false\n",
|
|
}
|
|
for name, body := range files {
|
|
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=summercms-test-only-admin-hs256-secret"}})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
app := backpack.New(cfg)
|
|
if err := lagoon.Publish(app, db, gdb); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := cabana.Activate(app, plugins); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var admin uint
|
|
if err := db.QueryRow(`INSERT INTO backend_users (login, email, password, permissions, is_activated, is_superuser)
|
|
VALUES ('editor', 'editor@acme.test', 'x', '{}', TRUE, TRUE) RETURNING id`).Scan(&admin); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := app.Publish[pact.MCPTokenVerifier](backendGrantVerifier{admin: admin}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// A frontend guard is registered too: an administrator-only grant must
|
|
// still get no frontend subject.
|
|
reg := pact.NewMCPGuards()
|
|
if err := reg.Register(&acmeGuard{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := app.Publish(reg); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return app, admin
|
|
}
|
|
|
|
// TestBackendSubjectSmoke is the tracer of administrator-only OAuth grants:
|
|
// a grant with Subject backend, UserID 0 and BackendUserID set lists, over
|
|
// a real /mcp request, the read-only backend tool and not the write tool,
|
|
// because its admin:read scope caps the superuser like a personal token
|
|
// with that scope (the read/write ceiling is off for it). It sees no
|
|
// frontend tool, its backend tool call runs as the administrator, and a
|
|
// grant without the backend subject kind and without a frontend user is
|
|
// refused with 401.
|
|
func TestBackendSubjectSmoke(t *testing.T) {
|
|
if testing.Short() {
|
|
t.Skip("requires testcontainers postgres")
|
|
}
|
|
plugins := []party.Plugin{adminToolsPlugin{}, acmePlugin{tools: []pact.MCPTool{echoTool()}}}
|
|
app, admin := backendSubjectApp(t, plugins)
|
|
host, err := mountPier(t, app, plugins)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
srv := httptest.NewServer(host)
|
|
defer srv.Close()
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
client := mcp.NewClient(&mcp.Implementation{Name: "backend-subject", Version: "1"}, nil)
|
|
cs, err := client.Connect(ctx, &mcp.StreamableClientTransport{
|
|
Endpoint: srv.URL + "/mcp",
|
|
HTTPClient: &http.Client{Transport: bearerTransport{token: "oas_at_admin_read"}},
|
|
}, nil)
|
|
if err != nil {
|
|
t.Fatalf("connect: %v", err)
|
|
}
|
|
defer cs.Close()
|
|
list, err := cs.ListTools(ctx, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var names []string
|
|
for _, tl := range list.Tools {
|
|
names = append(names, tl.Name)
|
|
}
|
|
if !slices.Equal(names, []string{"admintools_list_items"}) {
|
|
t.Fatalf("tools/list = %v, want only the read-only backend tool", names)
|
|
}
|
|
res, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "admintools_list_items", Arguments: map[string]any{}})
|
|
if err != nil || res.IsError {
|
|
t.Fatalf("tools/call = %+v, %v", res, err)
|
|
}
|
|
if structured, _ := res.StructuredContent.(map[string]any); structured["admin"] != float64(admin) {
|
|
t.Fatalf("the backend tool ran as %+v, want admin %d", res.StructuredContent, admin)
|
|
}
|
|
res, err = cs.CallTool(ctx, &mcp.CallToolParams{Name: "admintools_create_item", Arguments: map[string]any{}})
|
|
if err == nil && (res == nil || !res.IsError) {
|
|
t.Fatalf("the write tool was callable: %+v", res)
|
|
}
|
|
|
|
refused := rpc(t, ctx, srv.URL+"/mcp", "oas_at_nobody", "", initializeBody)
|
|
if refused.status != http.StatusUnauthorized {
|
|
t.Fatalf("a grant with no subject kind and UserID 0 = %d %s, want 401", refused.status, refused.body)
|
|
}
|
|
}
|