Files
pad/go.mod
T
xarmian 48776a3967 feat(oauth): DCR + authorize + token endpoints + populated discovery (TASK-1025, sub-PR C of TASK-951) (#372)
* feat(oauth): DCR + authorize + token endpoints + populated discovery doc (TASK-1025, sub-PR C of TASK-951)

Third of 5 sub-PRs landing the OAuth 2.1 authorization server in
PLAN-943. Mounts the three flow-driving HTTP endpoints over the
fosite-backed server constructed in sub-PR B, replaces the
TASK-950 501 stub with the real RFC 8414 discovery doc, and ships
an inline-HTML consent stub as a TASK-952 placeholder so the
auth-code flow runs end-to-end.

What lands:

- internal/server/handlers_oauth.go (744 LoC)
  - POST /oauth/register: RFC 7591 DCR. Hand-written, no fosite.
    Public clients only (token_endpoint_auth_method=none rejected
    for any other value), authorization_code + refresh_token
    grants only, code response type only. Validates redirect_uris
    (absolute, no fragment, https or loopback-http or custom-
    scheme like claude://, blocks file:/javascript:/data:/vbscript:).
  - GET /oauth/authorize: starts auth-code flow. fosite validates
    request shape (PKCE-S256 required, audience matched, redirect
    exact-match). If user has session → renders inline consent
    stub. If not → 302 to /login?redirect=<self> (TASK-998's
    plumbing in pad-cloud honors the redirect=).
  - POST /oauth/authorize/decide: processes consent decision.
    Form-bound CSRF token (the existing __Host-pad_csrf cookie,
    read from a hidden form field instead of header). Approve →
    fosite NewAuthorizeResponse → 303 to client.redirect_uri
    with code. Deny → fosite WriteAuthorizeError(access_denied).
  - POST /oauth/token: code + refresh exchange. fosite verifies
    PKCE verifier (S256-required) + RFC 8707 audience. Returns
    {access_token, token_type, expires_in, refresh_token, scope}.
    RefreshTokenScopes=[] from sub-PR B means refresh ALWAYS
    issues on authorize-code grant.
  - Inline consent stub: minimal HTML form with Approve/Deny,
    auto-grants every requested scope (TASK-952's UI replaces
    with workspace allow-list selection per TASK-953).

- internal/server/handlers_well_known.go: handleOAuthAuthorizationServerStub
  → handleOAuthAuthorizationServer. Returns RFC 8414 metadata
  with all six endpoint URLs (revoke + introspect URLs sub-PR D
  fills with handlers; the URLs are stable now), advertised
  scopes, S256-only code_challenge_methods,
  resource_indicators_supported=true, authorization_response_iss_parameter_supported=true.

- internal/server/server.go: Server.oauthServer field +
  SetOAuthServer + registerOAuthRoutes called from setupRouter
  inside an r.Group with requireCloudMode + SessionAuth (so
  /authorize can detect the logged-in user via __Host-pad_session;
  SessionAuth falls through gracefully when no cookie).

- cmd/pad/main.go: oauthpkg.NewServer wired in cloud mode using
  cfg.EncryptionKey as HMAC secret + cfg.MCPPublicURL+/mcp as
  AllowedAudience. Wiring is conditional on PAD_MCP_PUBLIC_URL
  being set (the OAuth surface needs a canonical audience to
  bind tokens to).

CSRF posture: middleware_csrf.go runs only on /api/* paths so
/oauth/* is naturally exempt. The consent decision endpoint
adds its own form-token check (validateConsentCSRFToken) using
the same __Host-pad_csrf cookie the SPA uses, just with the
token in a hidden form field rather than a header. Same security
model, different transport.

Tests (12, all passing):
- TestOAuth_AuthorizationServerMetadata_PopulatedShape: pins
  RFC 8414 metadata fields including S256-only PKCE +
  resource_indicators_supported.
- DCR (5): happy path; missing redirect_uris; bad redirect-URI
  shapes (relative, non-loopback http, fragment, javascript:);
  non-public client auth method rejected; unknown grant type
  rejected; not mounted outside cloud mode.
- /authorize (3): redirects to /login when no session;
  renders consent stub when logged in; rejects audience
  mismatch via fosite's audienceMatchingStrategy.
- /authorize/decide (2): rejects missing csrf_token; deny
  produces access_denied redirect.
- Full PKCE flow: end-to-end /authorize/decide (approve) →
  /token with code_verifier → 200 with access+refresh tokens.
- /token: rejects missing PKCE verifier.

Replaces the 501 stub assertion in TestMCP_AuthServerStub with
TestMCP_AuthServerMetadata_Mounted (just confirms 200; full
shape lives in the OAuth-handler test).

Out of scope:
- /oauth/revoke + /oauth/introspect (sub-PR D, TASK-1026)
- MCPBearerAuth OAuth introspection branch (sub-PR E, TASK-1027)
- Real consent UI with workspace allow-list (TASK-952)

* fix(oauth): translate RFC 8707 resource= to audience= + omit unmounted endpoints from discovery per Codex review (round 1)

Two findings from PR #372 round 1:

1. P1: Real RFC 8707 clients (Claude Desktop / Cursor / ChatGPT)
   send `resource=` not `audience=`. fosite v0.49 reads only
   `audience` from the form, so audienceMatchingStrategy was hit
   with an empty needle and rejected every real-world authorize /
   token request. Tests masked the gap by sending both keys.

   Fix: translateResourceToAudience() copies r.Form["resource"]
   into r.Form["audience"] before each handler invokes fosite.
   Idempotent — if both keys are present, audience wins (test
   harness sends both for belt-and-suspenders). Applied at
   /authorize, /authorize/decide, and /token entry points.

   Test TestOAuth_Authorize_AcceptsResourceOnly sends ONLY
   resource= (no audience=) and asserts the request reaches the
   consent stub. Without the translation it 303s with
   invalid_request.

2. P2: /.well-known/oauth-authorization-server advertised
   /oauth/revoke + /oauth/introspect endpoints that don't exist
   yet (sub-PR D wires them). Real clients dialing those URLs
   would get 404. RFC 8414 §2 lists revocation_endpoint +
   introspection_endpoint as OPTIONAL, so omitting until the
   handlers ship is spec-compliant + honest.

   Fix: drop revocation_endpoint, introspection_endpoint, and
   their *_endpoint_auth_methods_supported counterparts from
   authServerMetadata. Sub-PR D's PR description includes
   "populate these here" as a follow-up.

   Test TestOAuth_AuthorizationServerMetadata_OmitsUnimplementedEndpoints
   asserts the four fields are absent.

* fix(oauth): rate-limit /oauth/register + drop misleading iss flag per Codex review (round 2)

Two findings from PR #372 round 2:

1. P1: /oauth/register is open by RFC 7591 design (Claude Desktop /
   Cursor self-register without prior auth) but had no rate limit.
   An attacker could flood the oauth_clients table indefinitely.

   Fix: extend RateLimit middleware to gate /oauth/register at
   the same 5/hour/IP rate the existing /api/v1/auth/register
   uses (RateLimiters.Register, burst 5). Added the OAuth route
   group to the s.RateLimit middleware chain so the new path
   actually runs through the limiter.

   Other /oauth/* endpoints aren't rate-limited here: /authorize
   rides session cookies (cheap to abuse but ineffective without
   a logged-in user), /token is PKCE-bound to a stored code
   (single-use), /authorize/decide is form-bound. Explicit per-
   endpoint /oauth/* limits arrive with TASK-959.

   Test TestOAuth_Register_RateLimited fires 5 requests
   successfully, asserts the 6th returns 429.

2. P2: Discovery doc advertised
   authorization_response_iss_parameter_supported=true, but the
   /authorize success path delegates to fosite v0.49 which doesn't
   add iss=<issuer> to the redirect. RFC 9207-aware clients seeing
   the flag would treat the missing parameter as a protocol
   violation.

   Fix: drop the field from authServerMetadata. RFC 8414 §2
   marks it OPTIONAL — omission is spec-compliant. We'll add
   the parameter (+ post-processing of fosite's response) in a
   future PR if a real client requires it; today's MCP clients
   (Claude Desktop, Cursor, ChatGPT) don't.

   Test TestOAuth_AuthorizationServerMetadata_OmitsUnimplementedEndpoints
   extended to cover the field.

* fix(oauth): gate auth-server discovery doc on oauthServer != nil per Codex review (round 3)

Codex round 3 caught: /.well-known/oauth-authorization-server lives
in the MCP route group (registerMCPRoutes), while the /oauth/{
register,authorize,token} handlers live in the OAuth route group
(registerOAuthRoutes, gated on s.oauthServer != nil). A cloud
deployment with PAD_MCP_PUBLIC_URL unset gets MCP routes mounted
but NOT OAuth — the discovery doc would 200 with /oauth/* URLs
that 404. Worse for clients than no document at all.

Fix: handleOAuthAuthorizationServer now also nil-checks
s.oauthServer; on nil it returns 503 with config_error, matching
the existing fail-loud branch for when the issuer URL isn't
configured. Ops detect the misconfiguration immediately rather
than fielding "OAuth registration is failing with 404" tickets.

Test:
- TestOAuth_AuthorizationServerMetadata_503WhenOAuthDisabled
  builds a Server with SetCloudMode + SetMCPTransport (so the
  MCP route group mounts) but NOT SetOAuthServer; asserts the
  endpoint returns 503 with config_error.
- TestMCP_AuthServerMetadata_Mounted renamed →
  TestMCP_AuthServerMetadata_MountedAndGated to reflect the new
  behavior under mcpEnabledTestServer (which doesn't wire OAuth).
  The full 200 happy path lives in
  TestOAuth_AuthorizationServerMetadata_PopulatedShape (uses
  oauthEnabledTestServer).

* fix(oauth): apply gofmt to handlers_oauth_test + handlers_well_known

* fix(oauth): bump go-jose/v3 to v3.0.4 to resolve GO-2025-3485

CI govulncheck rejected the build: fosite v0.49.0 transitively
pulls github.com/go-jose/go-jose/v3@v3.0.3 which has
GO-2025-3485 (DoS in JWS parsing). Affected call site:
internal/server/handlers_oauth.go:408 — handleOAuthAuthorize calls
fosite.NewAuthorizeRequest which eventually calls jose.ParseSigned.

Fix: bump go-jose/v3 to v3.0.4 (the fixed version per the advisory).
go mod tidy auto-bumped dependent indirect deps too.

Verified locally:
  govulncheck ./... → "No vulnerabilities found"
  go test ./...     → all green
  go build ./...    → clean
2026-05-02 11:56:57 -04:00

125 lines
5.7 KiB
Modula-2

module github.com/PerpetualSoftware/pad
go 1.26.0
require (
github.com/BurntSushi/toml v1.6.0
github.com/disintegration/imaging v1.6.2
github.com/fatih/color v1.19.0
github.com/go-chi/chi/v5 v5.2.5
github.com/go-chi/cors v1.2.2
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.9.1
github.com/mark3labs/mcp-go v0.50.0
github.com/ory/fosite v0.49.0
github.com/pquerna/otp v1.5.0
github.com/prometheus/client_golang v1.23.2
github.com/prometheus/client_model v0.6.2
github.com/redis/go-redis/v9 v9.18.0
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
github.com/sergi/go-diff v1.4.0
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.0.9
github.com/trustelem/zxcvbn v1.0.1
golang.org/x/crypto v0.49.0
golang.org/x/image v0.39.0
golang.org/x/term v0.41.0
golang.org/x/text v0.36.0
golang.org/x/time v0.15.0
modernc.org/sqlite v1.47.0
)
require (
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cristalhq/jwt/v4 v4.0.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgraph-io/ristretto v1.0.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dlclark/regexp2 v1.12.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-jose/go-jose/v3 v3.0.4 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/gobuffalo/pop/v6 v6.1.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.1 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.7 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/goveralls v0.0.12 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/openzipkin/zipkin-go v0.4.2 // indirect
github.com/ory/go-acc v0.2.9-0.20230103102148-6b1c9a70dbbe // indirect
github.com/ory/go-convenience v0.1.0 // indirect
github.com/ory/x v0.0.665 // indirect
github.com/pelletier/go-toml/v2 v2.0.9 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/seatgeek/logrus-gelf-formatter v0.0.0-20210414080842-5b05eb8ff761 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.7.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/viper v1.16.0 // indirect
github.com/stretchr/testify v1.11.1 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
github.com/test-go/testify v1.1.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.46.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 // indirect
go.opentelemetry.io/contrib/propagators/b3 v1.21.0 // indirect
go.opentelemetry.io/contrib/propagators/jaeger v1.21.1 // indirect
go.opentelemetry.io/contrib/samplers/jaegerremote v0.15.1 // indirect
go.opentelemetry.io/otel v1.40.0 // indirect
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.21.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.21.0 // indirect
go.opentelemetry.io/otel/exporters/zipkin v1.21.0 // indirect
go.opentelemetry.io/otel/metric v1.40.0 // indirect
go.opentelemetry.io/otel/sdk v1.40.0 // indirect
go.opentelemetry.io/otel/trace v1.40.0 // indirect
go.opentelemetry.io/proto/otlp v1.0.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/mod v0.34.0 // indirect
golang.org/x/net v0.52.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/tools v0.43.0 // indirect
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20231106174013-bbf56f31fb17 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231106174013-bbf56f31fb17 // indirect
google.golang.org/grpc v1.59.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.70.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)