From 4465bde56db700b6adfd6d5c68a13174e7bad012 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 24 Nov 2026 21:20:46 +0200 Subject: [PATCH 1/4] fix(secret): secret_file_dirs hardening follow-ups Bounded data-dir identity walk, doctor/diagnostics finding for ${file:} refs outside the allow-list, startup warning for unusable roots, stderr warning for standalone CLI saves, refuse saves over an undecodable file holding secret_file_dirs, pin tests for wildcard swap and the api_key override lookup. refs #2031 Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + docs/configuration/config-file.md | 2 +- docs/configuration/upstream-servers.md | 18 ++++- internal/config/load_warnings.go | 25 +++++- internal/config/loader.go | 3 + .../config/loader_secret_warnings_test.go | 26 ++++++ internal/config/process_overrides.go | 23 +++++- internal/config/secret_file_dirs.go | 33 ++++++++ .../secret_file_dirs_undecodable_test.go | 58 ++++++++++++++ internal/config/superseded_config.go | 2 +- internal/config/superseded_config_test.go | 18 +++++ internal/management/diagnostics.go | 26 ++++++ .../management/diagnostics_file_refs_test.go | 62 ++++++++++++++ internal/secret/deny_at_read.go | 66 ++++++++------- internal/secret/file_policy_deep_deny_test.go | 80 +++++++++++++++++++ 15 files changed, 405 insertions(+), 38 deletions(-) create mode 100644 internal/config/secret_file_dirs_undecodable_test.go create mode 100644 internal/management/diagnostics_file_refs_test.go create mode 100644 internal/secret/file_policy_deep_deny_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 60b74e9c8..68ca348a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 `` (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 `/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 `/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) diff --git a/docs/configuration/config-file.md b/docs/configuration/config-file.md index f3c54d934..d439a3b13 100644 --- a/docs/configuration/config-file.md +++ b/docs/configuration/config-file.md @@ -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 `/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 `/secrets` if you use it), or move the file under `/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 `/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 `/secrets` if you use it), or move the file under `/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. diff --git a/docs/configuration/upstream-servers.md b/docs/configuration/upstream-servers.md index e986cb184..814d81c75 100644 --- a/docs/configuration/upstream-servers.md +++ b/docs/configuration/upstream-servers.md @@ -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 `` (except under `/secrets`) -- Regular files one level below `/certs`, `/index.bleve`, or `/tpa-lkg` (not deeper subtrees) +- Regular files in the subdirectories of ``, except `/secrets`. The identity comparison walks the data directory breadth-first with a fixed budget (8 levels, 4096 directory entries per read, shallow entries first), so its cost does not grow with the data directory. A file beyond the budget is still refused by path (anything under `` 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 @@ -389,9 +389,19 @@ 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 such a swap onto a proxy file +or a hard-linked file is refused; 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 diff --git a/internal/config/load_warnings.go b/internal/config/load_warnings.go index 41c55132d..2400ff571 100644 --- a/internal/config/load_warnings.go +++ b/internal/config/load_warnings.go @@ -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) @@ -51,3 +56,21 @@ 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.RLock() + noRecorder := loadWarnRecorder == nil + loadWarnMu.RUnlock() + if noRecorder { + fmt.Fprintf(loadWarningStderr, "warning: %s (%s=%s)\n", message, key, value) + } + emitLoadWarning(message, key, value) +} diff --git a/internal/config/loader.go b/internal/config/loader.go index 93cae5dd9..47de3b097 100644 --- a/internal/config/loader.go +++ b/internal/config/loader.go @@ -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", "*") } diff --git a/internal/config/loader_secret_warnings_test.go b/internal/config/loader_secret_warnings_test.go index 88bc18ada..98a319e5a 100644 --- a/internal/config/loader_secret_warnings_test.go +++ b/internal/config/loader_secret_warnings_test.go @@ -1,6 +1,7 @@ package config import ( + "os" "path/filepath" "testing" @@ -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") +} diff --git a/internal/config/process_overrides.go b/internal/config/process_overrides.go index 3c64813c5..68c00d1f9 100644 --- a/internal/config/process_overrides.go +++ b/internal/config/process_overrides.go @@ -1,8 +1,10 @@ package config import ( + "encoding/json" "errors" "io/fs" + "os" "reflect" "sort" "sync" @@ -505,6 +507,25 @@ 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 that is not even a JSON object holds no +// readable 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 { + return false + } + _, ok := top["secret_file_dirs"] + return ok +} + // 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 @@ -525,7 +546,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 { diff --git a/internal/config/secret_file_dirs.go b/internal/config/secret_file_dirs.go index c2ef11a1a..b2397e2d2 100644 --- a/internal/config/secret_file_dirs.go +++ b/internal/config/secret_file_dirs.go @@ -216,6 +216,39 @@ 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) + 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 != "" { diff --git a/internal/config/secret_file_dirs_undecodable_test.go b/internal/config/secret_file_dirs_undecodable_test.go new file mode 100644 index 000000000..3429df073 --- /dev/null +++ b/internal/config/secret_file_dirs_undecodable_test.go @@ -0,0 +1,58 @@ +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) +} diff --git a/internal/config/superseded_config.go b/internal/config/superseded_config.go index 9be3166c3..de4c4a145 100644 --- a/internal/config/superseded_config.go +++ b/internal/config/superseded_config.go @@ -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)) } } diff --git a/internal/config/superseded_config_test.go b/internal/config/superseded_config_test.go index f283919ef..ff215d188 100644 --- a/internal/config/superseded_config_test.go +++ b/internal/config/superseded_config_test.go @@ -1,6 +1,7 @@ package config import ( + "bytes" "os" "path/filepath" "testing" @@ -28,3 +29,20 @@ func TestNoteSupersededConfig_WarnsOnCaptureFailure(t *testing.T) { assert.Equal(t, MsgSupersededConfigNotRecorded, got[0].msg) assert.Equal(t, "cfg-dir", got[0].value, "file name only, never the full path or contents") } + +// A standalone CLI save installs no recorder; the warning must still reach the +// operator on stderr. +func TestNoteSupersededConfig_PrintsToStderrWithoutRecorder(t *testing.T) { + SetLoadWarningRecorder(nil) + var buf bytes.Buffer + prev := loadWarningStderr + loadWarningStderr = &buf + t.Cleanup(func() { loadWarningStderr = prev; DrainLoadWarnings() }) + + blocked := filepath.Join(t.TempDir(), "cfg-dir") + require.NoError(t, os.Mkdir(blocked, 0o700)) + noteSupersededConfig(blocked) + assert.Contains(t, buf.String(), MsgSupersededConfigNotRecorded) + assert.Contains(t, buf.String(), "cfg-dir") + assert.NotContains(t, buf.String(), filepath.Dir(blocked), "file name only") +} diff --git a/internal/management/diagnostics.go b/internal/management/diagnostics.go index e795fc9d6..86ba742f9 100644 --- a/internal/management/diagnostics.go +++ b/internal/management/diagnostics.go @@ -309,6 +309,14 @@ func (s *service) Doctor(ctx context.Context) (*contracts.Diagnostics, error) { diag.RuntimeWarnings = append(diag.RuntimeWarnings, warning) } + // #2031: upstream ${file:} references that secret_file_dirs refuses. The + // startup WARN is gone from the log by now; this keeps the finding in + // doctor and GET /api/v1/diagnostics. Server names only (never paths), and + // a scoped caller sees only the servers it may enumerate. + if warning, ok := s.fileRefsOutsideAllowListWarning(ctx); ok { + diag.RuntimeWarnings = append(diag.RuntimeWarnings, warning) + } + // Spec 123 FR-030: the OAuth token storage section, and one runtime // warning per undecryptable server so the issue count and tray badge // reflect it. Optional: a runtime that cannot report leaves it out. @@ -430,3 +438,21 @@ func getStringFromMap(m map[string]interface{}, key string) string { } return "" } + +// fileRefsOutsideAllowListWarning builds the doctor line for upstream servers +// whose ${file:} references secret_file_dirs refuses by path. +func (s *service) fileRefsOutsideAllowListWarning(ctx context.Context) (string, bool) { + if s.config == nil { + return "", false + } + var visible []string + for _, name := range config.UpstreamFileRefsOutsideAllowList(s.config) { + if auth.CanEnumerateServer(ctx, name) { + visible = append(visible, name) + } + } + if len(visible) == 0 { + return "", false + } + return fmt.Sprintf("%s: %s", config.MsgUpstreamFileRefsOutsideAllowList, strings.Join(visible, ", ")), true +} diff --git a/internal/management/diagnostics_file_refs_test.go b/internal/management/diagnostics_file_refs_test.go new file mode 100644 index 000000000..ba0903335 --- /dev/null +++ b/internal/management/diagnostics_file_refs_test.go @@ -0,0 +1,62 @@ +package management + +import ( + "context" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// #2031: ${file:} references outside secret_file_dirs are a doctor finding +// (and so a GET /api/v1/diagnostics runtime warning), not only a startup WARN. +func TestDoctor_FileRefsOutsideAllowList(t *testing.T) { + root := t.TempDir() + allowed := filepath.Join(root, "ok") + dirs := config.SecretFileDirs{allowed} + cfg := &config.Config{ + DataDir: filepath.Join(root, "data"), + SecretFileDirs: &dirs, + Servers: []*config.ServerConfig{ + {Name: "alpha", Env: map[string]string{"K": "${file:" + filepath.Join(root, "elsewhere", "k") + "}"}}, + {Name: "delta", Env: map[string]string{"K": "${file:" + filepath.Join(root, "other", "k") + "}"}}, + {Name: "fine", Env: map[string]string{"K": "${file:" + filepath.Join(allowed, "k") + "}"}}, + }, + } + rt := newMockRuntime() + svc := NewService(rt, cfg, "", &mockEventEmitter{}, nil, nopSugar()).(*service) + + diag, err := svc.Doctor(auth.WithAuthContext(context.Background(), auth.AdminContext())) + require.NoError(t, err) + require.Len(t, diag.RuntimeWarnings, 1) + w := diag.RuntimeWarnings[0] + assert.Contains(t, w, "alpha") + assert.Contains(t, w, "delta") + assert.NotContains(t, w, "fine") + assert.NotContains(t, w, root, "paths are never shown") + assert.Equal(t, 1, diag.TotalIssues) + + scoped := auth.WithAuthContext(context.Background(), &auth.AuthContext{ + Type: auth.AuthTypeAgent, AllowedServers: []string{"delta"}, + }) + diag, err = svc.Doctor(scoped) + require.NoError(t, err) + require.Len(t, diag.RuntimeWarnings, 1) + assert.Contains(t, diag.RuntimeWarnings[0], "delta") + assert.NotContains(t, diag.RuntimeWarnings[0], "alpha") +} + +func TestDoctor_NoFileRefWarningInWildcardMode(t *testing.T) { + dirs := config.SecretFileDirs{"*"} + cfg := &config.Config{SecretFileDirs: &dirs, Servers: []*config.ServerConfig{ + {Name: "alpha", Env: map[string]string{"K": "${file:/etc/k}"}}, + }} + svc := NewService(newMockRuntime(), cfg, "", &mockEventEmitter{}, nil, nopSugar()).(*service) + diag, err := svc.Doctor(auth.WithAuthContext(context.Background(), auth.AdminContext())) + require.NoError(t, err) + assert.Empty(t, diag.RuntimeWarnings) +} diff --git a/internal/secret/deny_at_read.go b/internal/secret/deny_at_read.go index 8aa61f70b..0de35cb2f 100644 --- a/internal/secret/deny_at_read.go +++ b/internal/secret/deny_at_read.go @@ -5,17 +5,22 @@ import ( "path/filepath" ) -// dataDirStateSubdirs are data-dir children that hold proxy state files. Files -// directly inside these directories are refused (not deeper nesting). The -// secrets/ subtree is always excluded. -var dataDirStateSubdirs = []string{ - "certs", - "index.bleve", - "tpa-lkg", -} +// The data directory is walked breadth-first for files to compare with the +// opened handle. Cost must not depend on how large the data dir has grown +// (the Bleve index holds many segment files), so the walk has fixed budgets: +// at most maxDenyWalkDepth directory levels and maxDenyWalkEntries directory +// entries per read, shallow entries first. A file beyond the budget is still +// refused by path containment (deniedByPath) and, when it has another name, +// by the link-count rule; only a path swapped to it after those checks goes +// unmatched, which the budget trades for a bounded cost. +const ( + maxDenyWalkDepth = 8 + maxDenyWalkEntries = 4096 +) // denyPathsAtRead returns filesystem paths to stat for handle identity checks. -// Paths are fresh on every read so renames and new inodes are caught. +// Paths are fresh on every read so renames and new inodes are caught. The +// secrets/ subtree is always excluded. func (p *FilePolicy) denyPathsAtRead() []string { if p == nil || p.Scope != ScopeUpstream { return nil @@ -28,34 +33,35 @@ func (p *FilePolicy) denyPathsAtRead() []string { if p.Deny.DataDir == "" { return uniqueAbsPaths(paths) } - entries, err := os.ReadDir(p.Deny.DataDir) - if err != nil { - return uniqueAbsPaths(paths) + type level struct { + dir string + depth int } - for _, e := range entries { - name := e.Name() - if name == "secrets" { + queue := []level{{p.Deny.DataDir, 1}} + budget := maxDenyWalkEntries + for len(queue) > 0 && budget > 0 { + cur := queue[0] + queue = queue[1:] + entries, err := os.ReadDir(cur.dir) + if err != nil { continue } - full := filepath.Join(p.Deny.DataDir, name) - if !e.IsDir() { - paths = append(paths, full) - continue - } - for _, sub := range dataDirStateSubdirs { - if name != sub { + for _, e := range entries { + if budget == 0 { + break + } + budget-- + full := filepath.Join(cur.dir, e.Name()) + if cur.depth == 1 && e.Name() == "secrets" { continue } - subEntries, err := os.ReadDir(full) - if err != nil { - break + if !e.IsDir() { + paths = append(paths, full) + continue } - for _, se := range subEntries { - if !se.IsDir() { - paths = append(paths, filepath.Join(full, se.Name())) - } + if cur.depth < maxDenyWalkDepth { + queue = append(queue, level{full, cur.depth + 1}) } - break } } return uniqueAbsPaths(paths) diff --git a/internal/secret/file_policy_deep_deny_test.go b/internal/secret/file_policy_deep_deny_test.go new file mode 100644 index 000000000..1182ca088 --- /dev/null +++ b/internal/secret/file_policy_deep_deny_test.go @@ -0,0 +1,80 @@ +//go:build unix + +package secret + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +// A proxy state file nested deeper than the old "top level plus three named +// subdirectories" walk must still be refused by identity when a path swap +// (symlink) lands the handle on it after the path checks. +func TestReadFileWithPolicy_DeepDataDirFileRefusedByIdentity(t *testing.T) { + root := t.TempDir() + dataDir := filepath.Join(root, "data") + deep := filepath.Join(dataDir, "a", "b", "c", "d", "state.db") + require.NoError(t, os.MkdirAll(filepath.Dir(deep), 0o700)) + require.NoError(t, os.WriteFile(deep, []byte("proxy-state\n"), 0o600)) + require.NoError(t, os.MkdirAll(filepath.Join(dataDir, "secrets"), 0o700)) + + other := filepath.Join(root, "other") + require.NoError(t, os.Mkdir(other, 0o700)) + target := filepath.Join(other, "token") + require.NoError(t, os.WriteFile(target, []byte("ok\n"), 0o600)) + + for _, wildcard := range []bool{false, true} { + t.Run(fmt.Sprintf("wildcard=%v", wildcard), func(t *testing.T) { + policy := &FilePolicy{ + Wildcard: wildcard, AllowedRoots: []string{other}, Scope: ScopeUpstream, + Deny: DenyPaths{DataDir: dataDir, DataSecretsDir: filepath.Join(dataDir, "secrets")}, + } + require.NoError(t, os.WriteFile(target, []byte("ok\n"), 0o600)) + SetBeforeSecretOpenHookForTest(func() { + require.NoError(t, os.Remove(target)) + require.NoError(t, os.Symlink(deep, target)) + }) + t.Cleanup(func() { SetBeforeSecretOpenHookForTest(nil) }) + _, err := ReadFileWithPolicy(target, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) + }) + } +} + +// The walk is bounded: a data dir with more files than the entry budget costs +// at most the budget in stats, never the whole tree. +func TestDenyPathsAtRead_WalkIsBounded(t *testing.T) { + dataDir := t.TempDir() + sub := filepath.Join(dataDir, "big") + require.NoError(t, os.Mkdir(sub, 0o700)) + for i := 0; i < maxDenyWalkEntries+200; i++ { + require.NoError(t, os.WriteFile(filepath.Join(sub, fmt.Sprintf("f%05d", i)), nil, 0o600)) + } + require.NoError(t, os.WriteFile(filepath.Join(dataDir, "top.db"), nil, 0o600)) + p := &FilePolicy{Scope: ScopeUpstream, Deny: DenyPaths{DataDir: dataDir}} + paths := p.denyPathsAtRead() + require.LessOrEqual(t, len(paths), maxDenyWalkEntries+1) + require.Contains(t, paths, filepath.Join(dataDir, "top.db"), "shallow files come first") +} + +// Wildcard mode binds the deny check to the opened descriptor: a path swapped +// to the config after the path-level checks is still refused. +func TestReadFileWithPolicy_WildcardSwapToConfigRefused(t *testing.T) { + root := t.TempDir() + cfg := filepath.Join(root, "mcp_config.json") + require.NoError(t, os.WriteFile(cfg, []byte(`{"api_key":"k"}`), 0o600)) + target := filepath.Join(root, "token") + require.NoError(t, os.WriteFile(target, []byte("ok\n"), 0o600)) + policy := &FilePolicy{Wildcard: true, Scope: ScopeUpstream, Deny: DenyPaths{ConfigFile: cfg}} + SetBeforeSecretOpenHookForTest(func() { + require.NoError(t, os.Remove(target)) + require.NoError(t, os.Symlink(cfg, target)) + }) + t.Cleanup(func() { SetBeforeSecretOpenHookForTest(nil) }) + _, err := ReadFileWithPolicy(target, policy) + require.ErrorIs(t, err, ErrSecretFileDenied) +} From fe575fd199cdef8890f39899e4ac52b24adef98c Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 24 Nov 2026 21:59:58 +0200 Subject: [PATCH 2/4] fix(secret): keep original deny coverage unbudgeted, bound directory reads, case-insensitive key guard Review round 1 (Sol 6.2): the shared walk budget could starve the state directories the old walk always compared; os.ReadDir enumerated whole directories; the undecodable-file guard missed upper-case keys and a file with a syntax error after the setting. refs #2031 Co-Authored-By: Claude Sonnet 5.5 --- docs/configuration/upstream-servers.md | 2 +- internal/config/process_overrides.go | 20 +++- .../secret_file_dirs_undecodable_test.go | 15 +++ internal/secret/deny_at_read.go | 111 +++++++++++++----- internal/secret/file_policy_deep_deny_test.go | 31 +++++ 5 files changed, 146 insertions(+), 33 deletions(-) diff --git a/docs/configuration/upstream-servers.md b/docs/configuration/upstream-servers.md index 814d81c75..7968b4c69 100644 --- a/docs/configuration/upstream-servers.md +++ b/docs/configuration/upstream-servers.md @@ -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 `` (except under `/secrets`) -- Regular files in the subdirectories of ``, except `/secrets`. The identity comparison walks the data directory breadth-first with a fixed budget (8 levels, 4096 directory entries per read, shallow entries first), so its cost does not grow with the data directory. A file beyond the budget is still refused by path (anything under `` other than `secrets/`) and by the link-count rule; only a path swapped to it after those checks goes unmatched +- Proxy state files under `` (except `/secrets`). Files directly in ``, `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 does not grow with the data directory. A file beyond the budget is still refused by path (anything under `` 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 diff --git a/internal/config/process_overrides.go b/internal/config/process_overrides.go index 68c00d1f9..d23e436b1 100644 --- a/internal/config/process_overrides.go +++ b/internal/config/process_overrides.go @@ -1,12 +1,14 @@ package config import ( + "bytes" "encoding/json" "errors" "io/fs" "os" "reflect" "sort" + "strings" "sync" ) @@ -511,19 +513,27 @@ var ErrSecretFileDirsUnverified = errors.New("config file cannot be decoded; ref // 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 that is not even a JSON object holds no -// readable setting and may be overwritten, so a repair save stays possible. +// 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 { + 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 } - _, ok := top["secret_file_dirs"] - return ok + // 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. + return bytes.Contains(bytes.ToLower(data), []byte(`"secret_file_dirs"`)) } // persistableConfigWithEdits is PersistableConfigWithEdits for the save path: diff --git a/internal/config/secret_file_dirs_undecodable_test.go b/internal/config/secret_file_dirs_undecodable_test.go index 3429df073..685bf1c8e 100644 --- a/internal/config/secret_file_dirs_undecodable_test.go +++ b/internal/config/secret_file_dirs_undecodable_test.go @@ -56,3 +56,18 @@ func TestRunningAPIKeyFromReference_NoEntryOrLiteralKey(t *testing.T) { 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) + } +} diff --git a/internal/secret/deny_at_read.go b/internal/secret/deny_at_read.go index 0de35cb2f..18e874104 100644 --- a/internal/secret/deny_at_read.go +++ b/internal/secret/deny_at_read.go @@ -5,19 +5,30 @@ import ( "path/filepath" ) -// The data directory is walked breadth-first for files to compare with the -// opened handle. Cost must not depend on how large the data dir has grown -// (the Bleve index holds many segment files), so the walk has fixed budgets: -// at most maxDenyWalkDepth directory levels and maxDenyWalkEntries directory -// entries per read, shallow entries first. A file beyond the budget is still -// refused by path containment (deniedByPath) and, when it has another name, -// by the link-count rule; only a path swapped to it after those checks goes +// Two passes pick the files compared with the opened handle. +// +// Pass 1 is the original, unbudgeted coverage: every non-directory entry +// directly in the data dir, and every non-directory entry directly in certs/, +// index.bleve/ and tpa-lkg/. It cannot be starved by anything below. +// +// Pass 2 extends it deeper. Its cost must not depend on how large the data dir +// has grown (the Bleve index holds many segment files), so it has fixed +// budgets: at most maxDenyWalkDepth directory levels and maxDenyWalkEntries +// directory entries per read, read in bounded batches (a huge directory is +// never enumerated whole), shallow entries first. It lists only regular files +// and never follows symlinks. A file beyond the budget is still refused by +// path containment (deniedByPath) and, when it has another name, by the +// link-count rule; only a path swapped to it after those checks goes // unmatched, which the budget trades for a bounded cost. const ( maxDenyWalkDepth = 8 maxDenyWalkEntries = 4096 ) +// dataDirStateSubdirs are data-dir children whose direct files are always +// compared (pass 1). +var dataDirStateSubdirs = []string{"certs", "index.bleve", "tpa-lkg"} + // denyPathsAtRead returns filesystem paths to stat for handle identity checks. // Paths are fresh on every read so renames and new inodes are caught. The // secrets/ subtree is always excluded. @@ -33,38 +44,84 @@ func (p *FilePolicy) denyPathsAtRead() []string { if p.Deny.DataDir == "" { return uniqueAbsPaths(paths) } - type level struct { - dir string - depth int + + // Pass 1. + entries, err := os.ReadDir(p.Deny.DataDir) + if err != nil { + return uniqueAbsPaths(paths) + } + var queue []denyWalkLevel + for _, e := range entries { + name := e.Name() + if name == "secrets" { + continue + } + full := filepath.Join(p.Deny.DataDir, name) + if !e.IsDir() { + paths = append(paths, full) + continue + } + queue = append(queue, denyWalkLevel{full, 2}) + for _, sub := range dataDirStateSubdirs { + if name != sub { + continue + } + if subEntries, err := os.ReadDir(full); err == nil { + for _, se := range subEntries { + if !se.IsDir() { + paths = append(paths, filepath.Join(full, se.Name())) + } + } + } + break + } } - queue := []level{{p.Deny.DataDir, 1}} + + // Pass 2: breadth-first from the data dir's subdirectories (their direct + // children were read in pass 1 only for the three state directories). budget := maxDenyWalkEntries for len(queue) > 0 && budget > 0 { cur := queue[0] queue = queue[1:] - entries, err := os.ReadDir(cur.dir) - if err != nil { - continue + budget = walkDenyDir(cur, budget, &paths, &queue) + } + return uniqueAbsPaths(paths) +} + +type denyWalkLevel struct { + dir string + depth int +} + +// walkDenyDir reads up to budget entries of one directory in batches and +// returns the budget left. +func walkDenyDir(cur denyWalkLevel, budget int, paths *[]string, queue *[]denyWalkLevel) int { + d, err := os.Open(cur.dir) + if err != nil { + return budget + } + defer d.Close() + for budget > 0 { + batch := budget + if batch > 256 { + batch = 256 } + entries, err := d.ReadDir(batch) for _, e := range entries { - if budget == 0 { - break - } budget-- full := filepath.Join(cur.dir, e.Name()) - if cur.depth == 1 && e.Name() == "secrets" { - continue - } - if !e.IsDir() { - paths = append(paths, full) - continue - } - if cur.depth < maxDenyWalkDepth { - queue = append(queue, level{full, cur.depth + 1}) + switch { + case e.Type().IsRegular(): + *paths = append(*paths, full) + case e.IsDir() && cur.depth < maxDenyWalkDepth: + *queue = append(*queue, denyWalkLevel{full, cur.depth + 1}) } } + if err != nil || len(entries) == 0 { + break + } } - return uniqueAbsPaths(paths) + return budget } func uniqueAbsPaths(paths []string) []string { diff --git a/internal/secret/file_policy_deep_deny_test.go b/internal/secret/file_policy_deep_deny_test.go index 1182ca088..452c8bda4 100644 --- a/internal/secret/file_policy_deep_deny_test.go +++ b/internal/secret/file_policy_deep_deny_test.go @@ -78,3 +78,34 @@ func TestReadFileWithPolicy_WildcardSwapToConfigRefused(t *testing.T) { _, err := ReadFileWithPolicy(target, policy) require.ErrorIs(t, err, ErrSecretFileDenied) } + +// A large early-sorting directory must not use up the budget before the +// state directories that were always compared (certs, index.bleve, tpa-lkg). +func TestDenyPathsAtRead_StateDirsNotStarvedByBudget(t *testing.T) { + dataDir := t.TempDir() + big := filepath.Join(dataDir, "aaa-big") + require.NoError(t, os.Mkdir(big, 0o700)) + for i := 0; i < maxDenyWalkEntries+50; i++ { + require.NoError(t, os.WriteFile(filepath.Join(big, fmt.Sprintf("f%05d", i)), nil, 0o600)) + } + lkg := filepath.Join(dataDir, "tpa-lkg") + require.NoError(t, os.Mkdir(lkg, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(lkg, "bundle.json"), nil, 0o600)) + p := &FilePolicy{Scope: ScopeUpstream, Deny: DenyPaths{DataDir: dataDir}} + require.Contains(t, p.denyPathsAtRead(), filepath.Join(lkg, "bundle.json")) +} + +// The deeper pass lists regular files only: a symlink below the data dir is +// not followed into the deny set. +func TestDenyPathsAtRead_DeepPassIgnoresSymlinks(t *testing.T) { + root := t.TempDir() + dataDir := filepath.Join(root, "data") + allowed := filepath.Join(root, "allowed") + require.NoError(t, os.MkdirAll(filepath.Join(dataDir, "sub"), 0o700)) + require.NoError(t, os.Mkdir(allowed, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(allowed, "k"), nil, 0o600)) + link := filepath.Join(dataDir, "sub", "link") + require.NoError(t, os.Symlink(filepath.Join(allowed, "k"), link)) + p := &FilePolicy{Scope: ScopeUpstream, Deny: DenyPaths{DataDir: dataDir}} + require.NotContains(t, p.denyPathsAtRead(), link) +} From 976e153db883afd4b2183ce6d6ca68ac9194d8b0 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 24 Nov 2026 22:05:32 +0200 Subject: [PATCH 3/4] fix(management): file-ref doctor warning follows the live config; docs accuracy Review round 1 (Sol 6.2, chunk 4). refs #2031 Co-Authored-By: Claude Sonnet 5.5 --- docs/configuration/upstream-servers.md | 9 ++++--- internal/management/diagnostics.go | 11 ++++++-- .../management/diagnostics_file_refs_test.go | 26 +++++++++++++++++++ 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/docs/configuration/upstream-servers.md b/docs/configuration/upstream-servers.md index 7968b4c69..a9ffad098 100644 --- a/docs/configuration/upstream-servers.md +++ b/docs/configuration/upstream-servers.md @@ -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 `` (except under `/secrets`) -- Proxy state files under `` (except `/secrets`). Files directly in ``, `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 does not grow with the data directory. A file beyond the budget is still refused by path (anything under `` other than `secrets/`) and by the link-count rule; only a path swapped to it after those checks goes unmatched +- Proxy state files under `` (except `/secrets`). Files directly in ``, `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 `` 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 @@ -392,9 +392,10 @@ Keep allowed directories writable only by the account that runs mcpproxy. `["*"]` 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 such a swap onto a proxy file -or a hard-linked file is refused; the allow-list mode additionally opens through -the allowed root. +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 diff --git a/internal/management/diagnostics.go b/internal/management/diagnostics.go index 86ba742f9..71bc8f8b1 100644 --- a/internal/management/diagnostics.go +++ b/internal/management/diagnostics.go @@ -442,11 +442,18 @@ func getStringFromMap(m map[string]interface{}, key string) string { // fileRefsOutsideAllowListWarning builds the doctor line for upstream servers // whose ${file:} references secret_file_dirs refuses by path. func (s *service) fileRefsOutsideAllowListWarning(ctx context.Context) (string, bool) { - if s.config == nil { + // The live config (it changes on hot reload), when the runtime offers it. + cfg := s.config + if lc, ok := s.runtime.(interface{ Config() *config.Config }); ok { + if live := lc.Config(); live != nil { + cfg = live + } + } + if cfg == nil { return "", false } var visible []string - for _, name := range config.UpstreamFileRefsOutsideAllowList(s.config) { + for _, name := range config.UpstreamFileRefsOutsideAllowList(cfg) { if auth.CanEnumerateServer(ctx, name) { visible = append(visible, name) } diff --git a/internal/management/diagnostics_file_refs_test.go b/internal/management/diagnostics_file_refs_test.go index ba0903335..4dc1ca9fe 100644 --- a/internal/management/diagnostics_file_refs_test.go +++ b/internal/management/diagnostics_file_refs_test.go @@ -60,3 +60,29 @@ func TestDoctor_NoFileRefWarningInWildcardMode(t *testing.T) { require.NoError(t, err) assert.Empty(t, diag.RuntimeWarnings) } + +type liveConfigRuntime struct { + *mockRuntimeOperations + live *config.Config +} + +func (r *liveConfigRuntime) Config() *config.Config { return r.live } + +// After a hot reload the finding follows the live config, not the boot one. +func TestDoctor_FileRefWarningFollowsLiveConfig(t *testing.T) { + root := t.TempDir() + ref := "${file:" + filepath.Join(root, "elsewhere", "k") + "}" + srv := func() []*config.ServerConfig { + return []*config.ServerConfig{{Name: "alpha", Env: map[string]string{"K": ref}}} + } + boot := config.SecretFileDirs{filepath.Join(root, "ok")} + bootCfg := &config.Config{DataDir: filepath.Join(root, "data"), SecretFileDirs: &boot, Servers: srv()} + widened := config.SecretFileDirs{filepath.Join(root, "elsewhere")} + liveCfg := &config.Config{DataDir: filepath.Join(root, "data"), SecretFileDirs: &widened, Servers: srv()} + + rt := &liveConfigRuntime{mockRuntimeOperations: newMockRuntime(), live: liveCfg} + svc := NewService(rt, bootCfg, "", &mockEventEmitter{}, nil, nopSugar()).(*service) + diag, err := svc.Doctor(auth.WithAuthContext(context.Background(), auth.AdminContext())) + require.NoError(t, err) + assert.Empty(t, diag.RuntimeWarnings, "the reloaded allow-list now covers the reference") +} From 2ba4796eb904e40180a4444fc6957bc7a040b51c Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 24 Nov 2026 22:36:28 +0200 Subject: [PATCH 4/4] =?UTF-8?q?fix(secret):=20review=20round=202=20?= =?UTF-8?q?=E2=80=94=20charge=20empty=20dirs,=20atomic=20stderr=20fallback?= =?UTF-8?q?,=20ELOOP=20chains,=20escaped=20keys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- internal/config/load_warnings.go | 14 ++++++++------ internal/config/process_overrides.go | 4 +++- internal/config/secret_file_dirs.go | 7 +++++++ .../secret_file_dirs_undecodable_test.go | 10 ++++++++++ internal/secret/deny_at_read.go | 1 + internal/secret/file_policy_deep_deny_test.go | 19 +++++++++++++++++++ 6 files changed, 48 insertions(+), 7 deletions(-) diff --git a/internal/config/load_warnings.go b/internal/config/load_warnings.go index 2400ff571..44edbdd9a 100644 --- a/internal/config/load_warnings.go +++ b/internal/config/load_warnings.go @@ -66,11 +66,13 @@ var loadWarningStderr io.Writer = os.Stderr // 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.RLock() - noRecorder := loadWarnRecorder == nil - loadWarnMu.RUnlock() - if noRecorder { - fmt.Fprintf(loadWarningStderr, "warning: %s (%s=%s)\n", message, key, value) + loadWarnMu.Lock() + defer loadWarnMu.Unlock() + if loadWarnRecorder != nil { + loadWarnRecorder(message, key, value) + return } - emitLoadWarning(message, key, value) + // %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}) } diff --git a/internal/config/process_overrides.go b/internal/config/process_overrides.go index d23e436b1..ecc6539c1 100644 --- a/internal/config/process_overrides.go +++ b/internal/config/process_overrides.go @@ -533,7 +533,9 @@ func fileMayHoldSecretFileDirs(path string) bool { // 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. - return bytes.Contains(bytes.ToLower(data), []byte(`"secret_file_dirs"`)) + // 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: diff --git a/internal/config/secret_file_dirs.go b/internal/config/secret_file_dirs.go index b2397e2d2..673766654 100644 --- a/internal/config/secret_file_dirs.go +++ b/internal/config/secret_file_dirs.go @@ -233,6 +233,13 @@ func UnusableSecretFileDirRoots(cfg *Config) []string { 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 diff --git a/internal/config/secret_file_dirs_undecodable_test.go b/internal/config/secret_file_dirs_undecodable_test.go index 685bf1c8e..733cd184b 100644 --- a/internal/config/secret_file_dirs_undecodable_test.go +++ b/internal/config/secret_file_dirs_undecodable_test.go @@ -71,3 +71,13 @@ func TestPersistableConfig_UndecodableFileKeyDetection(t *testing.T) { 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) +} diff --git a/internal/secret/deny_at_read.go b/internal/secret/deny_at_read.go index 18e874104..f9062bb8c 100644 --- a/internal/secret/deny_at_read.go +++ b/internal/secret/deny_at_read.go @@ -96,6 +96,7 @@ type denyWalkLevel struct { // walkDenyDir reads up to budget entries of one directory in batches and // returns the budget left. func walkDenyDir(cur denyWalkLevel, budget int, paths *[]string, queue *[]denyWalkLevel) int { + budget-- // an empty or unreadable directory still costs its open d, err := os.Open(cur.dir) if err != nil { return budget diff --git a/internal/secret/file_policy_deep_deny_test.go b/internal/secret/file_policy_deep_deny_test.go index 452c8bda4..b70288fa4 100644 --- a/internal/secret/file_policy_deep_deny_test.go +++ b/internal/secret/file_policy_deep_deny_test.go @@ -33,6 +33,7 @@ func TestReadFileWithPolicy_DeepDataDirFileRefusedByIdentity(t *testing.T) { Wildcard: wildcard, AllowedRoots: []string{other}, Scope: ScopeUpstream, Deny: DenyPaths{DataDir: dataDir, DataSecretsDir: filepath.Join(dataDir, "secrets")}, } + _ = os.Remove(target) // a previous subtest left a symlink here require.NoError(t, os.WriteFile(target, []byte("ok\n"), 0o600)) SetBeforeSecretOpenHookForTest(func() { require.NoError(t, os.Remove(target)) @@ -109,3 +110,21 @@ func TestDenyPathsAtRead_DeepPassIgnoresSymlinks(t *testing.T) { p := &FilePolicy{Scope: ScopeUpstream, Deny: DenyPaths{DataDir: dataDir}} require.NotContains(t, p.denyPathsAtRead(), link) } + +// Empty directories are not free: each visit costs budget, so thousands of +// them cannot force unbounded opens on every read. +func TestDenyPathsAtRead_EmptyDirsCostBudget(t *testing.T) { + dataDir := t.TempDir() + for i := 0; i < maxDenyWalkEntries+100; i++ { + require.NoError(t, os.Mkdir(filepath.Join(dataDir, fmt.Sprintf("d%05d", i)), 0o700)) + } + p := &FilePolicy{Scope: ScopeUpstream, Deny: DenyPaths{DataDir: dataDir}} + budget := maxDenyWalkEntries + var paths []string + var queue []denyWalkLevel + for i := 0; i < maxDenyWalkEntries+100 && budget > 0; i++ { + budget = walkDenyDir(denyWalkLevel{filepath.Join(dataDir, fmt.Sprintf("d%05d", i)), 2}, budget, &paths, &queue) + } + require.Equal(t, 0, budget) + _ = p +}