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:
Jakub Zych
2026-11-21 00:06:19 +01:00
parent 45eb34e5c4
commit c63bfa3ef2
12 changed files with 506 additions and 33 deletions

View File

@@ -128,6 +128,8 @@ What pier does with it at boot:
Every request is authorized afresh from its bearer; a session never replaces the bearer. An OAuth access token of the application's authorization server (`oas_at_…`) is verified through the `pact.MCPTokenVerifier` the OAuth server plugin publishes: the grant's user is the frontend subject, the grant's scopes are the ceiling. With the `backend` scope and a link the published `pact.MCPLinkedBackendResolver` confirms, the linked administrator is the backend subject, resolved on every request (cached for at most five seconds on one instance and dropped at once by a link event), so unlinking takes effect on the next call with no token surgery. The verifier also reports which administrator the user consented to (`pact.MCPGrant.BackendUserID`); while the link names anyone else, or when the grant records none, the grant has no backend subject, so a link that changes after the consent never re-targets it. The backend principal keeps the administrator's real permissions, superuser included, under the grant's ceiling.
An application without frontend users can sign administrators in directly. The OAuth server plugin then issues administrator-only grants: the verifier answers `pact.MCPGrant.Subject` as `pact.MCPGrantSubjectBackend`, `UserID` 0 and the administrator in `pact.MCPGrant.BackendUserID`. Such a grant has only a backend subject, taken straight from the grant with no link lookup, and its sessions are bound to `oauth:backend:<client_id>:<admin_id>`, so two administrators of one client never share a session. The read/write ceiling does not apply; instead the subject is `pact.MCPSubject.ScopeLimited`, and the backend guard caps it with the same scope limit an administrator's `g15_` token with those scopes gets: a grant of `admin:read` lists and runs only the routes that limit allows for `GET`. A grant that names neither a frontend user nor an administrator is refused. Grants of linked frontend users are unchanged.
The `read` and `write` scopes are a ceiling, and that ceiling is unchanged: a grant with only `read` sees tools whose read-only hint is true, `write` unlocks the rest, and permissions always filter on top. The `ai` and `offline_access` scopes play no part in it. `pact.MCPSubject.Scopes` on a call is the grant, not an implied expansion of `pact.FrontendTokenScope.Implies`.
Every tool call stores a `pact.MCPCall` with `pact.WithMCPCall` immediately before the dispatch marker. A route reads it with `pact.MCPCallFrom`; a request pier did not dispatch has none. `pact.MCPCall.Subject` is the subject resolved for that 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. `pact.MCPSubject.TokenID` is a member personal-token id only when `pact.MCPSubject.ClientID` is empty, and the OAuth access-token row otherwise.

View File

@@ -106,7 +106,7 @@ The metadata document advertises these paths under the issuer, so mount them at
## Consent
The authorization endpoint sends the browser to `<issuer>/connect?request=<id>`. That page belongs to the application: it signs the user in, shows what the client asks for and posts the decision to the application's own consent handler, which calls:
The authorization endpoint sends the browser to `<issuer>/connect?request=<id>`, or to `wristband.Options.ConsentPath` on the issuer when the application sets one (for a consent page under the admin prefix, for example); an empty path keeps the PHP bytes exactly. A request that names no data scope gets `read`, or `wristband.Options.DefaultScopes` filtered to the accepted scopes when that list leaves anything. That page belongs to the application: it signs the user in, shows what the client asks for and posts the decision to the application's own consent handler, which calls:
- `wristband.Server.PendingRequest` to read what to show, as a `wristband.PendingRequestView`, including `wristband.PendingRequestView.OfflineAccess` (the pending row's flag; `offline_access` is not a scope on the view and `wristband.Server.IssueCode` is unchanged);
- `wristband.Server.IssueCode` to grant, which returns the redirect URL carrying the code, `iss` and `state`;
@@ -116,6 +116,8 @@ The authorization endpoint sends the browser to `<issuer>/connect?request=<id>`.
`wristband.Server.Revoke` disconnects an app: it revokes an access token and the refresh lineage behind it.
An OAuth server plugin that signs administrators in instead of frontend users answers its verifier's grants with `pact.MCPGrant.Subject` set to `pact.MCPGrantSubjectBackend`, `UserID` 0 and the administrator in `pact.MCPGrant.BackendUserID`. The MCP endpoint then acts as that administrator only, scope-limited like a `g15_` token with the granted scopes (see [MCP](mcp.md)).
## Clients created outside registration
Operator tooling that creates clients directly uses the same rules as registration. `wristband.RejectRedirectURI` accepts `https://` URIs and loopback `http://` URIs only:

View File

@@ -154,12 +154,12 @@ func (p *BlogPlugin) Schedule() []pact.ScheduledCommand {
| `pact.MCPPrompt` | One prompt template: name, title, description, guard, permissions, `Arguments` (`pact.MCPPromptArgument`), the `Render` func returning `pact.MCPPromptMessage` values (`Role` user or assistant, `Text`) and `Writes`, set when the prompt directs tools that are not read-only so it is listed only for an identity that may write (zero value: offered to read-only grants too). |
| `pact.MCPGuard` | A guard provider the owner of a route guard publishes: its name, whether a middleware list is token-guarded by it, the scopes and permissions a middleware list requires (`pact.MCPRequirements`), whether a subject may call a tool, and the pre-resolved principal for one in-process call (`pact.MCPDispatch`). |
| `pact.MCPGuards` | The registry of guard providers published on the application; `pact.NewMCPGuards` creates it, `Register` refuses an empty or duplicate name with a `pact:` error naming the guard, `Lookup` finds one and `Names` lists them sorted. Safe for concurrent use. |
| `pact.MCPSubject` | The identity an MCP session acts as under one guard: guard name, user id, granted scopes, OAuth client id and token id. `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. |
| `pact.MCPSubject` | The identity an MCP session acts as under one guard: guard name, user id, granted scopes, OAuth client id and token id. `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. `pact.MCPSubject.ScopeLimited` makes the backend guard cap the subject with the scope limit a personal token with the same scopes gets; pier sets it on the backend subject of an administrator-only grant, and false keeps today's rule (only a personal-token subject is scope-limited). |
| `pact.MCPCall` | One in-process MCP tool call: `pact.MCPCall.Subject`, `pact.MCPCall.SessionID` (empty on the stateless path) and `pact.MCPCall.Tool`. |
| `pact.WithMCPCall` | Stores a `pact.MCPCall` on a context. A nil context is returned as nil. |
| `pact.MCPCallFrom` | Returns the `pact.MCPCall` on a context. The boolean is false when the context is nil or carries none, including a plain HTTP request. |
| `pact.MCPDispatch` | A guard provider's answer for one call: the principal (as `any`), an optional credential and the bouncer guard names that honour the dispatch marker. |
| `pact.MCPTokenVerifier` | Published by the OAuth server plugin: verifies an access token at the MCP endpoint into a `pact.MCPGrant` (user, client, token, scopes, expiry and, for a `backend` grant, `BackendUserID`, the backend account the consent showed) and names its resource. A refused token is `pact.ErrMCPTokenInvalid`. The interface is only `MCPVerifyToken` and `MCPResource`. |
| `pact.MCPTokenVerifier` | Published by the OAuth server plugin: verifies an access token at the MCP endpoint into a `pact.MCPGrant` (user, client, token, scopes, expiry and, for a `backend` grant, `BackendUserID`, the backend account the consent showed) and names its resource. `pact.MCPGrant.Subject` says what the grant acts as: empty is the frontend user in `UserID` (the meaning every grant had before), `pact.MCPGrantSubjectBackend` is the administrator in `pact.MCPGrant.BackendUserID` alone, with `UserID` 0 and no frontend user. A refused token is `pact.ErrMCPTokenInvalid`. The interface is only `MCPVerifyToken` and `MCPResource`. |
| `pact.MCPAdvertisedScopes` | Optional second interface on that verifier. `pact.MCPAdvertisedScopes.MCPScopesSupported` is the MCP scope list pier copies into protected-resource metadata when the slice is non-empty. |
| `pact.MCPPersonalTokenResolver` | Published by the one plugin whose personal tokens may open an MCP session (one resolver per application): resolves a raw token into a `pact.MCPSubject` whose `TokenID` identifies the token row (it keys the session binding; a subject without one is refused); false when the prefix is not its own, which the endpoint answers as unauthorized. |
| `pact.MCPLinkedBackendResolver` | Published by the plugin that owns the frontend-to-backend account link: the `pact.LinkedBackendUser` (id, login, display name) of a frontend user, false when unlinked. |

View File

@@ -137,6 +137,14 @@ type MCPSubject struct {
Scopes []string
ClientID string
TokenID uint
// ScopeLimited, when true, makes the backend guard cap the subject with
// the same scope limit a personal token with these Scopes gets, so the
// subject can do no more than its scopes allow even where its account
// could. The MCP endpoint sets it on the backend subject of an
// administrator-only OAuth grant (MCPGrantSubjectBackend). False keeps
// today's rule: only a personal-token subject (TokenID set, no
// ClientID) is scope-limited.
ScopeLimited bool
}
// mcpCallKey is the unexported context key of an MCPCall. A plain HTTP
@@ -274,23 +282,41 @@ type MemberTokenScopeCatalog interface {
MemberTokenScopes() []FrontendTokenScope
}
// MCPGrant is a verified OAuth access token: the frontend user, the client,
// the token row, the granted scopes, the expiry and, for a grant carrying
// the backend scope, the backend account the user consented to.
// MCPGrant is a verified OAuth access token: the client, the token row, the
// granted scopes, the expiry and the subject the token acts as. With Subject
// empty that is the frontend user in UserID and, for a grant carrying the
// backend scope, the backend account the user consented to. With Subject
// MCPGrantSubjectBackend it is the administrator in BackendUserID alone.
type MCPGrant struct {
UserID uint
ClientID string
TokenID uint
Scopes []string
ExpiresAt time.Time
// BackendUserID is the backend account the consent page showed when
// the user granted the backend scope. The MCP endpoint gives the grant
// a backend subject only while the user's current link names this
// BackendUserID is the backend account of the grant. With Subject
// empty it is the account the consent page showed when the user
// granted the backend scope: the MCP endpoint gives the grant a
// backend subject only while the user's current link names this
// account, so a grant never acts as an administrator its consent did
// not show; zero (none recorded) gives no backend subject.
// not show, and zero (none recorded) gives no backend subject. With
// Subject MCPGrantSubjectBackend it is the administrator who signed in
// and consented, and the grant's only subject.
BackendUserID uint
// Subject is the kind of subject the grant names. Empty means the
// frontend user in UserID, the meaning every grant had before Subject
// existed. MCPGrantSubjectBackend means the backend account in
// BackendUserID, with UserID 0 and no frontend user involved.
Subject string
}
// MCPGrantSubjectBackend is the MCPGrant.Subject of an administrator-only
// grant: the subject is the backend account in BackendUserID, UserID is 0
// and no frontend user is involved. The MCP endpoint gives such a grant a
// backend subject straight from BackendUserID (no link lookup), keys its
// sessions on oauth:backend:<client>:<admin> and scope-limits it like a
// personal token with the same scopes (MCPSubject.ScopeLimited).
const MCPGrantSubjectBackend = "backend"
// ErrMCPTokenInvalid is what an MCPTokenVerifier answers for a token it does
// not accept.
var ErrMCPTokenInvalid = errors.New("pact: mcp token invalid")

View File

@@ -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.

View File

@@ -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

View 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)
}
}

View File

@@ -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

View File

@@ -27,7 +27,7 @@ Use cases:
- RFC 8414 metadata document (`wristband.Server.Metadata`) advertising the authorize, token and registration endpoints under the issuer, the `authorization_code` and `refresh_token` grants, S256 PKCE and the RFC 9207 `iss` response parameter.
- RFC 7591 dynamic client registration (`wristband.Server.Register`): JSON only, a bounded request body, redirect URI validation (HTTPS, or loopback HTTP), public (`none`) and confidential (`client_secret_post`, `client_secret_basic`) clients, a cap on unrevoked clients and a sweep of old clients that never got consent, all in one transaction.
- Authorization endpoint (`wristband.Server.Authorize`): the client and its exact registered redirect URI are validated before any redirect is sent (an unknown client gets a local plain-text 400, never an open redirect); then S256 PKCE, the client's scope ceiling and the RFC 8707 `resource` value are checked, a pending request is stored and the browser is sent to the application's consent page at `<issuer>/connect?request=<id>`. The accepted scopes are the same resolved list `wristband.Server.Metadata` advertises. A non-empty `wristband.Options.ScopesSupported` is used as given (`read`, `write`, `ai` and `offline_access` from `wristband.DefaultOptions`, which still refuses `backend`; a host that lists an extra scope accepts it). An empty or nil list on the MCP flavour resolves to `read`, `write`, `ai`, `offline_access` and `backend`. The OpenID Connect identity scopes `openid`, `profile` and `email` are dropped from the request before that check (RFC 6749 section 3.3 lets a server grant fewer scopes than requested), so a client that also reads the issuer's OpenID Connect discovery document still connects; a request with nothing else left gets the default `read`, and the three are never advertised. Any other value is `invalid_scope`. OpenID Connect discovery stays `openid`, `profile` and `email` and does not use this list. The OAuth server plugin publishes that list as `pact.MCPAdvertisedScopes`; pier copies `pact.MCPAdvertisedScopes.MCPScopesSupported` when it is non-empty. A route the MCP endpoint runs reads the caller with `pact.MCPCallFrom`.
- Authorization endpoint (`wristband.Server.Authorize`): the client and its exact registered redirect URI are validated before any redirect is sent (an unknown client gets a local plain-text 400, never an open redirect); then S256 PKCE, the client's scope ceiling and the RFC 8707 `resource` value are checked, a pending request is stored and the browser is sent to the application's consent page at `<issuer>/connect?request=<id>`, or at `wristband.Options.ConsentPath` on the issuer when that is set (an empty path keeps the PHP bytes). The accepted scopes are the same resolved list `wristband.Server.Metadata` advertises. A non-empty `wristband.Options.ScopesSupported` is used as given (`read`, `write`, `ai` and `offline_access` from `wristband.DefaultOptions`, which still refuses `backend`; a host that lists an extra scope accepts it). An empty or nil list on the MCP flavour resolves to `read`, `write`, `ai`, `offline_access` and `backend`. The OpenID Connect identity scopes `openid`, `profile` and `email` are dropped from the request before that check (RFC 6749 section 3.3 lets a server grant fewer scopes than requested), so a client that also reads the issuer's OpenID Connect discovery document still connects; a request with nothing else left gets the default `read` (or `wristband.Options.DefaultScopes`, filtered to the accepted list, when that leaves anything), and the three are never advertised. Any other value is `invalid_scope`. OpenID Connect discovery stays `openid`, `profile` and `email` and does not use this list. The OAuth server plugin publishes that list as `pact.MCPAdvertisedScopes`; pier copies `pact.MCPAdvertisedScopes.MCPScopesSupported` when it is non-empty. A route the MCP endpoint runs reads the caller with `pact.MCPCallFrom`.
- Consent operations for the application's own consent screen: `wristband.Server.PendingRequest` (what to show, including `wristband.PendingRequestView.OfflineAccess`, the pending row's flag; `offline_access` is not a scope on the view), `wristband.Server.IssueCode` (grant, returning the redirect URL with `code`, `iss` and `state`; the signature is unchanged) and `wristband.Server.DenyPending` (returning an `access_denied` redirect). Missing, foreign, used and expired requests all report the same `wristband.ErrPendingNotFound`.
- Token endpoint (`wristband.Server.Token`): code exchange with PKCE verification, then an access token minted by the application plus a rotating refresh token. Reusing a spent refresh token revokes its whole lineage and the linked access tokens. Expired codes and refresh tokens are swept on each call.
- Connected-app revocation: `wristband.Server.Revoke` kills an access token and the refresh lineage attached to it.
@@ -138,7 +138,7 @@ func providerRoutes(r pact.Router, srv *wristband.Server) {
| `wristband.Server.IssueCode` | Grants consent and returns the redirect URL carrying the code. |
| `wristband.Server.DenyPending` | Refuses consent and returns the `access_denied` redirect URL. |
| `wristband.Server.Revoke` | Revokes an access token and its refresh-token lineage. |
| `wristband.Options` | Issuer, advertised scopes and auth methods, registration limits, resource indicator and token lifetimes. |
| `wristband.Options` | Issuer, advertised scopes and auth methods, registration limits, resource indicator, token lifetimes, the authorize consent path and the default scopes. |
| `wristband.DefaultOptions` | Defaults for every option except `wristband.Options.Issuer`. |
| `wristband.Backend` | Runs a function inside one transaction with a `wristband.Tx`. |
| `wristband.Tx` | Transaction-scoped bundle of the stores and the token issuer. |
@@ -204,6 +204,8 @@ wristband reads no config keys or environment variables; the application passes
| `wristband.Options.CodeTTL` | 10 minutes |
| `wristband.Options.AccessTokenTTL` | 1 hour |
| `wristband.Options.RefreshTokenTTL` | 30 days |
| `wristband.Options.ConsentPath` | none (empty), which hands authorize off to `/connect` on the issuer, byte for byte as the PHP server; a set path (for example `/admin/connect`) replaces `/connect` on the same issuer |
| `wristband.Options.DefaultScopes` | none (empty), which keeps the PHP fallback `read` for a request that names no data scope; a set list is filtered to the accepted scopes and replaces `read` when anything is left |
Always set `wristband.Options.Issuer` and `wristband.Options.Resource` for your deployment. While `wristband.Options.Resource` is empty, an MCP authorization request that sends `resource` is refused with `invalid_target`.

View File

@@ -40,7 +40,8 @@ func (s *Server) allowedAuthorizeScopes() map[string]bool {
// middleware). It validates the client and exact redirect before any
// redirect response, enforces S256 PKCE syntax, the client's scope ceiling,
// and the RFC 8707 resource check, then persists an opaque pending request
// and redirects to the app's /connect handoff.
// and redirects to the app's consent handoff (Options.ConsentPath on
// Issuer, /connect by default).
//
// On an OIDC server it dispatches to the OIDC flavour before any MCP code
// runs: GET starts an authorization request, POST is the consent decision.
@@ -106,7 +107,8 @@ func (s *Server) Authorize(w http.ResponseWriter, r *http.Request) {
return
}
scopes, scopeErr := parseAuthorizeScopes(q.Get("scope"), s.allowedAuthorizeScopes())
allowed := s.allowedAuthorizeScopes()
scopes, scopeErr := parseAuthorizeScopes(q.Get("scope"), allowed, s.defaultAuthorizeScopes(allowed))
if scopeErr != "" {
s.authorizeErrorRedirect(w, redirectURI, "invalid_scope", scopeErr, state)
return
@@ -184,7 +186,7 @@ func (s *Server) Authorize(w http.ResponseWriter, r *http.Request) {
return
}
spa := s.opts.Issuer + "/connect?request=" + rfc3986Escape(requestID)
spa := s.opts.Issuer + s.consentPath() + "?request=" + rfc3986Escape(requestID)
// Laravel appends ", private" to every explicit Cache-Control this
// endpoint sets (session-cookie default merge); recorded PHP traffic is
// "no-store, private", never a bare "no-store" (D-04, live-recorded byte
@@ -193,6 +195,33 @@ func (s *Server) Authorize(w http.ResponseWriter, r *http.Request) {
writeRedirectHTML(w, http.StatusFound, spa)
}
// consentPath is the path the authorize handoff appends to Issuer:
// Options.ConsentPath, or the PHP "/connect" while it is empty.
func (s *Server) consentPath() string {
if s.opts.ConsentPath != "" {
return s.opts.ConsentPath
}
return "/connect"
}
// defaultAuthorizeScopes is the fallback of an authorize request that names
// no data scope: Options.DefaultScopes filtered to allowed, in their given
// order without repeats, or the PHP ["read"] when nothing remains.
func (s *Server) defaultAuthorizeScopes(allowed map[string]bool) []string {
out := make([]string, 0, len(s.opts.DefaultScopes))
for _, sc := range s.opts.DefaultScopes {
sc = strings.TrimSpace(sc)
if sc == "" || !allowed[sc] || mcpIgnoredIdentityScopes[sc] || stringSliceContains(out, sc) {
continue
}
out = append(out, sc)
}
if len(out) == 0 {
return []string{"read"}
}
return out
}
// writeAuthorizeLocalError writes the PHP localError() response: a bare
// text/plain 400 with no Location and no house envelope
// (T-08-OPEN-REDIRECT).
@@ -236,9 +265,11 @@ var mcpIgnoredIdentityScopes = map[string]bool{
// issues no ID tokens and never grants identity scopes (phase 19.4 D-07,
// narrowed from refusal to dropping), so the drop happens even when a host
// lists one of them in Options.ScopesSupported. An absent, empty or
// identity-only scope value falls back to ["read"]; any other token outside
// allowed, the server's set (allowedAuthorizeScopes), is refused.
func parseAuthorizeScopes(raw string, allowed map[string]bool) ([]string, string) {
// identity-only scope value falls back to fallback (the PHP ["read"] unless
// Options.DefaultScopes says otherwise, see defaultAuthorizeScopes); any
// other token outside allowed, the server's set (allowedAuthorizeScopes),
// is refused.
func parseAuthorizeScopes(raw string, allowed map[string]bool, fallback []string) ([]string, string) {
parts := strings.Fields(strings.TrimSpace(raw))
kept := make([]string, 0, len(parts))
for _, p := range parts {
@@ -247,7 +278,7 @@ func parseAuthorizeScopes(raw string, allowed map[string]bool) ([]string, string
}
}
if len(kept) == 0 {
return []string{"read"}, ""
return append([]string(nil), fallback...), ""
}
for _, p := range kept {
if !allowed[p] {

View File

@@ -0,0 +1,113 @@
package wristband
import (
"context"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
)
// TestConsentPathSmoke covers the configurable MCP authorize handoff: the
// default options hand a valid request off to {issuer}/connect?request=<id>
// exactly as the PHP server does, a ConsentPath replaces /connect on the
// same issuer, and DefaultScopes (filtered to the accepted set) is what a
// request naming no data scope gets instead of read.
func TestConsentPathSmoke(t *testing.T) {
const issuer = "https://issuer.example.test"
_, challenge := s256Pair(t)
newServer := func(mutate func(*Options)) (*Server, *memoryBackend) {
backend := newMemoryBackend()
opts := DefaultOptions()
opts.Issuer = issuer
opts.Resource = issuer + "/mcp"
if mutate != nil {
mutate(&opts)
}
srv := NewServer(opts)
srv.SetBackend(backend)
insertAuthorizeTestClient(backend, "cli", []string{authorizeTestRedirect}, nil)
return srv, backend
}
authorize := func(srv *Server, scope string) string {
params := map[string]string{
"client_id": "cli",
"redirect_uri": authorizeTestRedirect,
"response_type": "code",
"code_challenge": challenge,
"code_challenge_method": "S256",
}
if scope != "" {
params["scope"] = scope
}
rec := httptest.NewRecorder()
srv.Authorize(rec, authorizeRequest(params))
if rec.Code != http.StatusFound {
t.Fatalf("status = %d, want 302", rec.Code)
}
return rec.Header().Get("Location")
}
requestOf := func(t *testing.T, location, prefix string) string {
t.Helper()
if !strings.HasPrefix(location, prefix) {
t.Fatalf("Location = %q, want prefix %q", location, prefix)
}
id := strings.TrimPrefix(location, prefix)
if id == "" || strings.ContainsAny(id, "?&#/") {
t.Fatalf("Location = %q carries no plain request id", location)
}
return id
}
t.Run("default options hand off to /connect", func(t *testing.T) {
srv, _ := newServer(nil)
requestOf(t, authorize(srv, "read"), issuer+"/connect?request=")
})
t.Run("a consent path replaces /connect on the issuer", func(t *testing.T) {
srv, _ := newServer(func(o *Options) { o.ConsentPath = "/admin/connect" })
requestOf(t, authorize(srv, "read"), issuer+"/admin/connect?request=")
})
t.Run("default scopes fill a request without a data scope", func(t *testing.T) {
srv, _ := newServer(func(o *Options) {
o.ScopesSupported = append(o.ScopesSupported, "acme")
o.DefaultScopes = []string{"acme", "not-accepted"}
})
for _, scope := range []string{"", "openid profile"} {
id := requestOf(t, authorize(srv, scope), issuer+"/connect?request=")
view, err := srv.PendingRequest(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(view.ScopesRequested, []string{"acme"}) {
t.Fatalf("scope %q stored %v, want [acme]", scope, view.ScopesRequested)
}
}
})
t.Run("without default scopes the PHP read fallback stays", func(t *testing.T) {
srv, _ := newServer(nil)
id := requestOf(t, authorize(srv, ""), issuer+"/connect?request=")
view, err := srv.PendingRequest(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(view.ScopesRequested, []string{"read"}) {
t.Fatalf("stored %v, want [read]", view.ScopesRequested)
}
})
t.Run("default scopes outside the accepted set fall back to read", func(t *testing.T) {
srv, _ := newServer(func(o *Options) { o.DefaultScopes = []string{"acme"} })
id := requestOf(t, authorize(srv, ""), issuer+"/connect?request=")
view, err := srv.PendingRequest(context.Background(), id, 1)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(view.ScopesRequested, []string{"read"}) {
t.Fatalf("stored %v, want [read]", view.ScopesRequested)
}
})
}

View File

@@ -90,6 +90,21 @@ type Options struct {
// from issuance (PHP OAuthCodeManager::REFRESH_TTL_DAYS, D-03). PHP
// default: 30 days.
RefreshTokenTTL time.Duration
// ConsentPath is appended to Issuer for the MCP authorize handoff: the
// page the browser is sent to with ?request=<id> after a valid
// authorize request. Empty or unset means "/connect", the PHP handoff,
// so the redirect bytes stay identical to the PHP server. A host whose
// consent page lives elsewhere on the same origin (for example under
// the admin prefix) sets the path here. The OIDC flavour ignores it.
ConsentPath string
// DefaultScopes is what an MCP authorize request gets when it names no
// data scope (an absent, empty or identity-only scope value). Only the
// names the server accepts (ScopesSupported, resolved) are kept; empty
// or unset, or empty after that filter, means the PHP default ["read"].
// The OIDC flavour ignores it.
DefaultScopes []string
}
// DefaultOptions returns PHP-parity defaults for every metadata option