From 96c088d83d399b2de563ce0312adffa56e63ef11 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 18 Nov 2026 19:16:56 +0200 Subject: [PATCH 1/4] fix(upstream): never send an unresolved secret reference to an HTTP upstream Release QA F9: a ${keyring:...} reference that could not be resolved in a configured header was sent to the upstream verbatim ("Authorization: Bearer ${keyring:name}") and health stayed green. The core client logged the failure and kept the raw value. - A secret reference in the URL, headers or OAuth settings that cannot be resolved when the client is built now makes the client refuse to connect, sign in or refresh a token, before any HTTP request (core.UnresolvedSecretError). The error names the reference and field, never a value, and says how to add the secret and restart the server. It classifies as MCPX_CONFIG_MISSING_SECRET and health shows "Missing secret" with the set_secret action. References that resolve on the same server and other servers are unaffected; local stdio fields keep the old behaviour. - The resolution-failure log names the references only, not the field value. - Storing a secret through REST or the Web UI restarted only servers that referenced it in env or args; servers referencing it in the URL, headers or OAuth settings are now restarted too. Tests go through the runtime: a missing synthetic keyring key is refused with nothing sent, an unrelated server connects, and after the key is added an upstream restart (or storing the secret through the API) connects with the resolved header and keeps a valid substitution; no secret value is logged. --- docs/errors/MCPX_CONFIG_MISSING_SECRET.md | 23 ++ internal/health/calculator.go | 14 ++ internal/runtime/runtime.go | 58 +++-- .../runtime/unresolved_header_secret_test.go | 217 ++++++++++++++++++ internal/upstream/core/client.go | 49 +++- internal/upstream/core/connection.go | 5 + internal/upstream/core/connection_oauth.go | 5 + internal/upstream/core/unresolved_secrets.go | 127 ++++++++++ .../upstream/core/unresolved_secrets_test.go | 153 ++++++++++++ 9 files changed, 627 insertions(+), 24 deletions(-) create mode 100644 internal/runtime/unresolved_header_secret_test.go create mode 100644 internal/upstream/core/unresolved_secrets.go create mode 100644 internal/upstream/core/unresolved_secrets_test.go diff --git a/docs/errors/MCPX_CONFIG_MISSING_SECRET.md b/docs/errors/MCPX_CONFIG_MISSING_SECRET.md index a595c39f9..2b2981b86 100644 --- a/docs/errors/MCPX_CONFIG_MISSING_SECRET.md +++ b/docs/errors/MCPX_CONFIG_MISSING_SECRET.md @@ -16,6 +16,22 @@ The upstream config references a secret (typically via `${keyring:NAME}` in `env` or `headers`), but the secret was not found in the active secret store when mcpproxy tried to start that server. +### HTTP upstreams: nothing is sent + +When the missing reference is in a remote server's `url`, `headers` or `oauth` +settings, mcpproxy does not connect, sign in or refresh a token for that +server, so the raw `${keyring:NAME}` text never reaches the upstream. The +server shows **Missing secret** with the reference name, and the error names +the field, for example: + +```text +unresolved secret reference ${keyring:my_api_key} in Headers[Authorization]: the secret is not available, so nothing was sent to the upstream. Add it with: mcpproxy secrets set my_api_key, then restart the server (mcpproxy upstream restart my-server) +``` + +Other servers are not affected. A missing reference in a local (stdio) +server's `env`, `args` or `working_dir` is logged and the value is used as +written. + ## How to fix ### List what's defined @@ -26,6 +42,13 @@ mcpproxy secrets list If the name you referenced isn't there, add it. +Secrets are resolved when the server's connection is created, so after adding +one restart the server: + +```bash +mcpproxy upstream restart +``` + ### Add the missing secret ```bash diff --git a/internal/health/calculator.go b/internal/health/calculator.go index 292ca098c..7ee930612 100644 --- a/internal/health/calculator.go +++ b/internal/health/calculator.go @@ -1069,6 +1069,20 @@ func ExtractMissingSecret(lastError string) string { return "" } + // Pattern: "unresolved secret reference ${keyring:NAME} in Headers[...]" + // (core.UnresolvedSecretError, release QA F9): the connection was refused + // before any request, for any secret type. + const unresolvedPrefix = "unresolved secret reference ${" + if idx := findSubstring(lastError, unresolvedPrefix); idx >= 0 { + start := idx + len(unresolvedPrefix) + if end := findChar(lastError[start:], '}'); end > 0 { + ref := lastError[start : start+end] + if colon := findChar(ref, ':'); colon >= 0 && colon+1 < len(ref) { + return ref[colon+1:] + } + } + } + // Pattern: "environment variable VARNAME not found or empty" const prefix = "environment variable " const suffix = " not found or empty" diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index be7ec2640..f91945e2d 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -1494,25 +1494,16 @@ func (r *Runtime) NotifySecretsChanged(ctx context.Context, operation, secretNam return fmt.Errorf("config not available") } - // Find all servers that reference this secret in their env vars or args + // Find all servers that reference this secret, in any field that is + // resolved when the connection is created: env, args, working dir, and + // for remote servers the URL, headers and OAuth settings (release QA F9: + // a header reference was never restarted). secretRef := fmt.Sprintf("${keyring:%s}", secretName) var affectedServers []string for _, server := range cfg.Servers { - // Check environment variables - for _, value := range server.Env { - if strings.Contains(value, secretRef) { - affectedServers = append(affectedServers, server.Name) - break - } - } - - // Check arguments - for _, arg := range server.Args { - if strings.Contains(arg, secretRef) { - affectedServers = append(affectedServers, server.Name) - break - } + if serverReferencesSecret(server, secretRef) { + affectedServers = append(affectedServers, server.Name) } } @@ -4947,3 +4938,40 @@ func (r *Runtime) callTimeOAuthRequired(name string) bool { func shouldProbeStoredOAuthRow(url string, haveStorage, tokenInPlay, callTimeOAuthRequired bool) bool { return url != "" && haveStorage && (tokenInPlay || callTimeOAuthRequired) } + +// serverReferencesSecret reports whether any field of server that is expanded +// when its connection is created contains ref (e.g. "${keyring:name}"). +func serverReferencesSecret(server *config.ServerConfig, ref string) bool { + if server == nil { + return false + } + has := func(v string) bool { return strings.Contains(v, ref) } + anyOf := func(vs []string) bool { + for _, v := range vs { + if has(v) { + return true + } + } + return false + } + values := func(m map[string]string) bool { + for _, v := range m { + if has(v) { + return true + } + } + return false + } + if has(server.URL) || has(server.Command) || has(server.WorkingDir) || + anyOf(server.Args) || values(server.Env) || values(server.Headers) { + return true + } + if o := server.OAuth; o != nil { + if has(o.ClientID) || has(o.ClientSecret) || has(o.RedirectURI) || has(o.CallbackBaseURL) || + has(o.AuthorizationEndpoint) || has(o.TokenEndpoint) || has(o.RegistrationEndpoint) || + has(o.AuthServerMetadataURL) || anyOf(o.Scopes) || values(o.ExtraParams) { + return true + } + } + return false +} diff --git a/internal/runtime/unresolved_header_secret_test.go b/internal/runtime/unresolved_header_secret_test.go new file mode 100644 index 000000000..646ed2e00 --- /dev/null +++ b/internal/runtime/unresolved_header_secret_test.go @@ -0,0 +1,217 @@ +package runtime + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/mark3labs/mcp-go/mcp" + mcpserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest/observer" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// fakeKeyring is an in-memory keyring provider; a missing name is an error, +// like the OS keychain's "secret not found". +type fakeKeyring struct { + mu sync.Mutex + values map[string]string +} + +func (k *fakeKeyring) CanResolve(t string) bool { return t == "keyring" } +func (k *fakeKeyring) IsAvailable() bool { return true } +func (k *fakeKeyring) Resolve(_ context.Context, ref secret.Ref) (string, error) { + k.mu.Lock() + defer k.mu.Unlock() + v, ok := k.values[ref.Name] + if !ok { + return "", errors.New("secret not found in keyring") + } + return v, nil +} +func (k *fakeKeyring) Store(_ context.Context, ref secret.Ref, v string) error { + k.mu.Lock() + defer k.mu.Unlock() + k.values[ref.Name] = v + return nil +} +func (k *fakeKeyring) Delete(context.Context, secret.Ref) error { return nil } +func (k *fakeKeyring) List(context.Context) ([]secret.Ref, error) { return nil, nil } + +// headerRecorder is a streamable-HTTP MCP upstream that records every request +// it receives and the headers that came with it. +type headerRecorder struct { + next http.Handler + mu sync.Mutex + seen []http.Header +} + +func (h *headerRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { + h.mu.Lock() + h.seen = append(h.seen, r.Header.Clone()) + h.mu.Unlock() + h.next.ServeHTTP(w, r) +} + +func (h *headerRecorder) requests() []http.Header { + h.mu.Lock() + defer h.mu.Unlock() + return append([]http.Header(nil), h.seen...) +} + +func newHeaderRecordingUpstream(t *testing.T) (*headerRecorder, string) { + t.Helper() + srv := mcpserver.NewMCPServer("f9", "0.0.1", mcpserver.WithToolCapabilities(true)) + srv.AddTool(mcp.NewTool("echo", mcp.WithDescription("Echoes.")), func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return mcp.NewToolResultText("ok"), nil + }) + rec := &headerRecorder{next: mcpserver.NewStreamableHTTPServer(srv)} + ts := httptest.NewServer(rec) + t.Cleanup(ts.Close) + return rec, ts.URL +} + +// Release QA F9: an unavailable ${keyring:...} in a configured upstream HTTP +// header was sent to the upstream verbatim, and health stayed green. A header, +// URL or OAuth field whose secret reference cannot be resolved must stop that +// server before any HTTP request, with an actionable missing-secret error; +// valid substitutions on the same server and unrelated servers are unaffected. +// After the secret is added, a restart of that server connects it with the +// resolved value. No secret value may reach the logs. +func TestUnresolvedHeaderSecret_RefusedBeforeAnyRequestThenRecoversOnRestart(t *testing.T) { + t.Run("upstream restart", func(t *testing.T) { + testUnresolvedHeaderSecret(t, func(rt *Runtime) error { return rt.RestartServer("f9-secret") }) + }) + // Storing the secret through REST / the Web UI restarts the servers that + // reference it; a header reference was not found by that scan (F9). + t.Run("secret stored through the API", func(t *testing.T) { + testUnresolvedHeaderSecret(t, func(rt *Runtime) error { + return rt.NotifySecretsChanged(context.Background(), "store", "f9-missing") + }) + }) +} + +func testUnresolvedHeaderSecret(t *testing.T, restart func(*Runtime) error) { + t.Setenv("MCPPROXY_DISABLE_OAUTH", "true") + const presentValue = "f9-present-value-6b1e" + const addedValue = "f9-added-later-value-93ac" + + secretUp, secretURL := newHeaderRecordingUpstream(t) + otherUp, otherURL := newHeaderRecordingUpstream(t) + + secretCfg := &config.ServerConfig{ + Name: "f9-secret", URL: secretURL, Protocol: "streamable-http", Enabled: true, + Headers: map[string]string{ + "Authorization": "Bearer ${keyring:f9-missing}", + "X-Present": "${keyring:f9-present}", + }, + } + otherCfg := &config.ServerConfig{Name: "f9-other", URL: otherURL, Protocol: "streamable-http", Enabled: true} + + core, logs := observer.New(zapcore.DebugLevel) + quarantineOff := false // admission is not under test here + rt, err := New(&config.Config{DataDir: t.TempDir(), Listen: "127.0.0.1:0", QuarantineEnabled: &quarantineOff, + Servers: []*config.ServerConfig{secretCfg, otherCfg}}, "", zap.New(core)) + require.NoError(t, err) + t.Cleanup(func() { _ = rt.Close() }) + + keyring := &fakeKeyring{values: map[string]string{"f9-present": presentValue}} + rt.secretResolver.RegisterProvider("keyring", keyring) + for _, c := range []*config.ServerConfig{secretCfg, otherCfg} { + require.NoError(t, rt.storageManager.SaveUpstreamServer(c)) + } + + rt.StartBackgroundInitialization() + + // The unrelated server connects as usual. + require.Eventually(t, func() bool { + c, ok := rt.UpstreamManager().GetClient("f9-other") + return ok && c.IsConnected() + }, 15*time.Second, 50*time.Millisecond, "an unrelated server must connect") + assert.NotEmpty(t, otherUp.requests()) + + // The server with the missing secret reports it, and sent nothing. + var status map[string]interface{} + require.Eventually(t, func() bool { + servers, err := rt.GetAllServers() + if err != nil { + return false + } + for _, s := range servers { + if s["name"] == "f9-secret" { + status = s + le, _ := s["last_error"].(string) + return strings.Contains(le, "f9-missing") + } + } + return false + }, 15*time.Second, 50*time.Millisecond, "the missing secret must be reported on the server (status %v; upstream saw %d requests, first Authorization %q)", + status, len(secretUp.requests()), firstAuthorization(secretUp)) + c, ok := rt.UpstreamManager().GetClient("f9-secret") + require.True(t, ok) + assert.False(t, c.IsConnected()) + assert.Empty(t, secretUp.requests(), "no HTTP request may be sent with an unresolved secret reference") + + lastErr, _ := status["last_error"].(string) + assert.Contains(t, lastErr, "${keyring:f9-missing}", "the error names the reference") + assert.Contains(t, lastErr, "Headers[Authorization]", "the error names the field") + assert.Contains(t, lastErr, "mcpproxy secrets set f9-missing", "the error says how to fix it") + assert.NotContains(t, lastErr, presentValue, "a resolved value never appears in the error") + h, ok := status["health"].(*contracts.HealthStatus) + require.True(t, ok, "no health on the server status: %#v", status["health"]) + assert.Equal(t, "unhealthy", h.Level, "health is not green") + assert.Equal(t, "Missing secret", h.Summary) + assert.Equal(t, "f9-missing", h.Detail) + assert.Equal(t, "set_secret", h.Action) + + // The secret is added later; a restart of that server picks it up. + require.NoError(t, keyring.Store(context.Background(), secret.Ref{Type: "keyring", Name: "f9-missing"}, addedValue)) + require.NoError(t, restart(rt)) + require.Eventually(t, func() bool { + c, ok := rt.UpstreamManager().GetClient("f9-secret") + return ok && c.IsConnected() + }, 15*time.Second, 50*time.Millisecond, "after the secret is added, a restart connects the server") + + reqs := secretUp.requests() + require.NotEmpty(t, reqs) + for _, h := range reqs { + assert.Equal(t, "Bearer "+addedValue, h.Get("Authorization"), "the resolved header is sent") + assert.Equal(t, presentValue, h.Get("X-Present"), "a valid substitution is preserved") + assert.NotContains(t, h.Get("Authorization"), "${keyring:", "never the raw reference") + } + + // No secret value reaches the logs. + for _, e := range logs.All() { + line := e.Message + for _, f := range e.Context { + line += " " + f.String + if f.Interface != nil { + if err, ok := f.Interface.(error); ok { + line += " " + err.Error() + } + } + } + for _, v := range []string{presentValue, addedValue} { + assert.NotContains(t, line, v, "a secret value was logged: %q", e.Message) + } + } +} + +func firstAuthorization(h *headerRecorder) string { + if r := h.requests(); len(r) > 0 { + return r[0].Get("Authorization") + } + return "" +} diff --git a/internal/upstream/core/client.go b/internal/upstream/core/client.go index f4caba0e8..ef6423e46 100644 --- a/internal/upstream/core/client.go +++ b/internal/upstream/core/client.go @@ -209,6 +209,22 @@ type Client struct { listenMu sync.Mutex listen *listChangedStream listenClient *client.Client + + // unresolvedSecrets, when non-nil, names secret references in the URL, + // headers or OAuth settings that could not be resolved when this client + // was built (release QA F9). Connect, sign-in and token refresh refuse + // with it before any HTTP request. Set once in NewClientWithOptions; a + // restart builds a new client and resolves again. + unresolvedSecrets *UnresolvedSecretError +} + +// UnresolvedSecrets returns the refusal for unresolved secret references in +// the fields sent to the upstream, or nil. +func (c *Client) UnresolvedSecrets() error { + if c.unresolvedSecrets == nil { + return nil + } + return c.unresolvedSecrets } // NewClient creates a new core MCP client @@ -223,25 +239,37 @@ func NewClientWithOptions(id string, serverConfig *config.ServerConfig, logger * // every string field of ServerConfig and its nested structs (IsolationConfig, OAuthConfig) // without an explicit per-field allowlist (FR-001 / US2). resolvedServerConfig := config.CopyServerConfig(serverConfig) + var unresolved *UnresolvedSecretError if secretResolver != nil { ctx := context.Background() errs := secretResolver.ExpandStructSecretsCollectErrors(ctx, resolvedServerConfig) for _, e := range errs { - logger.Error("CRITICAL: Failed to resolve secret reference - field will use UNRESOLVED placeholder", + // Log the references only, never the field's value (release QA + // F9): the value may hold literal credentials around them. + var refNames []string + for _, ref := range secret.FindSecretRefs(e.Reference) { + refNames = append(refNames, ref.Original) + } + logger.Error("Failed to resolve secret reference", zap.String("server", serverConfig.Name), zap.String("field", e.FieldPath), - zap.String("reference", e.Reference), - zap.Error(e.Err), - zap.String("help", "Use Web UI (http://localhost:8080/ui/) or API to add the secret to keyring")) + zap.Strings("references", refNames), + zap.Bool("blocks_connection", wireSecretField(e.FieldPath)), + zap.String("help", "Add the secret (mcpproxy secrets set , or the Web UI), then restart the server")) } + unresolved = unresolvedWireSecrets(serverConfig.Name, errs, func(ref secret.Ref) bool { + _, err := secretResolver.Resolve(ctx, ref) + return err == nil + }) } c := &Client{ - id: id, - config: resolvedServerConfig, - globalConfig: globalConfig, - storage: storage, - secretResolver: secretResolver, // Store resolver for future use + id: id, + config: resolvedServerConfig, + globalConfig: globalConfig, + storage: storage, + secretResolver: secretResolver, // Store resolver for future use + unresolvedSecrets: unresolved, logger: logger.With( zap.String("upstream_id", id), zap.String("upstream_name", serverConfig.Name), @@ -852,6 +880,9 @@ func extractOAuthHandler(mcpClient *client.Client) *transport.OAuthHandler { // mcp-go's handler.RefreshToken when the live handler has a client id, else // the stored DCR credentials. func (c *Client) RefreshOAuthTokenDirect(ctx context.Context) error { + if err := c.UnresolvedSecrets(); err != nil { + return err + } // Spec 123 FR-031: an undecryptable stored row is reported with its own // code whether or not a live handler exists, and the refresh never falls // back to a login. Only that outcome is decided here; every other case diff --git a/internal/upstream/core/connection.go b/internal/upstream/core/connection.go index d2ee78748..6a55cf9c5 100644 --- a/internal/upstream/core/connection.go +++ b/internal/upstream/core/connection.go @@ -245,6 +245,11 @@ func (c *Client) Connect(ctx context.Context) error { if c.Gate().Retired() { return fmt.Errorf("connect refused: %w", dialgate.ErrRetired) } + // Release QA F9: a header, URL or OAuth setting whose secret reference + // could not be resolved is never sent; refuse before any transport. + if err := c.UnresolvedSecrets(); err != nil { + return err + } // Reset connection state for fresh connection attempt if c.connected { diff --git a/internal/upstream/core/connection_oauth.go b/internal/upstream/core/connection_oauth.go index e4fb4e498..23503f82b 100644 --- a/internal/upstream/core/connection_oauth.go +++ b/internal/upstream/core/connection_oauth.go @@ -1904,6 +1904,11 @@ func (c *Client) storedOAuthTokenUndecryptable() error { // manual-login entry point (quick and forced HTTP/SSE). It is // storedOAuthTokenUndecryptable plus the warning the automatic strategies log. func (c *Client) rejectManualLoginOnUndecryptableToken() error { + // Release QA F9: a sign-in would send the unresolved OAuth settings (or + // headers) to the authorization server. + if err := c.UnresolvedSecrets(); err != nil { + return err + } err := c.storedOAuthTokenUndecryptable() if err != nil { c.logger.Warn("Stored OAuth token cannot be decrypted; not starting a manual OAuth login", diff --git a/internal/upstream/core/unresolved_secrets.go b/internal/upstream/core/unresolved_secrets.go new file mode 100644 index 000000000..6b5eb5220 --- /dev/null +++ b/internal/upstream/core/unresolved_secrets.go @@ -0,0 +1,127 @@ +package core + +import ( + "errors" + "fmt" + "sort" + "strings" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/diagnostics" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +// UnresolvedSecretError reports secret references in the fields an HTTP +// upstream receives (URL, headers, OAuth settings) that could not be resolved +// when the client was built. Release QA F9: such a reference used to be sent +// to the upstream verbatim (`Authorization: Bearer ${keyring:name}`) while +// health stayed green. The client now refuses to connect, sign in or refresh +// a token, so nothing reaches the upstream, and the error says which +// reference is missing, where, and how to add it. +// +// The error names references (`${keyring:name}`) and field paths only, never +// a field's value: a value may hold literal text or other resolved secrets. +type UnresolvedSecretError struct { + Server string + Refs []UnresolvedSecretRef +} + +// UnresolvedSecretRef is one reference that could not be resolved. +type UnresolvedSecretRef struct { + Field string // e.g. "Headers[Authorization]", "OAuth.ClientSecret" + Reference string // e.g. "${keyring:github-token}" + Type string // e.g. "keyring" + Name string // e.g. "github-token" +} + +func (e *UnresolvedSecretError) Error() string { + if len(e.Refs) == 0 { + return fmt.Sprintf("unresolved secret reference in server %q; nothing was sent to the upstream", e.Server) + } + var b strings.Builder + for i, r := range e.Refs { + if i > 0 { + b.WriteString("; ") + } + fmt.Fprintf(&b, "unresolved secret reference %s in %s", r.Reference, r.Field) + } + fmt.Fprintf(&b, ": the secret is not available, so nothing was sent to the upstream. %s, then restart the server (mcpproxy upstream restart %s)", + e.fixHint(), e.Server) + return b.String() +} + +// fixHint names the command that makes the first missing reference available. +func (e *UnresolvedSecretError) fixHint() string { + r := e.Refs[0] + switch r.Type { + case "keyring": + return fmt.Sprintf("Add it with: mcpproxy secrets set %s", r.Name) + case "env": + return fmt.Sprintf("Set the environment variable %s for mcpproxy", r.Name) + case "file": + return fmt.Sprintf("Make the file %s readable by mcpproxy", r.Name) + default: + return "Make the secret available" + } +} + +// Unwrap lets diagnostics classify the failure as MCPX_CONFIG_MISSING_SECRET. +func (e *UnresolvedSecretError) Unwrap() error { + return diagnostics.WrapConfigMissingSecret(errMissingSecret) +} + +var errMissingSecret = errors.New("missing secret") + +// IsUnresolvedSecretError reports whether err carries an UnresolvedSecretError. +func IsUnresolvedSecretError(err error) bool { + var u *UnresolvedSecretError + return errors.As(err, &u) +} + +// wireSecretField reports whether a ServerConfig field path is sent to an HTTP +// upstream or its authorization server: the URL, the headers and every OAuth +// setting. Fields only a local process sees (command, args, env, working dir, +// isolation) keep the existing behaviour: logged, used as written. +func wireSecretField(path string) bool { + return path == "URL" || + strings.HasPrefix(path, "Headers[") || + path == "OAuth" || strings.HasPrefix(path, "OAuth.") +} + +// unresolvedWireSecrets builds the refusal for the expansion failures that +// affect fields sent over HTTP, or nil when there are none. A field whose +// expansion failed keeps its raw value, so its references are re-parsed and +// each one is checked; only the ones that fail are named. +func unresolvedWireSecrets(server string, errs []secret.SecretExpansionError, resolveOK func(secret.Ref) bool) *UnresolvedSecretError { + out := &UnresolvedSecretError{Server: server} + seen := map[string]bool{} + for _, e := range errs { + if !wireSecretField(e.FieldPath) { + continue + } + refs := secret.FindSecretRefs(e.Reference) + added := false + for _, ref := range refs { + if resolveOK != nil && resolveOK(*ref) { + continue + } + key := e.FieldPath + "\x00" + ref.Original + if seen[key] { + continue + } + seen[key] = true + out.Refs = append(out.Refs, UnresolvedSecretRef{Field: e.FieldPath, Reference: ref.Original, Type: ref.Type, Name: ref.Name}) + added = true + } + if !added { + // The field failed but each reference resolves on its own now (a + // secret added meanwhile): still refuse, naming the field, since + // the client holds the unresolved value. + out.Refs = append(out.Refs, UnresolvedSecretRef{Field: e.FieldPath, Reference: "a secret reference"}) + } + } + if len(out.Refs) == 0 { + return nil + } + sort.SliceStable(out.Refs, func(i, j int) bool { return out.Refs[i].Field < out.Refs[j].Field }) + return out +} diff --git a/internal/upstream/core/unresolved_secrets_test.go b/internal/upstream/core/unresolved_secrets_test.go new file mode 100644 index 000000000..0228f8279 --- /dev/null +++ b/internal/upstream/core/unresolved_secrets_test.go @@ -0,0 +1,153 @@ +package core + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest/observer" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/diagnostics" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/health" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" +) + +type mapKeyring map[string]string + +func (k mapKeyring) CanResolve(t string) bool { return t == "keyring" } +func (k mapKeyring) IsAvailable() bool { return true } +func (k mapKeyring) Resolve(_ context.Context, ref secret.Ref) (string, error) { + if v, ok := k[ref.Name]; ok { + return v, nil + } + return "", errors.New("secret not found in keyring") +} +func (k mapKeyring) Store(context.Context, secret.Ref, string) error { return nil } +func (k mapKeyring) Delete(context.Context, secret.Ref) error { return nil } +func (k mapKeyring) List(context.Context) ([]secret.Ref, error) { return nil, nil } + +func resolverWith(k mapKeyring) *secret.Resolver { + r := secret.NewResolver() + r.RegisterProvider("keyring", k) + return r +} + +// Release QA F9, at the client: every way the client talks to an HTTP upstream +// or its authorization server is refused before a request, the error names only +// the references that failed, and no value is logged. +func TestUnresolvedWireSecret_RefusesConnectLoginAndRefresh(t *testing.T) { + t.Setenv("MCPPROXY_DISABLE_OAUTH", "true") + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(srv.Close) + + const present = "present-value-7c41" + const literal = "literal-credential-55d0" + cfg := &config.ServerConfig{ + Name: "f9", URL: srv.URL + "/mcp", Protocol: "http", Enabled: true, + Headers: map[string]string{ + // one header mixes a resolvable reference, a missing one and literal text + "Authorization": literal + " ${keyring:present} ${keyring:missing}", + }, + } + coreLog, logs := observer.New(zapcore.DebugLevel) + c, err := NewClient(cfg.Name, cfg, zap.New(coreLog), nil, &config.Config{}, nil, resolverWith(mapKeyring{"present": present})) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + err = c.Connect(ctx) + require.Error(t, err) + assert.True(t, IsUnresolvedSecretError(err)) + assert.Equal(t, int32(0), hits.Load(), "nothing is sent") + + msg := err.Error() + assert.Contains(t, msg, "unresolved secret reference ${keyring:missing} in Headers[Authorization]") + assert.NotContains(t, msg, "${keyring:present}", "a reference that resolves is not named") + assert.Contains(t, msg, "mcpproxy secrets set missing") + assert.Contains(t, msg, "mcpproxy upstream restart f9") + assert.NotContains(t, msg, present) + assert.NotContains(t, msg, literal) + assert.Equal(t, diagnostics.ConfigMissingSecret, diagnostics.Classify(err, diagnostics.ClassifierHints{Transport: "http"})) + assert.Equal(t, "missing", health.ExtractMissingSecret(msg)) + + assert.Error(t, c.CheckManualLoginAllowed(), "no sign-in with unresolved settings") + _, err = c.StartOAuthFlowQuick(ctx) + assert.Error(t, err, "quick sign-in refused") // OAuth is off in this test, which refuses first + assert.True(t, IsUnresolvedSecretError(c.RefreshOAuthTokenDirect(ctx)), "token refresh refused") + assert.Equal(t, int32(0), hits.Load(), "still nothing sent") + + for _, e := range logs.All() { + line := e.Message + for _, f := range e.Context { + line += " " + f.String + if f.Interface != nil { + line += " " + toString(f.Interface) + } + } + assert.NotContains(t, line, present, "resolved value logged in %q", e.Message) + assert.NotContains(t, line, literal, "field value logged in %q", e.Message) + } +} + +func toString(v interface{}) string { + switch x := v.(type) { + case error: + return x.Error() + case []string: + out := "" + for _, s := range x { + out += s + " " + } + return out + } + return "" +} + +// Only fields an HTTP upstream receives block the connection; a stdio +// server's env keeps the existing behaviour (logged, used as written), and a +// server whose references all resolve is untouched. +func TestUnresolvedSecret_OnlyWireFieldsBlock(t *testing.T) { + r := resolverWith(mapKeyring{"ok": "v"}) + stdio := &config.ServerConfig{Name: "local", Command: "true", Protocol: "stdio", Enabled: true, + Env: map[string]string{"TOKEN": "${keyring:missing}"}} + c, err := NewClient(stdio.Name, stdio, zap.NewNop(), nil, &config.Config{}, nil, r) + require.NoError(t, err) + assert.NoError(t, c.UnresolvedSecrets()) + + good := &config.ServerConfig{Name: "good", URL: "http://127.0.0.1:1/mcp", Protocol: "http", Enabled: true, + Headers: map[string]string{"Authorization": "Bearer ${keyring:ok}"}} + c, err = NewClient(good.Name, good, zap.NewNop(), nil, &config.Config{}, nil, r) + require.NoError(t, err) + assert.NoError(t, c.UnresolvedSecrets()) + assert.Equal(t, "Bearer v", c.config.Headers["Authorization"]) + + for _, tc := range []struct { + name string + cfg *config.ServerConfig + want string + }{ + {"url", &config.ServerConfig{Name: "u", URL: "https://x.example/${keyring:missing}/mcp", Protocol: "http"}, "in URL"}, + {"oauth", &config.ServerConfig{Name: "o", URL: "https://x.example/mcp", Protocol: "http", + OAuth: &config.OAuthConfig{ClientID: "id", ClientSecret: "${keyring:missing}"}}, "in OAuth.ClientSecret"}, + } { + t.Run(tc.name, func(t *testing.T) { + c, err := NewClient(tc.cfg.Name, tc.cfg, zap.NewNop(), nil, &config.Config{}, nil, r) + require.NoError(t, err) + require.Error(t, c.UnresolvedSecrets()) + assert.Contains(t, c.UnresolvedSecrets().Error(), tc.want) + }) + } +} From 1ec76f3b0fbcfb827c4259ae88a301ae010542d6 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 18 Nov 2026 19:34:36 +0200 Subject: [PATCH 2/4] fix(upstream): scope the unresolved-secret refusal to HTTP servers Review r1 on the F9 fix: - Only an HTTP-family server sends its URL, headers and OAuth settings, so a stale reference in those fields of a stdio server no longer stops it. - The fix hint for ${env:NAME} says to restart mcpproxy: the env provider reads mcpproxy's own environment, which a server restart cannot change. - A field whose references resolve on a second look is reported with its first reference, so health still reads "Missing secret". - The resolution-failure log carries the provider's reason again (it names references only), so "keyring unavailable" and "not found" stay apart. - Storing or deleting a secret no longer restarts, and so re-enables, a disabled server that references it. - Tests check every logged field (arrays too), exercise both sign-in flows with OAuth applicable, the hints, the reference scan and the disabled skip. - Docs: ${env:} and other ${type:name} text in those fields is now refused when it cannot be resolved; which restart picks a secret up. --- docs/errors/MCPX_CONFIG_MISSING_SECRET.md | 14 +++- internal/runtime/runtime.go | 5 ++ .../runtime/unresolved_header_secret_test.go | 45 ++++++++--- internal/upstream/core/client.go | 18 +++-- internal/upstream/core/unresolved_secrets.go | 32 ++++---- .../upstream/core/unresolved_secrets_test.go | 75 +++++++++++++------ 6 files changed, 138 insertions(+), 51 deletions(-) diff --git a/docs/errors/MCPX_CONFIG_MISSING_SECRET.md b/docs/errors/MCPX_CONFIG_MISSING_SECRET.md index 2b2981b86..e6b2f1b4a 100644 --- a/docs/errors/MCPX_CONFIG_MISSING_SECRET.md +++ b/docs/errors/MCPX_CONFIG_MISSING_SECRET.md @@ -30,7 +30,14 @@ unresolved secret reference ${keyring:my_api_key} in Headers[Authorization]: the Other servers are not affected. A missing reference in a local (stdio) server's `env`, `args` or `working_dir` is logged and the value is used as -written. +written; a stdio server never sends its `headers`, `url` or `oauth` values, so +a reference there does not stop it either. + +This also applies to `${env:NAME}` references and to any text in those fields +that has the `${type:name}` form: earlier versions sent them literally when +they could not be resolved, and mcpproxy now refuses instead. A `${env:NAME}` +reference reads mcpproxy's own environment, so set the variable and restart +mcpproxy (or its service) rather than the server. ## How to fix @@ -42,8 +49,9 @@ mcpproxy secrets list If the name you referenced isn't there, add it. -Secrets are resolved when the server's connection is created, so after adding -one restart the server: +Secrets are resolved when the server's connection is created. Storing a +secret through the Web UI or REST API restarts the enabled servers that use it; +after `mcpproxy secrets set`, restart the server: ```bash mcpproxy upstream restart diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index f91945e2d..cd43c656c 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -1502,6 +1502,11 @@ func (r *Runtime) NotifySecretsChanged(ctx context.Context, operation, secretNam var affectedServers []string for _, server := range cfg.Servers { + // A restart enables a disabled server (RestartServerCtx), and a + // secret change is no reason to undo the operator's disable. + if !server.Enabled { + continue + } if serverReferencesSecret(server, secretRef) { affectedServers = append(affectedServers, server.Name) } diff --git a/internal/runtime/unresolved_header_secret_test.go b/internal/runtime/unresolved_header_secret_test.go index 646ed2e00..5e1488db5 100644 --- a/internal/runtime/unresolved_header_secret_test.go +++ b/internal/runtime/unresolved_header_secret_test.go @@ -3,6 +3,7 @@ package runtime import ( "context" "errors" + "fmt" "net/http" "net/http/httptest" "strings" @@ -194,15 +195,7 @@ func testUnresolvedHeaderSecret(t *testing.T, restart func(*Runtime) error) { // No secret value reaches the logs. for _, e := range logs.All() { - line := e.Message - for _, f := range e.Context { - line += " " + f.String - if f.Interface != nil { - if err, ok := f.Interface.(error); ok { - line += " " + err.Error() - } - } - } + line := e.Message + " " + fmt.Sprint(e.ContextMap()) for _, v := range []string{presentValue, addedValue} { assert.NotContains(t, line, v, "a secret value was logged: %q", e.Message) } @@ -215,3 +208,37 @@ func firstAuthorization(h *headerRecorder) string { } return "" } + +// Review r1: a secret change restarts the servers that reference it, and a +// restart enables a disabled server, so a disabled server is skipped. +func TestNotifySecretsChanged_LeavesDisabledServersDisabled(t *testing.T) { + quarantineOff := false + disabled := &config.ServerConfig{Name: "off", URL: "http://127.0.0.1:1/mcp", Protocol: "streamable-http", Enabled: false, + Headers: map[string]string{"Authorization": "Bearer ${keyring:tok}"}} + rt, err := New(&config.Config{DataDir: t.TempDir(), Listen: "127.0.0.1:0", QuarantineEnabled: &quarantineOff, + Servers: []*config.ServerConfig{disabled}}, "", zap.NewNop()) + require.NoError(t, err) + t.Cleanup(func() { _ = rt.Close() }) + require.NoError(t, rt.storageManager.SaveUpstreamServer(disabled)) + + require.NoError(t, rt.NotifySecretsChanged(context.Background(), "store", "tok")) + time.Sleep(300 * time.Millisecond) // restarts run in the background + srv := rt.Config().Servers[0] + assert.False(t, srv.Enabled, "storing a secret must not enable a disabled server") +} + +func TestServerReferencesSecret_Fields(t *testing.T) { + ref := "${keyring:tok}" + for name, cfg := range map[string]*config.ServerConfig{ + "header": {Headers: map[string]string{"A": "Bearer " + ref}}, + "url": {URL: "https://x/" + ref}, + "oauth": {OAuth: &config.OAuthConfig{ClientSecret: ref}}, + "extra": {OAuth: &config.OAuthConfig{ExtraParams: map[string]string{"k": ref}}}, + "env": {Env: map[string]string{"T": ref}}, + "args": {Args: []string{"--t=" + ref}}, + } { + assert.True(t, serverReferencesSecret(cfg, ref), name) + } + assert.False(t, serverReferencesSecret(&config.ServerConfig{Headers: map[string]string{"A": "${keyring:other}"}}, ref)) + assert.False(t, serverReferencesSecret(nil, ref)) +} diff --git a/internal/upstream/core/client.go b/internal/upstream/core/client.go index ef6423e46..0a8c17a92 100644 --- a/internal/upstream/core/client.go +++ b/internal/upstream/core/client.go @@ -243,6 +243,9 @@ func NewClientWithOptions(id string, serverConfig *config.ServerConfig, logger * if secretResolver != nil { ctx := context.Background() errs := secretResolver.ExpandStructSecretsCollectErrors(ctx, resolvedServerConfig) + // Only an HTTP-family server sends its URL, headers and OAuth + // settings; a stdio server's copies of those fields are never used. + overHTTP := proxytransport.DetermineTransportType(serverConfig) != proxytransport.TransportStdio for _, e := range errs { // Log the references only, never the field's value (release QA // F9): the value may hold literal credentials around them. @@ -250,17 +253,22 @@ func NewClientWithOptions(id string, serverConfig *config.ServerConfig, logger * for _, ref := range secret.FindSecretRefs(e.Reference) { refNames = append(refNames, ref.Original) } + // e.Err names the reference and the provider's reason (not found, + // keyring unavailable), never a value. logger.Error("Failed to resolve secret reference", zap.String("server", serverConfig.Name), zap.String("field", e.FieldPath), zap.Strings("references", refNames), - zap.Bool("blocks_connection", wireSecretField(e.FieldPath)), + zap.Bool("blocks_connection", overHTTP && wireSecretField(e.FieldPath)), + zap.Error(e.Err), zap.String("help", "Add the secret (mcpproxy secrets set , or the Web UI), then restart the server")) } - unresolved = unresolvedWireSecrets(serverConfig.Name, errs, func(ref secret.Ref) bool { - _, err := secretResolver.Resolve(ctx, ref) - return err == nil - }) + if overHTTP { + unresolved = unresolvedWireSecrets(serverConfig.Name, errs, func(ref secret.Ref) bool { + _, err := secretResolver.Resolve(ctx, ref) + return err == nil + }) + } } c := &Client{ diff --git a/internal/upstream/core/unresolved_secrets.go b/internal/upstream/core/unresolved_secrets.go index 6b5eb5220..1ec42ad65 100644 --- a/internal/upstream/core/unresolved_secrets.go +++ b/internal/upstream/core/unresolved_secrets.go @@ -44,23 +44,26 @@ func (e *UnresolvedSecretError) Error() string { } fmt.Fprintf(&b, "unresolved secret reference %s in %s", r.Reference, r.Field) } - fmt.Fprintf(&b, ": the secret is not available, so nothing was sent to the upstream. %s, then restart the server (mcpproxy upstream restart %s)", - e.fixHint(), e.Server) + fmt.Fprintf(&b, ": the secret is not available, so nothing was sent to the upstream. %s", e.fixHint()) return b.String() } -// fixHint names the command that makes the first missing reference available. +// fixHint says how to make the first missing reference available and pick it +// up: secrets are resolved when the server's connection is created. func (e *UnresolvedSecretError) fixHint() string { r := e.Refs[0] + restart := fmt.Sprintf("then restart the server (mcpproxy upstream restart %s)", e.Server) switch r.Type { case "keyring": - return fmt.Sprintf("Add it with: mcpproxy secrets set %s", r.Name) + return fmt.Sprintf("Add it with: mcpproxy secrets set %s, %s", r.Name, restart) case "env": - return fmt.Sprintf("Set the environment variable %s for mcpproxy", r.Name) + // The env provider reads mcpproxy's own environment, which a server + // restart cannot change. + return fmt.Sprintf("Set the environment variable %s and restart mcpproxy", r.Name) case "file": - return fmt.Sprintf("Make the file %s readable by mcpproxy", r.Name) + return fmt.Sprintf("Make the file %s readable by mcpproxy, %s", r.Name, restart) default: - return "Make the secret available" + return "Make the secret available, " + restart } } @@ -79,8 +82,10 @@ func IsUnresolvedSecretError(err error) bool { // wireSecretField reports whether a ServerConfig field path is sent to an HTTP // upstream or its authorization server: the URL, the headers and every OAuth -// setting. Fields only a local process sees (command, args, env, working dir, -// isolation) keep the existing behaviour: logged, used as written. +// setting. It applies to HTTP-family servers only (see NewClientWithOptions); +// fields only a local process sees (command, args, env, working dir, +// isolation), and every field of a stdio server, keep the existing behaviour: +// logged, used as written. func wireSecretField(path string) bool { return path == "URL" || strings.HasPrefix(path, "Headers[") || @@ -112,11 +117,12 @@ func unresolvedWireSecrets(server string, errs []secret.SecretExpansionError, re out.Refs = append(out.Refs, UnresolvedSecretRef{Field: e.FieldPath, Reference: ref.Original, Type: ref.Type, Name: ref.Name}) added = true } - if !added { + if !added && len(refs) > 0 { // The field failed but each reference resolves on its own now (a - // secret added meanwhile): still refuse, naming the field, since - // the client holds the unresolved value. - out.Refs = append(out.Refs, UnresolvedSecretRef{Field: e.FieldPath, Reference: "a secret reference"}) + // secret added meanwhile): still refuse, since the client holds the + // unresolved value, naming the field's first reference. + r := refs[0] + out.Refs = append(out.Refs, UnresolvedSecretRef{Field: e.FieldPath, Reference: r.Original, Type: r.Type, Name: r.Name}) } } if len(out.Refs) == 0 { diff --git a/internal/upstream/core/unresolved_secrets_test.go b/internal/upstream/core/unresolved_secrets_test.go index 0228f8279..929ee120c 100644 --- a/internal/upstream/core/unresolved_secrets_test.go +++ b/internal/upstream/core/unresolved_secrets_test.go @@ -3,6 +3,7 @@ package core import ( "context" "errors" + "fmt" "net/http" "net/http/httptest" "sync/atomic" @@ -89,31 +90,19 @@ func TestUnresolvedWireSecret_RefusesConnectLoginAndRefresh(t *testing.T) { assert.True(t, IsUnresolvedSecretError(c.RefreshOAuthTokenDirect(ctx)), "token refresh refused") assert.Equal(t, int32(0), hits.Load(), "still nothing sent") - for _, e := range logs.All() { - line := e.Message - for _, f := range e.Context { - line += " " + f.String - if f.Interface != nil { - line += " " + toString(f.Interface) - } - } - assert.NotContains(t, line, present, "resolved value logged in %q", e.Message) - assert.NotContains(t, line, literal, "field value logged in %q", e.Message) - } + assertNoValueLogged(t, logs, present, literal) } -func toString(v interface{}) string { - switch x := v.(type) { - case error: - return x.Error() - case []string: - out := "" - for _, s := range x { - out += s + " " +// assertNoValueLogged checks every logged message and field (strings, errors, +// arrays: through ContextMap) for any of the values. +func assertNoValueLogged(t *testing.T, logs *observer.ObservedLogs, values ...string) { + t.Helper() + for _, e := range logs.All() { + line := e.Message + " " + fmt.Sprint(e.ContextMap()) + for _, v := range values { + assert.NotContains(t, line, v, "a value was logged in %q", e.Message) } - return out } - return "" } // Only fields an HTTP upstream receives block the connection; a stdio @@ -127,6 +116,15 @@ func TestUnresolvedSecret_OnlyWireFieldsBlock(t *testing.T) { require.NoError(t, err) assert.NoError(t, c.UnresolvedSecrets()) + // A stdio server never sends its headers, URL or OAuth settings, so a + // stale reference there does not stop it (review r1). + stdioHeaders := &config.ServerConfig{Name: "local-h", Command: "true", URL: "https://x.example/mcp", Protocol: "stdio", Enabled: true, + Headers: map[string]string{"Authorization": "${keyring:missing}"}, + OAuth: &config.OAuthConfig{ClientSecret: "${keyring:missing}"}} + c, err = NewClient(stdioHeaders.Name, stdioHeaders, zap.NewNop(), nil, &config.Config{}, nil, r) + require.NoError(t, err) + assert.NoError(t, c.UnresolvedSecrets(), "a stdio server's headers never reach a wire") + good := &config.ServerConfig{Name: "good", URL: "http://127.0.0.1:1/mcp", Protocol: "http", Enabled: true, Headers: map[string]string{"Authorization": "Bearer ${keyring:ok}"}} c, err = NewClient(good.Name, good, zap.NewNop(), nil, &config.Config{}, nil, r) @@ -151,3 +149,38 @@ func TestUnresolvedSecret_OnlyWireFieldsBlock(t *testing.T) { }) } } + +// With OAuth applicable, both manual sign-in flows stop at the guard: they +// would send the unresolved settings to the authorization server. +func TestUnresolvedWireSecret_SignInFlowsRefused(t *testing.T) { + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusUnauthorized) + })) + t.Cleanup(srv.Close) + cfg := &config.ServerConfig{Name: "f9-oauth", URL: srv.URL + "/mcp", Protocol: "http", Enabled: true, + OAuth: &config.OAuthConfig{ClientID: "id", ClientSecret: "${keyring:missing}"}} + c, err := NewClient(cfg.Name, cfg, zap.NewNop(), nil, &config.Config{}, nil, resolverWith(mapKeyring{})) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _, err = c.StartOAuthFlowQuick(ctx) + assert.True(t, IsUnresolvedSecretError(err), "quick sign-in: %v", err) + _, err = c.ForceOAuthFlowWithResult(ctx) + assert.True(t, IsUnresolvedSecretError(err), "forced sign-in: %v", err) + assert.Contains(t, err.Error(), "in OAuth.ClientSecret") + assert.Equal(t, int32(0), hits.Load(), "nothing sent to the upstream or its authorization server") +} + +// The fix hint matches what recovers: a keyring or file secret is picked up by +// a server restart; an environment variable only by restarting mcpproxy. +func TestUnresolvedSecretError_FixHints(t *testing.T) { + keyring := &UnresolvedSecretError{Server: "s", Refs: []UnresolvedSecretRef{{Field: "Headers[A]", Reference: "${keyring:k}", Type: "keyring", Name: "k"}}} + assert.Contains(t, keyring.Error(), "mcpproxy secrets set k, then restart the server (mcpproxy upstream restart s)") + env := &UnresolvedSecretError{Server: "s", Refs: []UnresolvedSecretRef{{Field: "Headers[A]", Reference: "${env:TOKEN}", Type: "env", Name: "TOKEN"}}} + assert.Contains(t, env.Error(), "Set the environment variable TOKEN and restart mcpproxy") + assert.NotContains(t, env.Error(), "upstream restart") + assert.Equal(t, "TOKEN", health.ExtractMissingSecret(env.Error())) +} From 3baa5d2fcef48e42662e4b003a447eeb26049fd2 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 18 Nov 2026 19:36:50 +0200 Subject: [PATCH 3/4] test(upstream): decide the unresolved-secret gate on the resolved config; poll the disabled-server check --- internal/runtime/unresolved_header_secret_test.go | 6 +++--- internal/upstream/core/client.go | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/internal/runtime/unresolved_header_secret_test.go b/internal/runtime/unresolved_header_secret_test.go index 5e1488db5..62d8065a8 100644 --- a/internal/runtime/unresolved_header_secret_test.go +++ b/internal/runtime/unresolved_header_secret_test.go @@ -222,9 +222,9 @@ func TestNotifySecretsChanged_LeavesDisabledServersDisabled(t *testing.T) { require.NoError(t, rt.storageManager.SaveUpstreamServer(disabled)) require.NoError(t, rt.NotifySecretsChanged(context.Background(), "store", "tok")) - time.Sleep(300 * time.Millisecond) // restarts run in the background - srv := rt.Config().Servers[0] - assert.False(t, srv.Enabled, "storing a secret must not enable a disabled server") + // Restarts run in the background: the server must stay disabled. + assert.Never(t, func() bool { return rt.Config().Servers[0].Enabled }, time.Second, 20*time.Millisecond, + "storing a secret must not enable a disabled server") } func TestServerReferencesSecret_Fields(t *testing.T) { diff --git a/internal/upstream/core/client.go b/internal/upstream/core/client.go index 0a8c17a92..afe809983 100644 --- a/internal/upstream/core/client.go +++ b/internal/upstream/core/client.go @@ -245,7 +245,8 @@ func NewClientWithOptions(id string, serverConfig *config.ServerConfig, logger * errs := secretResolver.ExpandStructSecretsCollectErrors(ctx, resolvedServerConfig) // Only an HTTP-family server sends its URL, headers and OAuth // settings; a stdio server's copies of those fields are never used. - overHTTP := proxytransport.DetermineTransportType(serverConfig) != proxytransport.TransportStdio + // Decided on the resolved copy, exactly as Connect decides. + overHTTP := proxytransport.DetermineTransportType(resolvedServerConfig) != proxytransport.TransportStdio for _, e := range errs { // Log the references only, never the field's value (release QA // F9): the value may hold literal credentials around them. From dc864055d02591825debc7fb6f9f50bf39996c61 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 18 Nov 2026 21:08:43 +0200 Subject: [PATCH 4/4] test(server): isolate the cached-only sweep fixture as in #1918 --- .../server/tpa_bundle_fetch_e2e_stray_test.go | 93 +++++++++++++++++++ internal/server/tpa_bundle_fetch_e2e_test.go | 93 +++++++++++++++++-- 2 files changed, 178 insertions(+), 8 deletions(-) create mode 100644 internal/server/tpa_bundle_fetch_e2e_stray_test.go diff --git a/internal/server/tpa_bundle_fetch_e2e_stray_test.go b/internal/server/tpa_bundle_fetch_e2e_stray_test.go new file mode 100644 index 000000000..530738539 --- /dev/null +++ b/internal/server/tpa_bundle_fetch_e2e_stray_test.go @@ -0,0 +1,93 @@ +package server + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/mark3labs/mcp-go/client" + "github.com/mark3labs/mcp-go/mcp" + mcpserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// #1918 CI run 44349461004: TestTPAFetchLifecycle_ActivatesReprotectsAndRefusesBadReleases +// saw 2 requests on its fake upstream although the sweep never dials it. The +// run logged 1,335 refused `DELETE http://127.0.0.1:` session-close +// requests from clients of earlier tests closing after their servers had gone. +// This reproduces that mechanism deterministically; it does not prove what the +// two historical requests were (the old fixture recorded nothing about them). +// +// A real mcp-go client of an earlier test, holding a session, closes after its +// server's port was reused for the fake upstream: its DELETE reaches the +// upstream at "/" and is recorded as another path, not as a call. Deliberate +// requests to the configured target count whatever their method or headers, +// including a session-carrying DELETE, and so do the OAuth endpoints the proxy +// derives from the target's origin. +func TestTPAFetchFixture_ForeignCloseVersusCallsToTheConfiguredTarget(t *testing.T) { + // An earlier test's MCP server and a client with a live (legacy) session. + mcpSrv := mcpserver.NewMCPServer("earlier-test", "0.0.1", mcpserver.WithToolCapabilities(true)) + mcpSrv.AddTool(mcp.NewTool("noop"), func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return mcp.NewToolResultText("ok"), nil + }) + earlier := httptest.NewServer(mcpserver.NewStreamableHTTPServer(mcpSrv)) + t.Cleanup(earlier.Close) // idempotent; covers an early failure + addr := earlier.Listener.Addr().String() + + c, err := client.NewStreamableHttpClient("http://" + addr) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, c.Start(ctx)) + init := mcp.InitializeRequest{} + init.Params.ProtocolVersion = mcp.LATEST_LEGACY_PROTOCOL_VERSION + init.Params.ClientInfo = mcp.Implementation{Name: "earlier-test-client", Version: "0"} + _, err = c.Initialize(ctx, init) + require.NoError(t, err) + + // That test's server goes away; its port is given to this test's upstream. + earlier.Close() + up := newE2EUpstream(t) + ln, err := net.Listen("tcp", addr) + require.NoError(t, err, "rebinding the freed port") + fake := httptest.NewUnstartedServer(up) + fake.Listener = ln + fake.Start() + t.Cleanup(fake.Close) + + // Injected foreign close: the earlier client closes late. + require.NoError(t, c.Close()) + assert.Equal(t, []string{"DELETE /"}, up.otherRequests(), "the late session close reaches the reused port") + assert.Empty(t, up.callsToTarget(), "it is not a call to this fixture's configured target") + // The old fixture counted every request: this one would have failed the assertion. + + // Deliberate calls to the configured target all count. + do := func(method, path string, header map[string]string) { + req, err := http.NewRequest(method, fake.URL+path, nil) + require.NoError(t, err) + for k, v := range header { + req.Header.Set(k, v) + } + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + _ = resp.Body.Close() + } + do(http.MethodPost, up.target, nil) + do(http.MethodDelete, up.target, map[string]string{"Mcp-Session-Id": "a-session"}) + do(http.MethodGet, "/.well-known/oauth-protected-resource"+up.target, nil) + // Requests the proxy derives from the origin alone count too. + do(http.MethodGet, "/.well-known/oauth-authorization-server", nil) + do(http.MethodPost, "/register", nil) + assert.Equal(t, []string{ + "POST " + up.target, + "DELETE " + up.target, + "GET /.well-known/oauth-protected-resource" + up.target, + "GET /.well-known/oauth-authorization-server", + "POST /register", + }, up.callsToTarget(), "every method and header on the configured target, and origin-derived OAuth endpoints, count") + assert.Equal(t, []string{"DELETE /"}, up.otherRequests()) +} diff --git a/internal/server/tpa_bundle_fetch_e2e_test.go b/internal/server/tpa_bundle_fetch_e2e_test.go index 49e0bd40a..4ef4a8fc3 100644 --- a/internal/server/tpa_bundle_fetch_e2e_test.go +++ b/internal/server/tpa_bundle_fetch_e2e_test.go @@ -4,7 +4,9 @@ import ( "bytes" "context" "crypto/ed25519" + "crypto/rand" "encoding/base64" + "encoding/hex" "encoding/json" "fmt" "net/http" @@ -12,7 +14,6 @@ import ( "os" "strings" "sync" - "sync/atomic" "testing" "time" @@ -209,10 +210,82 @@ type e2eFixture struct { keyID string genAt string upstream *httptest.Server - upCalls atomic.Int64 + up *e2eUpstream acts *e2eActivations } +// e2eUpstream is the fake upstream the re-protection sweep must never reach. +// +// It is configured at a path unique to this fixture (target, a random token). +// A request counts as a call from the proxy under test, whatever its method or +// headers, when its path +// - contains the token: the target itself and path-derived discovery such as +// /.well-known/oauth-protected-resource/; or +// - is one the proxy derives from the origin alone: any /.well-known/ path +// (RFC 8414 / OpenID metadata at the host root) and the default OAuth +// endpoints /authorize, /token and /register (mcp-go getDefaultEndpoints). +// +// Any other request is recorded separately, by method and path only (never +// headers or session IDs), and logged rather than counted: the proxy builds +// no other path from this fixture's config. A likely source is shown by #1918 +// CI run 44349461004, which logged 1,335 refused `DELETE http://127.0.0.1:` +// session-close requests from clients of earlier tests closing after their +// servers were gone; one that reaches a port reused for this upstream is +// answered and never logged, and it never has one of the counted shapes. +type e2eUpstream struct { + target string + + mu sync.Mutex + calls []string // requests to this fixture's configured target + others []string // requests to any other path +} + +func newE2EUpstream(t *testing.T) *e2eUpstream { + t.Helper() + token := make([]byte, 8) + _, err := rand.Read(token) + require.NoError(t, err) + return &e2eUpstream{target: "/mcp-e2e-" + hex.EncodeToString(token)} +} + +func (u *e2eUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + line := r.Method + " " + r.URL.Path + u.mu.Lock() + if u.isProxyCall(r.URL.Path) { + u.calls = append(u.calls, line) + } else { + u.others = append(u.others, line) + } + u.mu.Unlock() + http.Error(w, "the re-protection sweep must never reach an upstream", http.StatusTeapot) +} + +// isProxyCall reports whether the proxy under test could have built path from +// this fixture's config (see e2eUpstream). +func (u *e2eUpstream) isProxyCall(path string) bool { + switch { + case strings.Contains(path, strings.TrimPrefix(u.target, "/")), + strings.HasPrefix(path, "/.well-known/"), + path == "/authorize", path == "/token", path == "/register": + return true + } + return false +} + +// callsToTarget returns the requests the proxy under test could have made. +func (u *e2eUpstream) callsToTarget() []string { + u.mu.Lock() + defer u.mu.Unlock() + return append([]string(nil), u.calls...) +} + +// otherRequests returns the requests to any other path. +func (u *e2eUpstream) otherRequests() []string { + u.mu.Lock() + defer u.mu.Unlock() + return append([]string(nil), u.others...) +} + // e2eActivations records the scanner's activation notifications. type e2eActivations struct { mu sync.Mutex @@ -236,10 +309,14 @@ func newE2EFixture(t *testing.T, fetchPath string, withApprovedTool bool) *e2eFi } f := &e2eFixture{channel: newE2EChannel(t), acts: &e2eActivations{}} - f.upstream = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - f.upCalls.Add(1) - http.Error(w, "the re-protection sweep must never reach an upstream", http.StatusTeapot) - })) + f.up = newE2EUpstream(t) + f.upstream = httptest.NewServer(f.up) + // Registered first so it runs after the upstream is closed (LIFO). + t.Cleanup(func() { + if others := f.up.otherRequests(); len(others) > 0 { + t.Logf("the fake upstream also received %d request(s) on paths this fixture's config does not produce (not counted): %v", len(others), others) + } + }) t.Cleanup(f.upstream.Close) f.priv = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{0x5a}, ed25519.SeedSize)) @@ -262,7 +339,7 @@ func newE2EFixture(t *testing.T, fetchPath string, withApprovedTool bool) *e2eFi work := &config.ServerConfig{ // Disabled so the runtime's own background start never dials it: any // request the fake upstream sees would then come from the sweep. - Name: "work", Enabled: false, Protocol: "http", URL: f.upstream.URL + "/mcp", + Name: "work", Enabled: false, Protocol: "http", URL: f.upstream.URL + f.up.target, TrustMode: string(config.TrustModeManual), } // An operator-decided, unquarantined server: without the explicit mark the @@ -452,7 +529,7 @@ func TestTPAFetchLifecycle_ActivatesReprotectsAndRefusesBadReleases(t *testing.T stored, err := f.rt.StorageManager().GetUpstreamServer("work") require.NoError(t, err) assert.False(t, stored.Quarantined, "the server is not quarantined") - assert.Zero(t, f.upCalls.Load(), "the fake upstream gets zero calls: the sweep is cached-only") + assert.Empty(t, f.up.callsToTarget(), "the fake upstream gets zero calls: the sweep is cached-only (other paths: %v)", f.up.otherRequests()) reg := f.rt.TelemetryRegistry() require.NotNil(t, reg) assert.EqualValues(t, 1, reg.Snapshot().TPABundleReprotectHits, "bundle_reprotect_hits counts the one server")