mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 16:07:16 +01:00
feat(crypto): encrypt webhook_endpoints secrets at rest (phase 1 of 2)
The PHASE-2 debt the user explicitly chose 30+ commits ago in
2755a8a5 ("plaintext for now, encrypt later"). Webhook signing secrets
are needed at fire time (the worker must sign each delivery), so they
have to live somewhere — but a DB compromise should NOT reveal them.
This commit lands the encryption infrastructure and starts dual-write.
Commit 2 of 2 will backfill secret_encrypted (no-op today: prod has
zero webhook_endpoints rows), flip getEndpointSigningContext to
decrypt, drop secret_plaintext.
Cipher (src/lib/crypto/webhookSecretCipher.ts):
AES-256-GCM with WEBHOOK_SECRET_KEY env var (32-byte hex). Ciphertext
layout: IV(12B) || GCM tag(16B) || ciphertext. Authenticated — a
flipped byte anywhere in the blob throws on decrypt, so a DB
compromise can't return a forged secret to the worker (only DoS by
deleting rows). loadKey() validates the env var at first use and
caches the parsed key; resetCachedKey() is test-only.
Schema (migration 20260604000003, applied to remote):
ALTER webhook_endpoints ADD COLUMN secret_encrypted BYTEA.
Service dual-writes; reads still come from secret_plaintext so the
worker keeps signing deliveries unchanged.
Service (webhookEndpointsService.createWebhookEndpoint):
Dual-writes secret_plaintext + secret_encrypted on mint. If
encryptWebhookSecret throws (env var missing/malformed), the mint
fails — we never store a row that phase 2 can't decrypt.
Deploy checklist: new step 9 (WEBHOOK_SECRET_KEY env var) with
generation command, verification (mint a webhook endpoint and watch
for 500), rollback warning (rotating the key requires re-encryption,
mention of incident-response posture).
Tests (16):
loadKey: cache, missing env, empty env, non-hex, wrong length
round-trip: exact equality, len-1, 4KB, unicode, IV-randomness,
blob layout assertion (12+16+len(plaintext))
tampering: flipped ciphertext / IV / tag byte, truncated blob,
wrong key → all throw
Suite: 55 suites · 717 tests · 0 failures (+1 suite, +16 tests).
tsc + eslint clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
643c775c14
commit
cc76194fd6
5 files changed
+310
-1
No files matched your search
@@ -26,6 +26,8 @@ step has the exact command, a verification, and a rollback if it fails.
|
||||
[ ] 7. Set CRON_SECRET in OrangeCat Vercel env
|
||||
[ ] 8. Set UPSTASH_REDIS_REST_URL + UPSTASH_REDIS_REST_TOKEN
|
||||
in OrangeCat Vercel env
|
||||
[ ] 9. Set WEBHOOK_SECRET_KEY in OrangeCat Vercel env
|
||||
(master key encrypting webhook_endpoints.secret_plaintext at rest)
|
||||
|
||||
[ ] Smoke test: trigger an entity-create on the customer side,
|
||||
watch the webhook fire end-to-end.
|
||||
@@ -225,9 +227,36 @@ in-memory. Not data-harmful, just less correct under load.
|
||||
|
||||
---
|
||||
|
||||
## Step 9 — Set WEBHOOK_SECRET_KEY in OrangeCat Vercel env
|
||||
|
||||
Without this, every `POST /api/webhook-endpoints` mint **throws** —
|
||||
the service encrypts the signing secret at rest with this key, and
|
||||
will not silently fall back to plaintext storage.
|
||||
|
||||
Generate a high-entropy 32-byte hex key:
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
---
|
||||
|
||||
## Smoke test — exercise the full path
|
||||
|
||||
After all 8 steps land:
|
||||
After all 9 steps land:
|
||||
|
||||
1. **From customer side**, trigger whatever flow creates an OrangeCat
|
||||
entity (for FleetCrown: create a subscription).
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* AES-256-GCM cipher for webhook signing secrets at rest.
|
||||
*
|
||||
* The webhook signing path needs the plaintext secret at fire time
|
||||
* (the worker must sign each delivery). Plaintext-at-rest is the
|
||||
* PHASE-2 debt I documented in 2755a8a5 when the user picked
|
||||
* "plaintext for now, encrypt later". This util lets the service
|
||||
* encrypt at insert and decrypt at fire while keeping the secret out
|
||||
* of disk dumps + DB backups.
|
||||
*
|
||||
* Key material: WEBHOOK_SECRET_KEY env var, a 32-byte hex string
|
||||
* (64 hex chars). Generate with:
|
||||
*
|
||||
* node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||
*
|
||||
* Ciphertext layout (stored in webhook_endpoints.secret_encrypted):
|
||||
*
|
||||
* [ 12B IV ][ 16B GCM tag ][ N bytes ciphertext ]
|
||||
*
|
||||
* Authenticated: tampering anywhere in the blob causes decrypt to
|
||||
* throw, so a DB compromise can't return a forged secret to the
|
||||
* worker — it can only DoS by deleting rows.
|
||||
*
|
||||
* Created: 2026-06-04
|
||||
*/
|
||||
|
||||
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm' as const;
|
||||
const KEY_BYTES = 32;
|
||||
const IV_BYTES = 12;
|
||||
const TAG_BYTES = 16;
|
||||
|
||||
let cachedKey: Buffer | null = null;
|
||||
|
||||
/**
|
||||
* Load the master encryption key from WEBHOOK_SECRET_KEY. Throws if
|
||||
* the env var is missing OR malformed — we want to fail at startup,
|
||||
* not silently store unencrypted-looking blobs.
|
||||
*
|
||||
* The key is cached after the first read so we don't re-validate on
|
||||
* every encrypt/decrypt. Tests can clear with resetCachedKey().
|
||||
*/
|
||||
export function loadKey(): Buffer {
|
||||
if (cachedKey) {
|
||||
return cachedKey;
|
||||
}
|
||||
const hex = process.env.WEBHOOK_SECRET_KEY;
|
||||
if (!hex) {
|
||||
throw new Error(
|
||||
"WEBHOOK_SECRET_KEY is not set. Generate one with `node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"` and set it in Vercel env."
|
||||
);
|
||||
}
|
||||
if (!/^[0-9a-f]{64}$/i.test(hex)) {
|
||||
throw new Error(
|
||||
'WEBHOOK_SECRET_KEY must be 64 hex characters (a 32-byte key). Got ' +
|
||||
`${hex.length} characters of ${/[^0-9a-f]/i.test(hex) ? 'non-hex' : 'hex'} data.`
|
||||
);
|
||||
}
|
||||
cachedKey = Buffer.from(hex, 'hex');
|
||||
if (cachedKey.length !== KEY_BYTES) {
|
||||
throw new Error(
|
||||
`WEBHOOK_SECRET_KEY decoded to ${cachedKey.length} bytes; expected ${KEY_BYTES}.`
|
||||
);
|
||||
}
|
||||
return cachedKey;
|
||||
}
|
||||
|
||||
/** Test-only helper. Production callers never invalidate the key. */
|
||||
export function resetCachedKey(): void {
|
||||
cachedKey = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt a plaintext webhook secret. Returns a Buffer suitable for
|
||||
* storage in webhook_endpoints.secret_encrypted (BYTEA). Each call
|
||||
* generates a fresh 12-byte IV — never reuse IVs with the same key.
|
||||
*/
|
||||
export function encryptWebhookSecret(plaintext: string): Buffer {
|
||||
const key = loadKey();
|
||||
const iv = randomBytes(IV_BYTES);
|
||||
const cipher = createCipheriv(ALGORITHM, key, iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return Buffer.concat([iv, tag, ciphertext]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a stored ciphertext blob. Throws on:
|
||||
* - malformed blob (too short for IV + tag)
|
||||
* - tampered ciphertext (GCM auth tag mismatch)
|
||||
* - wrong key
|
||||
*
|
||||
* Callers never branch on the failure reason — a decrypt failure
|
||||
* means the secret is unrecoverable; surface the error so the worker
|
||||
* can mark the delivery as a non-retryable failure.
|
||||
*/
|
||||
export function decryptWebhookSecret(blob: Buffer): string {
|
||||
if (blob.length < IV_BYTES + TAG_BYTES + 1) {
|
||||
throw new Error(
|
||||
`webhook secret ciphertext too short (got ${blob.length}B, need at least ${IV_BYTES + TAG_BYTES + 1}B)`
|
||||
);
|
||||
}
|
||||
const key = loadKey();
|
||||
const iv = blob.subarray(0, IV_BYTES);
|
||||
const tag = blob.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
||||
const ciphertext = blob.subarray(IV_BYTES + TAG_BYTES);
|
||||
const decipher = createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
return plaintext.toString('utf8');
|
||||
}
|
||||
@@ -25,6 +25,7 @@
|
||||
|
||||
import { randomBytes } from 'crypto';
|
||||
import { createAdminClient } from '@/lib/supabase/admin';
|
||||
import { encryptWebhookSecret } from '@/lib/crypto/webhookSecretCipher';
|
||||
import { logger } from '@/utils/logger';
|
||||
import { DATABASE_TABLES } from '@/config/database-tables';
|
||||
import {
|
||||
@@ -83,6 +84,11 @@ 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.
|
||||
const secretEncrypted = encryptWebhookSecret(secret);
|
||||
|
||||
const admin = createAdminClient();
|
||||
const { data, error } = await (
|
||||
@@ -97,6 +103,7 @@ export async function createWebhookEndpoint(params: {
|
||||
name: name.trim(),
|
||||
url: url.trim(),
|
||||
secret_plaintext: secret,
|
||||
secret_encrypted: secretEncrypted,
|
||||
secret_prefix: secretPrefix,
|
||||
event_types: eventTypes && eventTypes.length > 0 ? eventTypes : null,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- ============================================================================
|
||||
-- Phase 1 of 2: webhook_endpoints.secret_encrypted (encrypt-at-rest)
|
||||
-- ============================================================================
|
||||
-- The PHASE-2 debt I documented when 20260603000005 swapped secret_hash for
|
||||
-- secret_plaintext: webhook signing secrets need encryption-at-rest with a
|
||||
-- master KMS key. This migration adds the encrypted column alongside the
|
||||
-- existing plaintext column. Service dual-writes on mint; reads still come
|
||||
-- from secret_plaintext so the worker keeps signing deliveries identically.
|
||||
--
|
||||
-- Commit 2 will:
|
||||
-- 1. Backfill secret_encrypted from secret_plaintext (no-op today since
|
||||
-- no prod rows exist yet).
|
||||
-- 2. Flip getEndpointSigningContext to decrypt secret_encrypted.
|
||||
-- 3. Drop the secret_plaintext column.
|
||||
--
|
||||
-- Encryption: AES-256-GCM with WEBHOOK_SECRET_KEY env var (32-byte key).
|
||||
-- Ciphertext blob layout: IV(12B) || GCM tag(16B) || ciphertext.
|
||||
--
|
||||
-- Created: 2026-06-04
|
||||
-- ============================================================================
|
||||
|
||||
ALTER TABLE webhook_endpoints ADD COLUMN secret_encrypted BYTEA;
|
||||
|
||||
COMMENT ON COLUMN webhook_endpoints.secret_encrypted IS
|
||||
'AES-256-GCM ciphertext of the signing secret. Layout: IV(12B)||tag(16B)||ciphertext. Decrypted with WEBHOOK_SECRET_KEY env var. Phase 1: dual-write with secret_plaintext. Phase 2 will drop secret_plaintext.';
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* webhookSecretCipher — round-trip + tampering tests.
|
||||
*
|
||||
* AES-256-GCM, randomized IV. The contract:
|
||||
* - encrypt → decrypt round-trips exactly
|
||||
* - each encrypt of the same plaintext produces a different blob
|
||||
* (because IV is random)
|
||||
* - tampering anywhere in the blob causes decrypt to throw
|
||||
* - malformed env (missing / wrong length / non-hex) fails at load
|
||||
* - wrong key fails decrypt
|
||||
*
|
||||
* Created: 2026-06-04
|
||||
*/
|
||||
|
||||
import {
|
||||
encryptWebhookSecret,
|
||||
decryptWebhookSecret,
|
||||
loadKey,
|
||||
resetCachedKey,
|
||||
} from '@/lib/crypto/webhookSecretCipher';
|
||||
|
||||
const VALID_KEY = 'a'.repeat(64); // 64 hex chars = 32 bytes
|
||||
|
||||
beforeEach(() => {
|
||||
resetCachedKey();
|
||||
process.env.WEBHOOK_SECRET_KEY = VALID_KEY;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
resetCachedKey();
|
||||
delete process.env.WEBHOOK_SECRET_KEY;
|
||||
});
|
||||
|
||||
describe('loadKey', () => {
|
||||
it('caches the parsed key across calls', () => {
|
||||
const k1 = loadKey();
|
||||
const k2 = loadKey();
|
||||
expect(k1).toBe(k2);
|
||||
});
|
||||
|
||||
it.each([undefined, ''])('throws when WEBHOOK_SECRET_KEY is %p', value => {
|
||||
resetCachedKey();
|
||||
if (value === undefined) {
|
||||
delete process.env.WEBHOOK_SECRET_KEY;
|
||||
} else {
|
||||
process.env.WEBHOOK_SECRET_KEY = value;
|
||||
}
|
||||
expect(() => loadKey()).toThrow(/WEBHOOK_SECRET_KEY/);
|
||||
});
|
||||
|
||||
it('throws on non-hex characters', () => {
|
||||
resetCachedKey();
|
||||
process.env.WEBHOOK_SECRET_KEY = 'x'.repeat(64);
|
||||
expect(() => loadKey()).toThrow(/64 hex characters/);
|
||||
});
|
||||
|
||||
it('throws on wrong length', () => {
|
||||
resetCachedKey();
|
||||
process.env.WEBHOOK_SECRET_KEY = 'a'.repeat(32);
|
||||
expect(() => loadKey()).toThrow(/64 hex characters/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encrypt/decrypt round-trip', () => {
|
||||
it('decrypts to the exact original plaintext', () => {
|
||||
const plaintext = 'ock_whk_abcdef0123456789abcdef0123456789abcdef0123456789';
|
||||
const blob = encryptWebhookSecret(plaintext);
|
||||
expect(decryptWebhookSecret(blob)).toBe(plaintext);
|
||||
});
|
||||
|
||||
it('round-trips empty-ish but valid strings', () => {
|
||||
// length-1 plaintext is the minimum the layout (IV+tag+ct) accepts.
|
||||
expect(decryptWebhookSecret(encryptWebhookSecret('a'))).toBe('a');
|
||||
});
|
||||
|
||||
it('round-trips long strings', () => {
|
||||
const long = 'x'.repeat(4096);
|
||||
expect(decryptWebhookSecret(encryptWebhookSecret(long))).toBe(long);
|
||||
});
|
||||
|
||||
it('round-trips unicode', () => {
|
||||
const unicode = 'secrét‐𝓌ith‐unicodé‐𠮷';
|
||||
expect(decryptWebhookSecret(encryptWebhookSecret(unicode))).toBe(unicode);
|
||||
});
|
||||
|
||||
it('produces different blobs for the same plaintext (random IV)', () => {
|
||||
const plaintext = 'same-input';
|
||||
const a = encryptWebhookSecret(plaintext);
|
||||
const b = encryptWebhookSecret(plaintext);
|
||||
expect(a.equals(b)).toBe(false);
|
||||
// Both still decrypt to the same value.
|
||||
expect(decryptWebhookSecret(a)).toBe(plaintext);
|
||||
expect(decryptWebhookSecret(b)).toBe(plaintext);
|
||||
});
|
||||
|
||||
it('produces blobs with the expected layout (IV+tag+ct)', () => {
|
||||
const blob = encryptWebhookSecret('hello');
|
||||
expect(blob.length).toBe(12 + 16 + 5); // IV + tag + len('hello')
|
||||
});
|
||||
});
|
||||
|
||||
describe('tampering detection', () => {
|
||||
it('throws on flipped ciphertext byte', () => {
|
||||
const blob = encryptWebhookSecret('ock_whk_real');
|
||||
const flipped = Buffer.from(blob);
|
||||
// Flip the last byte of the ciphertext.
|
||||
flipped[flipped.length - 1] = flipped[flipped.length - 1] ^ 0x01;
|
||||
expect(() => decryptWebhookSecret(flipped)).toThrow();
|
||||
});
|
||||
|
||||
it('throws on flipped IV byte', () => {
|
||||
const blob = encryptWebhookSecret('ock_whk_real');
|
||||
const flipped = Buffer.from(blob);
|
||||
flipped[0] = flipped[0] ^ 0x01;
|
||||
expect(() => decryptWebhookSecret(flipped)).toThrow();
|
||||
});
|
||||
|
||||
it('throws on flipped tag byte', () => {
|
||||
const blob = encryptWebhookSecret('ock_whk_real');
|
||||
const flipped = Buffer.from(blob);
|
||||
flipped[12] = flipped[12] ^ 0x01; // first byte of tag
|
||||
expect(() => decryptWebhookSecret(flipped)).toThrow();
|
||||
});
|
||||
|
||||
it('throws on truncated blob', () => {
|
||||
const blob = encryptWebhookSecret('ock_whk_real');
|
||||
expect(() => decryptWebhookSecret(blob.subarray(0, 10))).toThrow(/too short/);
|
||||
});
|
||||
|
||||
it('throws when decrypted with the wrong key', () => {
|
||||
const blob = encryptWebhookSecret('ock_whk_real');
|
||||
resetCachedKey();
|
||||
process.env.WEBHOOK_SECRET_KEY = 'b'.repeat(64);
|
||||
expect(() => decryptWebhookSecret(blob)).toThrow();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user