Skip to content

docs(spec): Spec 123 encrypt upstream OAuth tokens at rest - #1886

Merged
Dumbris merged 5 commits into
mainfrom
123-oauth-token-encryption
Nov 11, 2026
Merged

Dumbris merged 5 commits into
mainfrom
123-oauth-token-encryption

Conversation

@Dumbris

@Dumbris Dumbris commented Nov 11, 2026

Copy link
Copy Markdown
Member

Summary

Spec, plan and tasks for #1697: opt-in encryption of upstream OAuth tokens at rest, both editions.

  • Threat: a copy of config.db at rest (backups, snapshots, a disk mounted elsewhere). Not a process that can read the key.
  • Key: oauth_token_encryption_key, normally a ${file:} reference; MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] override.
  • Format: whole oauth_tokens record sealed with AES-256-GCM as enc:v1:<kid>:<base64>, AAD bound to bucket and row key, in the existing bucket.
  • Failure: an unresolvable key reference exits 4; a wrong or absent key degrades per row and never deletes or overwrites a token.
  • Migration: plaintext rows are sealed at startup; auth tokens decrypt is the downgrade path.
  • Delivery: three PRs. PR-1 corrects the docs that claim keyring storage, PR-2 is the feature core, PR-3 adds doctor, the auth tokens CLI and compaction.

Review

Two independent reviews (security lens and feasibility lens) ran against the code; accepted findings are applied in the second commit. A cross-model review did not run (reviewer CLI login failed), so that round is UNREVIEWED.

Refs #1697

Related #1697

Spec, plan and tasks for opt-in, edition-neutral encryption of the
oauth_tokens bucket: enc:v1 AES-256-GCM envelopes bound to the bucket key,
HKDF-derived record key and key id, oauth_token_encryption_key resolved
through the secret providers (${file:} first) with
MCPPROXY_OAUTH_TOKEN_ENCRYPTION_KEY[_FILE] overrides, fail-closed writers
and per-row degrade for a missing or wrong key, a boot sweep plus offline
auth tokens status|encrypt|decrypt, doctor and health surfaces, and the
correction of the docs that claim keyring storage.
Related #1697

- Threat model: disk/VM snapshot protection needs the key off that disk
  (LoadCredentialEncrypted, tmpfs secrets, a secret store); a plain
  LoadCredential source or compose file secret covers config.db copies only.
- Resolve the key only at storage-open sites; Config.Validate is
  syntax-only, so CLI commands and hot reload do not need the key. Exit 4
  is carried as a config.StartupError.
- US2 is no-key/wrong-key; a missing secret mount is US3 (exit 4, bytes
  unchanged). Offline auth tokens commands take the key via the env
  override.
- Read-path inventory of every token reader with the typed error;
  HasPersistedTokenBound and GetPersistedRefreshToken gain error results.
- Boot sweep moves into runtime.New right after storage opens; sweep and
  decrypt collect before writing; named fault-injection hook.
- Compaction marker is set by any plaintext-to-envelope write and cleared
  only by db compact --keep-backup=false; doctor reports config.db.bak.
- Strict row partition, KeySource for doctor warnings, go/types codec
  source test, eight decode sites, kid-edit classification, redaction
  round-trip test, settings parity needs no script change, login
  pre-flight, docs page list, informational benchmark.
- Split into three PRs: docs correction, feature core, operator surfaces.
@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: 5875e0c
Status: ✅  Deploy successful!
Preview URL: https://b2902e04.mcpproxy-docs.pages.dev
Branch Preview URL: https://123-oauth-token-encryption.mcpproxy-docs.pages.dev

View logs

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: 123-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 (25 MB)
  • smart-mcp-proxymcpproxy-go3EN8O7.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 43076370796 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Qualify the no-readable-tokens claim (key outside copy, sealed, compacted,
rows skipped by the sweep excluded), make base64 padding classification
precise, share the reference recogniser between validation and config
output, distinguish key resolution for use from the secrets inventory
presence probe, allow the public key id and key-source metadata in output,
document four fixed resolution sentences, scope US3.2 to key-aware helpers,
and limit key-restore recovery to the missing-key and wrong-key cases.
@Dumbris
Dumbris enabled auto-merge (squash) November 11, 2026 19:46
@Dumbris
Dumbris merged commit 4376a6e into main Nov 11, 2026
78 of 86 checks passed
Dumbris added a commit that referenced this pull request Nov 11, 2026
## Summary

The docs said upstream OAuth tokens are stored encrypted in the OS
keyring. They are not. This PR makes every such claim say what the code
does today. It is PR-1 of Spec 123 (#1886) and contains no behaviour
change.

Refs #1697. Reported by @james-crowley.

## What the code does

- Upstream OAuth records (access token, refresh token, DCR client
secret) are plain JSON in the `oauth_tokens` bucket of `config.db`.
- The only protection is file permissions: data directory `0700`,
`config.db` `0600`.
- The OS keyring is used only for `${keyring:NAME}` config references.

## Changes

- `docs/features/oauth-authentication.md`: flow step 6, the Token
Storage section (keyring table removed), Security Best Practices item 3.
- `docs/docker-isolation.md`, `docs/features/docker-isolation.md`,
`docs/features/sandbox-isolation.md`: `config.db` holds the tokens in
readable form.
- `docs/mcp-go-oauth.md`: "secure storage" replaced with "persistence in
`config.db`".
- `specs/023-oauth-state-persistence/plan.md`,
`specs/039-security-scanner-plugins/spec.md`: the false "encrypted
BBolt" claims are struck through.
- `internal/storage/bbolt.go`: comment only.

## Not changed

- `docs/features/auth-broker.md` and Spec 029: these describe the
server-edition broker store, which is AES-encrypted.
- Text about `${keyring:}` references: accurate.

## Testing

- `cd website && npm ci && npm run build` passes, including the link
verification step.
- `go build ./internal/storage/` and `gofmt` are clean. The only Go
change is a comment.
Dumbris added a commit that referenced this pull request Nov 12, 2026
## 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.
Dumbris added a commit that referenced this pull request Nov 16, 2026
…n macOS runners (#1890)

## Summary

Two `internal/server` tests failed on macOS runners on unrelated PRs
(#1885, #1887). Both are races in the tests, not in production code.
This PR fixes them. Test-only.

## Causes and fixes

**`TestSearchTools_WithholdsApprovalLockedHits`** returned only
`cedar:pending_item` when `orchid:read_item` was also expected.

- After `PhaseReady` the runtime starts background tool indexing, whose
first step deletes index entries for servers the upstream manager does
not know.
- The test seeds two hand-made servers into the index right after
`PhaseReady`, so the cleanup could delete a seeded document mid-seeding.
- Reproduced locally with `GOMAXPROCS=1 go test -race -count=40`: failed
within the first two runs.
- Fix: a `newSettledConsistencyServer` fixture waits for `PhaseReady`
and for the cleanup's completion log line before the test seeds
anything. `TestSearchTools_AnnotationsSurviveToTier` seeds the same way
and now uses it too.

**`TestTPAFetchLifecycle_ActivatesReprotectsAndRefusesBadReleases`**
failed with "exactly one cycle reported activated: expected 1, actual
0".

- The test waited for the bundle source to flip, which happens inside
the fetch leg. The telemetry counter is incremented later, by the
observer that runs after the cycle is recorded.
- Reproduced deterministically by delaying that observer by 400 ms (not
part of this PR).
- Fix: poll until the counter reaches 1, then keep the exact `== 1`
assertion.

## Not fixed here

The `test timed out after 40m0s` failure on #1886 was not a hang. The
whole `internal/server` package ran 40 minutes on a slow runner; the
same job passed in 20 minutes on retry. A healthy macOS run already uses
about half the 40-minute budget. Raising the timeout or trimming the
fixed 12-second waits in the upstream-add tests is a separate decision.

## Testing

- `GOMAXPROCS=1 go test -race -count=100 -run
TestSearchTools_WithholdsApprovalLockedHits ./internal/server/`: pass.
- Both search tests together, `-race -count=15`: pass.
- The fetch lifecycle test, `GOMAXPROCS=1 -race`: 15 of 15 runs passed.
- `golangci-lint` v2 on `./internal/server/...`: 0 issues.
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.

2 participants