feat(19.7-01): streaming routes, MCP mount hook, configurable authorize scopes

- surf.Router.MountStream and recoverStream: a raw, unbuffered route kind
  whose http.Flusher reaches the client; panic after the first byte only
  aborts the body
- surf.MCPBuildTag and the mountPier hook: mcp.enabled is inert without the
  summercms_mcp tag until it is true, then boot fails naming the tag
  (pier_off.go is the untagged side)
- wristband parseAuthorizeScopes takes the server's allowed set built from
  Options.ScopesSupported; the default set is unchanged
- cooler.KeyPrefix exported for the MCP module's Redis keys
- smoke tests TestStreamingRouteSmoke, TestPierMountSmoke, TestMCPScopesSmoke
- surf, wristband and cooler READMEs, docs/services/{routing,oauth-server}.md
This commit is contained in:
Jakub Zych
2026-10-22 16:11:37 +02:00
parent 1bd91a4522
commit 5c15dea569
13 changed files with 506 additions and 12 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>`. Accepted scopes are `read`, `write`, `ai` and `offline_access`.
- 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 exactly `wristband.Options.ScopesSupported`, the values the metadata document advertises (`read`, `write`, `ai` and `offline_access` by default; an empty list keeps that default), so a host that lists an extra scope accepts it at authorize and any other value is `invalid_scope`.
- Consent operations for the application's own consent screen: `wristband.Server.PendingRequest` (what to show), `wristband.Server.IssueCode` (grant, returning the redirect URL with `code`, `iss` and `state`) 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.
@@ -187,7 +187,7 @@ wristband reads no config keys or environment variables; the application passes
| Field | Default |
|-------|---------|
| `wristband.Options.ServiceDocumentationPath` | `/help` |
| `wristband.Options.ScopesSupported` | `read`, `write`, `ai`, `offline_access` |
| `wristband.Options.ScopesSupported` | `read`, `write`, `ai`, `offline_access` (also the authorize allow-list; empty keeps this default) |
| `wristband.Options.TokenEndpointAuthMethodsSupported` | `none`, `client_secret_post`, `client_secret_basic` |
| `wristband.Options.AuthorizationResponseIssParameterSupported` | `true` |
| `wristband.Options.DCRClientCap` | `200` |

View File

@@ -18,11 +18,29 @@ import (
"strings"
)
// authorizeAllowedScopes mirrors PHP OAuthAuthorizeController::ALLOWED_SCOPES.
// authorizeAllowedScopes mirrors PHP OAuthAuthorizeController::ALLOWED_SCOPES:
// the allow-list of a server whose Options.ScopesSupported is empty.
var authorizeAllowedScopes = map[string]bool{
"read": true, "write": true, "ai": true, "offline_access": true,
}
// allowedAuthorizeScopes is the set parseAuthorizeScopes accepts on this
// server: exactly Options.ScopesSupported, the values the metadata document
// advertises, so a host that lists an extra scope (such as backend for the
// MCP module) accepts it at authorize; an empty list keeps the PHP default.
func (s *Server) allowedAuthorizeScopes() map[string]bool {
if s == nil || len(s.opts.ScopesSupported) == 0 {
return authorizeAllowedScopes
}
allowed := make(map[string]bool, len(s.opts.ScopesSupported))
for _, sc := range s.opts.ScopesSupported {
if sc = strings.TrimSpace(sc); sc != "" {
allowed[sc] = true
}
}
return allowed
}
// Authorize handles GET /oauth/mcp/authorize (D-09: raw route, no
// middleware). It validates the client and exact redirect before any
// redirect response, enforces S256 PKCE syntax, the client's scope ceiling,
@@ -93,7 +111,7 @@ func (s *Server) Authorize(w http.ResponseWriter, r *http.Request) {
return
}
scopes, scopeErr := parseAuthorizeScopes(q.Get("scope"))
scopes, scopeErr := parseAuthorizeScopes(q.Get("scope"), s.allowedAuthorizeScopes())
if scopeErr != "" {
s.authorizeErrorRedirect(w, redirectURI, "invalid_scope", scopeErr, state)
return
@@ -208,14 +226,15 @@ func (s *Server) authorizeErrorRedirect(w http.ResponseWriter, redirectURI, errC
// parseAuthorizeScopes ports OAuthAuthorizeController::parseScopes. An
// absent or empty scope query value defaults to ["read"]; otherwise every
// whitespace-separated token must be one of authorizeAllowedScopes.
func parseAuthorizeScopes(raw string) ([]string, string) {
// whitespace-separated token must be in allowed, the server's set
// (allowedAuthorizeScopes).
func parseAuthorizeScopes(raw string, allowed map[string]bool) ([]string, string) {
parts := strings.Fields(strings.TrimSpace(raw))
if len(parts) == 0 {
return []string{"read"}, ""
}
for _, p := range parts {
if !authorizeAllowedScopes[p] {
if !allowed[p] {
return nil, "scope contains an unsupported value"
}
}

View File

@@ -0,0 +1,78 @@
package wristband
import (
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"testing"
)
// TestMCPScopesSmoke covers the configurable authorize scope set of phase
// 19.7 (RESEARCH Pitfall 5, D-21 framework side): the allow-list is exactly
// Options.ScopesSupported, so a host that lists backend accepts it, while
// the default server keeps refusing it.
func TestMCPScopesSmoke(t *testing.T) {
backend := newMemoryBackend()
opts := DefaultOptions()
opts.Issuer = "https://issuer.example.test"
opts.Resource = "https://resource.example.test/mcp"
opts.ScopesSupported = append(opts.ScopesSupported, "backend")
srv := NewServer(opts)
srv.SetBackend(backend)
insertAuthorizeTestClient(backend, "cli-backend", []string{authorizeTestRedirect}, nil)
_, challenge := s256Pair(t)
authorize := func(s *Server, clientID string) map[string]string {
rec := httptest.NewRecorder()
s.Authorize(rec, authorizeRequest(map[string]string{
"client_id": clientID,
"redirect_uri": authorizeTestRedirect,
"response_type": "code",
"code_challenge": challenge,
"code_challenge_method": "S256",
"scope": "read backend",
}))
if rec.Code != http.StatusFound {
t.Fatalf("status = %d, want 302", rec.Code)
}
return queryOf(t, rec.Header().Get("Location"))
}
if q := authorize(srv, "cli-backend"); q["error"] != "" {
t.Fatalf("host listing backend refused it: %v", q)
}
backend.mu.Lock()
if n := len(backend.codes); n != 1 || !slices.Equal(backend.codes[0].Scopes, []string{"read", "backend"}) {
backend.mu.Unlock()
t.Fatalf("pending request scopes = %+v", backend.codes)
}
backend.mu.Unlock()
rec := httptest.NewRecorder()
srv.Metadata(rec, httptest.NewRequest(http.MethodGet, "/.well-known/oauth-authorization-server", nil))
var doc struct {
Scopes []string `json:"scopes_supported"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &doc); err != nil {
t.Fatal(err)
}
if !slices.Equal(doc.Scopes, []string{"read", "write", "ai", "offline_access", "backend"}) {
t.Fatalf("scopes_supported = %v", doc.Scopes)
}
// The default server (DefaultOptions scopes) still refuses backend.
plain, plainBackend := newAuthorizeTestServer()
insertAuthorizeTestClient(plainBackend, "cli-backend", []string{authorizeTestRedirect}, nil)
q := authorize(plain, "cli-backend")
if q["error"] != "invalid_scope" || q["error_description"] != "scope contains an unsupported value" {
t.Fatalf("default server accepted backend: %v", q)
}
// An empty ScopesSupported keeps the PHP default allow-list.
empty := DefaultOptions()
empty.Issuer, empty.Resource, empty.ScopesSupported = opts.Issuer, opts.Resource, nil
if got := NewServer(empty).allowedAuthorizeScopes(); !got["read"] || !got["offline_access"] || got["backend"] || len(got) != 4 {
t.Fatalf("allowed scopes with empty ScopesSupported = %v", got)
}
}