Skip to content
Merged
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
1 change: 1 addition & 0 deletions docs/configuration/config-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ MCPProxy uses a JSON configuration file located at `~/.mcpproxy/mcp_config.json`
| `trusted_proxies` | string[] | `[]` (trust nobody) | CIDRs or IP addresses whose `X-Forwarded-For`, `X-Real-IP`, `X-Forwarded-Proto` and `X-Forwarded-Host` headers are believed. Headers from any other peer are ignored and the direct `RemoteAddr` is used. Env `MCPPROXY_TRUSTED_PROXIES` (comma list). Live (hot-reload, no restart). Validation: `trusted_proxies[N] "value" is not a valid CIDR or IP address` — refused identically at boot, `PATCH /api/v1/config` and `/config/apply`. See [Reverse Proxy Deployment](/operations/reverse-proxy#trusted_proxies-forwarded-headers) |
| `require_mcp_auth` | boolean | `false` | Require an API key on the `/mcp` endpoint (off by default for client compatibility). Enable when exposing MCPProxy beyond localhost. **Server edition:** forced to `true` whenever `server_edition.enabled` is `true` — an explicit `false` is not an error, but boot logs `require_mcp_auth: false is overridden to true because server_edition.enabled is true` and `mcpproxy doctor` reports the same finding |
| `mcp_reject_query_apikey` | boolean | `false` | Refuse a `?apikey=` query parameter on every MCP endpoint (`/mcp*` and the legacy `/v1/tool_code` aliases) with a 401, forcing clients onto `Authorization: Bearer <token>` or `X-API-Key` so tokens stop appearing in access logs, proxy logs and browser history (a URL already sent is still logged in transit; the option makes the client fail until it is migrated). MCP endpoints only: the REST API, the Web UI and `/events` keep accepting the query form. Entries written by an older Connect wizard with `?apikey=` in the URL (Codex, the generic fallback) must be reconnected first; current versions write an `X-API-Key` header. Live, no restart |
| `mcp_oauth_enabled` | boolean | `false` | Experimental. Opt-in browser login (OAuth 2.1 + PKCE) for MCP clients, served only to loopback peers and loopback `Host` values, personal edition only. With it off nothing changes: no new route behaves differently and nothing is stored. Env `MCPPROXY_MCP_OAUTH_ENABLED=true\|false` overrides it for the process (never persisted). Live, no restart. **Not functional yet in this release:** the endpoints (`/mcp/oauth`, `/oauth/register`, `/oauth/authorize`, `/oauth/token` and the two `/.well-known/oauth-*` documents) answer `501 Not Implemented` when enabled |
| `enable_socket` | boolean | `true` | Enable the Unix socket/named pipe the tray uses. Socket connections are trusted **without the API key**, including stdio servers spawned under `none` or `sandbox` isolation, which can then mint agent tokens. Set `false` on headless installs and whenever untrusted stdio servers run outside `docker` isolation. |
| `forward_client_headers` | boolean | `true` | Master switch for [client header forwarding](/configuration/upstream-servers#client-header-forwarding). Nothing is forwarded until a server lists names in `forward_headers`. Env `MCPPROXY_FORWARD_CLIENT_HEADERS=false` disables it for the process (never persisted). |

Expand Down
10 changes: 10 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,11 @@ type Config struct {
// MCP endpoints: the Web UI and its SSE stream (/events) still use the
// query form. Live, no restart needed.
MCPRejectQueryAPIKey bool `json:"mcp_reject_query_apikey,omitempty" mapstructure:"mcp-reject-query-apikey"`
// MCPOAuthEnabled turns on browser login (OAuth 2.1 + PKCE) for MCP
// clients on the loopback listener (Spec 132). Experimental, default false:
// with it off nothing changes. Env override MCPPROXY_MCP_OAUTH_ENABLED is
// process-only and never persisted. Live, no restart needed.
MCPOAuthEnabled bool `json:"mcp_oauth_enabled,omitempty" mapstructure:"mcp-oauth-enabled"`
// TrustedHosts lists non-loopback Host header values accepted on loopback
// listeners (GH #898). DNS-rebinding protection rejects requests whose Host
// header is not a loopback address when mcpproxy listens on loopback; a
Expand Down Expand Up @@ -2775,6 +2780,11 @@ func NormalizeForwardHeaders(cfg *Config) []ForwardHeaderNormalization {
return out
}

// EnvMCPOAuthEnabled is the process-only environment override for
// Config.MCPOAuthEnabled (Spec 132). Accepts true|1 / false|0; anything else
// is ignored. Never persisted.
const EnvMCPOAuthEnabled = "MCPPROXY_MCP_OAUTH_ENABLED"

// EnvForwardClientHeaders is the environment kill switch for client header
// forwarding (Spec 112 FR-003): false|0|off disables it for the process.
const EnvForwardClientHeaders = "MCPPROXY_FORWARD_CLIENT_HEADERS"
Expand Down
16 changes: 16 additions & 0 deletions internal/config/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,20 @@ func applyTLSEnvOverrides(cfg *Config) {
}
envOverride(b, cfg, FieldForwardClientHeaders, fwd != nil, fwd)

// Spec 132: MCPPROXY_MCP_OAUTH_ENABLED switches browser login on or off for
// this process. Only the documented vocabulary overrides; a typo leaves the
// file value.
var mcpOAuth *bool
switch strings.ToLower(strings.TrimSpace(os.Getenv(EnvMCPOAuthEnabled))) {
case trueValue, "1":
on := true
mcpOAuth = &on
case falseValue, "0":
off := false
mcpOAuth = &off
}
envOverride(b, cfg, FieldMCPOAuthEnabled, mcpOAuth != nil, derefBool(mcpOAuth))

// Override trusted hosts for reverse-proxy deployments (GH #898).
// Comma-separated list of Host header values accepted on loopback listeners.
var hosts []string
Expand Down Expand Up @@ -1109,3 +1123,5 @@ func envNonNegativeDuration(name, want string) (bool, *Duration) {
dur := Duration(d)
return true, &dur
}

func derefBool(p *bool) bool { return p != nil && *p }
50 changes: 50 additions & 0 deletions internal/config/mcp_oauth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package config

import (
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// Spec 132: the opt-in browser login switch is off by default, never written
// to disk while off, and its env override is process-only.
func TestConfig_MCPOAuthEnabled_DefaultOffAndOmitted(t *testing.T) {
t.Cleanup(ResetProcessOverrides)
ResetProcessOverrides()
t.Setenv(EnvMCPOAuthEnabled, "")

assert.False(t, DefaultConfig().MCPOAuthEnabled)

dir := t.TempDir()
path := filepath.Join(dir, "mcp_config.json")
require.NoError(t, SaveConfig(DefaultConfig(), path))
raw, err := os.ReadFile(path)
require.NoError(t, err)
assert.NotContains(t, string(raw), "mcp_oauth_enabled")

// Env override turns it on for this process only.
t.Setenv(EnvMCPOAuthEnabled, "true")
cfg, err := LoadFromFile(path)
require.NoError(t, err)
assert.True(t, cfg.MCPOAuthEnabled, "env overrides the file value")

require.NoError(t, SaveConfig(cfg, path))
raw, err = os.ReadFile(path)
require.NoError(t, err)
assert.NotContains(t, string(raw), "mcp_oauth_enabled", "the env override is not persisted")

// A file value of true is honoured and persisted.
t.Setenv(EnvMCPOAuthEnabled, "")
ResetProcessOverrides()
cfg, err = LoadFromFile(path)
require.NoError(t, err)
assert.False(t, cfg.MCPOAuthEnabled)
cfg.MCPOAuthEnabled = true
require.NoError(t, SaveConfig(cfg, path))
raw, err = os.ReadFile(path)
require.NoError(t, err)
assert.Contains(t, string(raw), `"mcp_oauth_enabled": true`)
}
1 change: 1 addition & 0 deletions internal/config/process_overrides.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ var (
FieldHTTPReadTimeout = scalar("http_read_timeout", func(c *Config) **Duration { return &c.HTTPReadTimeout })
FieldHTTPWriteTimeout = scalar("http_write_timeout", func(c *Config) **Duration { return &c.HTTPWriteTimeout })
FieldHTTPIdleTimeout = scalar("http_idle_timeout", func(c *Config) **Duration { return &c.HTTPIdleTimeout })
FieldMCPOAuthEnabled = scalar("mcp_oauth_enabled", func(c *Config) *bool { return &c.MCPOAuthEnabled })
FieldForwardClientHeaders = scalar("forward_client_headers", func(c *Config) **bool { return &c.ForwardClientHeaders })

FieldLogLevel = Field[string]{
Expand Down
7 changes: 7 additions & 0 deletions internal/mcplogin/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Package mcplogin holds the pure protocol logic for opt-in browser login
// (OAuth 2.1 + PKCE) of MCP clients against the local mcpproxy (Spec 132).
//
// Scope: protocol rules only. No HTTP wiring, no storage and no new external
// dependencies. From this repository it may import only internal/auth,
// internal/clientidentity and internal/upstream/limiter.
package mcplogin
2 changes: 1 addition & 1 deletion internal/runtime/config_hotreload.go
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ func (r *ConfigApplyResult) FormatChangedFields() string {
// adopted into the live config, and reported by its JSON key.
var undiffedHotConfigFields = []string{
"EnableTray", "TopK", "MaxResultSizeChars", "InitTimeout", "ForwardProxyEnv",
"RequireMCPAuth", "MCPRejectQueryAPIKey", "CheckServerRepo", "DockerRecovery",
"RequireMCPAuth", "MCPRejectQueryAPIKey", "MCPOAuthEnabled", "CheckServerRepo", "DockerRecovery",
"RegistriesLocked", "AllowPrivateRegistryFetch", "Features",
"ToolResponseSessionRiskWarning", "OAuthExpiryWarningHours",
"ActivityRetentionDays", "ActivityMaxRecords", "ActivityMaxSizeMB",
Expand Down
198 changes: 198 additions & 0 deletions internal/server/oauth_login_default_off_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package server

import (
"fmt"
"net/http"
"net/http/httptest"
"sort"
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.etcd.io/bbolt"
"go.uber.org/zap"

"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/storage"
)

const oauthLoginTestAPIKey = "test-api-key-oauth-login"

func newOAuthLoginTestServer(t *testing.T, mutate func(*config.Config)) *Server {
t.Helper()
cfg := config.DefaultConfig()
cfg.DataDir = t.TempDir()
cfg.Listen = "127.0.0.1:0"
cfg.APIKey = oauthLoginTestAPIKey
if mutate != nil {
mutate(cfg)
}
srv, err := NewServer(cfg, zap.NewNop())
require.NoError(t, err)
t.Cleanup(func() { _ = srv.Shutdown() })
return srv
}

// oauthLoginTestMuxes builds the mux as startCustomHTTPServer shapes it around
// the browser-login routes: the /mcp catch-all chain (real host validation and
// MCP auth middleware around a sentinel) and the real root handler. withRoutes
// adds the Spec 132 registrations.
func oauthLoginTestMux(s *Server, withRoutes bool) *http.ServeMux {
sentinel := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, "mcp-chain %s %s", r.Method, r.URL.Path)
})
mcpHandler := s.hostValidationMiddleware(s.mcpAuthMiddleware(sentinel))
rootHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/ui/", http.StatusFound)
return
}
http.NotFound(w, r)
})
mux := http.NewServeMux()
mux.Handle("/mcp", mcpHandler)
mux.Handle("/mcp/", mcpHandler)
mux.Handle("/", rootHandler)
if withRoutes {
s.registerOAuthLoginRoutes(mux, mcpHandler, rootHandler)
}
return mux
}

var oauthLoginTestPaths = []string{
"/mcp/oauth", "/mcp/oauth/", "/mcp/oauth/cursor",
"/oauth", "/oauth/", "/oauth/x",
"/oauth/register", "/oauth/authorize", "/oauth/token",
"/.well-known/oauth-authorization-server",
"/.well-known/oauth-protected-resource",
"/.well-known/oauth-protected-resource/mcp/oauth",
"/.well-known/oauth-protected-resource/mcp/oauth/cursor",
"/.well-known/x",
}

type oauthLoginResp struct {
code int
body string
location string
wwwAuthenticate string
}

func doOAuthLoginReq(mux http.Handler, method, path, remote string, hdr map[string]string) oauthLoginResp {
req := httptest.NewRequest(method, path, http.NoBody)
req.RemoteAddr = remote
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
return oauthLoginResp{
code: rec.Code,
body: rec.Body.String(),
location: rec.Header().Get("Location"),
wwwAuthenticate: rec.Header().Get("WWW-Authenticate"),
}
}

func TestOAuthLogin_DefaultOff_RoutesUnchanged(t *testing.T) {
creds := map[string]map[string]string{
"none": nil,
"admin": {"X-API-Key": oauthLoginTestAPIKey},
"garbage": {"Authorization": "Bearer garbage-token"},
}
for _, requireAuth := range []bool{false, true} {
srv := newOAuthLoginTestServer(t, func(c *config.Config) { c.RequireMCPAuth = requireAuth })
full := oauthLoginTestMux(srv, true)
ref := oauthLoginTestMux(srv, false)
for _, path := range oauthLoginTestPaths {
for _, method := range []string{http.MethodGet, http.MethodPost} {
for credName, hdr := range creds {
for _, remote := range []string{"192.0.2.1:4000", "127.0.0.1:4000"} {
name := fmt.Sprintf("require=%v %s %s cred=%s peer=%s", requireAuth, method, path, credName, remote)
want := doOAuthLoginReq(ref, method, path, remote, hdr)
got := doOAuthLoginReq(full, method, path, remote, hdr)
assert.Equal(t, want, got, name)
}
}
}
}
}
}

func bucketSnapshot(t *testing.T, db *bbolt.DB) (buckets []string, metaKeys []string) {
t.Helper()
require.NoError(t, db.View(func(tx *bbolt.Tx) error {
if err := tx.ForEach(func(name []byte, b *bbolt.Bucket) error {
buckets = append(buckets, string(name))
return nil
}); err != nil {
return err
}
if meta := tx.Bucket([]byte(storage.MetaBucket)); meta != nil {
return meta.ForEach(func(k, _ []byte) error {
metaKeys = append(metaKeys, string(k))
return nil
})
}
return nil
}))
sort.Strings(buckets)
sort.Strings(metaKeys)
return buckets, metaKeys
}

func TestOAuthLogin_DefaultOff_NoStorage(t *testing.T) {
srv := newOAuthLoginTestServer(t, nil)
db := srv.runtime.StorageManager().GetDB()
require.NotNil(t, db)
beforeBuckets, _ := bucketSnapshot(t, db)

mux := oauthLoginTestMux(srv, true)
for _, path := range oauthLoginTestPaths {
for _, method := range []string{http.MethodGet, http.MethodPost} {
doOAuthLoginReq(mux, method, path, "127.0.0.1:4000", nil)
doOAuthLoginReq(mux, method, path, "127.0.0.1:4000", map[string]string{"X-API-Key": oauthLoginTestAPIKey})
doOAuthLoginReq(mux, method, path, "127.0.0.1:4000", map[string]string{"Authorization": "Bearer garbage-token"})
}
}

// Only browser-login state is asserted: unrelated runtime startup tasks
// (e.g. the work-session backfill) may write to the database concurrently.
afterBuckets, afterMeta := bucketSnapshot(t, db)
before := map[string]bool{}
for _, name := range beforeBuckets {
before[name] = true
}
for _, name := range afterBuckets {
if strings.HasPrefix(name, "oauth_") && !before[name] {
t.Errorf("browser login created bucket %q while off", name)
}
}
for _, name := range []string{"oauth_registrations", "oauth_grants", "oauth_grant_access_index", "oauth_client_bindings"} {
assert.NotContains(t, afterBuckets, name, "lazy browser-login bucket must not exist")
}
for _, key := range afterMeta {
assert.False(t, strings.HasPrefix(key, "oauth_login"), "MetaBucket key %q must not exist", key)
}
}

// Patterns the gate guards (the ones registered by registerOAuthLoginRoutes).
var oauthLoginGatedPaths = []string{
"/mcp/oauth", "/mcp/oauth/", "/mcp/oauth/cursor",
"/oauth/register", "/oauth/authorize", "/oauth/token",
"/.well-known/oauth-authorization-server",
"/.well-known/oauth-protected-resource/mcp/oauth",
"/.well-known/oauth-protected-resource/mcp/oauth/cursor",
}

func TestOAuthLogin_Gate_OffAndEverUsed_404(t *testing.T) {
srv := newOAuthLoginTestServer(t, nil)
srv.oauthLoginEverUsed = func() bool { return true }
mux := oauthLoginTestMux(srv, true)
for _, path := range oauthLoginGatedPaths {
got := doOAuthLoginReq(mux, http.MethodGet, path, "127.0.0.1:4000", nil)
assert.Equal(t, http.StatusNotFound, got.code, path)
assert.NotContains(t, got.body, "mcp-chain", path)
}
}
6 changes: 6 additions & 0 deletions internal/server/oauth_login_edition.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//go:build !server

package server

// oauthLoginEditionSupported: the personal edition may serve browser login (Spec 132).
const oauthLoginEditionSupported = true
6 changes: 6 additions & 0 deletions internal/server/oauth_login_edition_server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//go:build server

package server

// oauthLoginEditionSupported: a server-edition binary never serves browser login, whatever the config (Spec 132).
const oauthLoginEditionSupported = false
Loading
Loading