Skip to content

feat(oauth): opt-in encryption of upstream OAuth tokens at rest - #1888

Merged
Dumbris merged 47 commits into
mainfrom
feat/oauth-token-encryption
Nov 12, 2026
Merged

Dumbris merged 47 commits into
mainfrom
feat/oauth-token-encryption

Conversation

@Dumbris

@Dumbris Dumbris commented Nov 11, 2026

Copy link
Copy Markdown
Member

Summary

Opt-in encryption at rest for the upstream OAuth records in config.db (access token, refresh token, DCR client secret). This is PR-2 of Spec 123 (#1886). With no key configured, behaviour and the bytes on disk are unchanged.

Refs #1697. Requested by @james-crowley.

How it works

  • Key: oauth_token_encryption_key in the config, as a literal or one ${file:}, ${env:} or ${keyring:} reference. MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY or MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILE override it. Changing it needs a restart.
  • Format: each oauth_tokens row becomes enc:v1:<key id>:<base64 nonce, ciphertext, tag>. AES-256-GCM with an HKDF-SHA256 record key. The key id, bucket name and bucket key are authenticated, so a row cannot be moved to another server.
  • New package: internal/tokenseal, standard library only. No new dependencies.
  • Storage: every read and write of the bucket goes through one codec in internal/storage. Source tests enforce that, and that every config.db open site passes the key.
  • Migration: on start, existing plaintext rows are sealed in one transaction before any OAuth component is built.

Failure behaviour

  • A key that is set but unusable stops the process with exit code 4 before the database is opened. This covers both variables set, a bad reference, an unresolvable reference, and an empty or malformed value.
  • A row that cannot be decrypted is never deleted or overwritten. The server reports MCPX_OAUTH_TOKEN_UNDECRYPTABLE with health action configure, and no login, DCR or callback server is started for it. Other servers keep working.
  • Restoring the key and restarting recovers every server without a browser.
  • If the key is lost, standalone mcpproxy auth logout --server=<name> discards the row even when the key reference no longer resolves.

Decisions worth a look

  • A wrong or missing key degrades per server instead of refusing to start.
  • The environment override beats the config field, and setting both environment variables is an error.
  • There is no fallback to MCPPROXY_CRED_KEY. The server-edition broker store is untouched.

Not in this PR

PR-3 adds the doctor check, mcpproxy auth tokens status|encrypt|decrypt, compaction of freed plaintext pages, and the login pre-flight. Until then, old plaintext can remain in free pages of config.db; the docs say so.

Docs

  • New page docs/features/oauth-token-encryption.md, including which key delivery protects against a disk snapshot and which only against a copy of config.db.
  • New error page docs/errors/MCPX_OAUTH_TOKEN_UNDECRYPTABLE.md.
  • Config and environment tables updated.

Testing

Run locally on macOS:

  • go build ./... and the server-edition build.
  • go test -race on internal/tokenseal, internal/storage, internal/config, internal/runtime and cmd/mcpproxy: all pass.
  • golangci-lint v2 with .github/.golangci.yml, bare and with --build-tags server: 0 issues.
  • ./scripts/check-upstream-write-sites.sh passes.
  • ./scripts/test-api-e2e.sh: 70 passed, 0 failed.
  • New scripts/test-oauth-token-encryption-e2e.sh against the OAuth fixture: no token bytes in config.db, logs or REST output with a key set.

Not run locally: Windows, and the server-tagged race suites for internal/server and internal/httpapi. CI covers both.

Reviewed in four rounds by security, correctness and cross-model reviewers. Every confirmed finding is fixed with a regression test.

…g and sweep tests (Spec 123)

Phase 2 tests first (T010-T016): every write seals under WithOAuthTokenKey, no-key bytes stay golden JSON, writers refuse undecryptable rows while key-only deletes still delete, listing is per-row tolerant, the boot sweep is one transaction, codec and open-site source tests, and a raw-file marker scan with a no-key control.
Phase 2 (T020-T025, FR-010..016): WithOAuthTokenKey open option on NewBoltDB/NewManager; encodeOAuthRecord/decodeOAuthRecord are the only codec of oauth_tokens values; putOAuthRecord seals inside the caller's transaction and sets meta/oauth_seal_compact_advised when it replaces plaintext; typed ErrOAuthTokenUndecryptable refused by every writer that starts from the stored record (SaveOAuthToken now reads first) while key-only deletes keep deleting; per-row tolerant ListOAuthTokens plus ListOAuthTokenRows; orphan cleanup keeps and reports undecryptable rows in one transaction; SealPlaintextOAuthTokens collects then writes in one transaction. Every open site passes WithOAuthTokenKey(nil) until Phase 3 resolves the key.
…en site (Spec 123)

Add the oauth_token_encryption_key config field (secret reference or
literal; MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] override it) and
config.ResolveOAuthTokenKey. Validate checks the reference syntax only;
the key is resolved where config.db is opened (runtime.New, the CLI
open sites, appctx, the upstream CLI client, dev tools). Any selected
source that cannot be resolved, resolves empty or is malformed stops
the process with a *config.StartupError (exit 4) before the database is
opened. The field is restart-gated and pinned, so saves keep the
reference.
…iagnostics code tests (Spec 123)

Phase 4 tests first (T040-T043, T047): the boot sweep seals before the upstream and refresh managers are built; GetToken, HasPersistedToken*, GetPersistedRefreshToken, the login save, the connection OAuth strategies and the proactive refresh return MCPX_OAUTH_TOKEN_UNDECRYPTABLE instead of starting a login; health reports configure, never login; the code has a catalog entry and docs page; a source test pins the read-path inventory.
…CPX_OAUTH_TOKEN_UNDECRYPTABLE (Spec 123)

Phase 4 (T044-T046): runtime.New seals plaintext oauth_tokens rows right after storage opens and before the upstream and refresh managers; GetToken, HasPersistedToken*, GetPersistedRefreshToken, the login save, the connection OAuth strategies, the proactive refresh and the dynamic-OAuth refresh return a coded TokenUndecryptableError instead of no token; health reports unhealthy/configure with the reason, never login; new diagnostics code with catalog entry, classifier rule and docs page; startup orphan cleanup logs kept undecryptable rows.
… recovery docs (Spec 123)

auth logout takes the server only through its required --server flag, so the
positional form on the feature page failed with a usage error during lost-key
recovery. The docs command smoke test now covers this page and rejects a
complete leaf invocation that omits a cobra-required flag.
… (Spec 123)

The Spec 080 shutdown marker must be the first DB operation after the
storage manager opens, so a crash or hang anywhere later in startup reads as
previous_shutdown=crash next time. The Spec 123 boot sweep ran before it, so a
crash loop inside the sweep kept the previous run's clean marker. The marker
is now armed first and the sweep still runs before any OAuth consumer exists;
a new oauth_boot_sweep stage hook lets the regression test observe the order.
…dirs

The key-reference tests used POSIX-rooted literals (/nonexistent/..., /run/credentials/...) that filepath.IsAbs rejects on Windows, so Validate and LoadFromFile failed on the Windows CI leg. Build them from t.TempDir() and skip the symlink case when Windows lacks the privilege.
…ce test

TestOAuthSweep_SealsEveryPlaintextRow checks results only, so a rewrite that seals inside a bucket.ForEach still passed it. The new source test requires every write in SealPlaintextOAuthTokens to sit in a range over the collectOAuthRows slice, forbids a cursor or ForEach in the sweep, and forbids writes in collectOAuthRows (FR-016, T014).
…erence is unresolvable

The documented lost-key recovery is 'mcpproxy auth logout --server=<server>',
but the standalone path went through cli.NewClient, which resolves the OAuth
token key first and refused with exit 4 when the key file or secret mount is
gone. The clear is a key-only delete, so standalone logout now opens config.db
without resolving the key. The docs say that login and startup still need a
readable key and that a new key must be configured before signing in.
Open returned malformed when a cut left an incomplete base64 quantum or a
payload shorter than nonce plus tag, so the reason depended on the cut
length. spec.md defines truncation as auth_failed. A payload that is base64
text (alphabet plus at most two trailing '=') but does not decode, or decodes
too short, now reports auth_failed; non-base64 characters stay malformed.
…s the resolved key

Keeps ClearOAuthTokenForStandaloneLogout inside internal/upstream/cli as the
write-site check requires, and opens config.db with the resolved OAuth token
key whenever it resolves (FR-017); only an unresolvable reference opens with
none, which is safe for the delete-only logout.
…before

With no key configured, SaveOAuthToken refused a corrupt plaintext row as
'cannot be decrypted' where main overwrote it (FR-011 / SC-003). It now
refuses only rows shaped like an envelope (enc: prefix) when no key is set;
with a key every undecodable row is still refused (FR-013).

The boot sweep re-marshalled the typed record, dropping JSON fields this
binary does not know. It now seals through putOAuthRecordKeeping, which
carries over the stored object's unknown top-level fields while still taking
a new revision and setting the compaction marker.
… is unresolvable

Standalone auth logout opened config.db without a key on every key
resolution error. Only a reference that no longer resolves is a lost key.
Both variables set, a bad reference, and an empty or malformed value are
mistakes in a key that is present, so they stop with the startup error
again (Spec 123 FR-022).
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 07fbe9c
Status: ✅  Deploy successful!
Preview URL: https://90af8702.mcpproxy-docs.pages.dev
Branch Preview URL: https://feat-oauth-token-encryption.mcpproxy-docs.pages.dev

View logs

Comment thread internal/tokenseal/tokenseal.go Fixed
Seal sized two buffers from len(plaintext) with no upper bound, which
CodeQL flags as a possible allocation-size overflow. An OAuth record is
a few kilobytes of JSON, so Seal now refuses a plaintext over 1 MiB.
Two debug lines in the HTTP transport passed the token store to
zap.Any. The store reaches config.db and now the OAuth token encryption
key, so CodeQL reports the key flowing to a log call. The lines log the
store's type instead.
Comment thread internal/transport/http.go Fixed
Comment thread internal/transport/http.go Fixed
The two save tests matched the reference as raw text. On Windows the
reference holds backslashes, which JSON escapes, so the match failed.
… so health never offers login over an undecryptable row
…very limits, health JSON fields and login refusal channels
…y references

GetAllServers read the call-time OAuth flag twice, so a concurrent tool
call could make health offer login over a row that was never probed. It
is now read once per server. The key reference recogniser accepted an
unclosed nested form such as ${env:${env:KEY} and config output showed
it unmasked; a name containing ${ is not a reference. The error page
states which cases restoring the key recovers.
@Dumbris
Dumbris enabled auto-merge (squash) November 11, 2026 20:05
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: feat/oauth-token-encryption

Available Artifacts

  • archive-darwin-amd64 (32 MB)
  • archive-darwin-arm64 (29 MB)
  • archive-linux-amd64 (20 MB)
  • archive-linux-arm64 (18 MB)
  • archive-windows-amd64 (32 MB)
  • archive-windows-arm64 (28 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (28 MB)
  • installer-dmg-darwin-arm64 (26 MB)
  • smart-mcp-proxymcpproxy-goZQFJNA.dockerbuild (0 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 43121357573 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

…at/oauth-token-encryption

# Conflicts:
#	docs/docker-isolation.md
#	docs/features/docker-isolation.md
#	docs/features/oauth-authentication.md
@codecov-commenter

codecov-commenter commented Nov 12, 2026 •

Copy link
Copy Markdown

@Dumbris
Dumbris merged commit 5babcfc into main Nov 12, 2026
67 of 68 checks passed
Dumbris added a commit that referenced this pull request Nov 12, 2026
… for encrypted OAuth tokens (#1891)

## Summary

Spec 123 PR-3: the operator surfaces for the encrypted upstream OAuth
rows that #1888 introduced. Refs #1697.

- **Doctor / diagnostics**: `mcpproxy doctor` prints an OAuth Token
Storage section, and `GET /api/v1/diagnostics` carries it as
`data.oauth_token_storage` (row counts by class, key source, compaction
advice, leftover `config.db.bak`, warnings). Each undecryptable server
also appears once in the runtime warnings.
- **`mcpproxy auth tokens status|encrypt [--dry-run]|decrypt --yes
[--leave-undecryptable]`**: offline commands for the rows. Exit 3 when
the core holds `config.db`, 4 with no or an unusable key, 1 when rows
remain.
- **`mcpproxy db compact --keep-backup=false`** clears the
compaction-advised marker; a retained backup is reported separately.
- **Login pre-flight**: `auth login` explains an undecryptable row
instead of starting a flow that cannot be stored, standalone (reads the
row) and through the daemon (matches the current row's bucket key).
`auth status` shows the state distinctly.
- **Web UI**: no sign-in button for a server whose stored token cannot
be decrypted.
- **Docs**: `docs/features/oauth-token-encryption.md` (doctor output,
commands, rotation, compaction, packaged service, container, downgrade),
`docs/cli/command-reference.md`, `docs/cli/db-commands.md`,
`docs/api/rest-api.md`, `docs/errors/MCPX_OAUTH_TOKEN_UNDECRYPTABLE.md`.

No new dependencies.

## Decisions worth a second look

- `auth tokens decrypt` refuses up front when any row cannot be opened,
unless `--leave-undecryptable` is passed (it then still exits 1).
- `auth tokens decrypt` leaves the compaction marker untouched; only `db
compact --keep-backup=false` clears it. The marker is cleared even when
an older `config.db.bak` exists, as the spec says; the backup is
reported on its own (`stale_backup_path`, warning
`backup_file_present`).
- A standalone `auth login` no longer falls back to in-memory storage
when `config.db` cannot be opened; it stops with the open error (exit 3
for a locked database).
- `status` and `--dry-run` are documented as "change no OAuth row"
rather than read-only, because opening the database can run open-time
maintenance.
- The `systemd-run ... LoadCredential=` example for a credential-only
key was written from the systemd documentation and has not been run on a
live systemd host.

## Testing

- `go test -race ./cmd/mcpproxy/ ./internal/management/...
./internal/storage/... ./internal/upstream/cli/...
./internal/httpapi/... ./internal/oauth/... ./internal/config/...
./internal/tokenseal/...`
- `golangci-lint` v2 with `.github/.golangci.yml`, bare and
`--build-tags server`
- `./scripts/test-oauth-token-encryption-e2e.sh` (status / decrypt /
encrypt / compact round trip with raw `config.db` scans, including a
control that the token text is still in freed pages before the no-backup
compaction)
- `frontend/tests/unit/oauth-undecryptable-signin.spec.ts`
Dumbris added a commit that referenced this pull request Nov 20, 2026
`roadmap.yaml` had no epics after Spec 117. This PR adds them and
regenerates `ROADMAP.md`.

- **Shipped:** 118 auto-rescan (#1689), 118 pin visibility boundary
(#1684, #1688, #1821), 119 (#1740), 120 (#1781), 122 (#1818) and 123
(#1886, #1887, #1888, #1891).
- **In review:** 121 install surfaces (#1711). There is no `spec:` link
yet because its folder exists only on the PR branch.
- **In progress:** 124 (PR-1 #1918 done; PR-2 CLI and PR-3 Web UI to do)
and 125 (spec plus PR-1..3 done; PR-4 Web UI to do). Merged PRs are
listed as done child tasks, so `--check-github` doesn't flag a merged PR
under an in-progress epic.
- **Spec-only PRs:** 127 (#1943), 128 (#1944) and 129 (#1945).

Merge this after #1943, #1944 and #1945. Until then, `--check-github`
reports their `spec:` links as unresolved; `--check`, the pre-commit
hook, passes.

Not covered: Spec 126 (#1940, open) and the unsynced tasks.md checkboxes
for 123 and 124.
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.

3 participants