From fdea74900511905af86ab79981397ab89fa99980 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Thu, 22 Oct 2026 12:37:19 +0200 Subject: [PATCH 1/2] feat: preserve encrypted credentials and MFA enrollments across staged key rotation with scoped token grace periods --- cmd/backend/main.go | 13 +-- cmd/warmblyctl/backup.go | 12 +++ cmd/warmblyctl/backup_key_rotation_test.go | 29 +++++++ deploy/docker-compose.coolify.yml | 11 +++ docker-compose.yml | 11 +++ .../docs/development/configuration.mdx | 31 ++++++- .../content/docs/development/data-control.mdx | 4 +- .../docs/development/whole-domain-connect.mdx | 2 +- internal/api/middleware/internal_auth.go | 23 ++++- .../api/middleware/token_rotation_test.go | 61 +++++++++++++ internal/app/instanceconfig/entries.go | 72 ++++++++++++++- internal/app/token/rotation_test.go | 31 +++++++ internal/app/twofa/enroll.go | 2 +- internal/app/twofa/rotation_test.go | 42 +++++++++ internal/app/twofa/service.go | 32 +++++-- internal/app/unsublink/rotation_test.go | 32 +++++++ internal/app/unsublink/signer.go | 38 ++++++-- internal/config/auth_rotation_test.go | 39 +++++++++ internal/config/config_auth.go | 47 ++++++++-- internal/pkg/encrypt/encrypter.go | 42 ++++++++- internal/pkg/encrypt/rotation_test.go | 87 +++++++++++++++++++ internal/pkg/secretset/parse.go | 24 +++++ internal/pkg/secretset/parse_test.go | 19 ++++ 23 files changed, 665 insertions(+), 39 deletions(-) create mode 100644 cmd/warmblyctl/backup_key_rotation_test.go create mode 100644 internal/api/middleware/token_rotation_test.go create mode 100644 internal/app/token/rotation_test.go create mode 100644 internal/app/twofa/rotation_test.go create mode 100644 internal/app/unsublink/rotation_test.go create mode 100644 internal/config/auth_rotation_test.go create mode 100644 internal/pkg/encrypt/rotation_test.go create mode 100644 internal/pkg/secretset/parse.go create mode 100644 internal/pkg/secretset/parse_test.go diff --git a/cmd/backend/main.go b/cmd/backend/main.go index e516262ea..bbeef88f8 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -971,7 +971,11 @@ func main() { // TOTP 2FA: the secret is sealed with a server-wide key (the per-user DEK // is unreachable at login time). Wire the challenger into auth so the login // gate can issue a pending challenge. - twofaService = twofa.NewService(repository.NewTOTPRepository(primaryDB.Pool), userRepostory, tokenService, cache, twofa.DeriveKey(authCfg.TwoFASecret)) + var twoFAReadKeys [][32]byte + for _, secret := range authCfg.TwoFAReadSecrets { + twoFAReadKeys = append(twoFAReadKeys, twofa.DeriveKey(secret)) + } + twofaService = twofa.NewService(repository.NewTOTPRepository(primaryDB.Pool), userRepostory, tokenService, cache, twofa.DeriveKey(authCfg.TwoFASecret), twoFAReadKeys...) authService.WireTwoFA(twofaService) // The native app proves itself with App Attest where a browser solves Turnstile. appAttestService = appattest.New(repository.NewAppAttestRepository(primaryDB.Pool), cache, appattest.Config{ @@ -1256,9 +1260,8 @@ func main() { // the mailbox-connect redirect_uri from it sends the provider // "0.0.0.0:8080/addresses/google/callback". oauth2Cfg := config.LoadOauth2(oauthPublicBaseURL(apiCfg.Hostname)) - // Recipient unsubscribe links live on the API origin, signed under the - // auth secret; the same base the OAuth callbacks are built on. - unsubSigner = unsublink.New(authCfg.AuthSecret, oauthPublicBaseURL(apiCfg.Hostname)) + // Recipient links use a separate purpose key when one is configured. + unsubSigner = unsublink.NewWithReadKeys(authCfg.UnsubscribeSigningSecret, oauthPublicBaseURL(apiCfg.Hostname), authCfg.UnsubscribeReadSecrets, authCfg.UnsubscribeReadUntil) emailService = email.NewServiceWithWorker( emailRepostory, cipherService, @@ -1854,7 +1857,7 @@ func main() { // Mailbox imports: files and pasted lists connected in the background, // with each domain's mail host detected from its DNS. // One prover for every DNS ownership proof, keyed by the instance secret. - domainProver := domainproof.New(authCfg.AuthSecret) + domainProver := domainproof.New(authCfg.DomainProofSecret) // Whole-domain connects: Google Workspace delegation to the instance's // service account, Microsoft 365 consent to its Outlook app. diff --git a/cmd/warmblyctl/backup.go b/cmd/warmblyctl/backup.go index 93983e05c..08a55b2a9 100644 --- a/cmd/warmblyctl/backup.go +++ b/cmd/warmblyctl/backup.go @@ -58,9 +58,21 @@ const ( // every worker and websocket connection, which reads as a broken restore. var backupKeys = []string{ "CREDENTIALS_ENCRYPTION_KEY", + "CREDENTIALS_ENCRYPTION_READ_KEYS", "KMS_LOCAL_MASTER_KEY", "AUTH_SECRET", + "TWOFA_SECRET", + "TWOFA_READ_SECRETS", + "UNSUBSCRIBE_SIGNING_SECRET", + "UNSUBSCRIBE_SIGNING_READ_SECRETS", + "UNSUBSCRIBE_SIGNING_READ_UNTIL", + "DOMAIN_PROOF_SECRET", "INTERNAL_API_TOKEN", + "INTERNAL_API_PREVIOUS_TOKENS", + "INTERNAL_API_PREVIOUS_UNTIL", + "NODE_BROKER_TOKEN", + "NODE_BROKER_PREVIOUS_TOKENS", + "NODE_BROKER_PREVIOUS_UNTIL", "SECRET_KEY_BASE", } diff --git a/cmd/warmblyctl/backup_key_rotation_test.go b/cmd/warmblyctl/backup_key_rotation_test.go new file mode 100644 index 000000000..c36623f21 --- /dev/null +++ b/cmd/warmblyctl/backup_key_rotation_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestBackupKeyListsRoundTrip(t *testing.T) { + root := t.TempDir() + dump := filepath.Join(root, "database.sql") + if err := os.WriteFile(dump, []byte("SELECT 1;\n"), 0600); err != nil { + t.Fatal(err) + } + keys := map[string]string{"CREDENTIALS_ENCRYPTION_KEY": "fixture-primary", "CREDENTIALS_ENCRYPTION_READ_KEYS": `["fixture-reader"]`, "TWOFA_SECRET": "fixture-mfa", "TWOFA_READ_SECRETS": `["reader,with,commas"]`, "UNSUBSCRIBE_SIGNING_READ_UNTIL": "2027-10-22T00:00:00Z", "NODE_BROKER_PREVIOUS_TOKENS": `["fixture-broker"]`} + bundle := filepath.Join(root, "bundle.tar.gz") + if err := writeBundle(bundle, manifest{Version: 1}, dump, nil, keys); err != nil { + t.Fatal(err) + } + restored, err := readKeys(bundle) + if err != nil { + t.Fatal(err) + } + for key, want := range keys { + if restored[key] != want { + t.Fatalf("backup must preserve %s exactly", key) + } + } +} diff --git a/deploy/docker-compose.coolify.yml b/deploy/docker-compose.coolify.yml index b631ed6d0..57eae8888 100644 --- a/deploy/docker-compose.coolify.yml +++ b/deploy/docker-compose.coolify.yml @@ -12,6 +12,7 @@ x-runtime-env: &runtime-env KMS_PROVIDER: local KMS_LOCAL_MASTER_KEY: ${KMS_LOCAL_MASTER_KEY:?} CREDENTIALS_ENCRYPTION_KEY: ${CREDENTIALS_ENCRYPTION_KEY:?} + CREDENTIALS_ENCRYPTION_READ_KEYS: ${CREDENTIALS_ENCRYPTION_READ_KEYS:-} BLOB_PROVIDER: filesystem BLOB_FS_ROOT: /data/blobs TASKS_PROVIDER: local @@ -19,8 +20,18 @@ x-runtime-env: &runtime-env BILLING_PROVIDER: none CAPTCHA_PROVIDER: none AUTH_SECRET: ${AUTH_SECRET:?} + TWOFA_SECRET: ${TWOFA_SECRET:-} + TWOFA_READ_SECRETS: ${TWOFA_READ_SECRETS:-} + UNSUBSCRIBE_SIGNING_SECRET: ${UNSUBSCRIBE_SIGNING_SECRET:-} + UNSUBSCRIBE_SIGNING_READ_SECRETS: ${UNSUBSCRIBE_SIGNING_READ_SECRETS:-} + UNSUBSCRIBE_SIGNING_READ_UNTIL: ${UNSUBSCRIBE_SIGNING_READ_UNTIL:-} + DOMAIN_PROOF_SECRET: ${DOMAIN_PROOF_SECRET:-} INTERNAL_API_TOKEN: ${INTERNAL_API_TOKEN:?} + INTERNAL_API_PREVIOUS_TOKENS: ${INTERNAL_API_PREVIOUS_TOKENS:-} + INTERNAL_API_PREVIOUS_UNTIL: ${INTERNAL_API_PREVIOUS_UNTIL:-} NODE_BROKER_TOKEN: ${NODE_BROKER_TOKEN:?} + NODE_BROKER_PREVIOUS_TOKENS: ${NODE_BROKER_PREVIOUS_TOKENS:-} + NODE_BROKER_PREVIOUS_UNTIL: ${NODE_BROKER_PREVIOUS_UNTIL:-} x-server-env: &server-env <<: *runtime-env diff --git a/docker-compose.yml b/docker-compose.yml index 9dcfa3646..051184652 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -74,6 +74,7 @@ x-selfhost-env: &selfhost-env KMS_LOCAL_MASTER_KEY: ${KMS_LOCAL_MASTER_KEY:-Xr0JA7gqF2POy29a7MRByyqddivTNt8WOyKsOXklazk=} KMS_AWS_KEY_ID: ${KMS_AWS_KEY_ID:-} CREDENTIALS_ENCRYPTION_KEY: ${CREDENTIALS_ENCRYPTION_KEY:-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef} + CREDENTIALS_ENCRYPTION_READ_KEYS: ${CREDENTIALS_ENCRYPTION_READ_KEYS:-} # Blob storage. s3 also needs BLOB_BUCKET + the AWS_* values below. BLOB_PROVIDER: ${BLOB_PROVIDER:-filesystem} @@ -192,11 +193,21 @@ x-selfhost-env: &selfhost-env PRIMARY_DB: ${PRIMARY_DB:-postgres://warmbly:warmbly@postgres:5432/warmbly_dev?sslmode=disable} REDIS: ${REDIS:-redis://redis:6379} AUTH_SECRET: ${AUTH_SECRET:-local-dev-auth-secret-minimum-32-characters-long} + TWOFA_SECRET: ${TWOFA_SECRET:-} + TWOFA_READ_SECRETS: ${TWOFA_READ_SECRETS:-} + UNSUBSCRIBE_SIGNING_SECRET: ${UNSUBSCRIBE_SIGNING_SECRET:-} + UNSUBSCRIBE_SIGNING_READ_SECRETS: ${UNSUBSCRIBE_SIGNING_READ_SECRETS:-} + UNSUBSCRIBE_SIGNING_READ_UNTIL: ${UNSUBSCRIBE_SIGNING_READ_UNTIL:-} + DOMAIN_PROOF_SECRET: ${DOMAIN_PROOF_SECRET:-} INTERNAL_API_TOKEN: ${INTERNAL_API_TOKEN:-local-dev-internal-token} + INTERNAL_API_PREVIOUS_TOKENS: ${INTERNAL_API_PREVIOUS_TOKENS:-} + INTERNAL_API_PREVIOUS_UNTIL: ${INTERNAL_API_PREVIOUS_UNTIL:-} # The broker routes (open a data key, sign a blob operation, mint a managed # mailbox's access token). Optional; empty falls back to the token above, and # every service that needs it reads it from here so the two never disagree. NODE_BROKER_TOKEN: ${NODE_BROKER_TOKEN:-} + NODE_BROKER_PREVIOUS_TOKENS: ${NODE_BROKER_PREVIOUS_TOKENS:-} + NODE_BROKER_PREVIOUS_UNTIL: ${NODE_BROKER_PREVIOUS_UNTIL:-} # AI assistant. Omit AI_PROVIDER to run with AI off (endpoints return 503). AI_PROVIDER: ${AI_PROVIDER:-} diff --git a/docs/content/docs/development/configuration.mdx b/docs/content/docs/development/configuration.mdx index 4ac31c554..42f41eb96 100644 --- a/docs/content/docs/development/configuration.mdx +++ b/docs/content/docs/development/configuration.mdx @@ -57,7 +57,7 @@ Five values protect the whole instance. Compose ships a working default for each | Variable | Format | What it protects | Restart needed | |---|---|---|---| -| `AUTH_SECRET` | 32 characters or more, enforced at boot | JWT and session signing. The realtime service reads the same value as `JWT_SECRET` and applies the same floor. Both refuse to start below it: a shorter HS256 key can be recovered offline from any token the service has issued. It also keys the `warmbly-verify=` values workspaces publish in `_warmbly` `TXT` records to prove a domain, so changing it changes every one of them: [root redirects](/guides/sending-domains/#root-redirects) stop at their next check until the new value is published | yes | +| `AUTH_SECRET` | 32 characters or more, enforced at boot | JWT and session signing. The realtime service reads the same value as `JWT_SECRET` and applies the same floor. Both refuse to start below it: a shorter HS256 key can be recovered offline from any token the service has issued. By default it also supplies the MFA sealing, unsubscribe signing and DNS ownership-proof keys. Configure the separate purpose keys below before rotating sessions when those values must remain stable | yes | | `INTERNAL_API_TOKEN` | any random string | The backend's `/api/v1/internal/` routes the tracking and forms services call (click tickets, root redirects, page views, hosted forms). Fleet nodes authenticate with it too when `NODE_BROKER_TOKEN` is unset | yes | | `NODE_BROKER_TOKEN` | any random string | Every internal route only a fleet node calls: organization data keys (read, store and open), blob signing, provider access tokens for a mailbox Warmbly Cloud manages, the message map and sync lookups, worker config and the node heartbeat. Optional, and falls back to `INTERNAL_API_TOKEN`. The same value has to be set on the control plane and on every node, or those routes answer 401; a node joined after it is set receives it in `node.env` in place of `INTERNAL_API_TOKEN`, and a node joined before has to join again. The installer generates one for a new install; an existing install keeps the shared token until you set one | yes | | `NODE_ACCEPT_INTERNAL_TOKEN` | `true` or unset | While `true`, the node-only routes other than the key and blob brokers also accept `INTERNAL_API_TOKEN`. An upgrade does not need it: a heartbeat sent with `INTERNAL_API_TOKEN` is always answered with the node's version and nothing is recorded, so an older node updates itself. Set it only to keep older nodes syncing until they have updated, then remove it: while it is on, the tracking and forms services' token reaches those routes | no | @@ -100,6 +100,31 @@ The secret check runs in the backend. The consumer and the workers start happily `KMS_LOCAL_MASTER_KEY` and `CREDENTIALS_ENCRYPTION_KEY` seal every stored credential and every stored message body. Losing them is unrecoverable, and a database backup without them cannot be decrypted. +### Rotate instance keys + +These settings are optional. An existing self-host keeps its current keys and behavior when they are unset. All list values are JSON arrays with at most four nonempty strings; `[]` means no additional keys. Keep them in your secret store or private `.env`. + +| Variable | Purpose | Default | +|---|---|---| +| `CREDENTIALS_ENCRYPTION_READ_KEYS` | Additional 64-character hex keys that can decrypt instance credential ciphertext. New writes use only `CREDENTIALS_ENCRYPTION_KEY` | unset | +| `TWOFA_READ_SECRETS` | Additional secrets that can open existing TOTP enrollments. New enrollments use `TWOFA_SECRET` | unset | +| `UNSUBSCRIBE_SIGNING_SECRET` | Signs recipient unsubscribe links independently of sessions. At least 32 characters | `AUTH_SECRET` | +| `UNSUBSCRIBE_SIGNING_READ_SECRETS` | Previous secrets accepted only for unsubscribe signatures, with the cutoff below | unset | +| `UNSUBSCRIBE_SIGNING_READ_UNTIL` | RFC3339 cutoff required with unsubscribe read secrets. Both the verification time and the signed link expiry must be within this window | unset | +| `DOMAIN_PROOF_SECRET` | Keys `_warmbly` DNS ownership proofs independently of sessions. At least 32 characters | `AUTH_SECRET` | +| `INTERNAL_API_PREVIOUS_TOKENS` | Previous bearer tokens for the tracking and forms routes, accepted only before the cutoff below | unset | +| `INTERNAL_API_PREVIOUS_UNTIL` | RFC3339 cutoff for previous internal tokens. Missing, malformed or elapsed deadlines reject previous tokens | unset | +| `NODE_BROKER_PREVIOUS_TOKENS` | Previous bearer tokens for fleet broker routes, accepted only before the cutoff below. These retain broker privileges during the window | unset | +| `NODE_BROKER_PREVIOUS_UNTIL` | RFC3339 cutoff for previous broker tokens. Missing, malformed or elapsed deadlines reject previous tokens | unset | + +Changing these settings requires restarting the affected service. Internal-token deadlines are checked on every request, so old tokens stop working at the cutoff without another restart. Tracking and forms overlap does not grant fleet broker access. JWT verification uses only `AUTH_SECRET`; encryption and unsubscribe read keys never authorize sessions. + +For encryption rotation, first deploy a compatible release everywhere with the existing primary key and the replacement included in its read-key list. Confirm that all readers use that baseline before a later deployment activates the replacement primary and retains the old key for reads. Reseal stored values with a resumable job that preserves concurrent writes. The supported rollback floor during rotation is that compatible baseline release, using keys that read both generations. A binary rollback keeps the current compatible key configuration; reverting a primary key alone does not migrate data. + +Retain old keys until stored ciphertext, retained events, pending jobs and the supported rollback window no longer need them. Keep the keys required by older backups for as long as those backups are retained. Organization DEKs and their KMS wrapping keys have a separate lifecycle; changing the instance credential key does not rotate them. + +To rotate sessions while preserving existing MFA enrollments, unsubscribe links and published DNS proofs, first pin `TWOFA_SECRET`, `UNSUBSCRIBE_SIGNING_SECRET` and `DOMAIN_PROOF_SECRET` to their existing resolved values. Then change `AUTH_SECRET` and realtime's matching `JWT_SECRET` together. Users sign in again. Rotate the independent purpose keys separately; issued unsubscribe links remain valid for one year, so their read cutoff must cover the last previously issued link's expiry. + ## Addresses Every emailed link (password reset, invitation, the first-run claim link) is built from `APP_URL`. Leave it unset and a self-hosted instance guesses the origin from `CORS_ALLOW_ORIGINS` or `PUBLIC_HOST` instead, and never falls back to the hosted service: a link nobody can open is a support ticket, while a working link to somebody else's dashboard carries a live reset token out of your deployment. Set it. @@ -154,7 +179,7 @@ TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12 | `WARMBLY_BOOTSTRAP_PASSWORD_HASH` | Argon2id PHC string for that owner, as `warmblyctl hash-password` prints it. Preferred over the plaintext form. A malformed hash, or one whose cost parameters are below `m=65536,t=3,p=2` with a 16-byte salt and 32-byte key, is refused and no owner is created | unset | yes | | `WARMBLY_BOOTSTRAP_PASSWORD` | Plaintext convenience form. Held to the same rules as any password (length, breached list); one that fails them is refused and no owner is created. Warns at boot, and leaves a password in your process environment | unset | yes | | `WARMBLY_BOOTSTRAP_ORG` | Name of the organization created with that owner. A value that breaks the [naming rules](/api/error-codes/#name-refusals) is ignored with a warning | derived from the name | yes | -| `TWOFA_SECRET` | Key that encrypts stored TOTP secrets. Falls back to `AUTH_SECRET`, so existing deployments keep working; rotating it invalidates every enrolled TOTP secret | `AUTH_SECRET` | yes | +| `TWOFA_SECRET` | Key that encrypts stored TOTP secrets. Falls back to `AUTH_SECRET`. Keep matching `TWOFA_READ_SECRETS` while existing enrollments are resealed under a replacement key | `AUTH_SECRET` | yes | | `WEBAUTHN_RP_ID` | Passkey relying party id. Derived from `APP_URL` when unset. Changing it invalidates every enrolled passkey | derived | yes | | `WEBAUTHN_RP_ORIGINS` | Origins accepted for passkey ceremonies | derived from `APP_URL` | yes | | `WEBAUTHN_RP_DISPLAY_NAME` | The name the passkey prompt shows | `Warmbly` | yes | @@ -589,7 +614,7 @@ Each customer's authorization is tied to the service account's Client ID, so cre A Google grant is recorded only for the workspace that proves it controls the domain, and only when the directory lists the admin address as a super administrator. The proof is one of: - **The administrator's Google sign-in**, through the dashboard's own sign-in client (`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`) and its existing redirect URI (`GOOGLE_REDIRECT_URI`, or `API_PUBLIC_URL` plus `/v1/auth/google/callback`), with the `openid` and `email` scopes only. The callback recognizes the proof and hands it back to the dashboard window rather than signing anyone in, so no new redirect URI needs registering. When that client is not configured, the `BOX_GOOGLE_*` mailbox client is used instead, the same way. Neither depends on `BOX_GOOGLE_OAUTH_CONNECT`. -- **A `TXT` record** at `_warmbly.` holding a `warmbly-verify=` value unique to the workspace and domain, always available and the only proof when neither client is set. The value is keyed by `AUTH_SECRET`. +- **A `TXT` record** at `_warmbly.` holding a `warmbly-verify=` value unique to the workspace and domain, always available and the only proof when neither client is set. The value is keyed by `DOMAIN_PROOF_SECRET`, which defaults to `AUTH_SECRET`. Microsoft 365 organizations reuse the Outlook app, `BOX_OUTLOOK_CLIENT_ID` and `BOX_OUTLOOK_CLIENT_SECRET`, and are on whenever those are set. The app registration needs three additions for them: diff --git a/docs/content/docs/development/data-control.mdx b/docs/content/docs/development/data-control.mdx index ca901c2d2..87a78b061 100644 --- a/docs/content/docs/development/data-control.mdx +++ b/docs/content/docs/development/data-control.mdx @@ -209,7 +209,7 @@ docker compose -p warmbly cp backend:/data/blobs/warmbly.tar.gz ./warmbly.tar.gz `/data/blobs` is a hand-off, not a destination: it is the one path the container and the host both see. The `&&` matters twice over. `backup` leaves its own output out of the archive, but a bundle left there is swept into the next run, so it has to be deleted; and a `cp` that failed must not be followed by deleting the only copy that exists. -The bundle is written 0600 and holds every mailbox credential on the instance plus the keys that open them. Treat the file as you would the instance itself. +The bundle is written 0600 and holds every mailbox credential on the instance plus the keys that open them. It includes configured credential and MFA read keys, purpose-specific signing keys and bounded internal-token overlap settings. Preserve those values when restoring a bundle that contains mixed generations of ciphertext. Treat the file as you would the instance itself. An install from `install.sh --wizard` can schedule this for you: `backup.sh` next to the install, a systemd timer, a retention count, and an optional `aws s3 cp` to somewhere off the host. A backup that only exists on the machine it backs up is not one. @@ -250,7 +250,7 @@ curl -fsSL https://warmbly.com/install.sh | sh -s -- --host ### Put the old keys in the new `.env` -Copy `CREDENTIALS_ENCRYPTION_KEY` and `KMS_LOCAL_MASTER_KEY` from the old install, then recreate the containers so they take: +Copy the saved keys from the old install, including `CREDENTIALS_ENCRYPTION_KEY`, `KMS_LOCAL_MASTER_KEY` and any configured read keys or separate MFA and signing keys. See [key rotation](/development/configuration/#rotate-instance-keys). Then recreate the containers so they take: ```bash docker compose -p warmbly up -d diff --git a/docs/content/docs/development/whole-domain-connect.mdx b/docs/content/docs/development/whole-domain-connect.mdx index d9b5342c3..81c1eb761 100644 --- a/docs/content/docs/development/whole-domain-connect.mdx +++ b/docs/content/docs/development/whole-domain-connect.mdx @@ -83,7 +83,7 @@ The backend runs as uid `1000`, so the file has to be readable by that user (`ch The Client ID belongs to your instance, not to any one workspace, so a customer's authorization says nothing about which workspace asked for it. A Google grant is therefore recorded only for the workspace that proves it controls the domain, and only when the domain's directory lists the administrator's address as a super administrator. The proof is one of: - **The administrator's Google sign-in.** It goes through the dashboard's own Google sign-in client (`GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`) and returns to its existing redirect URI (`GOOGLE_REDIRECT_URI`, or `API_PUBLIC_URL` plus `/v1/auth/google/callback`), asking only for `openid` and `email`. The callback recognizes an administrator's proof and hands it back to the dashboard window that opened it; it signs nobody in. No redirect URI needs registering beyond the one sign-in already uses. When that client is not configured, the `BOX_GOOGLE_*` mailbox client is used the same way, through its own redirect URI (`/addresses/google/callback`) and again with `openid` and `email` only. The sign-in carries a PKCE challenge and an OpenID nonce, and the backend redeems the code with the matching verifier and accepts the ID token only when it echoes that nonce. -- **A DNS record.** A `TXT` record at `_warmbly.` holding a `warmbly-verify=` value unique to the workspace and domain, keyed by `AUTH_SECRET`. Always offered, and the only proof on an instance with neither Google client. +- **A DNS record.** A `TXT` record at `_warmbly.` holding a `warmbly-verify=` value unique to the workspace and domain, keyed by `DOMAIN_PROOF_SECRET` (which defaults to `AUTH_SECRET`). Always offered, and the only proof on an instance with neither Google client. Customer administrators sign in to that client from their own organizations, so its OAuth consent screen has to be **External**. An **Internal** consent screen admits only accounts in your own Google organization, and every other administrator is refused and has to use the DNS record. diff --git a/internal/api/middleware/internal_auth.go b/internal/api/middleware/internal_auth.go index b49e3f164..dff0b6ba6 100644 --- a/internal/api/middleware/internal_auth.go +++ b/internal/api/middleware/internal_auth.go @@ -6,8 +6,10 @@ import ( "os" "strings" "sync" + "time" "github.com/gin-gonic/gin" + "github.com/warmbly/warmbly/internal/pkg/secretset" ) // InternalAuthMiddleware protects the internal routes the edge services @@ -40,7 +42,7 @@ func internalAuth(c *gin.Context) { return } provided := []byte(strings.TrimPrefix(header, "Bearer ")) - if subtle.ConstantTimeCompare(provided, internalToken) != 1 { + if subtle.ConstantTimeCompare(provided, internalToken) != 1 && !previousTokenMatches(provided, "INTERNAL_API") { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid bearer token"}) return } @@ -76,6 +78,22 @@ func nodeBrokerAuth(c *gin.Context) { checkNodeToken(c, brokerToken, nil) } +func previousTokenMatches(provided []byte, prefix string) bool { + until, err := time.Parse(time.RFC3339, os.Getenv(prefix+"_PREVIOUS_UNTIL")) + if err != nil || !time.Now().Before(until) { + return false + } + tokens, err := secretset.Parse(os.Getenv(prefix + "_PREVIOUS_TOKENS")) + if err != nil { + return false + } + matched := false + for _, token := range tokens { + matched = subtle.ConstantTimeCompare(provided, []byte(token)) == 1 || matched + } + return matched +} + // NodeAuthMiddleware guards node-only routes on NODE_BROKER_TOKEN; NODE_ACCEPT_INTERNAL_TOKEN=true also admits INTERNAL_API_TOKEN while older nodes upgrade. func (h *Handler) NodeAuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { @@ -139,6 +157,9 @@ func checkNodeToken(c *gin.Context, token, legacy []byte) { if !ok && len(legacy) > 0 { ok = subtle.ConstantTimeCompare(provided, legacy) == 1 } + if !ok { + ok = previousTokenMatches(provided, "NODE_BROKER") + } if !ok { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid bearer token"}) return diff --git a/internal/api/middleware/token_rotation_test.go b/internal/api/middleware/token_rotation_test.go new file mode 100644 index 000000000..36a82d1d7 --- /dev/null +++ b/internal/api/middleware/token_rotation_test.go @@ -0,0 +1,61 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" +) + +func TestTokenRotationGraceIsScopedAndExpires(t *testing.T) { + t.Setenv("INTERNAL_API_TOKEN", "internal-current") + t.Setenv("NODE_BROKER_TOKEN", "broker-current") + t.Setenv("INTERNAL_API_PREVIOUS_TOKENS", `["internal-previous"]`) + t.Setenv("NODE_BROKER_PREVIOUS_TOKENS", `["broker-previous"]`) + future := time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + t.Setenv("INTERNAL_API_PREVIOUS_UNTIL", future) + t.Setenv("NODE_BROKER_PREVIOUS_UNTIL", future) + internalTokenOnce = sync.Once{} + brokerTokenOnce = sync.Once{} + t.Cleanup(func() { + internalTokenOnce = sync.Once{} + brokerTokenOnce = sync.Once{} + internalToken = nil + brokerToken = nil + }) + h := &Handler{} + r := gin.New() + r.GET("/internal", h.InternalAuthMiddleware(), func(c *gin.Context) { c.Status(http.StatusOK) }) + r.GET("/broker", h.NodeBrokerAuthMiddleware(), func(c *gin.Context) { c.Status(http.StatusOK) }) + request := func(path, token string) int { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.Header.Set("Authorization", "Bearer "+token) + out := httptest.NewRecorder() + r.ServeHTTP(out, req) + return out.Code + } + for _, tc := range []struct { + path, token string + want int + }{{"/internal", "internal-current", 200}, {"/internal", "internal-previous", 200}, {"/internal", "broker-previous", 401}, {"/broker", "broker-current", 200}, {"/broker", "broker-previous", 200}, {"/broker", "internal-previous", 401}} { + if got := request(tc.path, tc.token); got != tc.want { + t.Fatalf("scope %s: got %d, want %d", tc.path, got, tc.want) + } + } + past := time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) + t.Setenv("INTERNAL_API_PREVIOUS_UNTIL", past) + t.Setenv("NODE_BROKER_PREVIOUS_UNTIL", past) + if request("/internal", "internal-previous") != 401 || request("/broker", "broker-previous") != 401 { + t.Fatal("previous tokens must expire without restarting") + } + if request("/internal", "internal-current") != 200 || request("/broker", "broker-current") != 200 { + t.Fatal("expiry must preserve current credentials") + } + t.Setenv("INTERNAL_API_PREVIOUS_UNTIL", future) + t.Setenv("INTERNAL_API_PREVIOUS_TOKENS", `["sensitive-value",5]`) + if request("/internal", "sensitive-value") != 401 { + t.Fatal("malformed overlap configuration must fail closed") + } +} diff --git a/internal/app/instanceconfig/entries.go b/internal/app/instanceconfig/entries.go index 367d447b5..b94a73d7e 100644 --- a/internal/app/instanceconfig/entries.go +++ b/internal/app/instanceconfig/entries.go @@ -324,6 +324,46 @@ var table = []Entry{ }, // Authentication and access. + { + Key: "DOMAIN_PROOF_SECRET", Group: GroupAuth, RuntimeChangeable: ChangeBootOnly, + Effect: "Keys DNS ownership proofs independently of AUTH_SECRET when configured.", + DocsAnchor: docsSecrets, WhenUnset: SourceDerived, + Resolve: func(*Runtime) string { + if value := os.Getenv("DOMAIN_PROOF_SECRET"); value != "" { + return value + } + return os.Getenv("AUTH_SECRET") + }, + }, + { + Key: "UNSUBSCRIBE_SIGNING_READ_UNTIL", Group: GroupAuth, RuntimeChangeable: ChangeBootOnly, + Effect: "RFC3339 cutoff for previous unsubscribe signatures and their maximum expiry.", + DocsAnchor: docsSecrets, + Resolve: envValue("UNSUBSCRIBE_SIGNING_READ_UNTIL"), + }, + { + Key: "UNSUBSCRIBE_SIGNING_READ_SECRETS", Group: GroupAuth, RuntimeChangeable: ChangeBootOnly, + Effect: "Previous unsubscribe signing secrets as a JSON array, accepted only through the configured cutoff.", + DocsAnchor: docsSecrets, + Resolve: envValue("UNSUBSCRIBE_SIGNING_READ_SECRETS"), + }, + { + Key: "UNSUBSCRIBE_SIGNING_SECRET", Group: GroupAuth, RuntimeChangeable: ChangeBootOnly, + Effect: "Signs recipient unsubscribe links independently of AUTH_SECRET when configured.", + DocsAnchor: docsSecrets, WhenUnset: SourceDerived, + Resolve: func(*Runtime) string { + if value := os.Getenv("UNSUBSCRIBE_SIGNING_SECRET"); value != "" { + return value + } + return os.Getenv("AUTH_SECRET") + }, + }, + { + Key: "TWOFA_READ_SECRETS", Group: GroupAuth, RuntimeChangeable: ChangeBootOnly, + Effect: "Additional TOTP decryption secrets as a JSON array. New enrollments use TWOFA_SECRET.", + DocsAnchor: docsSecrets, + Resolve: envValue("TWOFA_READ_SECRETS"), + }, { Key: "AUTH_SECRET", Group: GroupAuth, RuntimeChangeable: ChangeBootOnly, Effect: "Signs every session and JWT. It must be byte-identical to the realtime service's JWT_SECRET; compare the fingerprints.", @@ -332,7 +372,7 @@ var table = []Entry{ }, { Key: "TWOFA_SECRET", Group: GroupAuth, RuntimeChangeable: ChangeBootOnly, - Effect: "Seals stored TOTP secrets. Falls back to AUTH_SECRET; rotating it invalidates every enrolled authenticator.", + Effect: "Seals stored TOTP secrets. Falls back to AUTH_SECRET; retain matching read secrets while resealing existing enrollments.", DocsAnchor: docsSecrets, WhenUnset: SourceDerived, Resolve: func(*Runtime) string { if v := trimmed("TWOFA_SECRET"); v != "" { @@ -564,6 +604,12 @@ var table = []Entry{ }, // Encryption. + { + Key: "CREDENTIALS_ENCRYPTION_READ_KEYS", Group: GroupEncryption, RuntimeChangeable: ChangeBootOnly, + Effect: "Additional credential decryption keys as a JSON array. New ciphertext uses CREDENTIALS_ENCRYPTION_KEY.", + DocsAnchor: docsEncryption, + Resolve: envValue("CREDENTIALS_ENCRYPTION_READ_KEYS"), + }, { Key: "KMS_PROVIDER", Group: GroupEncryption, RuntimeChangeable: ChangeBootOnly, Effect: "local wraps organization keys with the master key below; aws wraps them with AWS KMS; brokered holds no key material and asks this instance to unwrap, which is what a node off this machine should run.", @@ -696,6 +742,30 @@ var table = []Entry{ }, // Workers. + { + Key: "NODE_BROKER_PREVIOUS_UNTIL", Group: GroupWorkers, RuntimeChangeable: ChangeBootOnly, + Effect: "RFC3339 cutoff for previous fleet broker bearer tokens.", + DocsAnchor: docsWorkers, + Resolve: envValue("NODE_BROKER_PREVIOUS_UNTIL"), + }, + { + Key: "NODE_BROKER_PREVIOUS_TOKENS", Group: GroupWorkers, RuntimeChangeable: ChangeBootOnly, + Effect: "Previous fleet broker bearer tokens as a JSON array, accepted only before the explicit cutoff.", + DocsAnchor: docsWorkers, + Resolve: envValue("NODE_BROKER_PREVIOUS_TOKENS"), + }, + { + Key: "INTERNAL_API_PREVIOUS_UNTIL", Group: GroupWorkers, RuntimeChangeable: ChangeBootOnly, + Effect: "RFC3339 cutoff for previous tracking and forms bearer tokens.", + DocsAnchor: docsWorkers, + Resolve: envValue("INTERNAL_API_PREVIOUS_UNTIL"), + }, + { + Key: "INTERNAL_API_PREVIOUS_TOKENS", Group: GroupWorkers, RuntimeChangeable: ChangeBootOnly, + Effect: "Previous tracking and forms bearer tokens as a JSON array, accepted only before the explicit cutoff.", + DocsAnchor: docsWorkers, + Resolve: envValue("INTERNAL_API_PREVIOUS_TOKENS"), + }, { Key: "INTERNAL_API_TOKEN", Group: GroupWorkers, RuntimeChangeable: ChangeBootOnly, Effect: "The token on the internal routes the tracking and forms services call. Fleet nodes use it too unless NODE_BROKER_TOKEN is set.", diff --git a/internal/app/token/rotation_test.go b/internal/app/token/rotation_test.go new file mode 100644 index 000000000..5b638a257 --- /dev/null +++ b/internal/app/token/rotation_test.go @@ -0,0 +1,31 @@ +package token + +import ( + "encoding/json" + "github.com/google/uuid" + "testing" + "time" +) + +func TestSessionRotationDoesNotAcceptPurposeReadKeys(t *testing.T) { + previous := &tokenService{AuthSecret: "previous-session-secret-at-least-32-characters"} + current := &tokenService{AuthSecret: "current-session-secret-at-least-32-characters"} + now := time.Now() + readKeys, err := json.Marshal([]string{previous.AuthSecret}) + if err != nil { + t.Fatal(err) + } + for _, key := range []string{"TWOFA_READ_SECRETS", "UNSUBSCRIBE_SIGNING_READ_SECRETS"} { + t.Setenv(key, string(readKeys)) + } + t.Setenv("UNSUBSCRIBE_SIGNING_READ_UNTIL", now.Add(time.Hour).UTC().Format(time.RFC3339)) + for _, purpose := range []string{PurposeAccess, PurposeRefresh, PurposeWebSocket, PurposePasswordReset, PurposeTwoFAPending} { + encoded, err := previous.GenerateTokenFor(purpose, uuid.New(), uuid.New(), "", "nonce", now, now.Add(time.Hour)) + if err != nil { + t.Fatal(err) + } + if _, err := current.VerifyTokenFor(purpose, encoded); err == nil { + t.Fatal("previous session signatures must be refused for every purpose") + } + } +} diff --git a/internal/app/twofa/enroll.go b/internal/app/twofa/enroll.go index c4bbff215..049a232f1 100644 --- a/internal/app/twofa/enroll.go +++ b/internal/app/twofa/enroll.go @@ -56,7 +56,7 @@ func (s *service) EnrollConfirm(ctx context.Context, userID uuid.UUID, code stri if row.Enabled { return nil, errx.New(errx.BadRequest, "2FA is already enabled") } - secret, err := Open(s.sealKey, row.SecretSealed) + secret, err := s.openSecret(row.SecretSealed) if err != nil { return nil, errx.InternalError() } diff --git a/internal/app/twofa/rotation_test.go b/internal/app/twofa/rotation_test.go new file mode 100644 index 000000000..2ea39d5fa --- /dev/null +++ b/internal/app/twofa/rotation_test.go @@ -0,0 +1,42 @@ +package twofa + +import ( + "testing" + "time" +) + +func TestMFAKeyRotationPreservesEnrollmentAndRollback(t *testing.T) { + oldKey, newKey := DeriveKey("previous-mfa-secret"), DeriveKey("replacement-mfa-secret") + secret, err := GenerateSecret() + if err != nil { + t.Fatal(err) + } + before, err := Seal(oldKey, secret) + if err != nil { + t.Fatal(err) + } + after, err := Seal(newKey, secret) + if err != nil { + t.Fatal(err) + } + baseline := &service{sealKey: oldKey, readKeys: [][32]byte{newKey}} + current := &service{sealKey: newKey, readKeys: [][32]byte{oldKey}} + for _, reader := range []*service{baseline, current} { + for _, sealed := range []string{before, after} { + got, err := reader.openSecret(sealed) + if err != nil || got != secret { + t.Fatal("MFA enrollment must survive resealing and rollback") + } + code, codeErr := hotp(secret, uint64(time.Now().Unix())/totpPeriod) + if codeErr != nil { + t.Fatal(codeErr) + } + if _, ok := ValidateCodeStep(got, code); !ok { + t.Fatal("the existing authenticator must remain usable") + } + } + } + if _, err := Open(oldKey, after); err == nil { + t.Fatal("replacement ciphertext must require the replacement key") + } +} diff --git a/internal/app/twofa/service.go b/internal/app/twofa/service.go index b656c9a76..e7570cda9 100644 --- a/internal/app/twofa/service.go +++ b/internal/app/twofa/service.go @@ -92,18 +92,32 @@ type IdentityLinker interface { } type service struct { - repo repository.TOTPRepository - users repository.UserRepository - tokens token.TokenService - cache *cache.Cache - sealKey [32]byte - linker IdentityLinker + repo repository.TOTPRepository + users repository.UserRepository + tokens token.TokenService + cache *cache.Cache + sealKey [32]byte + readKeys [][32]byte + linker IdentityLinker } func (s *service) WireIdentityLinker(l IdentityLinker) { s.linker = l } -func NewService(repo repository.TOTPRepository, users repository.UserRepository, tokens token.TokenService, c *cache.Cache, sealKey [32]byte) Service { - return &service{repo: repo, users: users, tokens: tokens, cache: c, sealKey: sealKey} +func NewService(repo repository.TOTPRepository, users repository.UserRepository, tokens token.TokenService, c *cache.Cache, sealKey [32]byte, readKeys ...[32]byte) Service { + return &service{repo: repo, users: users, tokens: tokens, cache: c, sealKey: sealKey, readKeys: readKeys} +} + +func (s *service) openSecret(sealed string) (string, error) { + secret, err := Open(s.sealKey, sealed) + if err == nil { + return secret, nil + } + for _, key := range s.readKeys { + if secret, readErr := Open(key, sealed); readErr == nil { + return secret, nil + } + } + return "", err } func (s *service) IsEnabled(ctx context.Context, userID uuid.UUID) (bool, error) { @@ -185,7 +199,7 @@ func (s *service) validCode(ctx context.Context, userID uuid.UUID, row *models.U if isRecoveryFormat(code) { return s.tryConsumeRecoveryCode(ctx, userID, code) } - secret, err := Open(s.sealKey, row.SecretSealed) + secret, err := s.openSecret(row.SecretSealed) if err != nil { return false } diff --git a/internal/app/unsublink/rotation_test.go b/internal/app/unsublink/rotation_test.go new file mode 100644 index 000000000..8f025d0c2 --- /dev/null +++ b/internal/app/unsublink/rotation_test.go @@ -0,0 +1,32 @@ +package unsublink + +import ( + "github.com/google/uuid" + "testing" + "time" +) + +func TestReadKeysPreserveIssuedLinksWithinCutoff(t *testing.T) { + now := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) + until := now.Add(Validity) + previous := New("previous-purpose-secret", "https://example.invalid") + current := NewWithReadKeys("current-purpose-secret", "https://example.invalid", []string{"previous-purpose-secret"}, until) + issued := previous.Token(uuid.New(), uuid.New(), uuid.New(), now.Add(-time.Hour)) + if _, err := current.Verify(issued, now); err != nil { + t.Fatal("previously issued links must remain usable") + } + beyond := previous.Token(uuid.New(), uuid.New(), uuid.New(), now.Add(time.Hour)) + if _, err := current.Verify(beyond, now); err != ErrInvalid { + t.Fatal("previous keys must not extend the configured window") + } + if _, err := current.Verify(issued, until); err != ErrInvalid { + t.Fatal("read keys must expire at the cutoff") + } + fresh := current.Token(uuid.New(), uuid.New(), uuid.New(), now) + if _, err := New("current-purpose-secret", "https://example.invalid").Verify(fresh, now); err != nil { + t.Fatal("new links must use the current key") + } + if _, err := previous.Verify(fresh, now); err != ErrInvalid { + t.Fatal("new links must not use a read key") + } +} diff --git a/internal/app/unsublink/signer.go b/internal/app/unsublink/signer.go index d9c4e00a9..1d25620d8 100644 --- a/internal/app/unsublink/signer.go +++ b/internal/app/unsublink/signer.go @@ -49,17 +49,32 @@ const Path = "/unsubscribe/" // key is scoped with a purpose string so an unsubscribe token can never be // replayed as any other signed artefact that shares the secret. type Signer struct { - key []byte - baseURL string + key []byte + baseURL string + readKeys [][]byte + readUntil time.Time } // New builds a signer. baseURL is the public origin of the API (the process // that serves /unsubscribe); empty means links cannot be minted and Enabled // reports false. func New(secret, baseURL string) *Signer { + return NewWithReadKeys(secret, baseURL, nil, time.Time{}) +} + +// NewWithReadKeys preserves issued links through a bounded verification window. +func NewWithReadKeys(secret, baseURL string, readSecrets []string, readUntil time.Time) *Signer { + s := &Signer{key: deriveKey(secret), baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"), readUntil: readUntil} + for _, value := range readSecrets { + s.readKeys = append(s.readKeys, deriveKey(value)) + } + return s +} + +func deriveKey(secret string) []byte { mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte("warmbly:unsubscribe-link:v1")) - return &Signer{key: mac.Sum(nil), baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/")} + return mac.Sum(nil) } // Enabled reports whether the signer knows a public origin to mint links on. @@ -130,14 +145,21 @@ func (s *Signer) Verify(token string, now time.Time) (Claims, error) { return Claims{}, ErrInvalid } body, sig := raw[:rawLen], raw[rawLen:] - if !hmac.Equal(sig, s.mac(body)) { + expiresAt := time.Unix(int64(binary.BigEndian.Uint64(body[48:56])), 0).UTC() + valid := hmac.Equal(sig, s.mac(body)) + if !valid && now.Before(s.readUntil) && !expiresAt.After(s.readUntil) { + for _, key := range s.readKeys { + valid = hmac.Equal(sig, macWithKey(key, body)) || valid + } + } + if !valid { return Claims{}, ErrInvalid } var c Claims copy(c.OrgID[:], body[0:16]) copy(c.CampaignID[:], body[16:32]) copy(c.ContactID[:], body[32:48]) - c.ExpiresAt = time.Unix(int64(binary.BigEndian.Uint64(body[48:56])), 0).UTC() + c.ExpiresAt = expiresAt if !now.Before(c.ExpiresAt) { return c, ErrExpired } @@ -145,7 +167,11 @@ func (s *Signer) Verify(token string, now time.Time) (Claims, error) { } func (s *Signer) mac(body []byte) []byte { - m := hmac.New(sha256.New, s.key) + return macWithKey(s.key, body) +} + +func macWithKey(key, body []byte) []byte { + m := hmac.New(sha256.New, key) m.Write(body) return m.Sum(nil)[:macLen] } diff --git a/internal/config/auth_rotation_test.go b/internal/config/auth_rotation_test.go new file mode 100644 index 000000000..feddcfd17 --- /dev/null +++ b/internal/config/auth_rotation_test.go @@ -0,0 +1,39 @@ +package config + +import ( + "strings" + "testing" +) + +func TestAuthRotationDefaultsPreserveSelfHosts(t *testing.T) { + t.Setenv("AUTH_SECRET", strings.Repeat("a", 32)) + for _, name := range []string{"TWOFA_SECRET", "TWOFA_READ_SECRETS", "UNSUBSCRIBE_SIGNING_SECRET", "UNSUBSCRIBE_SIGNING_READ_SECRETS", "UNSUBSCRIBE_SIGNING_READ_UNTIL", "DOMAIN_PROOF_SECRET"} { + t.Setenv(name, "") + } + t.Cleanup(func() { SetTurnstileSecretResolved(false) }) + cfg, err := (&Config{}).LoadAuthConfig(t.Context()) + if err != nil { + t.Fatal(err) + } + if cfg.TwoFASecret != cfg.AuthSecret || cfg.DomainProofSecret != cfg.AuthSecret || cfg.UnsubscribeSigningSecret != cfg.AuthSecret || len(cfg.TwoFAReadSecrets) != 0 || len(cfg.UnsubscribeReadSecrets) != 0 { + t.Fatal("unset optional settings must preserve the existing key configuration") + } + t.Setenv("TWOFA_SECRET", strings.Repeat("m", 32)) + t.Setenv("DOMAIN_PROOF_SECRET", strings.Repeat("d", 32)) + t.Setenv("UNSUBSCRIBE_SIGNING_SECRET", strings.Repeat("u", 32)) + cfg, err = (&Config{}).LoadAuthConfig(t.Context()) + if err != nil { + t.Fatal(err) + } + if cfg.AuthSecret != strings.Repeat("a", 32) || cfg.TwoFASecret != strings.Repeat("m", 32) || cfg.DomainProofSecret != strings.Repeat("d", 32) || cfg.UnsubscribeSigningSecret != strings.Repeat("u", 32) { + t.Fatal("separate purpose keys must resolve independently") + } + t.Setenv("UNSUBSCRIBE_SIGNING_READ_SECRETS", `["private-previous-signing-secret"]`) + if _, err := (&Config{}).LoadAuthConfig(t.Context()); err == nil || strings.Contains(err.Error(), "private-previous-signing-secret") { + t.Fatal("previous signing keys require a cutoff and must not appear in errors") + } + t.Setenv("UNSUBSCRIBE_SIGNING_READ_UNTIL", "2026-01-01T00:00:00Z") + if _, err := (&Config{}).LoadAuthConfig(t.Context()); err != nil { + t.Fatal("an elapsed cutoff must not prevent current services from starting") + } +} diff --git a/internal/config/config_auth.go b/internal/config/config_auth.go index 551c54569..897526408 100644 --- a/internal/config/config_auth.go +++ b/internal/config/config_auth.go @@ -6,6 +6,9 @@ import ( "net/url" "os" "strings" + "time" + + "github.com/warmbly/warmbly/internal/pkg/secretset" ) type AuthConfig struct { @@ -31,9 +34,13 @@ type AuthConfig struct { AppleIOSBundleID string GoogleIOSClientID string - AuthSecret string - TurnstileSecret string - TurnstileBypass string + AuthSecret string + UnsubscribeSigningSecret string + UnsubscribeReadSecrets []string + UnsubscribeReadUntil time.Time + DomainProofSecret string + TurnstileSecret string + TurnstileBypass string // AppAttestAppIDs are the "." values whose App Attest // proofs stand in for the captcha. Empty turns native app proofs off. @@ -44,7 +51,8 @@ type AuthConfig struct { // TwoFASecret is the server-wide key the TOTP secret is sealed with (AES-GCM). // Must be set when 2FA is in use; falls back to AuthSecret when unset so a // deployment without the env var still functions (sealed under the auth key). - TwoFASecret string + TwoFASecret string + TwoFAReadSecrets []string // WebAuthn / passkey relying-party configuration. // @@ -115,6 +123,26 @@ func (c *Config) LoadAuthConfig(ctx context.Context) (*AuthConfig, error) { // 2FA sealing key. Optional: falls back to AUTH_SECRET so existing // deployments keep working; rotating it invalidates enrolled TOTP secrets. twoFASecret := c.GetSecretOptional(ctx, "TWOFA_SECRET", "twofa_secret", authSecret) + twoFAReadSecrets, err := secretset.Parse(c.GetSecretOptional(ctx, "TWOFA_READ_SECRETS", "twofa_read_secrets", "")) + if err != nil { + return nil, fmt.Errorf("TWOFA_READ_SECRETS: %w", err) + } + unsubscribeSigningSecret := c.GetSecretOptional(ctx, "UNSUBSCRIBE_SIGNING_SECRET", "unsubscribe/signing_secret", authSecret) + domainProofSecret := c.GetSecretOptional(ctx, "DOMAIN_PROOF_SECRET", "domain_proof_secret", authSecret) + if len(unsubscribeSigningSecret) < MinAuthSecretLength || len(domainProofSecret) < MinAuthSecretLength { + return nil, fmt.Errorf("unsubscribe and domain proof signing secrets require at least %d characters", MinAuthSecretLength) + } + unsubscribeReadSecrets, err := secretset.Parse(c.GetSecretOptional(ctx, "UNSUBSCRIBE_SIGNING_READ_SECRETS", "unsubscribe/signing_read_secrets", "")) + if err != nil { + return nil, fmt.Errorf("UNSUBSCRIBE_SIGNING_READ_SECRETS: %w", err) + } + var unsubscribeReadUntil time.Time + if len(unsubscribeReadSecrets) > 0 { + unsubscribeReadUntil, err = time.Parse(time.RFC3339, c.GetStringOptional(ctx, "UNSUBSCRIBE_SIGNING_READ_UNTIL", "unsubscribe/signing_read_until", "")) + if err != nil { + return nil, fmt.Errorf("UNSUBSCRIBE_SIGNING_READ_SECRETS requires an RFC3339 UNSUBSCRIBE_SIGNING_READ_UNTIL") + } + } rpDisplayName := c.GetStringOptional(ctx, "WEBAUTHN_RP_DISPLAY_NAME", "webauthn/rp_display_name", "Warmbly") rpIDRaw := c.GetStringOptional(ctx, "WEBAUTHN_RP_ID", "webauthn/rp_id", "") @@ -135,13 +163,18 @@ func (c *Config) LoadAuthConfig(ctx context.Context) (*AuthConfig, error) { AppleIOSBundleID: appleIOSBundleID, GoogleIOSClientID: googleIOSClientID, - AuthSecret: authSecret, - TurnstileSecret: turnstileSecret, - TurnstileBypass: turnstileBypass, + AuthSecret: authSecret, + UnsubscribeSigningSecret: unsubscribeSigningSecret, + UnsubscribeReadSecrets: unsubscribeReadSecrets, + UnsubscribeReadUntil: unsubscribeReadUntil, + DomainProofSecret: domainProofSecret, + TurnstileSecret: turnstileSecret, + TurnstileBypass: turnstileBypass, AppAttestAppIDs: appAttestAppIDs, AppAttestAllowDevelopment: appAttestAllowDev, TwoFASecret: twoFASecret, + TwoFAReadSecrets: twoFAReadSecrets, WebAuthnRPID: rpID, WebAuthnRPDisplayName: rpDisplayName, diff --git a/internal/pkg/encrypt/encrypter.go b/internal/pkg/encrypt/encrypter.go index 4c462912f..88fa3e461 100644 --- a/internal/pkg/encrypt/encrypter.go +++ b/internal/pkg/encrypt/encrypter.go @@ -8,6 +8,8 @@ import ( "errors" "io" "os" + + "github.com/warmbly/warmbly/internal/pkg/secretset" ) // Encrypted holds the hex-encoded ciphertext and nonce. @@ -19,18 +21,40 @@ type Encrypted struct { // Encrypter performs AES-GCM encryption with a fixed 32-byte key. type Encrypter struct { - aead cipher.AEAD + aead cipher.AEAD + readKeys []cipher.AEAD } // FromEnv creates an Encrypter from the CREDENTIALS_ENCRYPTION_KEY env var // (64 hex chars = 32 bytes). Returns (nil, nil) when the var is unset so // callers can keep booting without credential sealing configured. func FromEnv() (*Encrypter, error) { + keys, err := secretset.Parse(os.Getenv("CREDENTIALS_ENCRYPTION_READ_KEYS")) + if err != nil { + return nil, err + } key := os.Getenv("CREDENTIALS_ENCRYPTION_KEY") if key == "" { + if len(keys) > 0 { + return nil, errors.New("credential read keys require a primary encryption key") + } return nil, nil } - return NewEncrypterFromHex(key) + primary, err := NewEncrypterFromHex(key) + if err != nil { + return nil, err + } + for _, value := range keys { + if value == key { + continue + } + reader, err := NewEncrypterFromHex(value) + if err != nil { + return nil, errors.New("invalid additional credential read key") + } + primary.readKeys = append(primary.readKeys, reader.aead) + } + return primary, nil } // NewEncrypterFromHex creates an Encrypter from a 64-character hex key. @@ -110,7 +134,19 @@ func (e *Encrypter) DecryptEncrypted(enc *Encrypted) ([]byte, error) { if err != nil { return nil, err } - return e.aead.Open(nil, nonce, ct, nil) + if len(nonce) != e.aead.NonceSize() { + return nil, errors.New("invalid encryption nonce") + } + plaintext, err := e.aead.Open(nil, nonce, ct, nil) + if err == nil { + return plaintext, nil + } + for _, reader := range e.readKeys { + if plaintext, readErr := reader.Open(nil, nonce, ct, nil); readErr == nil { + return plaintext, nil + } + } + return nil, err } // --------------------------------------------------------------------- diff --git a/internal/pkg/encrypt/rotation_test.go b/internal/pkg/encrypt/rotation_test.go new file mode 100644 index 000000000..550f31097 --- /dev/null +++ b/internal/pkg/encrypt/rotation_test.go @@ -0,0 +1,87 @@ +package encrypt + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestCredentialRotationPreservesMixedWritesAndRollback(t *testing.T) { + oldKey, newKey := strings.Repeat("11", 32), strings.Repeat("22", 32) + original, err := NewEncrypterFromHex(oldKey) + if err != nil { + t.Fatal(err) + } + before, err := original.Encrypt("existing-mailbox-password") + if err != nil { + t.Fatal(err) + } + t.Setenv("CREDENTIALS_ENCRYPTION_KEY", oldKey) + reads, _ := json.Marshal([]string{newKey}) + t.Setenv("CREDENTIALS_ENCRYPTION_READ_KEYS", string(reads)) + baseline, err := FromEnv() + if err != nil { + t.Fatal(err) + } + baselineWrite, err := baseline.Encrypt("baseline-password") + if err != nil { + t.Fatal(err) + } + if got, err := original.Decrypt(baselineWrite); err != nil || got != "baseline-password" { + t.Fatal("baseline must retain the original write format and key") + } + t.Setenv("CREDENTIALS_ENCRYPTION_KEY", newKey) + reads, _ = json.Marshal([]string{oldKey}) + t.Setenv("CREDENTIALS_ENCRYPTION_READ_KEYS", string(reads)) + replacement, err := FromEnv() + if err != nil { + t.Fatal(err) + } + after, err := replacement.Encrypt("new-mailbox-password") + if err != nil { + t.Fatal(err) + } + for _, reader := range []*Encrypter{baseline, replacement} { + for _, sample := range []struct{ sealed, want string }{{before, "existing-mailbox-password"}, {after, "new-mailbox-password"}} { + if got, err := reader.Decrypt(sample.sealed); err != nil || got != sample.want { + t.Fatal("compatible releases must read both generations") + } + } + } + newOnly, err := NewEncrypterFromHex(newKey) + if err != nil { + t.Fatal(err) + } + if got, err := newOnly.Decrypt(after); err != nil || got != "new-mailbox-password" { + t.Fatal("new writes must use only the primary key") + } + if _, err := newOnly.Decrypt(before); err == nil { + t.Fatal("raw-key constructors must not inherit instance read keys") + } + if _, err := original.Decrypt(after); err == nil { + t.Fatal("new writes must not remain sealed with the original key") + } +} + +func TestCredentialReadKeyConfiguration(t *testing.T) { + t.Setenv("CREDENTIALS_ENCRYPTION_KEY", "") + t.Setenv("CREDENTIALS_ENCRYPTION_READ_KEYS", "[]") + if got, err := FromEnv(); err != nil || got != nil { + t.Fatal("empty self-host defaults must remain supported") + } + t.Setenv("CREDENTIALS_ENCRYPTION_READ_KEYS", `["not-a-valid-key"]`) + if _, err := FromEnv(); err == nil { + t.Fatal("read keys require a primary key") + } + t.Setenv("CREDENTIALS_ENCRYPTION_KEY", strings.Repeat("11", 32)) + if _, err := FromEnv(); err == nil || strings.Contains(err.Error(), "not-a-valid-key") { + t.Fatal("invalid read keys must fail without disclosing them") + } + enc, err := NewEncrypterFromHex(strings.Repeat("11", 32)) + if err != nil { + t.Fatal(err) + } + if _, err := enc.DecryptEncrypted(&Encrypted{Nonce: "00", Ciphertext: "00"}); err == nil { + t.Fatal("malformed ciphertext must return an error") + } +} diff --git a/internal/pkg/secretset/parse.go b/internal/pkg/secretset/parse.go new file mode 100644 index 000000000..25499b22c --- /dev/null +++ b/internal/pkg/secretset/parse.go @@ -0,0 +1,24 @@ +package secretset + +import ( + "encoding/json" + "errors" + "strings" +) + +// Parse reads a bounded JSON array without including secret values in errors. +func Parse(value string) ([]string, error) { + if strings.TrimSpace(value) == "" { + return nil, nil + } + var keys []string + if err := json.Unmarshal([]byte(value), &keys); err != nil || keys == nil || len(keys) > 4 { + return nil, errors.New("expected a JSON array containing at most four nonempty secrets") + } + for _, key := range keys { + if key == "" { + return nil, errors.New("expected a JSON array containing at most four nonempty secrets") + } + } + return keys, nil +} diff --git a/internal/pkg/secretset/parse_test.go b/internal/pkg/secretset/parse_test.go new file mode 100644 index 000000000..a07e8ad06 --- /dev/null +++ b/internal/pkg/secretset/parse_test.go @@ -0,0 +1,19 @@ +package secretset + +import ( + "strings" + "testing" +) + +func TestParseSecretSets(t *testing.T) { + for _, raw := range []string{"", "[]", `["one","two"]`} { + if _, err := Parse(raw); err != nil { + t.Fatalf("valid list: %v", err) + } + } + for _, raw := range []string{`null`, `"private-input"`, `["private-input",3]`, `[""]`, `["a","b","c","d","e"]`} { + if _, err := Parse(raw); err == nil || strings.Contains(err.Error(), "private-input") { + t.Fatal("invalid lists must fail without returning their contents") + } + } +} From 5863b206a26419828f7b21a710f6fd1be918458f Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Thu, 22 Oct 2026 12:57:44 +0200 Subject: [PATCH 2/2] feat: verify AWS credential read keys, MFA purpose keys and the complete organization key inventory --- .../aws/runtime/checks/dependencies.cjs | 67 +++++++++++++------ deploy/terraform/aws/runtime/main.tf | 2 +- deploy/terraform/aws/runtime/validation.tf | 5 +- 3 files changed, 51 insertions(+), 23 deletions(-) diff --git a/deploy/terraform/aws/runtime/checks/dependencies.cjs b/deploy/terraform/aws/runtime/checks/dependencies.cjs index 142036c3a..aca266507 100644 --- a/deploy/terraform/aws/runtime/checks/dependencies.cjs +++ b/deploy/terraform/aws/runtime/checks/dependencies.cjs @@ -27,15 +27,30 @@ async function check(name, fn) { } } -function verifyCipher(key, encoded, encoding) { +function readSecrets(variable) { + const values = JSON.parse(process.env[variable] || "[]"); + if (!Array.isArray(values) || values.length > 4 || values.some((value) => typeof value !== "string" || !value)) throw new Error("Invalid read keys"); + return values; +} + +function verifyCipher(keys, encoded, encoding) { const raw = Buffer.from(encoded, encoding); if (raw.length < 28) throw new Error("Invalid ciphertext"); - const decipher = crypto.createDecipheriv("aes-256-gcm", key, raw.subarray(0, 12)); - decipher.setAuthTag(raw.subarray(raw.length - 16)); - const first = decipher.update(raw.subarray(12, raw.length - 16)); - const last = decipher.final(); - first.fill(0); - last.fill(0); + for (const key of keys) { + const parts = []; + try { + const decipher = crypto.createDecipheriv("aes-256-gcm", key, raw.subarray(0, 12)); + decipher.setAuthTag(raw.subarray(raw.length - 16)); + parts.push(decipher.update(raw.subarray(12, raw.length - 16))); + parts.push(decipher.final()); + return; + } catch { + // Try the next explicitly configured reader. + } finally { + parts.forEach((part) => part.fill(0)); + } + } + throw new Error("Ciphertext verification failed"); } async function withDatabase(connectionString, fn) { @@ -84,20 +99,30 @@ async function main() { } await check("stored_credentials_and_kms", () => withDatabase(process.env.PRIMARY_DB, async (db) => { - const key = Buffer.from(process.env.CREDENTIALS_ENCRYPTION_KEY, "hex"); - const fields = await db.query("SELECT v AS value FROM email_accounts_smtp_imap CROSS JOIN LATERAL (VALUES (smtp_host),(smtp_user),(smtp_password),(imap_host),(imap_user),(imap_password)) fields(v) WHERE v IS NOT NULL AND v<>'' UNION ALL SELECT v FROM email_accounts_oauth CROSS JOIN LATERAL (VALUES(access_token),(refresh_token)) fields(v) WHERE v IS NOT NULL AND v<>'' UNION ALL SELECT secret FROM webhook_endpoints WHERE secret IS NOT NULL AND secret<>''"); - for (const row of fields.rows) verifyCipher(key, row.value, "hex"); - key.fill(0); - const mfaKey = crypto.createHash("sha256").update(process.env.AUTH_SECRET).digest(); - const mfa = await db.query("SELECT totp_secret_sealed FROM user_totp_settings WHERE totp_enabled"); - for (const row of mfa.rows) verifyCipher(mfaKey, row.totp_secret_sealed, "base64"); - mfaKey.fill(0); - const wrapped = await db.query("SELECT encrypted_data_key FROM organization_encrypted_keys LIMIT 1"); - if (!wrapped.rowCount) throw new Error("No data key available to verify"); - const out = await kms.send(new DecryptCommand({ CiphertextBlob: Buffer.from(wrapped.rows[0].encrypted_data_key, "base64") })); - if (out.Plaintext?.length !== 32) throw new Error("Invalid data key"); - out.Plaintext.fill(0); - return { credential_fields: fields.rowCount, mfa_enrollments: mfa.rowCount, kms_decrypt_as_task_role: true }; + const keys = [process.env.CREDENTIALS_ENCRYPTION_KEY, ...readSecrets("CREDENTIALS_ENCRYPTION_READ_KEYS")].map((value) => Buffer.from(value, "hex")); + const mfaKeys = [process.env.TWOFA_SECRET || process.env.AUTH_SECRET, ...readSecrets("TWOFA_READ_SECRETS")].map((value) => crypto.createHash("sha256").update(value).digest()); + try { + const fields = await db.query("SELECT v AS value,false AS signing_secret FROM email_accounts_smtp_imap CROSS JOIN LATERAL (VALUES (smtp_host),(smtp_user),(smtp_password),(imap_host),(imap_user),(imap_password)) fields(v) WHERE v IS NOT NULL AND v<>'' UNION ALL SELECT v,false FROM email_accounts_oauth CROSS JOIN LATERAL (VALUES(access_token),(refresh_token)) fields(v) WHERE v IS NOT NULL AND v<>'' UNION ALL SELECT secret,true FROM webhook_endpoints WHERE secret IS NOT NULL AND secret<>'' UNION ALL SELECT webhook_secret,true FROM oauth_applications WHERE webhook_secret IS NOT NULL AND webhook_secret<>'' UNION ALL SELECT token,false FROM cloud_link WHERE token IS NOT NULL AND token<>'' UNION ALL SELECT refresh_token,false FROM mailbox_erasures WHERE refresh_token IS NOT NULL AND refresh_token<>''"); + let legacySigningFields = 0; + for (const row of fields.rows) { + if (row.signing_secret && row.value.startsWith("whsec_")) legacySigningFields++; + else verifyCipher(keys, row.value, "hex"); + } + const mfa = await db.query("SELECT totp_secret_sealed FROM user_totp_settings WHERE totp_secret_sealed IS NOT NULL AND totp_secret_sealed<>''"); + for (const row of mfa.rows) verifyCipher(mfaKeys, row.totp_secret_sealed, "base64"); + const wrapped = await db.query("SELECT encrypted_data_key FROM organization_encrypted_keys"); + if (!wrapped.rowCount) throw new Error("No data key available to verify"); + for (let offset = 0; offset < wrapped.rowCount; offset += 5) { + await Promise.all(wrapped.rows.slice(offset, offset + 5).map(async (row) => { + const out = await kms.send(new DecryptCommand({ CiphertextBlob: Buffer.from(row.encrypted_data_key, "base64") })); + try { if (out.Plaintext?.length !== 32) throw new Error("Invalid data key"); } + finally { out.Plaintext?.fill(0); } + })); + } + return { credential_fields: fields.rowCount - legacySigningFields, legacy_signing_fields: legacySigningFields, mfa_enrollments: mfa.rowCount, organization_keys: wrapped.rowCount, kms_decrypt_as_task_role: true }; + } finally { + [...keys, ...mfaKeys].forEach((key) => key.fill(0)); + } })); await check("existing_shared_cache", async () => { diff --git a/deploy/terraform/aws/runtime/main.tf b/deploy/terraform/aws/runtime/main.tf index 92ea91e63..afae9ec2f 100644 --- a/deploy/terraform/aws/runtime/main.tf +++ b/deploy/terraform/aws/runtime/main.tf @@ -72,7 +72,7 @@ variable "services" { service.desired_count >= 0 && service.desired_count == floor(service.desired_count) && !contains(service.secret_keys, "AWS_ACCESS_KEY_ID") && !contains(service.secret_keys, "AWS_SECRET_ACCESS_KEY") && alltrue([for key, value in service.environment : - !can(regex("(?i)(password|secret|token|private_key|access_key|primary_db(_direct)?|database_url|redis_url)$", key)) && + !can(regex("(?i)(passwords?|secrets?|tokens?|private_keys?|access_keys?|master_keys?|encryption_keys?|read_keys|primary_db(_direct)?|database_url|redis_url)$", key)) && !can(regex("://[^/@]+:[^/@]+@", value)) ]) ]) diff --git a/deploy/terraform/aws/runtime/validation.tf b/deploy/terraform/aws/runtime/validation.tf index 61a04d931..f2a87993e 100644 --- a/deploy/terraform/aws/runtime/validation.tf +++ b/deploy/terraform/aws/runtime/validation.tf @@ -55,7 +55,10 @@ resource "aws_ecs_task_definition" "validation" { name = key valueFrom = "${local.foundation.secret_arns["backend"]}:${key}::${var.services["backend"].secret_version_id}" } - ], [ + ], [for key in ["CREDENTIALS_ENCRYPTION_READ_KEYS", "TWOFA_SECRET", "TWOFA_READ_SECRETS"] : { + name = key + valueFrom = "${local.foundation.secret_arns["backend"]}:${key}::${var.services["backend"].secret_version_id}" + } if contains(var.services["backend"].secret_keys, key)], [ { name = "CONSUMER_DB", valueFrom = "${local.foundation.secret_arns["consumer"]}:PRIMARY_DB::${var.services["consumer"].secret_version_id}" }, { name = "REALTIME_DB", valueFrom = "${local.foundation.secret_arns["realtime"]}:DATABASE_URL::${var.services["realtime"].secret_version_id}" }, { name = "NEW_REDIS_PASSWORD", valueFrom = "${data.terraform_remote_state.foundation.outputs.cache.credential_secret}:REDIS_PASSWORD::" }