Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Run the daily cleanup from a Vercel cron job
Claudec18915d0a145
diff --git a/e2e/platform.spec.ts b/e2e/platform.spec.tsnew file mode 100644index 0000000..5482a44--- /dev/null+++ b/e2e/platform.spec.ts@@ -0,0 +1,94 @@+import { createHash } from "node:crypto";++import { expect, test } from "@playwright/test";+import pg from "pg";++import { e2eDatabaseUrl } from "../playwright.config";++// The cleanup route and the sign-in limit, as the running app serves them.+// What sits underneath (the rate limit statement, the job's lock and its+// hourly ration) is tested on its own with `npm run test:db`.++const RETENTION_RATION_KEY = createHash("sha256")+ .update("job:retention")+ .digest("hex");++let database: pg.Pool;++test.beforeAll(() => {+ database = new pg.Pool({ connectionString: e2eDatabaseUrl });+});++test.afterAll(async () => {+ await database.end();+});++test("the cleanup route runs for Vercel's cron call and tells a stranger nothing", async ({+ request,+}) => {+ await database.query("delete from public.rate_limits where key = $1", [+ RETENTION_RATION_KEY,+ ]);+ await database.query(+ "insert into public.rate_limits (key, count, expires_at) values ('e2e-finished-window', 3, 1)",+ );++ // This deployment has no CRON_SECRET, like one made with the Deploy+ // button, so Vercel's call arrives with no proof of who it is.+ const first = await request.get("/api/internal/retention");++ expect(first.status()).toBe(204);+ expect(await first.text()).toBe("");++ // It did the work: the finished window is gone.+ const leftover = await database.query(+ "select 1 from public.rate_limits where key = 'e2e-finished-window'",+ );++ expect(leftover.rowCount).toBe(0);++ // A second call inside the hour looks exactly the same from outside.+ const second = await request.post("/api/internal/retention");++ expect(second.status()).toBe(204);+ expect(await second.text()).toBe("");++ // Both were counted against the hourly ration.+ const ration = await database.query<{ count: number }>(+ "select count from public.rate_limits where key = $1",+ [RETENTION_RATION_KEY],+ );++ expect(ration.rows[0]?.count).toBe(2);+});++test("sign-in attempts are limited, and counted in the database", async ({+ request,+}) => {+ // Its own address, so this does not use up the allowance of the browser+ // in the other test.+ const headers = { "x-forwarded-for": "203.0.113.77" };+ const countRows = async () =>+ (+ await database.query<{ total: number }>(+ "select count(*)::int as total from public.rate_limits",+ )+ ).rows[0]?.total ?? 0;+ const before = await countRows();+ const statuses: number[] = [];++ for (let attempt = 0; attempt < 4; attempt += 1) {+ const response = await request.post("/api/auth/sign-in/email", {+ data: { email: "[email protected]", password: "not-the-password" },+ headers,+ });++ statuses.push(response.status());+ }++ // Three wrong passwords are answered as wrong passwords. The fourth+ // within ten seconds is turned away before it is looked at.+ expect(statuses.slice(0, 3)).not.toContain(429);+ expect(statuses[3]).toBe(429);+ expect(await countRows()).toBeGreaterThan(before);+});diff --git a/src/app/api/internal/retention/route.ts b/src/app/api/internal/retention/route.tsindex 4640c75..fb5bdf3 100644--- a/src/app/api/internal/retention/route.ts+++ b/src/app/api/internal/retention/route.ts@@ -1,34 +1,64 @@import { NextResponse } from "next/server";-import { runRetentionSweep } from "@/lib/retention";-import { getEnv } from "@/lib/utils/env";+import {+ identifyRetentionCaller,+ isCronLockedOutByOlderSecret,+ retentionSweepFailed,+ runRetentionJob,+} from "@/lib/retention-job";+import { logRouteError } from "@/lib/security/logging";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";-function isAuthorizedRequest(request: Request, secret: string) {- return request.headers.get("authorization") === `Bearer ${secret}`;-}+// The daily cleanup. Vercel's cron job calls this with GET (see+// vercel.json); a scheduler elsewhere can use POST as before.+//+// With a job secret configured, only a caller that presents it gets in, and+// it gets the summary back. With none, anyone may call and gets an empty+// answer whether or not anything ran: see src/lib/retention-job.ts for why+// that is safe to leave open.-export async function POST(request: Request) {- const retentionJobSecret = getEnv().internal.retentionJobSecret;+async function handle(request: Request) {+ const caller = identifyRetentionCaller(request.headers.get("authorization"));- if (!retentionJobSecret) {- return NextResponse.json(- {- error: "Retention job secret is not configured.",- },- { status: 503 },- );- }+ if (caller === "denied") {+ if (isCronLockedOutByOlderSecret(request.headers.get("user-agent"))) {+ console.warn(+ "[retention] Vercel's daily cleanup call was refused: RETENTION_JOB_SECRET is set, and Vercel only sends CRON_SECRET. Store the secret as CRON_SECRET instead, or remove it.",+ );+ }- if (!isAuthorizedRequest(request, retentionJobSecret)) {return NextResponse.json({ error: "Unauthorized." }, { status: 401 });}- const summary = await runRetentionSweep();- const hasFailures =- summary.accountPurgeFailures.length > 0 ||- summary.draftDeletionFailures.length > 0;+ try {+ const outcome = await runRetentionJob({ caller });+ const failed =+ outcome.status === "ran" && retentionSweepFailed(outcome.summary);++ if (caller === "authorized") {+ return NextResponse.json(+ outcome.status === "ran" ? outcome.summary : outcome,+ { status: failed ? 500 : 200 },+ );+ }++ return new NextResponse(null, { status: failed ? 500 : 204 });+ } catch (error) {+ logRouteError(error, {+ category: "retention_job_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "The cleanup job failed.",+ path: getRequestPathname(request),+ });++ return new NextResponse(null, { status: 500 });+ }+}++export function GET(request: Request) {+ return handle(request);+}- return NextResponse.json(summary, {- status: hasFailures ? 500 : 200,- });+export function POST(request: Request) {+ return handle(request);}diff --git a/src/lib/retention-job.dbtest.ts b/src/lib/retention-job.dbtest.tsnew file mode 100644index 0000000..6553928--- /dev/null+++ b/src/lib/retention-job.dbtest.ts@@ -0,0 +1,118 @@+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, before, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import {+ RETENTION_ADVISORY_LOCK_ID,+ runRetentionJob,+} from "./retention-job.ts";+import { createStorageService } from "./services/storage.ts";++// The cleanup job's hourly ration and its lock, against a real Postgres.+// Run with `npm run test:db`.++const RATION_KEY = createHash("sha256").update("job:retention").digest("hex");++let database: pg.Pool;+let storageDir: string;++function run(caller: "anonymous" | "authorized") {+ return runRetentionJob({+ caller,+ database,+ storageService: createStorageService({+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },+ }),+ });+}++async function clearRation() {+ await database.query("delete from public.rate_limits where key = $1", [+ RATION_KEY,+ ]);+}++before(async () => {+ database = await openTestDatabase();+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-retention-"));+});++after(async () => {+ await clearRation();+ await database.end();+ await rm(storageDir, { force: true, recursive: true });+});++test("a caller with no secret gets one run an hour", async () => {+ await clearRation();++ const first = await run("anonymous");++ assert.equal(first.status, "ran");+ assert.deepEqual(await run("anonymous"), {+ reason: "ran_recently",+ status: "skipped",+ });+ assert.deepEqual(await run("anonymous"), {+ reason: "ran_recently",+ status: "skipped",+ });+});++test("a caller with the secret is not rationed, and gets the summary", async () => {+ const first = await run("authorized");+ const second = await run("authorized");++ assert.equal(first.status, "ran");+ assert.equal(second.status, "ran");++ if (second.status === "ran") {+ assert.deepEqual(second.summary.accountPurgeFailures, []);+ assert.deepEqual(second.summary.draftDeletionFailures, []);+ }+});++test("a run clears finished rate limit windows", async () => {+ await database.query(+ `insert into public.rate_limits (key, count, expires_at)+ values ('dbtest-finished-window', 3, 1)+ on conflict (key) do nothing`,+ );++ assert.equal((await run("authorized")).status, "ran");++ const leftover = await database.query(+ "select 1 from public.rate_limits where key = 'dbtest-finished-window'",+ );++ assert.equal(leftover.rowCount, 0);+});++test("while one run holds the lock, another steps aside", async () => {+ const holder = await database.connect();++ try {+ await holder.query("begin");+ await holder.query("select pg_advisory_xact_lock($1)", [+ RETENTION_ADVISORY_LOCK_ID,+ ]);++ assert.deepEqual(await run("authorized"), {+ reason: "already_running",+ status: "skipped",+ });+ } finally {+ await holder.query("rollback");+ holder.release();+ }++ // The lock went with the holder's transaction, and a skipped run leaves+ // none of its own behind.+ assert.equal((await run("authorized")).status, "ran");+});diff --git a/src/lib/retention-job.test.ts b/src/lib/retention-job.test.tsnew file mode 100644index 0000000..40d8aaf--- /dev/null+++ b/src/lib/retention-job.test.ts@@ -0,0 +1,75 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ identifyRetentionCaller,+ isCronLockedOutByOlderSecret,+} from "./retention-job.ts";++// Running the job itself, with its lock and its hourly ration, is checked+// against a real Postgres in retention-job.dbtest.ts.++test("with no secret configured, anyone may ask and nobody is trusted", () => {+ assert.equal(identifyRetentionCaller(null, {}), "anonymous");+ assert.equal(identifyRetentionCaller("Bearer guess", {}), "anonymous");+});++test("with CRON_SECRET set, only a caller that presents it gets in", () => {+ const env = { CRON_SECRET: "cron-secret-value" };++ assert.equal(+ identifyRetentionCaller("Bearer cron-secret-value", env),+ "authorized",+ );+ assert.equal(identifyRetentionCaller(null, env), "denied");+ assert.equal(identifyRetentionCaller("Bearer wrong", env), "denied");+ assert.equal(identifyRetentionCaller("cron-secret-value", env), "denied");+ assert.equal(identifyRetentionCaller("Bearer ", env), "denied");+});++test("RETENTION_JOB_SECRET closes the route the same way, as it always did", () => {+ const env = { RETENTION_JOB_SECRET: "older-secret-value" };++ assert.equal(+ identifyRetentionCaller("Bearer older-secret-value", env),+ "authorized",+ );+ assert.equal(identifyRetentionCaller(null, env), "denied");+ assert.equal(identifyRetentionCaller("Bearer wrong", env), "denied");+});++test("Vercel's cron being refused for want of CRON_SECRET is recognized", () => {+ const olderOnly = { RETENTION_JOB_SECRET: "older-secret-value" };++ assert.equal(+ isCronLockedOutByOlderSecret("vercel-cron/1.0", olderOnly),+ true,+ );+ assert.equal(isCronLockedOutByOlderSecret("curl/8.0", olderOnly), false);+ assert.equal(isCronLockedOutByOlderSecret(null, olderOnly), false);+ assert.equal(+ isCronLockedOutByOlderSecret("vercel-cron/1.0", {+ ...olderOnly,+ CRON_SECRET: "cron-secret-value",+ }),+ false,+ );+ assert.equal(isCronLockedOutByOlderSecret("vercel-cron/1.0", {}), false);+});++test("with both set, either secret works", () => {+ const env = {+ CRON_SECRET: "cron-secret-value",+ RETENTION_JOB_SECRET: "older-secret-value",+ };++ assert.equal(+ identifyRetentionCaller("Bearer cron-secret-value", env),+ "authorized",+ );+ assert.equal(+ identifyRetentionCaller("Bearer older-secret-value", env),+ "authorized",+ );+ assert.equal(identifyRetentionCaller("Bearer wrong", env), "denied");+});diff --git a/src/lib/retention-job.ts b/src/lib/retention-job.tsnew file mode 100644index 0000000..5cac5d0--- /dev/null+++ b/src/lib/retention-job.ts@@ -0,0 +1,168 @@+import { createHash, timingSafeEqual } from "node:crypto";++import { getDb, type DbPool } from "./db/connection.ts";+import { runRetentionSweep, type RetentionSweepSummary } from "./retention.ts";+import {+ consumeRateLimit,+ deleteExpiredRateLimits,+} from "./security/rate-limit.ts";+import type { StorageService } from "./services/storage.ts";+import { isMissingSchemaError } from "./settings.ts";+import { getEnv, type EnvSource } from "./utils/env.ts";++// The daily cleanup: stale drafts, queued account deletions, expired+// download links and finished rate limit windows.+//+// On Vercel it is called by a cron job (see vercel.json). A click-to-deploy+// install has no secret for that call, because nobody typed one in, so the+// job protects itself instead: it runs at most once an hour, never twice at+// the same time, and tells an anonymous caller nothing. Calling it early+// only does work that was due anyway.++export const RETENTION_ADVISORY_LOCK_ID = 746108323;+const ANONYMOUS_RUN_INTERVAL_MS = 60 * 60 * 1000;++/**+ * - authorized: the caller proved it knows a job secret.+ * - anonymous: no secret is configured, so there is nothing to prove. The+ * run is rationed.+ * - denied: a secret is configured and the caller did not present it.+ */+export type RetentionCaller = "anonymous" | "authorized" | "denied";++export type RetentionJobOutcome =+ | { status: "ran"; summary: RetentionSweepSummary }+ | { status: "skipped"; reason: "already_running" | "ran_recently" };++function digest(value: string): Buffer {+ return createHash("sha256").update(value).digest();+}++function matchesAnySecret(presented: string, secrets: string[]): boolean {+ const presentedDigest = digest(presented);+ let matched = false;++ // Every secret is compared, so the time taken does not depend on which+ // one matched.+ for (const secret of secrets) {+ if (timingSafeEqual(presentedDigest, digest(secret))) {+ matched = true;+ }+ }++ return matched;+}++/**+ * Decides how much to trust a request to run the cleanup.+ *+ * Vercel sends CRON_SECRET as a bearer token on cron calls when that+ * variable is set, so setting it locks the route to Vercel's own calls.+ * RETENTION_JOB_SECRET is the older name, for a scheduler on another host.+ * If either is set, one of them has to be presented.+ * https://vercel.com/docs/cron-jobs/manage-cron-jobs#securing-cron-jobs+ */+export function identifyRetentionCaller(+ authorizationHeader: string | null,+ env: EnvSource = process.env,+): RetentionCaller {+ const { cronSecret, retentionJobSecret } = getEnv(env).internal;+ const secrets = [cronSecret, retentionJobSecret].filter(+ (secret): secret is string => Boolean(secret),+ );++ if (secrets.length === 0) {+ return "anonymous";+ }++ const presented = /^Bearer (.+)$/.exec(authorizationHeader ?? "")?.[1];++ return presented && matchesAnySecret(presented, secrets)+ ? "authorized"+ : "denied";+}++/**+ * True when Vercel's cron is being turned away only because the secret is+ * stored under the name Vercel does not send. Worth saying in the log:+ * nothing else would show that the daily cleanup never runs.+ */+export function isCronLockedOutByOlderSecret(+ userAgent: string | null,+ env: EnvSource = process.env,+): boolean {+ const { cronSecret, retentionJobSecret } = getEnv(env).internal;++ return Boolean(+ retentionJobSecret && !cronSecret && userAgent?.startsWith("vercel-cron/"),+ );+}++/**+ * Runs the cleanup unless another run holds the lock or, for an anonymous+ * caller, one ran within the last hour.+ */+export async function runRetentionJob({+ caller,+ database = getDb(),+ storageService,+}: {+ caller: Exclude<RetentionCaller, "denied">;+ database?: DbPool;+ storageService?: StorageService;+}): Promise<RetentionJobOutcome> {+ if (caller === "anonymous") {+ const ration = await consumeRateLimit(+ {+ key: "job:retention",+ limit: 1,+ windowMs: ANONYMOUS_RUN_INTERVAL_MS,+ },+ { database },+ );++ if (!ration.allowed) {+ return { reason: "ran_recently", status: "skipped" };+ }+ }++ // The lock lives as long as this transaction, which is held open on its+ // own connection while the cleanup works through the pool. A transaction+ // lock is used because it also holds through a connection pooler.+ const lockClient = await database.connect();++ try {+ await lockClient.query("begin");++ const lock = await lockClient.query<{ locked: boolean }>(+ "select pg_try_advisory_xact_lock($1) as locked",+ [RETENTION_ADVISORY_LOCK_ID],+ );++ if (!lock.rows[0]?.locked) {+ return { reason: "already_running", status: "skipped" };+ }++ const summary = await runRetentionSweep({ database, storageService });++ await deleteExpiredRateLimits(database).catch((error: unknown) => {+ // A database from before rate limits were kept in it has no table to+ // clear, which is fine.+ if (!isMissingSchemaError(error)) {+ console.error("Clearing finished rate limit windows failed:", error);+ }+ });++ return { status: "ran", summary };+ } finally {+ await lockClient.query("rollback").catch(() => undefined);+ lockClient.release();+ }+}++export function retentionSweepFailed(summary: RetentionSweepSummary): boolean {+ return (+ summary.accountPurgeFailures.length > 0 ||+ summary.draftDeletionFailures.length > 0+ );+}diff --git a/src/lib/utils/env.ts b/src/lib/utils/env.tsindex 6c75dab..8daed92 100644--- a/src/lib/utils/env.ts+++ b/src/lib/utils/env.ts@@ -273,6 +273,8 @@ export function getEnv(env: EnvSource = process.env) {supportAddress: readEnv(env, "SUPPORT_EMAIL"),},internal: {+ // Vercel sends this as a bearer token on cron calls when it is set.+ cronSecret: readEnv(env, "CRON_SECRET"),retentionJobSecret: readEnv(env, "RETENTION_JOB_SECRET"),},setup: {diff --git a/vercel.json b/vercel.jsonindex 7b1e26e..96a8419 100644--- a/vercel.json+++ b/vercel.json@@ -1,4 +1,10 @@{"$schema": "https://openapi.vercel.sh/vercel.json",- "buildCommand": "node db/migrate.mjs --optional && next build"+ "buildCommand": "node db/migrate.mjs --optional && next build",+ "crons": [+ {+ "path": "/api/internal/retention",+ "schedule": "0 9 * * *"+ }+ ]}