Skip to content

Re-encrypt stored secrets with the active key version - #386

Closed
tnkuehne wants to merge 4 commits into
secrets/keyringfrom
secrets/reencryption
Closed

tnkuehne wants to merge 4 commits into
secrets/keyringfrom
secrets/reencryption

Conversation

@tnkuehne

@tnkuehne tnkuehne commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

With #384, new secrets use the active key version, but values written earlier keep their key version. Nobody could tell when an earlier key was safe to remove. Installation administrators can now see how many stored secrets each key version protects and re-encrypt the rest with the active version.

Based on #384. Review only the commits after #384.

Where it runs

Stored secrets belong to every organization, so this is an installation-level operation for installation administrators (principal.admin). Settings → Deployment agents already follows this pattern, and it is exposed through the API, CLI and UI. The AGENTS.md rule that every capability is available through all three applies here too. One shared module, secret-reencryption.ts, serves every entry point:

  • API: GET /api/v1/encryption and POST /api/v1/encryption/reencrypt (one bounded batch per call; pass the returned cursor until it is null; the last batch also returns the final status, so platform:write suffices)
  • CLI: widefleet encryption status and widefleet encryption reencrypt (repeats batches and prints progress)
  • UI: Settings → Encryption keys, shown only to installation administrators
  • Self-hosted container: docker compose ... exec control-plane node tools/secret-encryption.ts status|reencrypt, following tools/recover.ts

Hosted installations use the API, CLI or UI. Everything runs server-side; no keys leave the control plane.

Behavior

Locations covered:

  • apps.secrets
  • organization_settings.directory_secret and app_client_secret
  • sso_provider.oidc_config and saml_config
  • the client secret in a leftover pre-plugin organization_settings.settings.identity

jobs.app_secrets no longer stores values since #382, so it is not covered.

Run properties:

  • Safe against concurrent writes. Each row is replaced with a compare-and-swap on the values that were read. A row that changed in the meantime keeps the concurrent write and is reported as changed.
  • Bounded batches. Each call reads about one page of rows (100) from the cursor and returns the counts and the next cursor. The API, CLI, page and container command repeat until the cursor is null, so no request runs long on Node or hosted Workers.
  • Idempotent and resumable. Rows are read in key order. The cursor and the stop test follow the raw database page, so rows without a secret never end a scan early. Values already on the active version are skipped, so a new run continues with whatever remains.
  • Secret revisions unchanged. Re-encryption leaves the secret revision alone and triggers no redeployment.
  • Missing versions. Values of a version that the installation lacks are counted as failed and left unchanged.

Progress counts: the status lists every configured version (active first), the legacy key, and any version found in data but missing from the keyring, each with its count.

Pending deployments (hosted): a template install's secrets travel encrypted in its deployment command, in R2 and in the Workflow parameters, until registration saves them on the app. The status reports pendingDeployments, and a pending count per key version, for commands whose deployment Workflow is still active and not yet registered. A version can be removed once its count and its pending count are 0 and no backup needs it.

Without a keyring (Cloudflare installations before PLATFORM_ENCRYPTION_KEYS is set), the legacy key is the active one and there is nothing to re-encrypt.

Visual review

Intended improvement: an installation administrator can see which key versions still protect stored secrets and move them to the active version from Settings.

Checked against the built server (Playwright, Chromium):

  • desktop 1280×800 and mobile 390×844, light and dark
  • earlier values present; after re-encryption
  • a version missing from the keyring, with and without readable earlier values
  • the result after a run with unreadable values
  • keyboard: Tab reaches Re-encrypt secrets, Enter submits, the focus ring is visible
  • the 403 page for a non-installation administrator

Fixed during review:

  • The missing-key and result messages were duplicated in two error boxes. Now there is one persistent error for missing versions and a success message only when something changed.
  • The button was hidden when only unreadable values remain, since re-encryption cannot help there.
  • The hint about the legacy key no longer says "keyring".

Re-checked after batching: desktop light before a run, mobile dark during and after a run. The running state now reads "Re-encrypting secrets …" until the first batch completes.

Not verified:

  • very long key IDs, beyond wrap-anywhere
  • the no-keyring state on Cloudflare in the browser (covered by the status API logic only)
  • the pending-deployment message and counts in the browser; Node installations have no pending deployments (covered by the status tests)

Testing

  • pnpm check; cargo fmt --check; cargo clippy -p platform-cli --all-targets -D warnings
  • tests/secret-reencryption.integration.test.ts:
    • every location moves from the legacy key and an earlier version to the active version
    • counts before and after, and a second run re-encrypts nothing
    • readers find every value with matching contexts
    • a keyring with only the new version still reads everything
    • a concurrent write between read and replace is kept and reported as changed
    • a value of a missing version is counted as failed
    • only installation administrators may call it
    • paging past 110 rows without a readable secret, and resuming each batch
    • pending hosted deployment secrets, with a synthetic R2 store and Workflow
  • tests/platform.integration.test.ts: API authorization, the cursor loop, the final status in the last batch and an invalid cursor
  • tests/cli.test.ts (RUN_CLI_TESTS=1): widefleet encryption status, and reencrypt looping over two batches with progress, against the synthetic API; a write-only token finishes with the final status and makes no GET request
  • tests/e2e/auth.spec.ts: an installation administrator re-encrypts 121 secrets from Settings over more than one batch; other administrators get 403

Stack

  1. Encrypt stored secrets through a context-aware service #383: context API, no behavior change
  2. Encrypt new secrets with a versioned keyring #384: versioned format and keyring
  3. This PR: re-encryption

GitHub stack: #387

Operator documentation (draft): #385 covers the keyring, re-encryption and removing key versions.

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; both numbered findings are fixed, and no new actionable issue was found.

Summary

Adds installation-wide key counts and re-encryption through the API, CLI, Settings page, and container command.

  • Stored secrets can move to the active key in resumable batches.
  • Key status shows where stored and pending secrets still rely on each key.
  • Administrators can check and re-encrypt secrets through the API, CLI, and container command.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Installation administrator] --> B[API, CLI, or Settings]
  B --> C[Shared maintenance service]
  C --> D[Read one page]
  D --> E[Re-encrypt older values]
  E --> F[Replace only unchanged rows]
  F --> G{More rows?}
  G -->|Yes| H[Return cursor and progress]
  H --> B
  G -->|No| I[Return final counts]
  J[Pending hosted deployments] --> I
Loading

Reviews (4) · Last reviewed commit: "Keep pending deployments on failed looku..." · Reviewed by Greptile

Installation administrators can see how many stored secrets each key
version protects and re-encrypt the others with the active version, so they
know when an earlier key can be removed. The same shared module serves the
API (GET /encryption, POST /encryption/reencrypt), the `widefleet
encryption` CLI command, the Encryption keys settings page and the
`node tools/secret-encryption.ts` command inside a self-hosted container.

It covers app secrets, directory and app sign-in client secrets, SSO
provider configurations and leftover pre-plugin identity documents. Each row
is replaced only if it still holds the values that were read, so concurrent
writes win and a later run continues with what remains. Values of missing
key versions are counted, not changed.
Comment thread crates/platform-cli/src/encryption.rs Resolved
@cloudflare-workers-and-pages

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

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
widefleet-docs bb535c9 Nov 25 2026, 12:05 PM

Re-encryption now handles about one page of rows per call and returns a
cursor for the next batch. The API, CLI, settings page and container
command repeat until the cursor is null, and the CLI prints progress, so
no single request runs long on Node or hosted Workers.

Each location continues after the database page it read, not after the
rows that carried ciphertexts, so rows without a secret no longer end the
scan early.

The status also counts secrets of hosted deployments that their Workflow
has not registered yet. These still carry earlier key versions until they
are saved on the app, so a version can go only once both counts are 0.
Comment thread crates/platform-cli/src/encryption.rs Resolved
The batch that ends with a null cursor now carries the final status. The
CLI prints it without a separate GET /encryption, so a token with only
platform:write gets the completed result. The settings page and the
container command use the same status instead of reading it again.
Comment thread crates/platform-cli/src/encryption.rs Resolved
Only a missing or finished deployment Workflow instance now drops a pending
command from the status. Any other lookup failure keeps it counted, so the
status never reports a key version as unused while a deployment may still
save secrets encrypted with it.

`widefleet encryption` fetches an access token before each request, so a
saved login refreshes during a long re-encryption instead of expiring
between batches.
@tnkuehne

Copy link
Copy Markdown
Contributor Author

Closing in favor of a smaller approach: re-encryption will be a single operator command run inside the control-plane environment, without new UI, API endpoints or CLI commands. A follow-up PR replaces this one.

@tnkuehne tnkuehne closed this Nov 25, 2026
@tnkuehne
tnkuehne removed this pull request from stack #387 November 25, 2026 14:28
tnkuehne added a commit that referenced this pull request Nov 25, 2026
Operators need a way to move every stored secret to the active key
version before an earlier key, or the legacy format, can be removed.
This adds one Node command for that, following `tools/recover.ts`. It
replaces the closed #386, without UI, API endpoints, a Rust CLI command,
a cursor protocol or pending-deployment counting.

Based on #384. Review only the commits after #384.

## Usage

```sh
# Self-hosted, inside the control-plane container
docker compose ... exec control-plane node tools/secret-encryption.ts status
docker compose ... exec control-plane node tools/secret-encryption.ts reencrypt

# Hosted, from CI with explicit settings
DATABASE_URL=... PLATFORM_ENCRYPTION_KEYS=... PLATFORM_ENCRYPTION_KEY=... \
  node apps/control-plane/tools/secret-encryption.ts reencrypt
```

The command reads only `DATABASE_URL`, `PLATFORM_STATE_DIRECTORY`, the
keyring settings and the legacy key settings.

**It never generates keys.** It requires `PLATFORM_ENCRYPTION_KEYS`,
`PLATFORM_ENCRYPTION_KEYS_FILE` or an existing `encryption.keys`, and
fails otherwise. `installationKeys` keeps generating the keyring on
first start; the command uses a new non-generating
`readInstallationKeyring`.

## Behavior

**Locations covered:**
- `apps.secrets`
- `organization_settings.directory_secret` and `app_client_secret`
- `sso_provider.oidc_config` and `saml_config`
- the client secret in a leftover pre-plugin
`organization_settings.settings.identity`

**How it works:**
- **Bounded pages.** Rows are read in pages of 100 in key order. The
page cursor follows the raw database rows, so rows without a secret
never end a scan early.
- **Compare-and-swap per row.** A row is replaced only if it still holds
what was read, so a concurrent write wins and is counted as `changed`.
- **Replacement by slot.** New ciphertexts are keyed by row and field or
secret name, not by ciphertext string, so two slots holding the same
ciphertext each get their own value.
- **Active values are verified.** Values whose header names the active
`kid` are decrypted, not skipped by their header.
- **Secret revisions unchanged.** The secret revision is left alone, so
nothing is redeployed.
- **Output.** JSON with counts per key version, the legacy count and the
failed count. Legacy values are recognized by their format, never by a
key name, and values without a readable `kid` count only as failed.
`reencrypt` also reports `reencrypted` and `changed`.
- **Exit status.** Nonzero if a value does not decrypt, or if
`reencrypt` leaves values under another key version or in the legacy
format.

## Testing

- `pnpm check`
- `tests/secret-reencryption.integration.test.ts`:
- every location moves from the legacy format and an earlier key version
to the active one
  - counts before and after, and a second run changes nothing
- readers find every value with matching contexts (context checks from
#383 active)
  - two slots holding the same ciphertext get distinct values
- an altered value under the active `kid` is counted as failed and left
unchanged
  - a concurrent write between read and replace is kept
  - paging past 110 rows without a secret
- key versions named `legacy`, `constructor` or `__proto__` are counted
under their own ID, not as legacy values or inherited properties
  - the command itself:
    - fails without a keyring and creates no file
    - `reencrypt` exits 0
    - `status` exits 1 while a value names an unknown `kid`
    - the state directory stays empty

## Stack

1. #383: context API, no behavior change
2. #384: JWE format, JWK Set keyring, temporary legacy reader
3. This PR: re-encryption command
4. #399: legacy cleanup (draft)

GitHub stack: #400. Operator documentation (draft): #385









<!-- greptile_comment -->

<!-- greptile_summary -->

<h2><a
href="https://app.greptile.com/api/retrigger?id=119521021&amp;sig=fd953f268e72c3f3f0356af21af5928972e43ebac759c5e0d10aa0fc250ddc73"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img
alt="Retrigger"
src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"
align="right"></picture></a><a
href="https://app.greptile.com/-/switch-tenant?tenant=mendra&amp;next=%2Fwidefleet%2Fwidefleet%2Fpull%2F398&amp;utm_source=greptile_review&amp;utm_medium=github&amp;utm_campaign=view_in_greptile"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img
alt="View in Greptile"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"
align="right"></picture></a>Confidence Score: 5/5 <sup><img alt="Tier:
plus" title="Review tier: plus"
src="https://greptile-static-assets.s3.amazonaws.com/badges/effort-plus.svg?v=3"
height="12"></sup></h2>

<!-- greptile-impact-verdict --> The PR appears safe to merge; no new
actionable issues remain.

<details open><summary><h3>Summary</h3></summary>

Adds an operator command to inspect stored secrets and re-encrypt them
under the active key.
- Secret status counts stored values by key version and decrypt
failures.
- Readable stored secrets move to the active key without changing their
values.
- Operators can check or re-encrypt secrets with an existing keyring.

Source and tests were inspected; tests were not run.
</details>

<details open><summary><h3>Diagram</h3></summary>

```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Read existing keys] --> B{Keyring found?}
  B -->|No| C[Exit unsuccessfully]
  B -->|Yes| D{Requested action}
  D -->|status| I[Scan and decrypt every secret]
  D -->|reencrypt| E[Read next page]
  E --> F[Decrypt each secret]
  F --> G[Encrypt values not using active key]
  G --> H[Replace only unchanged rows]
  H --> I
  I --> J[Print counts and set exit status]
```
</details>

<!-- greptile_confidence_score:5 -->

<sub>Reviews (4) · Last reviewed commit: ["Count key versions without
colliding
wit..."](128555c)
· [Reviewed by
Greptile](https://www.greptile.com/?utm_source=greptile_review&utm_medium=github&utm_campaign=review_public&utm_content=widefleet/widefleet)</sub>

<!-- /greptile_comment -->
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.

1 participant