Skip to content

feat(secret): secret_file_dirs allow-list for ${file:} and MCPPROXY_API_KEY_FILE, upstream secret guards (#1721) - #1884

Merged
Dumbris merged 32 commits into
smart-mcp-proxy:mainfrom
james-crowley:feat/secret-file-dirs
Nov 24, 2026
Merged

Dumbris merged 32 commits into
smart-mcp-proxy:mainfrom
james-crowley:feat/secret-file-dirs

Conversation

@james-crowley

Copy link
Copy Markdown
Contributor

Closes #1721. Built on #1716 and #1717, against your design of 2026-11-08. Point by point:

  1. Roots. Linux defaults are /run/secrets, /run/credentials and <data-dir>/secrets; on macOS, <data-dir>/secrets. Absent means defaults, [] disables file references, and exactly ["*"] is the compatibility mode, with a startup warning. null, relative roots and mixed wildcard lists are rejected. A missing root warns and stays unavailable. CREDENTIALS_DIRECTORY is honoured for systemd services.
  2. Admin key. A ${file:} in config api_key follows secret_file_dirs. MCPPROXY_API_KEY_FILE is exempt, but refused when it points at the active config file or the data dir, using the real --config path and the effective data dir. Unusable files still fail startup, both-set is still an error, and there is no generated-key fallback.
  3. Env guard. Server-entry expansion refuses the whole MCPPROXY_ namespace, including MCPPROXY_CRED_KEY, with Windows case rules. The proxy's own fields and readers (data_dir, api_key, the server edition's OAuth client config) resolve with a proxy-scoped resolver and are exempt.
  4. Reserved files. An upstream cannot read the active config, the active admin-key source, or the proxy's data files, even under an allowed root or in wildcard mode. This is checked on the opened handle (same file: device and inode), and the targets are stat'ed at read time. So hardlinks, aliases and a config replaced by write + rename are all refused, not only the literal path.
  5. Opening. Containment is checked, then the file is opened through os.Root relative to the matched root, with O_RDONLY|O_NONBLOCK. The handle is fstat'ed as a regular file, the read stays bounded at 64 KiB, and a FIFO returns instead of blocking. go.mod now requires go 1.26.5, the first patched release for GO-2026-4970. Deterministic swap tests use a test-only hook between the check and the open:
    • final file swapped to a symlink outside the root;
    • final file swapped to the admin key inside the root;
    • parent directory swapped to a symlink outside the root;
    • final file swapped to a FIFO.
  6. Platforms. No case folding on macOS. Windows starts with <data-dir>\secrets only. The defaults take GOOS as a parameter, so the macOS and Windows cases run on Linux CI.
  7. Operator policy. secret_file_dirs cannot be set or widened by REST PATCH, config apply/import, or the upstream_servers tool. Every resolver construction site uses the policy from the loaded config, including the CLI paths that expand server entries (call, code, tools, the CLI upstream client), so the daemon and the CLI enforce one policy. Hot reload picks up a changed policy. A server entry whose new or edited reference the policy refuses is rejected before it is saved, on every writer that saves server entries (REST add/PATCH, apply, import, the upstream_servers tool, runtime commit); the connect-time check stays as a second line. The bare secret.NewResolver() is no longer used in production code; tests that need the feat(secret): ${file:/absolute/path} references (Spec 111 FR-030) #1717 wildcard behaviour use NewTestWildcardResolver. Full config-file writers are documented as trusted for v1. data_dir is resolved only against independent roots before its secrets root is added.
  8. Errors. A policy denial keeps the daemon up and stops that upstream from connecting or spawning, with a fixed, safe public error in the health/status payload, the logs and doctor; neither the path nor the value is shown. Proxy-key and data-dir policy failures fail the load. The feat(secret): ${file:/absolute/path} references (Spec 111 FR-030) #1717 rotation/write-back regression still passes, and bad references are validated before saving.

Out of scope, as you asked: #1704 process read isolation and per-server secret delegation.

Tests: paths, platforms (macOS and Windows defaults) and errors; the missing-root and wildcard warnings; an api_key file reference outside the allow-list; policy bypass through each config writer; the admin file inside a root; hardlinks and aliases, including a renamed config and config.db; the env guard across every server-entry field (env, args, headers, url, command, nested isolation and OAuth); the four swap cases; persistence across reload and restart; hot reload; the pre-save refusal per writer; health, /api/v1/servers and doctor showing only the public error; and the proxy-scope exemption.

Checks, with Go 1.26.5:

  • go build ./... and go build -tags server ./...;
  • go test -race on internal/secret, internal/config, internal/upstream/... and cmd/mcpproxy;
  • the server-edition race command from CLAUDE.md;
  • golangci-lint v2.9.0 with .github/.golangci.yml, bare and --build-tags server: 0 issues each, the same as main;
  • ./scripts/test-api-e2e.sh.

TestE2E_CredentialsLifecycle_SecretSinks fails on main here too (3 of 3 runs), so I left it alone.

I'd welcome the security cross-review you mentioned before merge, especially of the read-time identity check (internal/secret/deny_at_read.go) and the resolver sites in cmd/mcpproxy.

…rds (smart-mcp-proxy#1721)

Restrict ${file:} reads to configured roots with os.Root-backed opens, deny
proxy-owned paths for upstream expansion, and block ${env:MCPPROXY_*} in server
entries while exempting operator-controlled MCPPROXY_API_KEY_FILE paths.
Correct the MCPPROXY_ env guard, open secrets with O_NONBLOCK and
handle-based deny checks, block management edits to secret_file_dirs,
fail upstream connect on policy denial, and bump the Go toolchain for
os.Root (GO-2026-4970).
Stat deny targets at open for config/data/admin-key inode identity; add
deterministic pre-open hook tests; refuse secret_file_dirs on POST apply.
NewOAuthHandler used the default upstream resolver and blocked MCPPROXY_
env refs; use ResolveOAuthSecretRef like validation does.
Run ServerSecretPolicyErrors on REST, MCP upstream_servers, and commit
create/update so ${file:}/${env:} policy failures return public errors
without persisting server entries.
Exercise REST/MCP/import writers, commit rejections, loader warnings,
GOOS defaults, Windows reserved-env case fold, and hot-reload resolver rebuild.
Parameterize EffectiveSecretFileDirRoots by GOOS for CI; assert darwin and
windows only get data-dir/secrets, and doctor/REST health show fixed denials.
@codecov-commenter

codecov-commenter commented Nov 11, 2026 •

Copy link
Copy Markdown

…t the merge base

make swagger adds secret_file_dirs to the config schema. scope_latency_test.go is copied onto the
merge-base checkout by the FR-011 gate, so it keeps using secret.NewResolver(), which exists on both
sides, instead of the new test-only constructor.
rejectPlatformAbsolutePath wrongly treated C:\... temp paths as
drive-relative, blocking MCPPROXY_API_KEY_FILE and upstream ${file:} policy.
Block UNC and extended device spellings before file opens so wildcard
secret_file_dirs cannot reach remote SMB or bypass roots; document in keyring guide.
Resolve both sides with EvalSymlinks before containment so 8.3 vs long
paths match; make traversal policy test use tempdir paths on every OS.
Dumbris added a commit that referenced this pull request Nov 18, 2026
…pstream (#1933)

## Description

Release QA finding F9: when a configured upstream HTTP header contained
a `${keyring:...}` reference that could not be resolved, mcpproxy sent
the raw text to the upstream (`Authorization: Bearer ${keyring:name}`),
and the server's health stayed green.

**Cause.** `core.NewClientWithOptions` expands secret references with
`ExpandStructSecretsCollectErrors`. A field that fails keeps its
original value. The failure was only logged, at ERROR, and that log line
also carried the field's full value. Nothing stopped the connection.

**Changes**

- **Refuse before any HTTP request.** A secret reference in the `url`,
the `headers` or the `oauth` settings that cannot be resolved when the
client is built records a `core.UnresolvedSecretError` on the client.
With that error present, the client does not connect (`Connect`), does
not start a sign-in (every manual-login entry point), and does not
refresh a token (`RefreshOAuthTokenDirect`). Nothing is dialled.
- **Actionable error, with no secret values in it.** The error names
each reference that failed and its field, but never a field value. For
example:
`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)`
If a field mixes references, those that resolve are not named. The error
classifies as `MCPX_CONFIG_MISSING_SECRET`.
- **Health.** `health.ExtractMissingSecret` recognises the error, so the
server shows **Missing secret** (`unhealthy`, `needs_secret`) with the
`set_secret` action and the reference name as the detail. It no longer
shows green.
- **Scope.** The refusal applies only to HTTP-family servers
(`DetermineTransportType` on the resolved config, the same decision
`Connect` makes). Each reference that resolves is still substituted, and
other servers are unaffected. A stdio server keeps the existing
behaviour for every field: it never sends its `headers`, `url` or
`oauth` values, and a missing reference in `env`, `args` or
`working_dir` is logged and used as written.
- **Behaviour change.** Any unresolvable `${type:name}` text in an HTTP
server's URL, headers or OAuth settings is now refused rather than sent
literally. That includes `${env:NAME}` for an unset variable. For
`${env:}` the fix hint says to restart mcpproxy, because the env
provider reads mcpproxy's own environment.
- **Logs.** The resolution-failure log names the references only
(`references: ["${keyring:x}"]`), never the field's value.
- **Restart after the secret is added.** `mcpproxy upstream restart`
already builds a new client, which resolves secrets again. Storing a
secret through REST or the Web UI (`NotifySecretsChanged`) restarted
only servers that referenced it in `env` or `args`. It now also restarts
servers that reference it in the URL, headers, working directory or
OAuth settings. It also skips disabled servers, because a restart
enables a disabled server; until now, storing or deleting a secret
re-enabled a disabled stdio server that used it.
- **Docs.** `docs/errors/MCPX_CONFIG_MISSING_SECRET.md` gains "HTTP
upstreams: nothing is sent" and the restart step.

## Testing

- [x] I have tested these changes locally
- [x] I have added/updated tests that prove my fix is effective or my
feature works
- [x] All existing tests pass

`internal/runtime/unresolved_header_secret_test.go` runs through the
normal configuration and connection path (`runtime.New` →
`StartBackgroundInitialization`). It uses a fake keyring and real
streamable-HTTP MCP upstreams that record every request and its headers.
The server under test has `Authorization: Bearer ${keyring:f9-missing}`
(missing) and `X-Present: ${keyring:f9-present}` (present). The test
checks that:
- the unrelated server connects;
- the server with the missing secret sends **no request**;
- its `last_error` names the reference, the field and the fix;
- its health is "Missing secret" / `set_secret` with detail
`f9-missing`.

After the key is added, the server connects with `Bearer <value>` and
the valid `X-Present` substitution. No request ever carries
`${keyring:`. This is run in two subtests: one through `RestartServer`,
one through `NotifySecretsChanged` (storing the secret through the API).
Every log entry is checked for the secret values.

On `main` the same test fails: the upstream received `Authorization:
Bearer ${keyring:f9-missing}`. The API subtest also fails if the header
scan is removed from `serverReferencesSecret`.

`internal/upstream/core/unresolved_secrets_test.go` covers:
- one header mixing literal text, a reference that resolves and a
missing one: only the missing one is named, and neither the literal nor
the resolved value appears in the error or the logs;
- connect, sign-in (guard and quick start) and token refresh: all
refused with zero requests;
- classification and health extraction;
- the URL and `OAuth.ClientSecret` cases;
- a stdio `env` reference and a header whose references all resolve:
neither is blocked.

Race tests pass for `./internal/upstream/...`, `./internal/runtime`,
`./internal/httpapi`, `./internal/secret/...`, `./internal/health/...`,
`./internal/diagnostics/...` and `./internal/config/...`.
`golangci-lint` with `.github/.golangci.yml`, bare and with
`--build-tags=server`, reports 0 new issues.

**Independent review:** an Opus 5.5 agent with fresh context, two
rounds.
- Round 1 found no MAJOR issues and 4 MINOR plus 6 NIT findings. Fixed:
the stdio transport gate, the `${env:}` hint, skipping disabled servers,
the provider reason restored in the log, the log checks covering array
fields, both sign-in flows tested with OAuth applicable, the race
fallback, and the docs.
- Left as they are: transient parking
(`TestTransientCodes_StayRetryable` pins it deliberately) and the gaps
below that predate this PR.
- Round 2: CLEAN. Its two NITs are applied in `3baa5d2fc`.

**Not covered / known gaps:**
- A reference that becomes resolvable later is only picked up by a
restart, or automatically when the secret is stored through REST or the
Web UI. A `mcpproxy secrets set` run while no core is running needs
`mcpproxy upstream restart <server>`; the error says so.
- `secret.Resolver.ExtractConfigSecrets` (the Web UI's secret listing)
does not walk maps, so header references are not listed there. This
predates this PR and is unchanged.
- These gaps predate this PR and are left as follow-ups:
  - `serverReferencesSecret` does not scan the `isolation` fields.
- The server edition's `AuthBroker.ClientSecret` is not expanded on the
broker path.
  - `httpapi.checkMissingSecrets` ignores headers.
- The login REST endpoint answers this refusal with a 500 rather than a
coded 409.
- Related, but a different defect: contributor PR #1884 adds a
`secret_file_dirs` policy for `${file:}` references and its own
connect-time refusal. The two touch nearby code in
`internal/upstream/core`; whichever merges second may need a small
rebase.
Dumbris and others added 13 commits November 23, 2026 19:03
Conflicts: internal/server and internal/upstream test fixtures take main's
newTestUpstreamManager with the wildcard test resolver; secrets_cmd.go takes
main's runSecretsSet with the keyring-only CLI resolver; runtime.go keeps the
load-warning recorder before main's OAuth token key resolution; core/client.go
keeps the policy-denial return before main's reference-only logging; oas
regenerated. go directive kept at main's 1.26.0.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… reads

An upstream ${file:} read now refuses an opened file with more than one
hard link (Stat_t.Nlink on unix, GetFileInformationByHandle NumberOfLinks
on Windows). That covers a hardlink to any live proxy file, including
logs/ and nested data-dir paths the identity list does not enumerate.

A link made to mcp_config.json before a save is not caught by the link
count: after SaveConfig renames a new file over the config, the old inode
(still holding api_key) has exactly one link left. The atomic config
writers now record the identity being replaced (NoteSupersededProxyFile),
and upstream reads refuse those identities for the life of the process.

Review smart-mcp-proxy#2 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ot be decoded

SecretFileDirsManagementEditRefused allowed the edit when the on-disk
config could not be read or decoded, so /config/apply could then set
secret_file_dirs to ["*"]. It now fails closed; a config file that does
not exist yet compares with an unset value.

Review smart-mcp-proxy#6 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…list

NewApplicationContext passed "" as the config path, so with --config
outside data_dir the deny list named <data-dir>/mcp_config.json instead
of the file actually loaded. Use cfg.ConfigFilePathForPolicy(), as the
CLI resolver does.

Review smart-mcp-proxy#8 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ide secret_file_dirs

Before smart-mcp-proxy#1721 any absolute ${file:} path resolved; after it, a reference
outside the allow-list stops resolving. Startup now logs one WARN naming
every upstream server with such a reference (path-only check, no file
read, no keyring access). The CHANGELOG entry moves under Breaking
Changes with a Migration line, and config-file.md / upstream-servers.md
gain the migration paragraph, the hard-link rules, a note that ["*"]
does not protect against a concurrent filesystem writer, and why the
OAuth token encryption key is not gated.

Review smart-mcp-proxy#1 (and the smart-mcp-proxy#4 docs note) on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…rs hot reload

SetSecretResolver wrote Manager.secretResolver with no lock while connect
paths read it, and the runtime's own copy was swapped under r.mu but read
by GetSecretResolver without it. The manager now guards the field with a
RWMutex and the runtime keeps it in an atomic.Pointer.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…not be decoded

The management guard decodes the file, then the save decodes it again to
restore secret_file_dirs from disk. If that second decode failed the save
fell back to the in-memory value, which may carry an edit (e.g. ["*"]).
The save now returns ErrSecretFileDirsUnverified and writes nothing when
the file exists, cannot be decoded and the config sets secret_file_dirs.
A config with the key unset still saves; a missing file is still created.

Cross-review round 1 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
UpstreamFileRefsOutsideAllowList marshalled the whole ServerConfig to
JSON, so a ${file:} inside the opaque auth_broker block (never resolved
in the personal build) warned on every start. secret.StructFileRefPaths
now walks exactly what ExpandStructSecretsCollectErrors walks (parity
test), and the finder uses it.

Cross-review round 1 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… on Windows

os.Stat on Windows fills the file ID lazily, by path, on the first
os.SameFile. The superseded-config list kept such a FileInfo, so after the
rename it named the new config and the protection did nothing on Windows.
Identities are now captured when noted or statted: device and inode on
unix, volume serial and file index from GetFileInformationByHandle on
Windows, and the opened file is compared by its handle's identity. The
live deny list (StatDenyIdentity) uses the same type; it was statted and
compared in one step, so it only had a small window, but it no longer
relies on a lazy load. The superseded list is bounded at 4096 entries
with a set for lookup.

Cross-review round 1 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…file:}

The superseded-config list is in memory, holds 4096 saves and only sees
this process's saves; a link to a rotated or deleted log also ends with
one link. Say plainly that hardlink protection against a local user who
can create links in an allowed directory is best-effort, and note in the
migration text that hardlinked secret files are refused.

Cross-review round 1 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Dumbris and others added 2 commits November 23, 2026 20:17
… and warn on failure

On Windows the identity capture used os.Open, which does not share
DELETE: while another process held the config open with DELETE access the
open failed with a sharing violation and NoteSupersededProxyFile returned
silently, so the replaced config was never recorded. The capture now opens
with CreateFile, FILE_READ_ATTRIBUTES access and FILE_SHARE_READ|WRITE|
DELETE. NoteSupersededProxyFile returns an error for any failure other
than a missing file, and the config writers log one warning naming the
file (base name only) when the identity cannot be recorded.

Cross-review round 2 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…pture

syscall.CreateFile, unlike the os package, does not add the extended-length
prefix, so a config path longer than MAX_PATH failed identity capture. The
path is made absolute and converted by windowsExtendedLengthPath (drive
and UNC forms, paths already in the extended or device namespace left
alone, separators and dot elements cleaned since the prefix turns off
normalization). The helper is pure string logic with a table test that
runs on every platform; a windows-tagged test captures a path over 260
characters.

Cross-review round 3 on smart-mcp-proxy#1884.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Dumbris
Dumbris enabled auto-merge (squash) November 23, 2026 18:24
Dumbris and others added 3 commits November 24, 2026 13:07
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Linux reuses a freed inode (and Windows a file index). The superseded
list recorded device+inode only, so once the replaced mcp_config.json
was deleted, any later file that got its inode was refused as a
"superseded proxy file" for the life of the process. In CI this failed
every Linux test that read a secret file after a SaveConfig test in the
same package process (secret, config, runtime).

Each record now carries the modification time from the same stat (the
same GetFileInformationByHandle call on Windows). A hardlink to the
replaced file keeps that time; a new file at a reused identity does not.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Dumbris
Dumbris merged commit e44b404 into smart-mcp-proxy:main Nov 24, 2026
55 checks passed
@Dumbris

Dumbris commented Nov 24, 2026

Copy link
Copy Markdown
Member

Merged — thank you @james-crowley. This was a large and careful piece of work: the threat model in #1721, the os.Root opens and the identity deny list made it reviewable, and it closes a real gap for anyone running upstream servers they do not fully trust.

What changed on the way in: we merged main twice and added maintainer commits on your branch for the link-count and superseded-identity checks, the fail-closed edit guard, the startup warning for refs outside the allow-list, and the Windows identity path. Your commits are kept as they were. The remaining hardening items are tracked in #2031.

It ships in the next release, with a Breaking Changes note in the changelog and the docs under "secret_file_dirs". If you write about how you use it, we would be glad to link to it — no pressure at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: secret_file_dirs allow-list for ${file:} and MCPPROXY_API_KEY_FILE, plus a guard for ${env:MCPPROXY_API_KEY}

3 participants