feat(32.2-01): administrator-only MCP grants and a configurable consent handoff
- 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
This commit is contained in:
@@ -10,7 +10,7 @@ Opt-in MCP endpoint that lists the tools and prompts plugins declare per caller
|
||||
|
||||
pier mounts a streamable HTTP MCP endpoint (POST, GET and DELETE at `mcp.path`, default `/mcp`) inside the application binary, on the official Go SDK. A plugin takes part by implementing `pact.HasMCP`: each `pact.MCPTool` names one of the plugin's own routes by method and path, an input struct whose tags say which fields fill the path, the query string and the body, and the guard the tool runs as. At boot pier compiles every declaration against the route table (an unknown route, a duplicate or invalid name, a route that is not token-guarded, a non-object input, a `path:` field the schema does not require, an embedded struct on a `GET` or `DELETE` tool all fail boot naming the plugin and the tool), reflects the input schema from the struct and prefixes the exposed name with the plugin's short code (`acme.blog` declaring `create_post` exposes `blog_create_post`).
|
||||
|
||||
Every request to the endpoint is authorized afresh from its bearer: an OAuth access token through the `pact.MCPTokenVerifier` the OAuth server plugin publishes, or, behind `mcp.allow_personal_tokens`, a personal API token (an admin `g15_` token through cabana, a frontend token through the published `pact.MCPPersonalTokenResolver`). The resulting `pier.Identity` names a frontend subject and, when the grant carries the `backend` scope and the published `pact.MCPLinkedBackendResolver` confirms a link, a backend subject, but only while that link names the administrator the grant was consented for (`pact.MCPGrant.BackendUserID`): a link changed to anyone else, or a grant that records no consented administrator, gets no backend subject. `tools/list` is computed for that identity: a tool needs a subject under its guard, a grant without `write` sees only read-only tools, and the guard provider's own check (the same logic its route middleware enforces) decides the rest. A `tools/call` runs the bound route's compiled middleware chain in-process with the `bouncer.Dispatch` marker carrying the principal the guard provider resolved, and, immediately before that marker, a `pact.MCPCall` stored with `pact.WithMCPCall`. `pact.MCPCall.Subject` is the subject resolved for the tool's guard, `pact.MCPCall.Tool` is the exposed tool name and `pact.MCPCall.SessionID` is the MCP session id, empty on the stateless path and never the audit word used when a stateful call has no session. A route reads the call with `pact.MCPCallFrom`; a context pier did not dispatch answers false. `pact.MCPSubject.TokenID` is a member personal-token id only when `pact.MCPSubject.ClientID` is empty, and the OAuth access-token row otherwise. `pact.MCPSubject.Scopes` is the grant, not an implied expansion. The read/write ceiling is unchanged: a grant without `write` still sees only read-only tools. The inner request never carries an `Authorization` or `Cookie` header. A 2xx answer becomes text plus structured content, anything else a tool error carrying the route's own body.
|
||||
Every request to the endpoint is authorized afresh from its bearer: an OAuth access token through the `pact.MCPTokenVerifier` the OAuth server plugin publishes, or, behind `mcp.allow_personal_tokens`, a personal API token (an admin `g15_` token through cabana, a frontend token through the published `pact.MCPPersonalTokenResolver`). The resulting `pier.Identity` names a frontend subject and, when the grant carries the `backend` scope and the published `pact.MCPLinkedBackendResolver` confirms a link, a backend subject, but only while that link names the administrator the grant was consented for (`pact.MCPGrant.BackendUserID`): a link changed to anyone else, or a grant that records no consented administrator, gets no backend subject. An administrator-only grant (`pact.MCPGrant.Subject` is `pact.MCPGrantSubjectBackend`, `UserID` 0, `pact.MCPGrant.BackendUserID` set) instead gets a backend subject straight from the grant: no frontend subject even when a frontend guard is registered, no link lookup, its own binding `oauth:backend:<client_id>:<admin_id>`, no read/write ceiling, and `pact.MCPSubject.ScopeLimited` set, so the backend guard caps the administrator with `cabana.ScopeLimitFor` exactly like a `g15_` token with the same scopes. A grant with neither a frontend user nor that subject kind is refused; linked user grants are unchanged and stay uncapped by a scope limit. `tools/list` is computed for that identity: a tool needs a subject under its guard, a grant without `write` sees only read-only tools, and the guard provider's own check (the same logic its route middleware enforces) decides the rest. A `tools/call` runs the bound route's compiled middleware chain in-process with the `bouncer.Dispatch` marker carrying the principal the guard provider resolved, and, immediately before that marker, a `pact.MCPCall` stored with `pact.WithMCPCall`. `pact.MCPCall.Subject` is the subject resolved for the tool's guard, `pact.MCPCall.Tool` is the exposed tool name and `pact.MCPCall.SessionID` is the MCP session id, empty on the stateless path and never the audit word used when a stateful call has no session. A route reads the call with `pact.MCPCallFrom`; a context pier did not dispatch answers false. `pact.MCPSubject.TokenID` is a member personal-token id only when `pact.MCPSubject.ClientID` is empty, and the OAuth access-token row otherwise. `pact.MCPSubject.Scopes` is the grant, not an implied expansion. The read/write ceiling is unchanged: a grant without `write` still sees only read-only tools. The inner request never carries an `Authorization` or `Cookie` header. A 2xx answer becomes text plus structured content, anything else a tool error carrying the route's own body.
|
||||
|
||||
Sessions (`Mcp-Session-Id`) are bound to the identity that opened them (client and user, or the personal token), live in a store with a sliding idle TTL, and are served by a per-session SDK server on whichever instance receives the request, rehydrated from the stored session state when it is not local. The memory store serves one instance; the Redis store shares sessions across instances and fans subject events out to every instance, so a permission or link change pushes `notifications/tools/list_changed` to the sessions it concerns and a revocation ends them everywhere. Clients of protocol 2026-07-28 and later, which have no sessions, are served statelessly from the same path by the SDK's stateless handler over per-identity servers, sharing identity, dispatch and filtering with the stateful path.
|
||||
|
||||
@@ -23,6 +23,7 @@ Use cases:
|
||||
- Let an editor connect one MCP client to the application once, through the application's own OAuth server, and reach the tools of every plugin they may use.
|
||||
- Expose a plugin's management routes to agents without a second server: the route's throttles, scopes and permissions run unchanged on every call.
|
||||
- Run backend tools as the linked administrator, with the administrator's real permissions capped by the grant's read or write scope.
|
||||
- Run backend tools for an administrator-only grant (`pact.MCPGrantSubjectBackend`) as that administrator, capped by the scope limit a personal token with the grant's scopes gets.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -32,8 +33,8 @@ Use cases:
|
||||
- Annotations from the method (D-14): `GET` read-only and idempotent, `PUT` idempotent, `DELETE` destructive; `ReadOnly`, `Destructive`, `Idempotent` and `OpenWorld` override; the destructive and open-world hints are always explicit.
|
||||
- In-process dispatch through `pier.Host.Handler`, the route's compiled chain, with `pact.WithMCPCall` immediately before `bouncer.WithDispatch` carrying the guard provider's `MCPDispatch` principal and credential, path values set as the mux would, `RemoteAddr`, the `Host`, `X-Forwarded-For`, `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Real-IP` and `Accept-Language` copied from the MCP request (never `Authorization` or `Cookie`), `mcp.call_timeout` on the context and the answer captured up to `mcp.max_result_bytes` (D-17). A failed guard dispatch answers the fixed tool error `pier: the tool could not be run for this caller` and logs the cause server-side, so no provider or database error reaches the agent (an invalid token, a deactivated account and an admin personal token whose stored scopes no longer resolve keep their own fixed texts); a dispatch whose guard list names `backend` for a frontend tool, or whose principal kind contradicts the tool's guard, is refused the same way.
|
||||
- Results (D-13): 2xx is text plus structured content (an object as is, any other JSON wrapped as `{"data": …}`); a 4xx or 5xx is a tool error whose text is the route's body; a too-large answer is a tool error with a fixed text.
|
||||
- Built-in `backend` guard provider (`pier.BackendGuard`): routes behind cabana's `backend` middleware, listing through `cabana.Allows` on the administrator's principal from `cabana.BackendPrincipal`, an admin personal token's scope limit computed per dispatched route method with `cabana.ScopeLimitFor`; a plugin that registers its own `backend` provider wins.
|
||||
- Identity per request (`pier.Identity`): `oas_at_` tokens through the published verifier, personal tokens only with `mcp.allow_personal_tokens`, the backend subject through the published link resolver with an in-process cache of at most `pier.LinkCacheTTL`; the binding key `oauth:<client_id>:<user_id>`, `pat:user:<token_id>` or `pat:backend:<token_id>` survives access-token rotation. One `pact.MCPPersonalTokenResolver` serves the application; a subject it answers without a `TokenID` is refused, so personal-token users never share a binding.
|
||||
- Built-in `backend` guard provider (`pier.BackendGuard`): routes behind cabana's `backend` middleware, listing through `cabana.Allows` on the administrator's principal from `cabana.BackendPrincipal`, an admin personal token's (or a `pact.MCPSubject.ScopeLimited` subject's) scope limit computed per dispatched route method with `cabana.ScopeLimitFor`; a plugin that registers its own `backend` provider wins.
|
||||
- Identity per request (`pier.Identity`): `oas_at_` tokens through the published verifier, personal tokens only with `mcp.allow_personal_tokens`, the backend subject through the published link resolver with an in-process cache of at most `pier.LinkCacheTTL`; the binding key `oauth:<client_id>:<user_id>`, `oauth:backend:<client_id>:<admin_id>` (an administrator-only grant), `pat:user:<token_id>` or `pat:backend:<token_id>` survives access-token rotation. One `pact.MCPPersonalTokenResolver` serves the application; a subject it answers without a `TokenID` is refused, so personal-token users never share a binding.
|
||||
- Per-identity SDK server plus a receiving middleware that re-filters `tools/list` and `prompts/list` and refuses `tools/call` and `prompts/get` for the identity of the current request, so a permission change takes effect on the next request (D-08, D-25).
|
||||
- Stateful sessions (D-25, D-27): `initialize` opens a session (429 above `mcp.sessions.max_per_binding`), a request with an unknown id answers 404 (the client re-initialises), another identity presenting the id answers 403 `session_binding`, DELETE ends the session everywhere, the record's TTL slides on every request, a session initialised on one instance is rehydrated on another from the stored `ServerSessionState`. A standalone GET stream re-verifies its bearer every minute and ends when it no longer resolves to the session's binding or the session's record is gone.
|
||||
- Session reaper (A-CR-01): most clients exit without DELETE, so a janitor started at mount checks every local session against the store every `min(mcp.sessions.idle_ttl/2, 1m)` and closes each local copy whose record has expired (its SDK server session ends and it leaves the fan-out set), logging the `expired` step. The store's TTL decides on every instance: a session another instance keeps alive still has its record, so no instance closes it. No configuration key; the reaper runs for the life of the process.
|
||||
|
||||
@@ -99,15 +99,17 @@ func (g backendGuard) MCPDispatch(ctx context.Context, subject pact.MCPSubject,
|
||||
|
||||
// principal loads the admin through cabana.BackendPrincipal (nil when the
|
||||
// admin does not exist or is deactivated) and, for a personal-token subject
|
||||
// (no OAuth client), sets the scope limit for method; a token whose stored
|
||||
// scopes are all unknown answers errScopeUnavailable, as the HTTP guard
|
||||
// refuses it.
|
||||
// (no OAuth client) or a ScopeLimited subject (an administrator-only OAuth
|
||||
// grant), sets the scope limit for method; scopes that are all unknown
|
||||
// answer errScopeUnavailable, as the HTTP guard refuses such a token. A
|
||||
// linked user-mode grant (ClientID set, ScopeLimited false) stays
|
||||
// unlimited.
|
||||
func (g backendGuard) principal(ctx context.Context, subject pact.MCPSubject, method string) (*bouncer.Principal, error) {
|
||||
principal, err := cabana.BackendPrincipal(ctx, g.app, subject.UserID)
|
||||
if err != nil || principal == nil {
|
||||
return nil, err
|
||||
}
|
||||
if subject.ClientID == "" && subject.TokenID != 0 {
|
||||
if (subject.ClientID == "" && subject.TokenID != 0) || subject.ScopeLimited {
|
||||
limit, known, _ := cabana.ScopeLimitFor(g.app, subject.Scopes, method)
|
||||
if known == 0 {
|
||||
return nil, errScopeUnavailable
|
||||
|
||||
238
modules/pier/backend_subject_smoke_test.go
Normal file
238
modules/pier/backend_subject_smoke_test.go
Normal file
@@ -0,0 +1,238 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -36,10 +36,12 @@ var ErrUnauthorized = errors.New("pier: unauthorized")
|
||||
|
||||
// Identity is who one MCP request acts as: the frontend subject (the OAuth
|
||||
// grant's user or a frontend personal token), the backend subject (the
|
||||
// linked admin when the grant carries the backend scope, or an admin
|
||||
// personal token), the scopes of the credential, the session binding key
|
||||
// (D-35: oauth:<client_id>:<user_id>, pat:user:<token_id> or
|
||||
// pat:backend:<token_id>), the credential's expiry and its kind. Every
|
||||
// linked admin when the grant carries the backend scope, the administrator
|
||||
// of an administrator-only grant, or an admin personal token), the scopes
|
||||
// of the credential, the session binding key (D-35:
|
||||
// oauth:<client_id>:<user_id>, oauth:backend:<client_id>:<admin_id>,
|
||||
// pat:user:<token_id> or pat:backend:<token_id>), the credential's expiry
|
||||
// and its kind. Every
|
||||
// request resolves its own Identity from its bearer; a session never
|
||||
// replaces it.
|
||||
type Identity struct {
|
||||
@@ -82,8 +84,9 @@ func (id Identity) writes() bool {
|
||||
}
|
||||
|
||||
// fingerprint encodes the authorization-relevant parts of the identity
|
||||
// (P-26): the sorted scopes, both subjects (guard, user, client and their
|
||||
// sorted scopes), the ceiling and the token kind. Two requests of one
|
||||
// (P-26): the sorted scopes, both subjects (guard, user, client, their
|
||||
// sorted scopes and whether they are scope-limited), the ceiling and the
|
||||
// token kind. Two requests of one
|
||||
// binding with different fingerprints may see different tools, so a cached
|
||||
// server is re-filtered when it changes (A-WR-04). Token ids are left out:
|
||||
// a guard decides on scopes, subjects and the ceiling, not on which token
|
||||
@@ -108,6 +111,8 @@ func (id Identity) fingerprint() string {
|
||||
b.WriteString(s.ClientID)
|
||||
b.WriteByte(':')
|
||||
b.WriteString(sorted(s.Scopes))
|
||||
b.WriteByte(':')
|
||||
b.WriteString(strconv.FormatBool(s.ScopeLimited))
|
||||
b.WriteByte('|')
|
||||
}
|
||||
b.WriteString(sorted(id.Scopes))
|
||||
@@ -207,7 +212,13 @@ func (r *identityResolver) resolveOAuth(ctx context.Context, raw string) (Identi
|
||||
return Identity{}, ErrUnauthorized
|
||||
}
|
||||
grant, err := verifier.MCPVerifyToken(ctx, raw)
|
||||
if err != nil || grant.UserID == 0 {
|
||||
if err != nil {
|
||||
return Identity{}, ErrUnauthorized
|
||||
}
|
||||
if grant.Subject == pact.MCPGrantSubjectBackend {
|
||||
return resolveBackendGrant(grant)
|
||||
}
|
||||
if grant.UserID == 0 {
|
||||
return Identity{}, ErrUnauthorized
|
||||
}
|
||||
scopes := append([]string(nil), grant.Scopes...)
|
||||
@@ -232,6 +243,36 @@ func (r *identityResolver) resolveOAuth(ctx context.Context, raw string) (Identi
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// resolveBackendGrant is the Identity of an administrator-only OAuth grant
|
||||
// (pact.MCPGrantSubjectBackend): the backend subject is the administrator
|
||||
// in BackendUserID, taken straight from the grant without a link lookup,
|
||||
// and there is no frontend subject even when a frontend guard is
|
||||
// registered. The binding oauth:backend:<client>:<admin> never collides
|
||||
// with a user grant's oauth:<client>:<user>. The read/write ceiling is off
|
||||
// and the subject is ScopeLimited, so the backend guard caps it with the
|
||||
// scope limit a personal token with the same scopes gets. A grant that
|
||||
// names a frontend user or no administrator is refused.
|
||||
func resolveBackendGrant(grant pact.MCPGrant) (Identity, error) {
|
||||
if grant.UserID != 0 || grant.BackendUserID == 0 {
|
||||
return Identity{}, ErrUnauthorized
|
||||
}
|
||||
scopes := append([]string(nil), grant.Scopes...)
|
||||
return Identity{
|
||||
Scopes: scopes,
|
||||
Binding: "oauth:backend:" + grant.ClientID + ":" + strconv.FormatUint(uint64(grant.BackendUserID), 10),
|
||||
ExpiresAt: grant.ExpiresAt,
|
||||
TokenKind: TokenKindOAuth,
|
||||
Backend: &pact.MCPSubject{
|
||||
Guard: BackendGuard,
|
||||
UserID: grant.BackendUserID,
|
||||
Scopes: append([]string(nil), scopes...),
|
||||
ClientID: grant.ClientID,
|
||||
TokenID: grant.TokenID,
|
||||
ScopeLimited: true,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// consentedBackendSubject is the backend subject of an OAuth grant of
|
||||
// userID: the linked administrator, when the grant carries the backend
|
||||
// scope and the link names consented, the account the grant was consented
|
||||
|
||||
Reference in New Issue
Block a user