Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/server-logs-config-hardening.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/webhook-retries-redirects.md
Original file line number Diff line number Diff line change
@@ -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.
28 changes: 14 additions & 14 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -125,26 +125,26 @@ 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 }}
password: ${{ secrets.GITHUB_TOKEN }}

- 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: |
Expand All @@ -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
Expand All @@ -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

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
65 changes: 65 additions & 0 deletions packages/server/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
10 changes: 9 additions & 1 deletion packages/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
26 changes: 26 additions & 0 deletions packages/server/src/config.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
32 changes: 19 additions & 13 deletions packages/server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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()
Expand All @@ -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'),
});

Expand Down
12 changes: 6 additions & 6 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -27,9 +28,8 @@ const main = async () => {
});
let cleanupFns: (() => Promise<void>)[] = [];
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 } =
Expand All @@ -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();
Expand All @@ -56,7 +56,7 @@ const main = async () => {
const httpWebhookSender = createHTTPWebhookSender({
logger,
requestTimeoutMs: config.webhookRequestTimeoutMs,
fetchFn: webhookSenderFetch,
validateUrl: validateWebhookUrl,
});
webhookSender = httpWebhookSender;
} else {
Expand Down
27 changes: 27 additions & 0 deletions packages/server/src/logging.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof serializeRequest> | 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');
});
});
Loading
Loading