From 66ee7c737fa4bb83752fa6b0d0c200d7425166d8 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:09:44 -0600 Subject: [PATCH 1/6] fix(server): parse boolean env vars so false means false z.coerce.boolean() turned every non-empty string into true, so OTEL_ENABLED=false enabled tracing and WEBHOOK_REMOVE_ON_FAIL=false was ignored. --- packages/server/src/config.test.ts | 26 ++++++++++++++++++++++++ packages/server/src/config.ts | 32 ++++++++++++++++++------------ 2 files changed, 45 insertions(+), 13 deletions(-) create mode 100644 packages/server/src/config.test.ts diff --git a/packages/server/src/config.test.ts b/packages/server/src/config.test.ts new file mode 100644 index 0000000..92a7c60 --- /dev/null +++ b/packages/server/src/config.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from 'vitest'; +import { envBoolean } from './config.js'; + +describe('envBoolean', () => { + it('reads "false" and "0" as false', () => { + const schema = envBoolean(true); + expect(schema.parse('false')).toBe(false); + expect(schema.parse('0')).toBe(false); + expect(schema.parse('FALSE')).toBe(false); + }); + + it('reads "true" and "1" as true', () => { + const schema = envBoolean(false); + expect(schema.parse('true')).toBe(true); + expect(schema.parse('1')).toBe(true); + }); + + it('uses the default when unset or empty', () => { + expect(envBoolean(true).parse(undefined)).toBe(true); + expect(envBoolean(false).parse('')).toBe(false); + }); + + it('rejects values that are not booleans', () => { + expect(() => envBoolean(false).parse('maybe')).toThrow(); + }); +}); diff --git a/packages/server/src/config.ts b/packages/server/src/config.ts index 8483ce7..3c9c0ad 100644 --- a/packages/server/src/config.ts +++ b/packages/server/src/config.ts @@ -10,6 +10,17 @@ const __dirname = dirname(__filename); const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8')); +/** + * Boolean environment variable. `z.coerce.boolean()` treats every non-empty + * string, including "false" and "0", as true. This accepts true/false, 1/0, + * yes/no and on/off, treats an empty value as unset and rejects anything else. + */ +export const envBoolean = (defaultValue: boolean) => + z.preprocess( + (value) => (typeof value === 'string' && value.trim() === '' ? undefined : value), + z.stringbool().default(defaultValue), + ); + export enum Environment { Dev = 'development', Test = 'test', @@ -99,7 +110,7 @@ const configSchema = z.object({ .describe( 'retired keys still accepted for reading existing entries during a key rotation (comma-separated)', ), - otelEnabled: z.coerce.boolean().default(false).describe('enable OpenTelemetry tracing'), + otelEnabled: envBoolean(false).describe('enable OpenTelemetry tracing'), otelExporterOtlpEndpoint: z.string().describe('OpenTelemetry collector endpoint').optional(), otelExporterOtlpHeaders: z .record(z.string(), z.string()) @@ -135,14 +146,10 @@ const configSchema = z.object({ .number() .default(5_000) .describe('webhook retry backoff delay in milliseconds'), - webhookRemoveOnComplete: z.coerce - .boolean() - .default(true) - .describe('remove webhook jobs from queue when complete'), - webhookRemoveOnFail: z.coerce - .boolean() - .default(true) - .describe('remove webhook jobs from queue when failed'), + webhookRemoveOnComplete: envBoolean(true).describe( + 'remove webhook jobs from queue when complete', + ), + webhookRemoveOnFail: envBoolean(true).describe('remove webhook jobs from queue when failed'), webhookConcurrency: z.coerce.number().default(50).describe('number of concurrent webhook jobs'), webhookDrainDelayMs: z.coerce .number() @@ -153,10 +160,9 @@ const configSchema = z.object({ .default(100) .describe('maximum length of webhook events stream'), webhookSender: z.enum(['bullmq', 'http']).default('bullmq').describe('webhook sender type'), - webhookRequireHttps: z.coerce - .boolean() - .default(false) - .describe('require webhook target URLs to use https (SSRF hardening)'), + webhookRequireHttps: envBoolean(false).describe( + 'require webhook target URLs to use https (SSRF hardening)', + ), rateLimiter: z.enum(['redis', 'memory']).default('redis').describe('rate limiter type'), }); From 174bcbf60a788b35484a580c230fc8755f1ae59e Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:09:45 -0600 Subject: [PATCH 2/6] fix(server): retry failed webhooks and stop following redirects The BullMQ worker wrapped a retrying fetch in a 3 second abort and then treated the resulting error as non-retryable, so failed deliveries were dropped. Make one attempt per job run and throw retryable errors so the queue's attempts and backoff apply. Deliveries also no longer follow redirects, and the URL is checked against private addresses again before each delivery. --- .changeset/webhook-retries-redirects.md | 5 + packages/server/src/index.ts | 12 +- packages/server/src/webhook.test.ts | 172 ++++++++++++++++++++++++ packages/server/src/webhook.ts | 66 ++++++--- 4 files changed, 230 insertions(+), 25 deletions(-) create mode 100644 .changeset/webhook-retries-redirects.md create mode 100644 packages/server/src/webhook.test.ts diff --git a/.changeset/webhook-retries-redirects.md b/.changeset/webhook-retries-redirects.md new file mode 100644 index 0000000..93c0261 --- /dev/null +++ b/.changeset/webhook-retries-redirects.md @@ -0,0 +1,5 @@ +--- +'@crypt.fyi/server': patch +--- + +Webhook deliveries are now retried with the configured `WEBHOOK_MAX_ATTEMPTS` and backoff when the receiver fails or times out; previously a failed delivery was dropped after about 3 seconds. Deliveries no longer follow redirects, and the webhook URL is checked again against private and reserved addresses before each delivery. diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index da22e32..7996739 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -11,7 +11,8 @@ import { createHTTPWebhookSender, type WebhookSender, } from './webhook.js'; -import { createFetchRetryClient, machine } from '@crypt.fyi/core'; +import { machine } from '@crypt.fyi/core'; +import { assertWebhookUrlAllowed } from './ssrf.js'; const main = async () => { const logger = await initLogging(config); @@ -27,9 +28,8 @@ const main = async () => { }); let cleanupFns: (() => Promise)[] = []; let webhookSender: WebhookSender; - const webhookSenderFetch = createFetchRetryClient({ - maxAttempts: config.webhookMaxAttempts, - }); + const validateWebhookUrl = (url: string) => + assertWebhookUrlAllowed(url, { requireHttps: config.webhookRequireHttps }); if (config.webhookSender === 'bullmq') { const bullmqRedis = new Redis(config.redisUrl, { maxRetriesPerRequest: null, family: 0 }); const { webhookSender: bullmqWebhookSender, cleanup: cleanupWebhookSender } = @@ -46,7 +46,7 @@ const main = async () => { concurrency: config.webhookConcurrency, drainDelayMs: config.webhookDrainDelayMs, streamEventsMaxLength: config.webhookStreamEventsMaxLength, - fetchFn: webhookSenderFetch, + validateUrl: validateWebhookUrl, }); cleanupFns.push(cleanupWebhookSender, async () => { await bullmqRedis.quit(); @@ -56,7 +56,7 @@ const main = async () => { const httpWebhookSender = createHTTPWebhookSender({ logger, requestTimeoutMs: config.webhookRequestTimeoutMs, - fetchFn: webhookSenderFetch, + validateUrl: validateWebhookUrl, }); webhookSender = httpWebhookSender; } else { diff --git a/packages/server/src/webhook.test.ts b/packages/server/src/webhook.test.ts new file mode 100644 index 0000000..97a11ac --- /dev/null +++ b/packages/server/src/webhook.test.ts @@ -0,0 +1,172 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { Redis } from 'ioredis'; +import { machine, SsrfError } from '@crypt.fyi/core'; +import { createBullMQWebhookSender, type Message } from './webhook.js'; +import type { Logger } from './logging.js'; + +// Own database so queued jobs never mix with other suites. +const TEST_DB = 10; + +const message: Message = { + url: 'https://hooks.example.com/crypt', + event: 'READ', + id: 'vault-id', + dt: 'delete-token', + ts: 0, +}; + +const createLogger = () => { + const messages: string[] = []; + const record = (...args: unknown[]) => { + const msg = args.find((arg) => typeof arg === 'string'); + if (typeof msg === 'string') messages.push(msg); + }; + const logger = { + level: 'info', + trace: record, + debug: record, + info: record, + warn: record, + error: record, + fatal: record, + silent: record, + child: () => logger, + } as Logger; + return { logger, messages }; +}; + +const waitFor = async (condition: () => boolean, timeoutMs = 5_000) => { + const start = Date.now(); + while (!condition()) { + if (Date.now() - start > timeoutMs) { + throw new Error('timed out waiting for condition'); + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } +}; + +describe('BullMQ webhook sender', () => { + let redis: Redis; + let cleanup: (() => Promise) | undefined; + + beforeEach(async () => { + redis = new Redis({ db: TEST_DB, maxRetriesPerRequest: null }); + await redis.flushdb(); + }); + + afterEach(async () => { + await cleanup?.(); + cleanup = undefined; + await redis.flushdb(); + await redis.quit(); + }); + + const start = (options: { + fetchFn?: typeof fetch; + validateUrl?: (url: string) => Promise; + requestTimeoutMs?: number; + }) => { + const { logger, messages } = createLogger(); + const sender = createBullMQWebhookSender({ + logger, + redis, + keyring: machine.createKeyring('foobar'), + requestTimeoutMs: options.requestTimeoutMs ?? 1_000, + maxAttempts: 3, + backoffType: 'fixed', + backoffDelayMs: 10, + removeOnComplete: true, + removeOnFail: true, + concurrency: 1, + drainDelayMs: 1_000, + streamEventsMaxLength: 100, + fetchFn: options.fetchFn, + validateUrl: options.validateUrl ?? (async () => {}), + }); + cleanup = sender.cleanup; + return { send: sender.webhookSender.send, messages }; + }; + + it('retries a failed delivery with the queue backoff', async () => { + const statuses = [503, 200]; + let calls = 0; + const fetchFn = (async () => + new Response(null, { status: statuses[calls++] ?? 200 })) as unknown as typeof fetch; + const { send, messages } = start({ fetchFn }); + + await send(message); + await waitFor(() => messages.includes('Webhook sent')); + expect(calls).toBe(2); + }); + + it('retries a delivery that timed out', async () => { + let calls = 0; + const fetchFn = ((_url: string, init: RequestInit) => { + calls++; + if (calls === 1) { + return new Promise((_, reject) => + init.signal!.addEventListener('abort', () => reject(init.signal!.reason)), + ); + } + return Promise.resolve(new Response(null, { status: 200 })); + }) as unknown as typeof fetch; + const { send, messages } = start({ fetchFn, requestTimeoutMs: 50 }); + + await send(message); + await waitFor(() => messages.includes('Webhook sent')); + expect(calls).toBe(2); + }); + + it('checks the URL again before delivering', async () => { + let calls = 0; + const fetchFn = (async () => { + calls++; + return new Response(null, { status: 200 }); + }) as unknown as typeof fetch; + const { send, messages } = start({ + fetchFn, + validateUrl: async () => { + throw new SsrfError('Webhook URL resolves to a private or reserved address'); + }, + }); + + await send(message); + await waitFor(() => messages.includes('Webhook URL not allowed')); + expect(calls).toBe(0); + }); + + it('does not follow redirects', async () => { + let redirectTargetHits = 0; + const target = http.createServer((_, res) => { + redirectTargetHits++; + res.end(); + }); + let receiverHits = 0; + const receiver = http.createServer((_, res) => { + receiverHits++; + const { port } = target.address() as AddressInfo; + res.writeHead(307, { Location: `http://127.0.0.1:${port}/internal` }); + res.end(); + }); + await Promise.all([ + new Promise((resolve) => target.listen(0, '127.0.0.1', resolve)), + new Promise((resolve) => receiver.listen(0, '127.0.0.1', resolve)), + ]); + + try { + const { port } = receiver.address() as AddressInfo; + const { send, messages } = start({}); + await send({ ...message, url: `http://127.0.0.1:${port}/hook` }); + await waitFor(() => messages.includes('Failed to send webhook')); + expect(receiverHits).toBe(1); + expect(redirectTargetHits).toBe(0); + } finally { + await Promise.all([ + new Promise((resolve) => target.close(resolve)), + new Promise((resolve) => receiver.close(resolve)), + ]); + } + }); +}); diff --git a/packages/server/src/webhook.ts b/packages/server/src/webhook.ts index fbd9359..8421812 100644 --- a/packages/server/src/webhook.ts +++ b/packages/server/src/webhook.ts @@ -1,5 +1,12 @@ import { Queue, Worker, type RedisOptions } from 'bullmq'; -import { machine, isRetryableFetchError } from '@crypt.fyi/core'; +import { + machine, + isRetryableFetchError, + HTTPError, + SsrfError, + TimeoutError, +} from '@crypt.fyi/core'; +import { assertWebhookUrlAllowed } from './ssrf.js'; import type { Logger } from './logging.js'; import { Redis } from 'ioredis'; import { z } from 'zod'; @@ -46,8 +53,25 @@ interface BaseWebhookSenderOptions { fetchFn?: typeof fetch; requestTimeoutMs: number; shouldRetry?: (error: unknown) => boolean; + /** + * Checked again before every delivery, because the hostname may resolve to a + * different address than it did when the secret was created. Throws SsrfError. + */ + validateUrl?: (url: string) => Promise; } +const postWebhook = (fetchFn: typeof fetch, message: Message, signal: AbortSignal) => + fetchFn(message.url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(message), + signal, + // A redirect could point at an address the URL checks never saw. + redirect: 'manual', + }); + type BullMQWebhookSenderOptions = BaseWebhookSenderOptions & { redis: Redis; keyring: machine.Keyring; @@ -76,6 +100,7 @@ export const createBullMQWebhookSender = ({ streamEventsMaxLength, fetchFn = fetch, shouldRetry = isRetryableFetchError, + validateUrl = assertWebhookUrlAllowed, }: BullMQWebhookSenderOptions): { webhookSender: WebhookSender; cleanup: () => Promise } => { const connection = toBullMQConnection(redis); const queue = new Queue(WEBHOOK_QUEUE_NAME, { @@ -106,19 +131,27 @@ export const createBullMQWebhookSender = ({ const dataString = await machine.decryptWithKeyring(job.data, keyring); const message = messageSchema.parse(JSON.parse(dataString)); + try { + await validateUrl(message.url); + } catch (error) { + if (error instanceof SsrfError) { + logger.info( + { jobId: job.id, event: message.event, id: message.id, error }, + 'Webhook URL not allowed', + ); + return; + } + throw error; + } + + // One attempt per job run: BullMQ owns retries and backoff. The abort + // reason is a TimeoutError so a slow receiver is retried. const ac = new AbortController(); - const timeoutId = setTimeout(() => ac.abort(), requestTimeoutMs); + const timeoutId = setTimeout(() => ac.abort(new TimeoutError()), requestTimeoutMs); try { - const response = await fetchFn(message.url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(message), - signal: ac.signal, - }); + const response = await postWebhook(fetchFn, message, ac.signal); if (!response.ok) { - throw new Error(`Unexpected status code: ${response.status}`); + throw new HTTPError(response.status, response.statusText); } logger.info({ jobId: job.id, event: message.event, id: message.id }, 'Webhook sent'); @@ -199,6 +232,7 @@ export const createHTTPWebhookSender = ({ logger, fetchFn = fetch, requestTimeoutMs, + validateUrl = assertWebhookUrlAllowed, }: BaseWebhookSenderOptions): WebhookSender => { return { send: async (message) => { @@ -206,14 +240,8 @@ export const createHTTPWebhookSender = ({ const timeoutId = setTimeout(() => ac.abort(), requestTimeoutMs); try { - const response = await fetchFn(message.url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(message), - signal: ac.signal, - }); + await validateUrl(message.url); + const response = await postWebhook(fetchFn, message, ac.signal); if (!response.ok) { throw new Error(`Unexpected status code: ${response.status}`); } From 3bf9b6033c919271de2b0bab6ff97d1c590d6bae Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:09:45 -0600 Subject: [PATCH 3/6] fix(server): redact the verification hash from OpenTelemetry spans --- packages/server/src/telemetry.test.ts | 37 +++++++++++++++++++++++++++ packages/server/src/telemetry.ts | 13 +++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 packages/server/src/telemetry.test.ts diff --git a/packages/server/src/telemetry.test.ts b/packages/server/src/telemetry.test.ts new file mode 100644 index 0000000..df2b4f3 --- /dev/null +++ b/packages/server/src/telemetry.test.ts @@ -0,0 +1,37 @@ +import { describe, it, expect, afterAll } from 'vitest'; +import { createRequire } from 'node:module'; +import type { AddressInfo } from 'node:net'; +import { NodeSDK } from '@opentelemetry/sdk-node'; +import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; +import { InMemorySpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; +import { autoInstrumentationConfig } from './telemetry.js'; + +describe('telemetry', () => { + const exporter = new InMemorySpanExporter(); + const sdk = new NodeSDK({ + spanProcessors: [new SimpleSpanProcessor(exporter)], + instrumentations: [getNodeAutoInstrumentations(autoInstrumentationConfig)], + }); + sdk.start(); + // Required after the SDK starts so the instrumentation can patch it. + const http = createRequire(import.meta.url)('node:http') as typeof import('node:http'); + + afterAll(async () => { + await sdk.shutdown(); + }); + + it('does not record the verification hash in server spans', async () => { + const server = http.createServer((_, res) => res.end()); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + + await fetch(`http://127.0.0.1:${port}/vault/some-id?h=secret-hash`); + await new Promise((resolve) => server.close(resolve)); + + const serverSpan = exporter.getFinishedSpans().find((span) => span.kind === 1); + expect(serverSpan).toBeDefined(); + const attributes = JSON.stringify(serverSpan!.attributes); + expect(attributes).toContain('/vault/some-id'); + expect(attributes).not.toContain('secret-hash'); + }); +}); diff --git a/packages/server/src/telemetry.ts b/packages/server/src/telemetry.ts index 8fc94e6..a2ef405 100644 --- a/packages/server/src/telemetry.ts +++ b/packages/server/src/telemetry.ts @@ -8,6 +8,17 @@ import { config } from './config.js'; import type { Attributes } from '@opentelemetry/api'; import { hostname } from 'node:os'; +/** + * Auto-instrumentation options. The verification hash `h` is sent as a query + * parameter on vault reads and works as a retrieval credential, so it must not + * be recorded in span attributes. + */ +export const autoInstrumentationConfig = { + '@opentelemetry/instrumentation-http': { + redactedQueryParamsServer: ['h'], + }, +} satisfies Parameters[0]; + let sdk: NodeSDK | undefined = undefined; if (config.otelEnabled) { @@ -28,7 +39,7 @@ if (config.otelEnabled) { [ATTR_SERVICE_VERSION]: config.serviceVersion, }), traceExporter: exporter, - instrumentations: [getNodeAutoInstrumentations()], + instrumentations: [getNodeAutoInstrumentations(autoInstrumentationConfig)], }); sdk.start(); From 12a801a1c757ef0a1a2f203bdf44354795222355 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:09:45 -0600 Subject: [PATCH 4/6] fix(server): keep client IPs and vault ids out of request logs Request logs paired the client address with the concrete /vault/ path, linking who created a secret to who read it. Log the route pattern and drop the address and port. --- packages/server/src/logging.test.ts | 27 +++++++++++++++++++++++++++ packages/server/src/logging.ts | 25 ++++++++++++++----------- 2 files changed, 41 insertions(+), 11 deletions(-) create mode 100644 packages/server/src/logging.test.ts diff --git a/packages/server/src/logging.test.ts b/packages/server/src/logging.test.ts new file mode 100644 index 0000000..74df20f --- /dev/null +++ b/packages/server/src/logging.test.ts @@ -0,0 +1,27 @@ +import { describe, it, expect } from 'vitest'; +import Fastify, { type FastifyRequest } from 'fastify'; +import { serializeRequest } from './logging.js'; + +describe('serializeRequest', () => { + it('logs the route pattern and no client address', async () => { + const app = Fastify(); + let serialized: ReturnType | undefined; + app.get('/vault/:vaultId', async (req: FastifyRequest) => { + serialized = serializeRequest(req); + return null; + }); + + await app.inject({ + method: 'GET', + url: '/vault/some-vault-id?h=secret-hash', + remoteAddress: '198.51.100.7', + }); + await app.close(); + + expect(serialized?.url).toBe('/vault/:vaultId'); + const logged = JSON.stringify(serialized); + expect(logged).not.toContain('some-vault-id'); + expect(logged).not.toContain('secret-hash'); + expect(logged).not.toContain('198.51.100.7'); + }); +}); diff --git a/packages/server/src/logging.ts b/packages/server/src/logging.ts index 2456a4c..8772938 100644 --- a/packages/server/src/logging.ts +++ b/packages/server/src/logging.ts @@ -13,6 +13,19 @@ const stripQueryParams = (url: string) => { } }; +/** + * Request log fields. Logs carry the route pattern rather than the concrete + * path and no client address, so they can't link the IP that created a vault + * entry to the IP that read it (see the privacy policy). + */ +export const serializeRequest = (request: FastifyRequest) => ({ + method: request.method, + url: request.routeOptions?.url ?? stripQueryParams(request.url), + hostname: request.hostname, + xClient: request.headers['x-client'], + userAgent: request.headers['user-agent'], +}); + export const initLogging = async (config: Config): Promise => { return pino({ level: config.logLevel, @@ -25,17 +38,7 @@ export const initLogging = async (config: Config): Promise => { err: pino.stdSerializers.err, error: pino.stdSerializers.err, // https://fastify.dev/docs/v2.15.x/Documentation/Logging/#log-redaction - req(request: FastifyRequest) { - return { - method: request.method, - url: stripQueryParams(request.url), - hostname: request.hostname, - remoteAddress: request.ip, - remotePort: request.socket.remotePort, - xClient: request.headers['x-client'], - userAgent: request.headers['user-agent'], - }; - }, + req: serializeRequest, }, }); }; From 6bf7a79e1f300706ac4516c7e804dc6895df6bbc Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:09:45 -0600 Subject: [PATCH 5/6] fix(server): fail open on rate-limit store errors and hide 5xx details The rate limiter shares Redis with the vault, so a Redis at maxmemory made every request fail. Skip rate limiting when its store errors, keep internal error messages out of 5xx responses, and document sizing and monitoring REDIS_MAXMEMORY. --- .changeset/server-logs-config-hardening.md | 5 ++ README.md | 1 + packages/server/src/app.test.ts | 65 ++++++++++++++++++++++ packages/server/src/app.ts | 10 +++- 4 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 .changeset/server-logs-config-hardening.md diff --git a/.changeset/server-logs-config-hardening.md b/.changeset/server-logs-config-hardening.md new file mode 100644 index 0000000..943f54d --- /dev/null +++ b/.changeset/server-logs-config-hardening.md @@ -0,0 +1,5 @@ +--- +'@crypt.fyi/server': patch +--- + +Boolean settings (`OTEL_ENABLED`, `WEBHOOK_REMOVE_ON_COMPLETE`, `WEBHOOK_REMOVE_ON_FAIL`, `WEBHOOK_REQUIRE_HTTPS`) now read `false` and `0` as false and reject unrecognised values; before, any non-empty value meant true. Request logs record the route pattern instead of the vault ID and no longer include client IP addresses or ports, and OpenTelemetry spans no longer record the verification hash. If the rate-limit store fails, requests are served instead of returning 500, and 5xx responses no longer include internal error messages. diff --git a/README.md b/README.md index a8060a8..e35722f 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,7 @@ What this means for operators: - **Don't back up the volume.** Restoring a backup can bring back burned secrets. - **Writes are slower** than without persistence, because each one waits for the disk. - **`docker compose down -v` deletes the volume** and every unexpired secret with it. +- **Size `REDIS_MAXMEMORY` for your traffic and watch it.** The compose file caps Redis at 256 MB with `noeviction`, so live secrets are never dropped. Once the cap is reached, new secrets and queued webhooks are rejected until entries expire, which can take up to the max TTL (7 days by default). Rate limiting fails open in that state so it does not turn every request into an error, but writes still fail. Alert on Redis `used_memory` approaching `maxmemory`, and lower `BODY_LIMIT_BYTES`, `VAULT_ENTRY_TTL_MS_MAX` or `RATE_LIMIT_MAX` if needed. To run without persistence, set `--appendonly no` and remove the volume. A Redis restart then drops all unexpired secrets and queued webhooks. If you run Redis any other way (the GHCR image with your own Redis, a managed service, a hosting platform), apply these settings yourself: by default Redis takes snapshots and doesn't use AOF. diff --git a/packages/server/src/app.test.ts b/packages/server/src/app.test.ts index 3158db4..0a41bb9 100644 --- a/packages/server/src/app.test.ts +++ b/packages/server/src/app.test.ts @@ -72,6 +72,71 @@ describe('app', () => { expect(response.statusCode).toBe(200); }); + describe('server-side failures', () => { + const createBody = { + c: 'foobar', + b: true, + h: 'abc123', + ttl: 1000, + m: { encryption: { algorithm: 'aes-256-gcm' } }, + } satisfies CreateVaultRequest; + + const createVault = () => + createRedisVault( + testContext.redis, + createTokenGenerator({ vaultEntryIdentifierLength: 20, vaultEntryDeleteTokenLength: 20 }), + createNopWebhookSender(), + machine.createKeyring('foobar'), + ); + + it('keeps serving requests when the rate limit store fails', async () => { + // A Redis client that rejects every command, like a Redis at maxmemory. + const failing = new Redis(1, 'localhost', { + lazyConnect: true, + enableOfflineQueue: false, + retryStrategy: () => null, + }); + const app = await initApp( + { ...testContext.config, rateLimiter: 'redis', rateLimitMax: 100 }, + { logger: pino({ enabled: false }), vault: createVault(), redis: failing }, + ); + try { + const response = await app.fastify.inject({ + method: 'POST', + url: '/vault', + payload: createBody, + }); + expect(response.statusCode).toBe(201); + } finally { + await app.fastify.close(); + failing.disconnect(); + } + }); + + it('does not return internal error messages', async () => { + const vault = createVault(); + const app = await initApp(testContext.config, { + logger: pino({ enabled: false }), + vault: { + ...vault, + get: async () => { + throw new Error( + 'vault entry digest was made with an encryption key that is not loaded', + ); + }, + }, + redis: testContext.redis, + }); + try { + const response = await app.fastify.inject({ method: 'GET', url: '/vault/some-id?h=abc' }); + expect(response.statusCode).toBe(500); + expect(response.json()).toEqual({ msg: 'Something went wrong' }); + } finally { + await app.fastify.close(); + } + }); + }); + it('serves the swagger UI, its assets and the OpenAPI document', async () => { const get = (path: string) => testContext.client.request({ method: 'GET', path }); const { swaggerUIPath } = testContext.config; diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts index ca48456..322066c 100644 --- a/packages/server/src/app.ts +++ b/packages/server/src/app.ts @@ -90,6 +90,10 @@ export const initApp = async (config: Config, deps: AppDeps) => { nameSpace: config.rateLimitNameSpace, max: config.rateLimitMax, timeWindow: config.rateLimitWindowMs, + // The counters share Redis with the vault. If Redis rejects writes (for + // example at maxmemory), failing open keeps reads of existing secrets + // working instead of turning every request into a 500. + skipOnError: true, }); app.register(helmet); @@ -389,7 +393,11 @@ export const initApp = async (config: Config, deps: AppDeps) => { if (res.sent) return; - res.status(error.statusCode ?? 500).send({ msg: error.message || 'Something went wrong' }); + const statusCode = error.statusCode ?? 500; + // Server-side failure details (Redis errors, key configuration) stay in the logs. + const msg = + statusCode >= 500 ? 'Something went wrong' : error.message || 'Something went wrong'; + res.status(statusCode).send({ msg }); }); await app.ready(); From 5097dc06c88fc8c777ac9b47aa1cdff23e93582a Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:09:45 -0600 Subject: [PATCH 6/6] ci: pin release workflow actions to commit SHAs --- .github/workflows/release.yml | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 58d2e94..768d2b2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,17 +26,17 @@ jobs: version: ${{ steps.version.outputs.version }} steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: run_install: false - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version-file: .nvmrc cache: 'pnpm' @@ -47,7 +47,7 @@ jobs: - name: Create Release Pull Request or Publish id: changesets - uses: changesets/action@v1 + uses: changesets/action@a45c4d594aa4e2c509dc14a9f2b3b67ba3780d0d # v1.9.0 with: version: pnpm version-packages publish: pnpm release @@ -80,17 +80,17 @@ jobs: contents: read steps: - name: Checkout release tag - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: refs/tags/@crypt.fyi/extension@${{ needs.release.outputs.version }} - name: Setup pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 with: run_install: false - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: # Explicit rather than .nvmrc: release tags cut before .nvmrc existed (<= 0.0.21) # must still build on manual recovery runs. Keep in sync with .nvmrc. @@ -125,18 +125,18 @@ jobs: packages: write steps: - name: Checkout release tag - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: refs/tags/@crypt.fyi/server@${{ needs.release.outputs.version }} - name: Set up QEMU - uses: docker/setup-qemu-action@v4 + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4 + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - name: Log in to GHCR - uses: docker/login-action@v4 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -144,7 +144,7 @@ jobs: - name: Image metadata id: meta - uses: docker/metadata-action@v6 + uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 with: images: ghcr.io/${{ github.repository_owner }}/crypt.fyi-server tags: | @@ -155,7 +155,7 @@ jobs: # Only the server image is published: the web image bakes VITE_API_URL in at build # time, so a prebuilt one would point every self-hoster at the same API. - name: Build and push - uses: docker/build-push-action@v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . file: Dockerfile.server @@ -180,7 +180,7 @@ jobs: contents: write steps: - name: Checkout main - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: main