- pact: MCPAdminConsent provider interface, MCPAdminConsentRequest,
MCPAdminConsentDecision, ErrMCPConsentNotFound, ErrMCPConsentNoScopes
- cabana: GET/POST {api}/mcp/consent/{request}, interactive-only, scope
policy of personal tokens (requested, catalog, owned; * collapses)
- cabana: TokenScopeNames and TokenScopeLabels export the token-scope catalog
- swag views and annotations; admin.json and schema.d.ts regenerated so the
contract and conformance inventories stay green
- phrasebook keys mcp_connect.request_not_found and no_grantable_scopes
303 lines
12 KiB
Go
303 lines
12 KiB
Go
package cabana
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
|
"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"
|
|
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var (
|
|
consentPGOnce sync.Once
|
|
consentPGDB *gorm.DB
|
|
consentPGErr error
|
|
)
|
|
|
|
// consentGorm starts one Postgres for the admin smoke tests of this file
|
|
// set and migrates the framework tables (backend_users and friends).
|
|
func consentGorm(t *testing.T) *gorm.DB {
|
|
t.Helper()
|
|
if testing.Short() {
|
|
t.Skip("requires testcontainers postgres")
|
|
}
|
|
consentPGOnce.Do(func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
|
defer cancel()
|
|
ctr, err := tcpostgres.Run(ctx, "postgres:16-alpine",
|
|
tcpostgres.WithDatabase("cabana"),
|
|
tcpostgres.WithUsername("cabana"),
|
|
tcpostgres.WithPassword("cabana"),
|
|
tcpostgres.BasicWaitStrategies(),
|
|
)
|
|
if err != nil {
|
|
consentPGErr = err
|
|
return
|
|
}
|
|
dsn, err := ctr.ConnectionString(ctx, "sslmode=disable")
|
|
if err != nil {
|
|
consentPGErr = err
|
|
return
|
|
}
|
|
db, err := sql.Open("pgx", dsn)
|
|
if err != nil {
|
|
consentPGErr = err
|
|
return
|
|
}
|
|
gdb, err := lagoon.Use(ctx, db)
|
|
if err != nil {
|
|
consentPGErr = err
|
|
return
|
|
}
|
|
if err := lagoon.Migrate(gdb, nil); err != nil {
|
|
consentPGErr = err
|
|
return
|
|
}
|
|
consentPGDB = gdb
|
|
})
|
|
if consentPGErr != nil {
|
|
t.Fatalf("postgres: %v", consentPGErr)
|
|
}
|
|
return consentPGDB
|
|
}
|
|
|
|
// consentScopesPlugin declares a read and a write permission and one plugin
|
|
// token scope behind the write permission.
|
|
type consentScopesPlugin struct{}
|
|
|
|
func (consentScopesPlugin) ID() string { return "acme.items" }
|
|
func (consentScopesPlugin) Requires() []string { return nil }
|
|
func (consentScopesPlugin) Register(*backpack.App) error { return nil }
|
|
func (consentScopesPlugin) Boot(*backpack.App) error { return nil }
|
|
func (consentScopesPlugin) Permissions() []pact.Permission {
|
|
return []pact.Permission{
|
|
{Code: "acme.items.read", Tab: "Items", Label: "Read items"},
|
|
{Code: "acme.items.write", Tab: "Items", Label: "Write items"},
|
|
}
|
|
}
|
|
func (consentScopesPlugin) TokenScopes() []pact.TokenScope {
|
|
return []pact.TokenScope{{Name: "acme:write", Label: "Write items", Description: "Create and change items.", Permissions: []string{"acme.items.write"}, Methods: []string{"GET", "POST"}}}
|
|
}
|
|
|
|
// fakeAdminConsent is the published pact.MCPAdminConsent of the test: one
|
|
// pending request "req1" for any administrator.
|
|
type fakeAdminConsent struct {
|
|
mu sync.Mutex
|
|
requested []string
|
|
decided []pact.MCPAdminConsentDecision
|
|
admins []uint
|
|
}
|
|
|
|
func (f *fakeAdminConsent) MCPAdminConsentShow(_ context.Context, adminID uint, requestID string) (pact.MCPAdminConsentRequest, error) {
|
|
if requestID != "req1" {
|
|
return pact.MCPAdminConsentRequest{}, pact.ErrMCPConsentNotFound
|
|
}
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return pact.MCPAdminConsentRequest{
|
|
RequestID: "req1", ClientID: "oas_client", ClientName: "Agent", LogoURL: "https://agent.example.com/logo.png",
|
|
RedirectURI: "https://agent.example.com:8443/callback?x=1", Scopes: append([]string(nil), f.requested...),
|
|
OfflineAccess: true, ConsentRequired: true, ExpiresAt: time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC),
|
|
}, nil
|
|
}
|
|
|
|
func (f *fakeAdminConsent) MCPAdminConsentDecide(_ context.Context, adminID uint, requestID string, decision pact.MCPAdminConsentDecision) (string, error) {
|
|
if requestID != "req1" {
|
|
return "", pact.ErrMCPConsentNotFound
|
|
}
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.decided = append(f.decided, decision)
|
|
f.admins = append(f.admins, adminID)
|
|
if !decision.Allow {
|
|
return "https://agent.example.com:8443/callback?error=access_denied", nil
|
|
}
|
|
return "https://agent.example.com:8443/callback?code=c1", nil
|
|
}
|
|
|
|
// TestMCPAdminConsentSmoke covers the admin consent endpoints over a fake
|
|
// provider: Show lists only requested catalog scopes the administrator can
|
|
// grant (a write scope they lack and an unknown name are hidden), Allow
|
|
// drops submitted scopes outside that set and calls Decide with the rest,
|
|
// offline access needs both the request and the body, Deny passes through,
|
|
// and the endpoint answers 401 anonymous, 403 interactive_only for a g15_
|
|
// token, 404 without a provider or for an unknown request, 422 when nothing
|
|
// grantable is submitted and 400 for an unknown body field.
|
|
func TestMCPAdminConsentSmoke(t *testing.T) {
|
|
gdb := consentGorm(t)
|
|
var admin BackendUser
|
|
admin = BackendUser{FirstName: "Ada", LastName: "Reader", Login: "consent-reader", Email: "reader@acme.test", Password: "x", Permissions: `{"acme.items.read":1}`, IsActivated: true}
|
|
if err := gdb.Create(&admin).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
reg, err := compileTokenCatalog([]party.Plugin{consentScopesPlugin{}})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
app := backpack.New(nil)
|
|
if err := app.Publish(gdb); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
provider := &fakeAdminConsent{requested: []string{"acme:write", "admin:read", "ghost"}}
|
|
svc := &service{app: app, reg: reg}
|
|
principal := &bouncer.Principal{ID: admin.ID, Backend: true, PermissionGrants: map[string]bool{"acme.items.read": true}}
|
|
|
|
request := func(method, id, body string, p *bouncer.Principal) *http.Request {
|
|
req := httptest.NewRequest(method, "/mcp/consent/"+id, strings.NewReader(body))
|
|
req.Header.Set("X-Requested-With", "XMLHttpRequest")
|
|
req.SetPathValue("request", id)
|
|
if p != nil {
|
|
req = req.WithContext(bouncer.WithUser(req.Context(), p))
|
|
}
|
|
return req
|
|
}
|
|
show := func(s *service, id string, p *bouncer.Principal) *httptest.ResponseRecorder {
|
|
rec := httptest.NewRecorder()
|
|
interactiveOnly(s.mcpConsentShow)(rec, request(http.MethodGet, id, "", p))
|
|
return rec
|
|
}
|
|
decide := func(s *service, id, body string, p *bouncer.Principal) *httptest.ResponseRecorder {
|
|
rec := httptest.NewRecorder()
|
|
interactiveOnly(requireAjax(s.mcpConsentDecide))(rec, request(http.MethodPost, id, body, p))
|
|
return rec
|
|
}
|
|
|
|
// No provider published: 404 request_not_found for both.
|
|
if rec := show(svc, "req1", principal); rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), `"request_not_found"`) {
|
|
t.Fatalf("show without provider = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if rec := decide(svc, "req1", `{"decision":"deny"}`, principal); rec.Code != http.StatusNotFound {
|
|
t.Fatalf("decide without provider = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if err := app.Publish[pact.MCPAdminConsent](provider); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
rec := show(svc, "req1", principal)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("show = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
var shown struct {
|
|
Data MCPConsentView `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &shown); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var names []string
|
|
for _, sc := range shown.Data.Scopes {
|
|
names = append(names, sc.Name)
|
|
}
|
|
if !slices.Equal(names, []string{"admin:read"}) {
|
|
t.Fatalf("shown scopes = %v, want [admin:read]", names)
|
|
}
|
|
d := shown.Data
|
|
if d.RequestID != "req1" || d.Client.ID != "oas_client" || d.Client.Name != "Agent" || d.Client.RedirectHost != "agent.example.com:8443" ||
|
|
d.Admin.Login != "consent-reader" || d.Admin.Name != "Ada Reader" || d.Admin.Email != "reader@acme.test" ||
|
|
!d.OfflineAccess || !d.ConsentRequired || d.ExpiresAt != "2026-11-21T10:00:00Z" || !shown.Data.Scopes[0].ReadOnly {
|
|
t.Fatalf("view = %+v", d)
|
|
}
|
|
if rec := show(svc, "nope", principal); rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), `"request_not_found"`) {
|
|
t.Fatalf("unknown request = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
// Allow: * was not requested and acme:write is not grantable, so both
|
|
// are dropped; offline access is requested and asked for.
|
|
rec = decide(svc, "req1", `{"decision":"allow","scopes":["*","admin:read","acme:write"],"offline_access":true}`, principal)
|
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"redirect_uri":"https://agent.example.com:8443/callback?code=c1"`) {
|
|
t.Fatalf("allow = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if last := provider.decided[len(provider.decided)-1]; !last.Allow || !slices.Equal(last.Scopes, []string{"admin:read"}) || !last.OfflineAccess || provider.admins[len(provider.admins)-1] != admin.ID {
|
|
t.Fatalf("decide called with %+v", last)
|
|
}
|
|
// Only hidden scopes submitted: 422, Decide not called.
|
|
calls := len(provider.decided)
|
|
if rec := decide(svc, "req1", `{"decision":"allow","scopes":["acme:write","ghost"]}`, principal); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"no_grantable_scopes"`) || len(provider.decided) != calls {
|
|
t.Fatalf("nothing grantable = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
// A requested * is offered, as on personal-token creation, and
|
|
// collapses the grant to ["*"].
|
|
provider.mu.Lock()
|
|
provider.requested = []string{"*", "admin:read"}
|
|
provider.mu.Unlock()
|
|
if rec := decide(svc, "req1", `{"decision":"allow","scopes":["admin:read","*"],"offline_access":false}`, principal); rec.Code != http.StatusOK {
|
|
t.Fatalf("allow * = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if last := provider.decided[len(provider.decided)-1]; !slices.Equal(last.Scopes, []string{"*"}) || last.OfflineAccess {
|
|
t.Fatalf("decide * called with %+v", last)
|
|
}
|
|
// Deny passes through without scopes.
|
|
if rec := decide(svc, "req1", `{"decision":"deny"}`, principal); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "access_denied") {
|
|
t.Fatalf("deny = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if last := provider.decided[len(provider.decided)-1]; last.Allow || len(last.Scopes) != 0 {
|
|
t.Fatalf("deny called with %+v", last)
|
|
}
|
|
// Malformed bodies: an unknown field and an unknown decision.
|
|
for _, body := range []string{`{"decision":"allow","scopes":["admin:read"],"extra":1}`, `{"decision":"maybe"}`, `not json`} {
|
|
if rec := decide(svc, "req1", body, principal); rec.Code != http.StatusBadRequest {
|
|
t.Fatalf("body %s = %d %s", body, rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
if rec := decide(svc, "nope", `{"decision":"allow","scopes":["admin:read"]}`, principal); rec.Code != http.StatusNotFound {
|
|
t.Fatalf("decide unknown request = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
// Anonymous: 401. A g15_ token: 403 interactive_only, for GET and POST.
|
|
if rec := show(svc, "req1", nil); rec.Code != http.StatusUnauthorized {
|
|
t.Fatalf("anonymous = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
tokenReq := request(http.MethodGet, "req1", "", principal)
|
|
tokenReq = tokenReq.WithContext(bouncer.WithCredential(tokenReq.Context(), &BackendAPIToken{ID: 3}))
|
|
rec = httptest.NewRecorder()
|
|
interactiveOnly(svc.mcpConsentShow)(rec, tokenReq)
|
|
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "interactive_only") {
|
|
t.Fatalf("token credential = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
bearer := request(http.MethodPost, "req1", `{"decision":"deny"}`, principal)
|
|
bearer.Header.Set("Authorization", "Bearer "+APITokenPrefix+strings.Repeat("0", 40))
|
|
rec = httptest.NewRecorder()
|
|
interactiveOnly(requireAjax(svc.mcpConsentDecide))(rec, bearer)
|
|
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "interactive_only") {
|
|
t.Fatalf("raw g15_ bearer = %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
// The POST needs X-Requested-With.
|
|
plain := request(http.MethodPost, "req1", `{"decision":"deny"}`, principal)
|
|
plain.Header.Del("X-Requested-With")
|
|
rec = httptest.NewRecorder()
|
|
interactiveOnly(requireAjax(svc.mcpConsentDecide))(rec, plain)
|
|
if rec.Code != http.StatusForbidden {
|
|
t.Fatalf("POST without X-Requested-With = %d", rec.Code)
|
|
}
|
|
}
|
|
|
|
// TestTokenScopeNamesAndLabels: the exported catalog answers names in
|
|
// catalog order before activation, and labels fall back to the name.
|
|
func TestTokenScopeNamesAndLabels(t *testing.T) {
|
|
app := backpack.New(nil)
|
|
if err := app.Publish(party.Activated([]party.Plugin{consentScopesPlugin{}})); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
names, err := TokenScopeNames(app)
|
|
if err != nil || !slices.Equal(names, []string{"*", "admin:read", "acme:write"}) {
|
|
t.Fatalf("names = %v, %v", names, err)
|
|
}
|
|
labels := TokenScopeLabels(context.Background(), app, []string{"acme:write", "ghost"})
|
|
if !slices.Equal(labels, []string{"Write items", "ghost"}) {
|
|
t.Fatalf("labels = %v", labels)
|
|
}
|
|
}
|