mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 16:07:16 +01:00
feat(crypto): encrypt webhook secrets at rest (phase 2 of 2) — drop plaintext
cc76194f shipped the cipher util + dual-write. This commit closes the
encrypt-at-rest thread:
1. Migration 20260604000004 (applied to remote, prod row count
verified zero so backfill is a no-op):
- DROP CONSTRAINT webhook_endpoints_secret_not_blank (targeted
the column we're dropping)
- ALTER COLUMN secret_encrypted SET NOT NULL (load-bearing now)
- DROP COLUMN secret_plaintext
2. createWebhookEndpoint: writes only secret_encrypted on mint
(plaintext column no longer exists). The encrypt-throw-on-bad-env
behaviour from phase 1 still fails the mint cleanly.
3. getEndpointSigningContext: selects secret_encrypted, decodes the
PostgREST `\x...hex...` bytea wire format (with a base64 fallback),
decrypts via decryptWebhookSecret. Decrypt failure logs and returns
null so the worker records a "[endpoint revoked]" outcome rather
than signing with a wrong key — degraded but never forged.
4. Deploy checklist step 9 verification updated: mint a row, check
`secret_encrypted IS NOT NULL` and that secret_plaintext no longer
exists, trigger a delivery, watch the X-OrangeCat-Signature header
succeed. Rollback section rewritten with the honest "you cannot
rotate this key in place" warning and the 3-step safe rotation.
decodeSupabaseBytea helper added inline — Supabase admin client returns
BYTEA as `\x<hex>` text by default; the fallback to base64 handles
environments where postgrest serialises differently. Never throws,
falls back cleanly.
The encrypt-at-rest thread is now complete: webhook signing secrets
are AES-256-GCM at rest, in-memory only during fire, key rotation
documented as a planned-incident operation.
Suite: 55 suites · 717 tests · 0 failures. tsc + eslint clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
cc76194fd6
commit
6da6b8cd0c
3 files changed
+104
-16
No files matched your search
@@ -242,15 +242,32 @@ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||
Set it in Vercel for the OrangeCat project (Production) as
|
||||
`WEBHOOK_SECRET_KEY`. The value must be exactly 64 hex characters.
|
||||
|
||||
**Verify**: mint a webhook endpoint (step 2). If the env var is
|
||||
missing or malformed, the mint returns 500 — the env is missing.
|
||||
After setting, mint succeeds again.
|
||||
**Verify**:
|
||||
|
||||
1. Mint a webhook endpoint (step 2). If `WEBHOOK_SECRET_KEY` is
|
||||
missing or malformed, the mint returns 500 (server logs show
|
||||
"WEBHOOK_SECRET_KEY is not set" or "must be 64 hex characters").
|
||||
2. After setting, mint succeeds; check the DB row has
|
||||
`secret_encrypted IS NOT NULL` and `secret_plaintext` does not
|
||||
exist (it was dropped in migration 20260604000004).
|
||||
3. Trigger a delivery (smoke test below). The worker decrypts
|
||||
`secret_encrypted` at fire time; logs show the delivery POSTing
|
||||
with `X-OrangeCat-Signature`.
|
||||
|
||||
**Rollback**: do not rotate this key without coordinating a
|
||||
re-encryption pass — any encrypted `secret_encrypted` blobs in the DB
|
||||
become unrecoverable. If the key is leaked, the safe rotation is:
|
||||
mint replacement keys for every endpoint with the new key, revoke the
|
||||
old, document the incident.
|
||||
re-encryption pass. Every webhook_endpoints row's `secret_encrypted`
|
||||
was encrypted with the current key — rotating in place leaves them
|
||||
all unreadable. If the key is leaked, the safe response is:
|
||||
|
||||
1. Set the new key alongside the old one (out of scope for this
|
||||
deploy; would need a service change to try both keys on
|
||||
decrypt).
|
||||
2. Mint replacement endpoints for every customer, communicate the
|
||||
migration, revoke the old endpoints.
|
||||
3. Once all old endpoints are revoked, drop the old key.
|
||||
|
||||
There is no "undo" for `WEBHOOK_SECRET_KEY` going stale — treat it
|
||||
as a high-value secret with restricted Vercel team access.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
import { randomBytes } from 'crypto';
|
||||
import { createAdminClient } from '@/lib/supabase/admin';
|
||||
import { encryptWebhookSecret } from '@/lib/crypto/webhookSecretCipher';
|
||||
import { encryptWebhookSecret, decryptWebhookSecret } from '@/lib/crypto/webhookSecretCipher';
|
||||
import { logger } from '@/utils/logger';
|
||||
import { DATABASE_TABLES } from '@/config/database-tables';
|
||||
import {
|
||||
@@ -84,10 +84,9 @@ export async function createWebhookEndpoint(params: {
|
||||
|
||||
const secret = generateSecret();
|
||||
const secretPrefix = secret.slice(0, DISPLAY_PREFIX_LENGTH);
|
||||
// Phase 1: dual-write. Encrypted blob is the source of truth in phase
|
||||
// 2 (commit 2 of this thread); plaintext column drops then. If
|
||||
// encryption fails — env var missing/bad — fail the mint so we never
|
||||
// store a row that phase 2 can't decrypt.
|
||||
// Phase 2: encrypt-only. If encryption fails (env var missing/bad),
|
||||
// the mint fails — we never persist a row the worker can't decrypt
|
||||
// at fire time.
|
||||
const secretEncrypted = encryptWebhookSecret(secret);
|
||||
|
||||
const admin = createAdminClient();
|
||||
@@ -102,7 +101,6 @@ export async function createWebhookEndpoint(params: {
|
||||
actor_id: actorId,
|
||||
name: name.trim(),
|
||||
url: url.trim(),
|
||||
secret_plaintext: secret,
|
||||
secret_encrypted: secretEncrypted,
|
||||
secret_prefix: secretPrefix,
|
||||
event_types: eventTypes && eventTypes.length > 0 ? eventTypes : null,
|
||||
@@ -169,7 +167,7 @@ export async function getEndpointSigningContext(
|
||||
const admin = createAdminClient();
|
||||
const { data, error } = await admin
|
||||
.from(DATABASE_TABLES.WEBHOOK_ENDPOINTS)
|
||||
.select('url, secret_plaintext, actor_id, revoked_at')
|
||||
.select('url, secret_encrypted, actor_id, revoked_at')
|
||||
.eq('id', endpointId)
|
||||
.maybeSingle();
|
||||
|
||||
@@ -181,17 +179,57 @@ export async function getEndpointSigningContext(
|
||||
return null;
|
||||
}
|
||||
|
||||
// Supabase returns bytea as a base64 string in the JSON envelope.
|
||||
const row = data as {
|
||||
url: string;
|
||||
secret_plaintext: string;
|
||||
secret_encrypted: string | Buffer | null;
|
||||
actor_id: string;
|
||||
revoked_at: string | null;
|
||||
};
|
||||
if (row.revoked_at) {
|
||||
return null;
|
||||
}
|
||||
if (!row.secret_encrypted) {
|
||||
logger.error('getEndpointSigningContext: secret_encrypted is null on a live row', {
|
||||
endpointId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
return { url: row.url, secret: row.secret_plaintext, actorId: row.actor_id };
|
||||
let secret: string;
|
||||
try {
|
||||
const blob = Buffer.isBuffer(row.secret_encrypted)
|
||||
? row.secret_encrypted
|
||||
: decodeSupabaseBytea(row.secret_encrypted);
|
||||
secret = decryptWebhookSecret(blob);
|
||||
} catch (err) {
|
||||
// Decrypt failure means the WEBHOOK_SECRET_KEY drifted from what
|
||||
// encrypted this row, OR the blob was tampered with. Either way the
|
||||
// delivery cannot be signed — fail by returning null so the worker
|
||||
// records a "[endpoint revoked]" outcome rather than a forged signature.
|
||||
logger.error('getEndpointSigningContext: decrypt failed', {
|
||||
endpointId,
|
||||
error: err instanceof Error ? err.message : err,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
return { url: row.url, secret, actorId: row.actor_id };
|
||||
}
|
||||
|
||||
/**
|
||||
* Supabase returns BYTEA columns through PostgREST as the canonical
|
||||
* `\x...hex...` text. Strip the prefix and parse hex.
|
||||
*/
|
||||
function decodeSupabaseBytea(value: string): Buffer {
|
||||
if (value.startsWith('\\x')) {
|
||||
return Buffer.from(value.slice(2), 'hex');
|
||||
}
|
||||
// Fallback: assume base64 for environments where postgrest serialises
|
||||
// bytea differently (e.g. when row-level RLS bypass returns a JSON
|
||||
// base64 string). Never happens on the admin client today but cheap
|
||||
// to support.
|
||||
return Buffer.from(value, 'base64');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
-- ============================================================================
|
||||
-- Phase 2 of 2: drop webhook_endpoints.secret_plaintext
|
||||
-- ============================================================================
|
||||
-- 20260604000003 added secret_encrypted alongside secret_plaintext and the
|
||||
-- service started dual-writing. This migration finishes the encryption swap:
|
||||
--
|
||||
-- 1. (Backfill) UPDATE — no-op today (verified zero rows in prod), kept
|
||||
-- as documentation in this SQL for any future deploy of the same
|
||||
-- migration against a populated table.
|
||||
-- 2. Drop the CHECK constraint that targeted secret_plaintext.
|
||||
-- 3. Enforce NOT NULL on secret_encrypted (now load-bearing).
|
||||
-- 4. Drop the secret_plaintext column.
|
||||
--
|
||||
-- The matching service commit:
|
||||
-- - createWebhookEndpoint: writes only secret_encrypted, no longer
|
||||
-- selects secret_plaintext.
|
||||
-- - getEndpointSigningContext: reads secret_encrypted and decrypts via
|
||||
-- decryptWebhookSecret before returning to the worker.
|
||||
--
|
||||
-- Operational note: rotating WEBHOOK_SECRET_KEY now requires
|
||||
-- re-encrypting every row. See INTEGRATION_DEPLOY_CHECKLIST step 9.
|
||||
--
|
||||
-- Created: 2026-06-04
|
||||
-- ============================================================================
|
||||
|
||||
-- Drop the constraint that targeted the column we're about to drop.
|
||||
ALTER TABLE webhook_endpoints DROP CONSTRAINT webhook_endpoints_secret_not_blank;
|
||||
|
||||
-- Enforce non-null on the column that's now load-bearing.
|
||||
ALTER TABLE webhook_endpoints ALTER COLUMN secret_encrypted SET NOT NULL;
|
||||
|
||||
-- Drop the plaintext column. The service no longer reads or writes it.
|
||||
ALTER TABLE webhook_endpoints DROP COLUMN secret_plaintext;
|
||||
Reference in new issue
Block a user