Skip to content

Sign tokens with a versioned server key so V1 can be retired - #15198

Merged
loks0n merged 2 commits into
mainfrom
claude/openssl-key-v2-598956
Nov 2, 2026
Merged

loks0n merged 2 commits into
mainfrom
claude/openssl-key-v2-598956

Conversation

@loks0n

@loks0n loks0n commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

What

_APP_OPENSSL_KEY_V1 no longer has to sign everything. One version of the server key signs tokens. Verification accepts every configured version from an "oldest" bound up. Once V1 is no longer accepted, nothing signed with it authenticates.

This PR only covers signing. Encrypting stored data with the new version, plus a task that re-encrypts existing data, follows in a stacked PR (#15199). That one is not needed to retire V1 as a signing key.

Config (new, all optional)

Variable Default Meaning
_APP_OPENSSL_KEY_V2 empty The next key
_APP_OPENSSL_KEY_CURRENT 1 Version that signs new tokens
_APP_OPENSSL_KEY_OLDEST 1 Oldest version still accepted when verifying tokens and signatures. 2 turns V1 acceptance off

Verification accepts the current key plus every configured _APP_OPENSSL_KEY_V{n} from OLDEST up to the first unset version. This means V2 is accepted as soon as it is configured, even while V1 is still current. During a rolling deploy, pods still on V1 accept tokens from pods already on V2. With the defaults nothing changes, so this can be deployed before V2 exists.

Changes

  • Appwrite\Auth\EncryptionKey gains version(), get(), current(), accepted() and decode(), which tries a JWT against each accepted key and stops at the first non-signature error. Startup checks (http, worker, realtime, mqtt, doctor) now check the current key, so CURRENT=2 without V2 refuses to start.
  • Signers use the current key:
    • account JWTs and Users JWTs
    • every ephemeral_ key mint site: preview proxy, deployments, executions, screenshots, project and organization ephemeral key endpoints, the functions worker and the migrations worker
    • deployment source tokens, resource tokens, push image tokens and data export links
    • OAuth2 session secret and state binding, and PKCE state
    • VCS state (GitHub, generic, Entire, Origin) and alert unsubscribe links
  • Verifiers accept every accepted key:
    • x-appwrite-jwt for console and project, in request.php, realtime and MQTT
    • the preview cookie, and ephemeral_ / dynamic_ keys (Auth/Key.php)
    • resource tokens, push file tokens and deployment tokens
    • OAuth2 secret JWT and state binding, PKCE, VCS callbacks and unsubscribe links
  • Vcs\State::verify() and Alert\Unsubscribe now take several keys.
  • Stored data is not touched. The encrypt filter and storage uploads keep using V1, and decryption still picks the key by the stored version.

Cutover runbook (ops)

Never paste key values into tickets, logs or chat. Generate V2 inside the secret store.

  1. Add V2 everywhere, still current=1. Set _APP_OPENSSL_KEY_V2 on every Appwrite deployment in every region (API, realtime, MQTT, workers, schedulers, tasks). Deploy. Nothing changes yet, but every pod now accepts V2.
  2. Switch signing to V2. Set _APP_OPENSSL_KEY_CURRENT=2 everywhere and deploy. New JWTs, ephemeral keys and tokens are signed with V2. V1 tokens still verify.
  3. Move every other signer to V2. Edge mints ephemeral_ keys with its own copy of the key, so edge has to be configured with the new key and deployed. Cloud code that reads _APP_OPENSSL_KEY_V1 directly must move to the current key too. Do not go on to step 4 until nothing signs with V1, or every key edge mints will be refused.
  4. Turn off V1 acceptance. Set _APP_OPENSSL_KEY_OLDEST=2 everywhere and deploy. From then on these are refused when signed with V1: JWTs, ephemeral keys, resource and file tokens, push and export links, unsubscribe links, and in-flight OAuth and VCS state. Expected fallout:
    • Clients using JWTs re-authenticate. JWTs live at most 1 hour.
    • Resource tokens (/v1/tokens, valid up to 10 years) and data-export links issued before step 2 stop working and must be reissued.
  5. Keep V1 for decryption. Stored attributes and storage files are still encrypted with V1, so _APP_OPENSSL_KEY_V1 stays configured. Encrypt stored data with the current key version and add a re-encrypt task #15199 moves encryption to the current version and adds the re-encrypt task.

What to watch after each step:

  • USER_JWT_INVALID and USER_UNAUTHORIZED rates on API and realtime
  • OAuth2 and VCS callback failures
  • function execution auth errors
  • startup logs: _APP_OPENSSL_KEY_V2 is missing means step 1 was skipped on that pod

Tests

  • tests/unit/Auth/EncryptionKeyTest.php covers:
    • the current key defaults to V1
    • V2 is accepted before it becomes current
    • tokens from the current key verify
    • V1 tokens verify during the grace window and are refused once OLDEST=2, which is the decode path every x-appwrite-jwt check uses, for console and project alike
    • foreign keys are refused
    • an expired old token reports expiry, not a signature error
  • tests/unit/Auth/KeyTest.php: a V1-signed ephemeral_ key is accepted during the grace window and refused (USER_UNAUTHORIZED) once V1 is retired. This test fails against the original code, which still accepts it.
  • Not covered: an e2e test that flips _APP_OPENSSL_KEY_OLDEST on a running server, because it needs a server config change mid-suite.

🤖 Generated with Claude Code

One key version now signs tokens and encrypts data
(_APP_OPENSSL_KEY_CURRENT). Verification accepts every configured version
from _APP_OPENSSL_KEY_OLDEST up, and stored data is still decrypted by the
version it records. With the defaults nothing changes, so this can ship
before V2 exists. Raising OLDEST to 2 refuses V1-signed account JWTs,
ephemeral keys and other tokens.

Adds the `encryption` task, which re-encrypts stored values with the
current version. It is a dry run unless --commit=true and resumes with
--after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Boot and doctor audits skip non-current accepted keys · EncryptionKey.php:98–113 · unchanged line

// src/Appwrite/Auth/EncryptionKey.php
98	    public static function assertProduction(string $env, ?string $key): void
99	    {
100	        if ($env !== 'production') {
101	            return;
102	        }
103	
104	        $name = '_APP_OPENSSL_KEY_V' . self::version();
105	
106	        if ($key === null || $key === '') {
107	            throw new \RuntimeException($name . ' is missing. Set a unique secret before running in production.');
108	        }
109	

assertProduction() is called with EncryptionKey::current() and Doctor runs EncryptionKey::isInsecure(EncryptionKey::current()) (src/Appwrite/Platform/Tasks/Doctor.php:88), but accepted() still verifies tokens against every configured older version. If a deployment rotates away from the placeholder key your-secret-key, the old _APP_OPENSSL_KEY_V1 remains in the accepted ring and anyone can still forge session JWTs, OAuth2 state HMAC bindings, VCS state signatures and unsubscribe tokens with the well-known placeholder — while boot checks and doctor report the instance as secure. isInsecure() already exists; it is simply never applied to the rest of the ring.

🧹 Nitpicks (4) — 🟢 4 low
  • 🟢 Restore original introduction version for _APP_LOGGING_FORMAT (variables.php:464) — The _APP_LOGGING_FORMAT entry was changed from introduction 1.9.6 to 2.7.0 (app/config/variables.php:464) as an unrelated side effect of this PR, so installer/docs now report the wrong release that introduced the variable.
  • 🟢 Ring-exhausted decode reports wrong error (EncryptionKey.php:79) — EncryptionKey::decode pre-allocates new JWTException('Signing key cannot be empty', JWT::ERROR_KEY_EMPTY) before the key-ring loop and throws it verbatim when every accepted key fails signature verification (src/Appwrite/Auth/EncryptionKey.php:79, 92).
  • 🟢 V24 filter decodes legacy JWTs with only current key (V24.php:48) — extractProjectId now decodes legacy ephemeral-key JWTs with EncryptionKey::current() instead of the previous fixed _APP_OPENSSL_KEY_V1 (src/Appwrite/Utopia/Response/Filters/V24.php:48).
  • 🟢 Removed empty-key guard hides misconfiguration as invalid state (Base.php:93) — The old code threw GENERAL_SERVER_ERROR with an explicit 'Signing key is not configured' message when _APP_OPENSSL_KEY_V1 was missing (src/Appwrite/Platform/Modules/VCS/Http/Callback/Base.php:93); now State::verify($state, ...EncryptionKey::accepted()) with an empty key ring silently returns null and the end user sees a generic 'Invalid state parameter' 400.

The change replaces single-key _APP_OPENSSL_KEY_V1 usage with an EncryptionKey abstraction that signs with the current key and verifies against every accepted key version, then migrates all call sites (sessions, JWTs, ephemeral keys, OAuth state, VCS callbacks, realtime/mqtt auth, deployment tokens) to it. Unit and e2e tests cover the new key-ring behavior and the encryption filter envelope.

Files Change
src/Appwrite/Auth/EncryptionKey.php, src/Appwrite/Auth/Key.php, tests/unit/Auth/* New key-ring helper (current/accepted/decode/isInsecure) plus updated auth-key tests
app/init/*, app/http.php, app/realtime.php, app/mqtt.php, app/worker.php, app/controllers/general.php Bootstrap, router, and connection auth switched to EncryptionKey::current()/decode()
src/Appwrite/Platform/Modules/** (JWTs, OAuth2, VCS, Keys, Storage, Messaging, Functions) Call sites updated to sign with the current key and verify across the ring
src/Appwrite/Vcs/State.php, src/Appwrite/Auth/OAuth2/PKCE.php, src/Appwrite/Alert/Unsubscribe.php, src/Appwrite/Deployment/* State/HMAC/PKCE/token verification loops over accepted keys
app/init/database/filters.php, src/Appwrite/Utopia/Response/*, tests/unit/Database/EncryptFilterTest.php Encrypt filter writes version envelope; V24 filter and ResourceToken model adjusted
src/Appwrite/Platform/Tasks/Encryption.php, Doctor.php, src/Appwrite/Platform/Services/Tasks.php New re-encryption CLI task and doctor audit of key strength
Dockerfile, docker-compose.yml, bin/encryption, app/config/variables.php New encryption worker entrypoint and env var documentation

Reviewed commit: 0ca63b7

@ghost

ghost commented Nov 2, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental documentation change introduces no actionable defect, and no unresolved issues remain from the previous review.

This pull request adds versioned server-key configuration and uses the selected current key for token signing while accepting configured older keys for verification. It also updates encryption to use versioned keys, adds a task to re-encrypt existing data, and updates startup checks, deployment configuration, and rotation tests. The latest change revises the V2 key description to omit the re-encryption task from its signing-key rotation steps.

Latest changes: The new commit removes the re-encryption-task instruction from the V2 key description, leaving steps to make the key current and then raise the oldest accepted version.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 5
File Change
app/config/variables.php, docker-compose.yml Defines versioned key settings and wires their configuration into deployment.
app/controllers/general.php, app/http.php, app/init/mqtt/connection.php, app/init/realtime/connection.php, app/init/resources/request.php, app/mqtt.php, app/realtime.php, app/worker.php Updates startup validation and request, realtime, and MQTT authentication to use versioned keys.
src/Appwrite/Auth, src/Appwrite/Alert, src/Appwrite/Deployment, src/Appwrite/Vcs Adds key selection and multi-key verification for authentication, OAuth, deployment, and unsubscribe flows.
src/Appwrite/Platform/Modules, src/Appwrite/Platform/Tasks, src/Appwrite/Platform/Workers, src/Appwrite/Utopia/Response Updates token signers and verifiers and adds the encryption migration task and related response handling.
tests/unit/Auth, tests/unit/Alert, tests/e2e/Services/Alerts Adds and updates coverage for key rotation, unsubscribe links, and encryption migration behavior.

Reviewed the commits since 0ca63b7 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

This PR now only moves signing off V1. The encrypt filter, storage file
encryption and the re-encrypt task follow in a stacked PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@loks0n loks0n changed the title Make _APP_OPENSSL_KEY_V1 retirable with versioned key rotation Sign tokens with a versioned server key so V1 can be retired Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Security rules

WARNING (2 new) — review signal only; does not fail the job.

php.appwrite.weak-secret-env-default (2)

Secret-like env var (SECRET, KEY, PASS, PASSWORD, TOKEN) read with a non-empty literal default. If the variable is unset the process silently runs with a shared, guessable value. Default to '' and fail or disable the feature when it is empty.

  • src/Appwrite/Auth/EncryptionKey.php:40 — EncryptionKey::version()
    • What's wrong: _APP_OPENSSL_KEY_CURRENT falls back to '1' when unset, so every install that does not set it shares that value.
    • How to fix: Read System::getEnv('_APP_OPENSSL_KEY_CURRENT', '') and fail or disable the dependent connection when it is empty; keep the example value in .env / app/config/variables.php.
  • src/Appwrite/Auth/EncryptionKey.php:64 — EncryptionKey::accepted()
    • What's wrong: _APP_OPENSSL_KEY_OLDEST falls back to '1' when unset, so every install that does not set it shares that value.
    • How to fix: Read System::getEnv('_APP_OPENSSL_KEY_OLDEST', '') and fail or disable the dependent connection when it is empty; keep the example value in .env / app/config/variables.php.
6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

Comment thread src/Appwrite/Auth/EncryptionKey.php Resolved
Comment thread src/Appwrite/Auth/EncryptionKey.php Resolved
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → claude/openssl-key-v2-598956 (after).

Metric Before After Change
🚀 Requests/sec 195.81 215.68 🟢 +10.1%
⏱️ Latency P50 85.49 ms 79.63 ms 🟢 -6.9%
⏱️ Latency P95 214.79 ms 187.74 ms 🟢 -12.6%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 79.63 187.74 13,680 215.68 -27.06
Account 161.6 305.74 720 11.96 -21.11
TablesDB 77.57 145.24 7,440 119.29 -7.81
Storage 72.47 165.37 3,600 59.7 -31.94
Functions 115.83 218.45 1,920 32.56 -85.2

Top API waits (after)

API request Max wait (ms)
functions.create 478.83
account.name.update 435.58
account.prefs.update 421.62
tablesdb.rows.create 364.35
functions.variables.update 341.67

@loks0n
loks0n merged commit 0380788 into main Nov 2, 2026
72 of 74 checks passed
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