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

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