Repository navigation
feat(oauth): opt-in encryption of upstream OAuth tokens at rest - #1888
Merged
Merged
Conversation
…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.
…I open-site tests (Spec 123)
…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.
…d read-path benchmarks (Spec 123)
…es, isolation caveats (Spec 123)
… 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).
Deploying mcpproxy-docs with
|
| 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 |
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.
CodeQL still traces the token encryption key to the two transport debug lines through the store's type name. The lines now log a boolean, so nothing derived from the store value reaches a log call.
…nce; harden the e2e script
The two save tests matched the reference as raw text. On Windows the reference holds backslashes, which JSON escapes, so the match failed.
…Auth and map it to 409 on login
… row the boot sweep skips
…uth row is undecryptable
… always mask literals
…viour and masking policy
… so health never offers login over an undecryptable row
… recogniser config validation uses
…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
enabled auto-merge (squash)
November 11, 2026 20:05
…reference is valid on Windows
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 43121357573 --repo smart-mcp-proxy/mcpproxy-go
|
…at/oauth-token-encryption # Conflicts: # docs/docker-isolation.md # docs/features/docker-isolation.md # docs/features/oauth-authentication.md
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
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.
1 task done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
oauth_token_encryption_keyin the config, as a literal or one${file:},${env:}or${keyring:}reference.MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEYorMCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY_FILEoverride it. Changing it needs a restart.oauth_tokensrow becomesenc: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.internal/tokenseal, standard library only. No new dependencies.internal/storage. Source tests enforce that, and that everyconfig.dbopen site passes the key.Failure behaviour
MCPX_OAUTH_TOKEN_UNDECRYPTABLEwith health actionconfigure, and no login, DCR or callback server is started for it. Other servers keep working.mcpproxy auth logout --server=<name>discards the row even when the key reference no longer resolves.Decisions worth a look
MCPPROXY_CRED_KEY. The server-edition broker store is untouched.Not in this PR
PR-3 adds the
doctorcheck,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 ofconfig.db; the docs say so.Docs
docs/features/oauth-token-encryption.md, including which key delivery protects against a disk snapshot and which only against a copy ofconfig.db.docs/errors/MCPX_OAUTH_TOKEN_UNDECRYPTABLE.md.Testing
Run locally on macOS:
go build ./...and the server-edition build.go test -raceoninternal/tokenseal,internal/storage,internal/config,internal/runtimeandcmd/mcpproxy: all pass.golangci-lintv2 with.github/.golangci.yml, bare and with--build-tags server: 0 issues../scripts/check-upstream-write-sites.shpasses../scripts/test-api-e2e.sh: 70 passed, 0 failed.scripts/test-oauth-token-encryption-e2e.shagainst the OAuth fixture: no token bytes inconfig.db, logs or REST output with a key set.Not run locally: Windows, and the server-tagged race suites for
internal/serverandinternal/httpapi. CI covers both.Reviewed in four rounds by security, correctness and cross-model reviewers. Every confirmed finding is fixed with a regression test.