Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 35 additions & 15 deletions cmd/thv/app/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/stacklok/toolhive/pkg/networking"
"github.com/stacklok/toolhive/pkg/transport"
"github.com/stacklok/toolhive/pkg/transport/middleware"
"github.com/stacklok/toolhive/pkg/transport/middleware/cors"
"github.com/stacklok/toolhive/pkg/transport/middleware/origin"
"github.com/stacklok/toolhive/pkg/transport/proxy/transparent"
"github.com/stacklok/toolhive/pkg/transport/types"
Expand Down Expand Up @@ -247,21 +248,10 @@ func proxyCmdFunc(cmd *cobra.Command, args []string) error {
Function: bodylimit.Middleware(proxyMaxRequestBodySize),
})

// Origin-header validation (DNS-rebinding protection per MCP 2025-11-25
// §"Security Warning"). Added after body-limit so disallowed Origins are
// rejected before authentication or any outbound token acquisition runs.
if allowed := origin.ResolveAllowedOrigins(proxyHost, port, proxyAllowedOrigins); len(allowed) > 0 {
middlewares = append(middlewares, types.NamedMiddleware{
Name: origin.MiddlewareType,
Function: origin.NewHandler(allowed),
})
} else {
slog.Warn("Origin validation disabled — no allowlist configured for non-loopback bind",
"host", proxyHost,
"port", port,
"hint", "pass --allowed-origins=https://your-client.example to enable DNS-rebind protection",
)
}
// Opt-in CORS (derived from --allowed-origins) and Origin-header validation
// (DNS-rebinding protection per MCP 2025-11-25 §"Security Warning"). Added
// after body-limit; CORS is ordered before Origin validation so it wraps it.
middlewares = appendOriginMiddlewares(middlewares, proxyHost, port, proxyAllowedOrigins)

// Get OIDC configuration if enabled (for protecting the proxy endpoint)
oidcConfig := getProxyOIDCConfig(cmd)
Expand Down Expand Up @@ -489,6 +479,36 @@ func createTokenInjectionMiddleware(tokenSource oauth2.TokenSource) types.Middle
return middleware.CreateTokenInjectionMiddleware(tokenSource)
}

// appendOriginMiddlewares appends the opt-in CORS handler followed by the
// Origin-validation handler, both derived from the same effective allowlist
// (origin.ResolveAllowedOrigins). CORS is appended first so it wraps Origin
// validation (runs first at request time): a genuine browser preflight carrying
// an allowed Origin is answered by CORS before the validator would reject the
// OPTIONS request with 403. When the allowlist is empty both are skipped and a
// WARN is logged, since Origin validation (and therefore CORS) is disabled.
func appendOriginMiddlewares(
middlewares []types.NamedMiddleware, host string, port int, explicit []string,
) []types.NamedMiddleware {
allowed := origin.ResolveAllowedOrigins(host, port, explicit)
if len(allowed) == 0 {
slog.Warn("Origin validation disabled — no allowlist configured for non-loopback bind",
"host", host,
"port", port,
"hint", "pass --allowed-origins=https://your-client.example to enable DNS-rebind protection",
)
return middlewares
}
middlewares = append(middlewares, types.NamedMiddleware{
Name: cors.MiddlewareType,
Function: cors.NewHandler(allowed),
})
middlewares = append(middlewares, types.NamedMiddleware{
Name: origin.MiddlewareType,
Function: origin.NewHandler(allowed),
})
return middlewares
}

// addExternalTokenMiddleware adds token exchange or token injection middleware to the middleware chain
func addExternalTokenMiddleware(middlewares *[]types.NamedMiddleware, tokenSource oauth2.TokenSource) error {
if remoteAuthFlags.TokenExchangeURL != "" {
Expand Down
50 changes: 49 additions & 1 deletion docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,54 @@ Like the tool filter, the middleware forwards a request whose response it reads

**Placement**: Inside the MCP Parser, whose parse names the `initialize` and `server/discover` requests, so the middleware outside it, such as audit and the tool filter, sees the rewritten result. Behind the stdio streamable HTTP proxy, a later handshake is answered from the cached InitializeResult. The cache holds the backend's own result and the middleware rewrites each response, so every client receives the configured text once.

### 14. Origin Validation and CORS Middleware

**Purpose**: Protect the MCP proxy endpoint against DNS-rebinding attacks (Origin validation, per MCP 2025-11-25 §"Security Warning") and let browser-based MCP clients (e.g. the MCP Inspector) reach it (CORS).

**Location**: `pkg/transport/middleware/origin` and `pkg/transport/middleware/cors`

**Availability**: `thv run` (all transports, including the stdio streamable-HTTP proxy) and `thv proxy`. Both are wired centrally — `thv run` via `prependOriginMiddleware`/`prependCorsMiddleware` in `pkg/runner`, `thv proxy` via `appendOriginMiddlewares` in `cmd/thv/app/proxy.go`.

**The shared allowlist**: Both middlewares derive from the same effective allowlist, resolved once by `origin.ResolveAllowedOrigins(host, port, --allowed-origins)`:

- An explicit `--allowed-origins` list is used verbatim.
- Otherwise, for a loopback bind (`localhost`/`127.0.0.1`/`::1`), the allowlist defaults to the proxy's own origin only (`http://localhost:PORT`, `http://127.0.0.1:PORT`, `http://[::1]:PORT`).
- Otherwise (a non-loopback bind with no explicit list) the allowlist is empty and both middlewares are disabled, logged at WARN.

Because CORS reads the same list, it can never grant an origin that Origin validation would reject — CORS is a strict subset. There is no separate CORS flag.

**Origin validation**: When a request carries an `Origin` header not in the allowlist, it is rejected with `403` and a JSON-RPC error. Requests without an `Origin` header (non-browser clients) pass through.

**CORS**: Placed just outside Origin validation so it runs first.

- A **genuine preflight** — `OPTIONS` carrying `Access-Control-Request-Method` — from an **allowed** origin is answered directly with `204` and the CORS headers below; it never reaches Origin validation. (Previously these returned `405 Method Not Allowed`, the bug in #4297.)
- A preflight from a **disallowed** origin, a bare `OPTIONS`, and every non-preflight request pass through unchanged. A preflight from a disallowed origin therefore still reaches Origin validation and gets `403`.
- For a non-preflight request from an allowed origin, the response is decorated with `Access-Control-Allow-Origin`, `Access-Control-Allow-Credentials`, `Access-Control-Expose-Headers` and `Vary: Origin`. These are set only if an upstream handler or reverse-proxied backend has not already set `Access-Control-Allow-Origin`, so an upstream CORS policy is preserved rather than double-set.

Preflight response headers:

| Header | Value |
|--------|-------|
| `Access-Control-Allow-Origin` | the (allowed) request `Origin` |
| `Access-Control-Allow-Methods` | `GET, POST, DELETE, OPTIONS` |
| `Access-Control-Allow-Headers` | `Content-Type, Authorization, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID` |
| `Access-Control-Expose-Headers` | `Mcp-Session-Id, Mcp-Protocol-Version, WWW-Authenticate` |
| `Access-Control-Allow-Credentials` | `true` |
| `Access-Control-Max-Age` | `86400` |
| `Vary` | `Origin` |

`WWW-Authenticate` is exposed so a browser client can read the OAuth challenge on a `401` and begin the auth flow.

**CLI Usage**:

```bash
# Allow the MCP Inspector (served on :6274) to reach a proxy on loopback.
# The loopback default only covers the proxy's own origin, so the browser
# origin must be named explicitly.
thv run --allowed-origins http://localhost:6274 my-server
thv proxy my-server --target-uri http://localhost:9000 --allowed-origins http://localhost:6274
```

## Data Flow Through Context

The middleware chain uses Go's `context.Context` to pass data between components:
Expand Down Expand Up @@ -1378,7 +1426,7 @@ The middleware chain execution order is critical and controlled by the order in
- Header Forward executes close to the backend handler (innermost position)
- OBO comes after Header Forward and before Recovery, so it has the final say on the outbound `Authorization` header; it needs the identity the Authentication Middleware publishes, which is why the operator requires `oidcConfigRef` alongside an `obo` config
- Recovery is always last in config, making it the innermost wrapper (the chain wraps in reverse config order, so the first entry is the outermost and runs first)
- Body-size limit and Origin validation stay OUTSIDE audit: oversized bodies must be rejected before audit buffers request data, and origin validation is a pre-auth DNS-rebind guard. The transparent proxy's `Connection` header check (see [Client `Connection` header](#client-connection-header)) runs before all of them. Their rejections (400/413/403) are the only ones not audited.
- Body-size limit, CORS, and Origin validation stay OUTSIDE audit: oversized bodies must be rejected before audit buffers request data, and origin validation is a pre-auth DNS-rebind guard. CORS is ordered just outside Origin validation (body-size limit remains outermost) so a genuine browser preflight from an allowed origin is answered before the Origin guard would reject the `OPTIONS` request; a `204` preflight it answers and the Origin guard's `403` are not audited. The transparent proxy's `Connection` header check (see [Client `Connection` header](#client-connection-header)) runs before all of them. Their rejections (204/400/413/403) are the only ones not audited.
- The list above (steps 1-17) describes the operator/proxyrunner path (`PopulateMiddlewareConfigs` in `pkg/runner/middleware.go`). The CLI flag path (`WithMiddlewareFromFlags` in `pkg/runner/config_builder.go`) has no rate limiting at all, and orders Usage Metrics before the webhooks rather than after (see the comment in `WithMiddlewareFromFlags`) — both paths still run Mutating before Validating webhooks and both before Authorization.

### Client `Connection` header
Expand Down
31 changes: 31 additions & 0 deletions pkg/runner/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/stacklok/toolhive/pkg/recovery"
"github.com/stacklok/toolhive/pkg/telemetry"
headerfwd "github.com/stacklok/toolhive/pkg/transport/middleware"
"github.com/stacklok/toolhive/pkg/transport/middleware/cors"
"github.com/stacklok/toolhive/pkg/transport/middleware/origin"
"github.com/stacklok/toolhive/pkg/transport/types"
"github.com/stacklok/toolhive/pkg/usagemetrics"
Expand Down Expand Up @@ -57,6 +58,7 @@ func GetSupportedMiddlewareFactories() map[string]types.MiddlewareFactory {
headerfwd.HeaderForwardMiddlewareName: headerfwd.CreateMiddleware,
headerfwd.StripAuthMiddlewareName: headerfwd.CreateStripAuthMiddleware,
origin.MiddlewareType: origin.CreateMiddleware,
cors.MiddlewareType: cors.CreateMiddleware,
validating.MiddlewareType: validating.CreateMiddleware,
mutating.MiddlewareType: mutating.CreateMiddleware,
}
Expand Down Expand Up @@ -887,6 +889,35 @@ func prependOriginMiddleware(middlewares []types.MiddlewareConfig, config *RunCo
return append([]types.MiddlewareConfig{*mwCfg}, middlewares...), nil
}

// prependCorsMiddleware prepends opt-in CORS handling for the MCP proxy
// endpoint, derived from the same effective allowlist as Origin validation
// (origin.ResolveAllowedOrigins). It is called from runner.Run immediately
// after prependOriginMiddleware so CORS sits just OUTSIDE the origin validator
// in the final chain (body-limit is prepended afterwards and remains
// outermost): a genuine browser preflight carrying an allowed Origin is
// answered here before the validator would reject the OPTIONS with 403, while
// every other request falls through to the validator unchanged.
//
// When the effective allowlist is empty the middleware is skipped entirely —
// CORS stays off, which is the correct default when no browser origin is
// trusted. No warning is logged here because prependOriginMiddleware already
// logs the empty-allowlist case for the same inputs.
func prependCorsMiddleware(middlewares []types.MiddlewareConfig, config *RunConfig) ([]types.MiddlewareConfig, error) {
allowed := origin.ResolveAllowedOrigins(config.Host, config.Port, config.AllowedOrigins)
if len(allowed) == 0 {
return middlewares, nil
}

params := cors.MiddlewareParams{AllowedOrigins: allowed}
mwCfg, err := types.NewMiddlewareConfig(cors.MiddlewareType, params)
if err != nil {
return nil, fmt.Errorf("failed to create cors middleware config: %w", err)
}
// Prepend so CORS wraps the origin validator (runs first at request time).
// Build a new slice to avoid mutating the caller's backing array.
return append([]types.MiddlewareConfig{*mwCfg}, middlewares...), nil
}

// addRateLimitMiddleware adds rate limit middleware if configured.
func addRateLimitMiddleware(middlewares []types.MiddlewareConfig, config *RunConfig) ([]types.MiddlewareConfig, error) {
if config.RateLimitConfig == nil {
Expand Down
11 changes: 11 additions & 0 deletions pkg/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,17 @@ func (r *Runner) Run(ctx context.Context) error {
return fmt.Errorf("failed to add origin middleware: %w", err)
}

// Opt-in CORS for the MCP proxy endpoint, derived from the same
// --allowed-origins allowlist as Origin validation. Prepended after the
// origin middleware so it wraps it (runs first at request time) and can
// answer a genuine browser preflight before Origin validation would reject
// the OPTIONS request. Body-limit is still prepended below and stays
// outermost.
r.Config.MiddlewareConfigs, err = prependCorsMiddleware(r.Config.MiddlewareConfigs, r.Config)
if err != nil {
return fmt.Errorf("failed to add cors middleware: %w", err)
}

// Body-size limit is always the outermost middleware, regardless of how the
// chain was assembled (PopulateMiddlewareConfigs above, or WithMiddlewareFromFlags
// which pre-populates the slice and takes the else branch). Existing body-limit
Expand Down
Loading