Skip to content
Open
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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ Releases follow [Semantic Versioning](https://semver.org/).

### Bug Fixes

- **secret: `secret_file_dirs` hardening follow-ups (#2031).** Upstream `${file:}` reads compare the opened file with proxy files anywhere under `<data-dir>` (bounded breadth-first walk), not only the top level and three subdirectories; `mcpproxy doctor` and `GET /api/v1/diagnostics` list servers whose `${file:}` references are outside `secret_file_dirs`; a `secret_file_dirs` entry that is not a directory or cannot be resolved gets a startup warning; the "could not record the identity of the config file" warning is printed on stderr by a standalone CLI save; a save no longer drops a `secret_file_dirs` key from a config file it could not decode.
- **Core no longer burns a CPU core while idle on installs with many held tool changes (#1724).** The per-tool change-gate scan (`trust_mode: scan` approval, and the hold evidence in `manual`) fed every other connected server's tools to the detector as cross-server context and then ran all checks, phrase/regex detection included, over that whole fleet for each held tool, discarding the peer findings afterwards. With a few hundred tools and a few dozen held changes each 5-minute discovery pass re-scanned tools × fleet (one report: 471 tools, 108 held, ~11 minutes at 100% CPU per pass). The detector now inspects only the scanned server's tools; peers stay in the cross-server index so the shadowing and impersonation checks see the same context and the verdict for the scanned tool is unchanged. One held-tool scan against a 470-tool fleet went from ~3 s to ~5 ms.
- **`serve --data-dir` (and `MCPPROXY_DATA_DIR`) now reads `<data-dir>/mcp_config.json`.** Until now `serve` looked for its config only in the working directory and `$HOME/.mcpproxy` and applied the data dir afterwards, so a config on a mounted volume was ignored and a fresh one (new listen address, new API key) was written under `$HOME`, while every management command already read the config from the data dir. `serve` now resolves it the same way: an explicit `--config` wins, then `<data-dir>/mcp_config.json` if it exists, and on a first run with no config anywhere the default is seeded inside the data dir. `MCPPROXY_DATA_DIR`, documented but never implemented, now works as an alias of `--data-dir` (the legacy `MCPPROXY_DATA` keeps relocating only the data directory, and loses when both are set). If you already export `MCPPROXY_DATA_DIR`, it takes effect for the first time on this upgrade: the data directory, and so the database, search index and socket, move to it. **Migration:** an instance started with `--data-dir X` that relied on the config under `$HOME/.mcpproxy` while a stale `X/mcp_config.json` also exists will now read the one in `X`.
- **audit: a profile tool-policy refusal now names its rule (#1703).** The `authz` audit line for a call refused by a profile's tier cap, deny rule or unannotated-tool policy used to read `reason: other`; it now reads `profile_tier`, `profile_rule` or `profile_unannotated` (`disclosed: true`), matching the `block_reason` of the same call in the activity log. A refusal inside a `code_execution` script used to be written as `token_scope` with `disclosed: false` and now uses the same three reasons. `profile_scope` is unchanged, and `profile_code_execution` / `profile_management` are not audit reasons because those built-in tools are not audited per call. The `reason` enum in `docs/schemas/audit-line-v1.schema.json` gains the three members, so a consumer that validates audit lines against the enum must accept them. (refs #1703)
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration/config-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ If `CREDENTIALS_DIRECTORY` is set to an absolute path (systemd user credentials,

Validation rejects JSON `null`, relative paths, and a list that mixes `*` with other entries. A configured root that does not exist yet produces a startup warning; reads under that root fail until the directory appears.

**Upgrading (breaking change):** releases before #1721 resolved any absolute `${file:}` path in an upstream server entry. After the upgrade, a reference outside the effective allow-list stops resolving and that server fails to connect; with the key omitted, macOS and Windows allow only `<data-dir>/secrets`. Startup logs one warning naming every affected server (`upstream ${file:} references are outside secret_file_dirs and will not resolve`). **Migration:** add the file's directory to `secret_file_dirs` in this file (an explicit list replaces the platform defaults, so include `<data-dir>/secrets` if you use it), or move the file under `<data-dir>/secrets`. A secret file with more than one hard link is refused, so copy a hardlinked secret instead of linking it. `["*"]` restores the old behaviour for every path; the upstream deny rules still apply, but it does not protect against a concurrent filesystem writer swapping a symlink between the check and the open.
**Upgrading (breaking change):** releases before #1721 resolved any absolute `${file:}` path in an upstream server entry. After the upgrade, a reference outside the effective allow-list stops resolving and that server fails to connect; with the key omitted, macOS and Windows allow only `<data-dir>/secrets`. Startup logs one warning naming every affected server (`upstream ${file:} references are outside secret_file_dirs and will not resolve`). **Migration:** add the file's directory to `secret_file_dirs` in this file (an explicit list replaces the platform defaults, so include `<data-dir>/secrets` if you use it), or move the file under `<data-dir>/secrets`. A secret file with more than one hard link is refused, so copy a hardlinked secret instead of linking it. `["*"]` restores the old behaviour for every path; the upstream deny rules still apply, but there is no allowed root to hold the open inside, so a concurrent writer can retarget a path between the check and the open (the deny rules are still decided on the opened file).

**OAuth token encryption key:** `oauth_token_encryption_key` and `MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE` are proxy-owned operator keys, like `MCPPROXY_API_KEY_FILE`, and are **not** gated by `secret_file_dirs`: the recommended key location is outside `data_dir` (see [OAuth Token Encryption](/features/oauth-token-encryption)), and the key is never shown or sent anywhere, so an unreadable or wrong file only stops startup with exit code 4.

Expand Down
19 changes: 15 additions & 4 deletions docs/configuration/upstream-servers.md
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ upstream-scoped read refuses:

- The active config file and the active admin API key source file(s)
- Regular files directly under `<data-dir>` (except under `<data-dir>/secrets`)
- Regular files one level below `<data-dir>/certs`, `<data-dir>/index.bleve`, or `<data-dir>/tpa-lkg` (not deeper subtrees)
- Proxy state files under `<data-dir>` (except `<data-dir>/secrets`). Files directly in `<data-dir>`, `certs`, `index.bleve` and `tpa-lkg` are always compared with the opened file. Deeper regular files are compared too, within a fixed budget (8 levels, 4096 directory entries per read, shallow first, symlinks not followed), so the cost of that deeper pass does not grow with the data directory (the first pass reads each of those four directories once, as before). A file beyond the budget is still refused by path (anything under `<data-dir>` other than `secrets/`) and by the link-count rule; only a path swapped to it after those checks goes unmatched
- Any file with more than one hard link
- An earlier version of the config file that this process replaced on save, when a hardlink to it was made before the save

Expand All @@ -389,9 +389,20 @@ same is true of a hardlink to a log file that has since been rotated or
deleted: once the original name is gone, the link is the file's only link.
Keep allowed directories writable only by the account that runs mcpproxy.

`["*"]` resolves the path and then opens it by path, so it does not protect
against a concurrent filesystem writer that swaps a symlink in between; the
allow-list mode opens through the allowed root and does.
`["*"]` resolves the path and then opens it by path, so there is no allowed root to
hold the open inside: a concurrent filesystem writer can still point the path
somewhere else between the check and the open. The refusals above are decided on the
opened file itself (its identity and link count), so a swap onto the config, the admin
key source, a file in the first-pass directories or a hard-linked file is refused. A
single-link proxy state file beyond the scan budget described above is the one case a
swap can still reach; the allow-list mode additionally opens through the allowed root.

`mcpproxy doctor` and `GET /api/v1/diagnostics` list the upstream servers whose
`${file:}` references are outside `secret_file_dirs` as a runtime warning (server
names only; a scoped token sees only its own servers). A `secret_file_dirs` entry
that does not exist, or exists but is not a directory or cannot be resolved, is
named in a startup warning. A save that cannot record the identity of the config
file it replaces prints that warning on standard error when no core is running.

#### Policy denials vs load failures

Expand Down
27 changes: 26 additions & 1 deletion internal/config/load_warnings.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package config

import "sync"
import (
"fmt"
"io"
"os"
"sync"
)

// LoadWarningRecorder receives non-fatal messages from config loading.
type LoadWarningRecorder func(message string, key string, value string)
Expand Down Expand Up @@ -51,3 +56,23 @@ func DrainLoadWarnings() []LoadWarning {
pendingLoadWarnings = nil
return out
}

// loadWarningStderr is where emitLoadWarningVisible writes when no recorder is
// installed. A variable so tests can capture it.
var loadWarningStderr io.Writer = os.Stderr

// emitLoadWarningVisible is emitLoadWarning for a warning that must not be lost
// in a process that never installs a recorder (a standalone CLI save): with no
// recorder it also prints one line to stderr. The warning is still queued, so
// a core that installs its recorder later logs it too.
func emitLoadWarningVisible(message, key, value string) {
loadWarnMu.Lock()
defer loadWarnMu.Unlock()
if loadWarnRecorder != nil {
loadWarnRecorder(message, key, value)
return
}
// %q: the value can be a file name, which may carry control characters.
fmt.Fprintf(loadWarningStderr, "warning: %s (%s=%q)\n", message, key, value)
pendingLoadWarnings = append(pendingLoadWarnings, pendingWarning{message, key, value})
}
3 changes: 3 additions & 0 deletions internal/config/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ func LoadFromFile(configPath string) (*Config, error) {
for _, root := range WarnMissingSecretFileDirRoots(cfg) {
emitLoadWarning("secret_file_dirs root does not exist yet", "secret_file_dirs", root)
}
for _, root := range UnusableSecretFileDirRoots(cfg) {
emitLoadWarning(MsgSecretFileDirsRootUnusable, "secret_file_dirs", root)
}
if cfg.SecretFileDirs != nil && SecretFileDirsWildcard([]string(*cfg.SecretFileDirs)) {
emitLoadWarning("secret_file_dirs is wildcard compatibility mode", "secret_file_dirs", "*")
}
Expand Down
26 changes: 26 additions & 0 deletions internal/config/loader_secret_warnings_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

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

Expand Down Expand Up @@ -56,3 +57,28 @@ func hasLoadWarning(rec []LoadWarning, message, value string) bool {
}
return false
}

func TestLoad_WarnsUnresolvableSecretFileDirRoot(t *testing.T) {
dir := t.TempDir()
notDir := filepath.Join(dir, "a-file")
require.NoError(t, os.WriteFile(notDir, []byte("x"), 0o600))
loopA, loopB := filepath.Join(dir, "loop-a"), filepath.Join(dir, "loop-b")
if err := os.Symlink(loopB, loopA); err != nil {
t.Skipf("symlinks unavailable: %v", err)
}
require.NoError(t, os.Symlink(loopA, loopB))
cfg := &Config{DataDir: dir, Listen: "127.0.0.1:8080", SecretFileDirs: &SecretFileDirs{notDir, loopA}}
path := filepath.Join(dir, ConfigFileName)
require.NoError(t, SaveConfig(cfg, path))

var rec []LoadWarning
SetLoadWarningRecorder(func(message, key, value string) {
rec = append(rec, LoadWarning{Message: message, Key: key, Value: value})
})
t.Cleanup(func() { SetLoadWarningRecorder(nil) })

_, err := LoadFromFile(path)
require.NoError(t, err)
assert.True(t, hasLoadWarning(rec, MsgSecretFileDirsRootUnusable, notDir), "a file is not a directory")
assert.True(t, hasLoadWarning(rec, MsgSecretFileDirsRootUnusable, loopA), "a symlink loop cannot be resolved")
}
35 changes: 34 additions & 1 deletion internal/config/process_overrides.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package config

import (
"bytes"
"encoding/json"
"errors"
"io/fs"
"os"
"reflect"
"sort"
"strings"
"sync"
)

Expand Down Expand Up @@ -505,6 +509,35 @@ func PersistableConfigWithEdits(effective, mergeBase *Config, path string) *Conf
// value the file never held.
var ErrSecretFileDirsUnverified = errors.New("config file cannot be decoded; refusing to save secret_file_dirs it does not hold")

// fileMayHoldSecretFileDirs reports whether the file at path, which could not
// be decoded as a config, still shows a secret_file_dirs key (or cannot be
// read at all, so nothing shows it does not). A save that dropped the key
// would turn an explicit setting (for instance [] = file references off) back
// into the platform default. A file whose text does not even mention the key
// holds no setting and may be overwritten, so a repair save stays possible.
func fileMayHoldSecretFileDirs(path string) bool {
data, err := os.ReadFile(path)
if err != nil {
return true
}
var top map[string]json.RawMessage
if json.Unmarshal(data, &top) == nil {
// The decoder matches keys case-insensitively, so this must too.
for k := range top {
if strings.EqualFold(k, "secret_file_dirs") {
return true
}
}
return false
}
// Not a JSON object (a trailing comma after the setting, say): the loader
// cannot read it either, but the text may still hold the key. Fail closed
// when the quoted key appears anywhere in it.
// A JSON escape can spell the key (\u005f for "_"), so any escape counts.
lower := bytes.ToLower(data)
return bytes.Contains(lower, []byte(`"secret_file_dirs"`)) || bytes.Contains(lower, []byte(`\u`))
}

// persistableConfigWithEdits is PersistableConfigWithEdits for the save path:
// it fails closed (ErrSecretFileDirsUnverified) where the comparison helper
// would fall back to the in-memory value. A missing file is not an error (the
Expand All @@ -525,7 +558,7 @@ func persistableConfigWithEdits(effective, mergeBase *Config, path string) (*Con
case err == nil:
base = onDisk
case !errors.Is(err, fs.ErrNotExist):
unverified = effective.SecretFileDirs != nil
unverified = effective.SecretFileDirs != nil || fileMayHoldSecretFileDirs(path)
}
}
if unverified {
Expand Down
40 changes: 40 additions & 0 deletions internal/config/secret_file_dirs.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,46 @@ func WarnMissingSecretFileDirRoots(cfg *Config) []string {
return missing
}

// MsgSecretFileDirsRootUnusable is the load warning for a secret_file_dirs
// entry that exists (or cannot be shown not to) but cannot serve as a root: it
// is not a directory, or its path cannot be resolved (loop, permission).
const MsgSecretFileDirsRootUnusable = "secret_file_dirs root cannot be resolved to a directory and will not let any file through"

// UnusableSecretFileDirRoots returns the configured entries that are neither
// missing (see WarnMissingSecretFileDirRoots) nor a resolvable directory.
func UnusableSecretFileDirRoots(cfg *Config) []string {
if cfg == nil || cfg.SecretFileDirs == nil || SecretFileDirsWildcard([]string(*cfg.SecretFileDirs)) {
return nil
}
var bad []string
for _, root := range []string(*cfg.SecretFileDirs) {
if !filepath.IsAbs(root) {
continue // rejected by validation
}
fi, err := os.Stat(root)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
// A long symlink chain makes Stat fail with ELOOP while the
// resolved path works, and the read policy resolves first.
if resolved, rerr := filepath.EvalSymlinks(root); rerr == nil {
fi, err = os.Stat(resolved)
}
}
switch {
case err != nil && errors.Is(err, fs.ErrNotExist):
continue
case err != nil:
bad = append(bad, root)
case !fi.IsDir():
bad = append(bad, root)
default:
if _, err := filepath.EvalSymlinks(root); err != nil {
bad = append(bad, root)
}
}
}
return bad
}

// ResolveConfigPath returns the effective on-disk config path.
func ResolveConfigPath(cfg *Config, configPath string) string {
if configPath != "" {
Expand Down
83 changes: 83 additions & 0 deletions internal/config/secret_file_dirs_undecodable_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package config

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

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

// An unrelated save, from a config that carries no secret_file_dirs, must not
// write the file back without a key the file holds but could not be decoded.
func TestPersistableConfig_RefusesWhenUndecodableFileHoldsSecretFileDirs(t *testing.T) {
ResetProcessOverrides()
t.Cleanup(ResetProcessOverrides)
dir := t.TempDir()
path := filepath.Join(dir, ConfigFileName)
// "listen" has the wrong type, so the file cannot be decoded, yet it
// plainly holds secret_file_dirs: [] (file references off).
require.NoError(t, os.WriteFile(path, []byte(`{"secret_file_dirs": [], "listen": 5}`), 0o600))

_, err := persistableConfigWithEdits(&Config{DataDir: dir, Listen: "127.0.0.1:8080"}, nil, path)
assert.ErrorIs(t, err, ErrSecretFileDirsUnverified)
}

func TestPersistableConfig_UndecodableFileWithoutTheKeyStillSaves(t *testing.T) {
ResetProcessOverrides()
t.Cleanup(ResetProcessOverrides)
dir := t.TempDir()
path := filepath.Join(dir, ConfigFileName)
for name, body := range map[string]string{
"no key, bad type": `{"listen": 5}`,
"not json at all": `{{{`,
} {
require.NoError(t, os.WriteFile(path, []byte(body), 0o600), name)
_, err := persistableConfigWithEdits(&Config{DataDir: dir, Listen: "127.0.0.1:8080"}, nil, path)
assert.NoError(t, err, name+": a repair save must stay possible")
}
}

// runningAPIKeyFromReference reads the override registry with a type
// assertion on a map value. An absent entry yields a nil interface; the
// comma-ok assertion must report "no" rather than panic (#2031).
func TestRunningAPIKeyFromReference_NoEntryOrLiteralKey(t *testing.T) {
ResetProcessOverrides()
t.Cleanup(ResetProcessOverrides)

v, ok := runningAPIKeyFromReference()
assert.False(t, ok)
assert.Empty(t, v)

cfg := &Config{APIKey: "literal-key"}
OverrideForProcess(cfg, FieldAPIKey, OverrideSourceEnv, "env-key")
v, ok = runningAPIKeyFromReference()
assert.False(t, ok, "a literal file value is not a reference")
assert.Empty(t, v)
}

func TestPersistableConfig_UndecodableFileKeyDetection(t *testing.T) {
ResetProcessOverrides()
t.Cleanup(ResetProcessOverrides)
dir := t.TempDir()
path := filepath.Join(dir, ConfigFileName)
for name, body := range map[string]string{
"upper-case key (decoder is case-insensitive)": `{"SECRET_FILE_DIRS": [], "listen": 5}`,
"trailing comma after the setting": `{"secret_file_dirs": [], "listen": "127.0.0.1:8080",}`,
} {
require.NoError(t, os.WriteFile(path, []byte(body), 0o600), name)
_, err := persistableConfigWithEdits(&Config{DataDir: dir, Listen: "127.0.0.1:8080"}, nil, path)
assert.ErrorIs(t, err, ErrSecretFileDirsUnverified, name)
}
}

func TestPersistableConfig_EscapedKeyInMalformedFileRefuses(t *testing.T) {
ResetProcessOverrides()
t.Cleanup(ResetProcessOverrides)
dir := t.TempDir()
path := filepath.Join(dir, ConfigFileName)
require.NoError(t, os.WriteFile(path, []byte(`{"secret_file_dirs": [],}`), 0o600))
_, err := persistableConfigWithEdits(&Config{DataDir: dir, Listen: "127.0.0.1:8080"}, nil, path)
assert.ErrorIs(t, err, ErrSecretFileDirsUnverified)
}
2 changes: 1 addition & 1 deletion internal/config/superseded_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ const MsgSupersededConfigNotRecorded = "could not record the identity of the con
// file only, when that fails.
func noteSupersededConfig(path string) {
if err := secret.NoteSupersededProxyFile(path); err != nil {
emitLoadWarning(MsgSupersededConfigNotRecorded, "config_file", filepath.Base(path))
emitLoadWarningVisible(MsgSupersededConfigNotRecorded, "config_file", filepath.Base(path))
}
}
Loading