Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Fix the review findings on webhooks
Claudea751e64203ae
diff --git a/docs/api.md b/docs/api.mdindex b69d3dd..9e1f0cf 100644--- a/docs/api.md+++ b/docs/api.md@@ -356,7 +356,8 @@ Answer with any `2xx` within 10 seconds, and do the slow work after. Anyother answer, a redirect, or no answer counts as a failure, and the deliveryis tried again 1 minute, 5 minutes, 30 minutes, 2 hours, 8 hours, 24 hoursand 24 hours later, about two and a half days in all. After the eighth try-it is marked failed. The delivery log in Settings shows the last 100+it is marked failed. A delivery whose envelope has since been deleted is+not sent again. The delivery log in Settings shows the last 100deliveries per endpoint, with your app's answer, and "Send again" puts adelivered or failed one back in line.diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex c283d9e..088e978 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -124,7 +124,7 @@ import {import { PERMITTED_USE_VERSION } from "./permitted-uses.ts";import { hashAccessCode } from "./signer-checks.ts";import { escapeHtml } from "./utils/html.ts";-import { requestWebhookDrain } from "./webhooks/outbox.ts";+import { releaseSentWebhook } from "./webhooks/outbox.ts";type CreateDraftEnvelopeOptions = {database?: DbPool;@@ -2701,13 +2701,14 @@ export async function sendDraftEnvelope(`,[envelopeId, sentAuditAt, input.senderEmail],);- // The envelope.sent webhook was waiting for the invitation to go out- // (see below); it did not, so there is nothing to tell.+ // The envelope.sent webhook was held for the invitation (see+ // releaseSentWebhook below); it did not go out, so there is nothing+ // to tell, whatever happened to the delivery meanwhile.await tx.query(`DELETE FROM webhook_deliveriesWHERE envelope_id = $1 AND event_type = 'envelope.sent'- AND status = 'pending' AND attempts = 0+ AND status = 'pending'`,[envelopeId],);@@ -2732,7 +2733,13 @@ export async function sendDraftEnvelope(database,);// Only now that the invitation is out is the envelope really sent.- requestWebhookDrain();+ await releaseSentWebhook(envelopeId, database).catch((error: unknown) => {+ // Then it goes out when its hold runs out instead.+ console.error(+ `Releasing the envelope.sent webhook of ${envelopeId} failed:`,+ error,+ );+ });return sendEnvelopeResponseSchema.parse({envelopeId,diff --git a/src/lib/webhooks/deliver.ts b/src/lib/webhooks/deliver.tsindex 2843e7c..ae7976f 100644--- a/src/lib/webhooks/deliver.ts+++ b/src/lib/webhooks/deliver.ts@@ -65,6 +65,12 @@ type ClaimedDelivery = {envelopeId: string | null;eventType: string;id: string;+ /**+ * The lease this drain took. Every write about this try checks it is+ * still the one on the row, so a try that outlived its lease (and was+ * taken over by a newer drain) cannot overwrite what the newer one did.+ */+ lockedUntil: number;/** The body exactly as first sent, or null before the first try. */payload: string | null;previousSecretEncrypted: string | null;@@ -169,6 +175,7 @@ async function claimDueDeliveries(c.signer_id AS "signerId",c.payload,c.attempts,+ c.locked_until AS "lockedUntil",c.created_at AS "createdAt",a.created_at AS "auditCreatedAt",a.metadata AS "auditMetadata",@@ -211,9 +218,9 @@ async function recordOutcome(SET status = 'delivered', delivered_at = $2, last_status_code = $3,last_error = NULL, locked_until = NULL, next_attempt_at = NULL,updated_at = $2- WHERE id = $1+ WHERE id = $1 AND locked_until = $4 AND status = 'pending'`,- [delivery.id, now, outcome.status],+ [delivery.id, now, outcome.status, delivery.lockedUntil],);return;}@@ -224,9 +231,9 @@ async function recordOutcome(UPDATE webhook_deliveriesSET status = 'failed', last_error = $3, locked_until = NULL,next_attempt_at = NULL, updated_at = $2- WHERE id = $1+ WHERE id = $1 AND locked_until = $4 AND status = 'pending'`,- [delivery.id, now, outcome.reason],+ [delivery.id, now, outcome.reason, delivery.lockedUntil],);return;}@@ -238,7 +245,7 @@ async function recordOutcome(UPDATE webhook_deliveriesSET status = $3, next_attempt_at = $4, last_status_code = $5,last_error = $6, locked_until = NULL, updated_at = $2- WHERE id = $1+ WHERE id = $1 AND locked_until = $7 AND status = 'pending'`,[delivery.id,@@ -247,23 +254,35 @@ async function recordOutcome(next,outcome.status,outcome.error.slice(0, MAX_ERROR_LENGTH),+ delivery.lockedUntil,],);}+async function envelopeExists(+ delivery: ClaimedDelivery,+ database: DbExecutor,+): Promise<boolean> {+ const row = await queryOne<{ id: string }>(+ database,+ `SELECT id FROM envelopes WHERE id = $1`,+ [delivery.envelopeId],+ );++ return row !== null;+}+async function sendOne(database: DbExecutor,delivery: ClaimedDelivery,env: EnvSource,-): Promise<"delivered" | "failed" | "dropped"> {+): Promise<"delivered" | "failed" | "dropped" | "skipped"> {let body = delivery.payload;- // Its event was taken back (a send whose invitation could not go out).- if (- body === null &&- delivery.auditEventId &&- delivery.auditCreatedAt === null- ) {+ // Checked before every try, the first and each retry: its event was+ // taken back (a send whose invitation could not go out), or its+ // envelope is gone. Either way there is nothing true left to tell.+ if (delivery.auditEventId && delivery.auditCreatedAt === null) {await recordOutcome(database,delivery,@@ -273,6 +292,16 @@ async function sendOne(return "dropped";}+ if (delivery.envelopeId && !(await envelopeExists(delivery, database))) {+ await recordOutcome(+ database,+ delivery,+ { kind: "dropped", reason: "The envelope was deleted." },+ nowInSeconds(),+ );+ return "dropped";+ }+if (body === null) {const payload = await buildWebhookPayload(delivery, database);@@ -280,21 +309,28 @@ async function sendOne(await recordOutcome(database,delivery,- {- kind: "dropped",- reason: "The envelope was deleted before it was sent.",- },+ { kind: "dropped", reason: "The envelope was deleted." },nowInSeconds(),);return "dropped";}body = JSON.stringify(payload);- // Kept, so every later try sends, and signs, the same bytes.- await database.query(- `UPDATE webhook_deliveries SET payload = $2 WHERE id = $1`,- [delivery.id, body],++ // Kept, so every later try sends, and signs, the same bytes. Only+ // while this drain still holds the lease: if it lost it, the newer+ // drain sends instead.+ const saved = await database.query(+ `+ UPDATE webhook_deliveries SET payload = $2+ WHERE id = $1 AND locked_until = $3 AND payload IS NULL+ `,+ [delivery.id, body, delivery.lockedUntil],);++ if ((saved.rowCount ?? 0) === 0) {+ return "skipped";+ }}const sentAt = nowInSeconds();@@ -352,6 +388,8 @@ export type DrainSummary = {delivered: number;dropped: number;failed: number;+ /** Tries that lost their lease to a newer drain, which sends instead. */+ skipped: number;};/**@@ -368,7 +406,12 @@ export async function drainWebhookDeliveries(): Promise<DrainSummary> {const database = options.database ?? getDb();const env = options.env ?? process.env;- const summary: DrainSummary = { delivered: 0, dropped: 0, failed: 0 };+ const summary: DrainSummary = {+ delivered: 0,+ dropped: 0,+ failed: 0,+ skipped: 0,+ };for (let batch = 0; batch < (options.maxBatches ?? 4); batch += 1) {const claimed = await claimDueDeliveries(diff --git a/src/lib/webhooks/outbox.ts b/src/lib/webhooks/outbox.tsindex 1d61812..33f7367 100644--- a/src/lib/webhooks/outbox.ts+++ b/src/lib/webhooks/outbox.ts@@ -28,6 +28,36 @@ export function requestWebhookDrain() {drainScheduler();}+/**+ * How long an envelope.sent delivery waits, unclaimable, for its+ * invitation email. sendDraftEnvelope releases it the moment the email is+ * out, or deletes it if the email fails and the send is undone. The wait+ * only runs out if the function died in between, and then the envelope+ * did stay sent, so the delivery is right to go.+ */+export const SENT_HOLD_SECONDS = 10 * 60;++/**+ * Makes an envelope's held envelope.sent delivery due now and starts+ * sending. Called once the envelope is really out.+ */+export async function releaseSentWebhook(+ envelopeId: string,+ database: DbExecutor,+ now: number = Math.floor(Date.now() / 1000),+): Promise<void> {+ await database.query(+ `+ UPDATE webhook_deliveries+ SET next_attempt_at = $2, updated_at = $2+ WHERE envelope_id = $1 AND event_type = 'envelope.sent'+ AND status = 'pending' AND attempts = 0 AND next_attempt_at > $2+ `,+ [envelopeId, now],+ );+ drainScheduler();+}+export async function enqueueWebhookDeliveries(input: {auditEventId: string;@@ -48,6 +78,15 @@ export async function enqueueWebhookDeliveries(typeof input.metadata?.signerId === "string"? input.metadata.signerId: null;+ const now = Math.floor(Date.now() / 1000);+ // Due now. The audit event's own time can be a second ahead, since+ // events on one envelope never share a second. A send is not finished+ // until its invitation email is out, so its delivery waits for that+ // (see SENT_HOLD_SECONDS) and no drain can take it early.+ const dueAt =+ input.event === "sent"+ ? now + SENT_HOLD_SECONDS+ : Math.min(input.createdAt, now);const result = await database.query(`INSERT INTO webhook_deliveries (@@ -56,25 +95,22 @@ export async function enqueueWebhookDeliveries()SELECT'msg_' || replace(gen_random_uuid()::text, '-', ''),- id, $1, $2, $3, $4, 'pending', 0, $5, $5, $5+ id, $1, $2, $3, $4, 'pending', 0, $5, $6, $6FROM webhook_endpointsWHERE enabled AND $1 = ANY(events)`,- // Due now. The audit event's own time can be a second ahead, since- // events on one envelope never share a second.[type,input.envelopeId,input.auditEventId,signerId,- Math.min(input.createdAt, Math.floor(Date.now() / 1000)),+ dueAt,+ Math.min(input.createdAt, now),],);const queued = result.rowCount ?? 0;- // A send is not finished until the invitation email has gone out, and- // is undone (with its delivery) if it cannot. sendDraftEnvelope starts- // sending once the email is out.+ // sendDraftEnvelope releases a send's delivery once the email is out.if (queued > 0 && input.event !== "sent") {afterCommit(database, () => {drainScheduler();diff --git a/src/lib/webhooks/webhooks.dbtest.ts b/src/lib/webhooks/webhooks.dbtest.tsindex f4df16d..00ae185 100644--- a/src/lib/webhooks/webhooks.dbtest.ts+++ b/src/lib/webhooks/webhooks.dbtest.ts@@ -37,7 +37,11 @@ import {resendWebhookDelivery,} from "./log.ts";import type { WebhookEventType } from "./events.ts";-import { setWebhookDrainScheduler } from "./outbox.ts";+import {+ releaseSentWebhook,+ SENT_HOLD_SECONDS,+ setWebhookDrainScheduler,+} from "./outbox.ts";import { verifyWebhook } from "./signing.ts";// Webhooks against a real Postgres and a real HTTP receiver on this@@ -512,6 +516,7 @@ test("a delivery for an envelope deleted before its first try is dropped", asyncdelivered: 0,dropped: 1,failed: 0,+ skipped: 0,});assert.equal(received.length, 0);assert.equal((await deliveriesFor(endpoint.id))[0]!.status, "failed");@@ -649,3 +654,100 @@ test("old deliveries are cleared, failed ones kept longer, and endpoints removedawait deleteWebhookEndpoint(admin, endpoint.id, database);assert.equal((await deliveriesFor(endpoint.id)).length, 0);});++test("envelope.sent waits, unclaimable, until the invitation is out", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin, ["envelope.sent"]);+ const envelope = await createEnvelope(admin, false);++ // What sendDraftEnvelope writes when it marks the envelope sent, before+ // the email goes.+ await withTransaction(+ (tx) =>+ recordAuditEvent(+ { actorType: "sender", envelopeId: envelope.id, event: "sent" },+ tx,+ ),+ database,+ );++ const [held] = await deliveriesFor(endpoint.id);+ const now = Math.floor(Date.now() / 1000);++ assert.ok(held!.nextAttemptAt! >= now + SENT_HOLD_SECONDS - 5);+ // Any drain meanwhile, from another request or the cron, takes nothing.+ assert.equal((await drainWebhookDeliveries({ database, env })).delivered, 0);+ assert.equal(received.length, 0);++ await releaseSentWebhook(envelope.id, database);+ assert.equal((await drainWebhookDeliveries({ database, env })).delivered, 1);+ assert.equal(received.length, 1);+});++test("a try that outlived its lease cannot overwrite the newer try's result", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin);++ await createEnvelope(admin);++ let releaseFirst: (status: number) => void = () => undefined;++ answer = () =>+ received.length === 1+ ? new Promise<number>((resolve) => {+ releaseFirst = resolve;+ })+ : 200;++ // The first drain sends and hangs waiting for the receiver.+ const stale = drainWebhookDeliveries({ database, env });++ while (received.length < 1) {+ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ // Its lease runs out; a newer drain takes the delivery and succeeds.+ await database.query(+ `update webhook_deliveries set locked_until = 0 where endpoint_id = $1`,+ [endpoint.id],+ );+ assert.equal((await drainWebhookDeliveries({ database, env })).delivered, 1);++ // Then the stale one hears back with a failure, and must change nothing.+ releaseFirst(500);+ await stale;++ const [row] = await deliveriesFor(endpoint.id);++ assert.equal(received.length, 2);+ assert.equal(received[0]!.body, received[1]!.body);+ assert.equal(row!.status, "delivered");+ assert.equal(row!.lastStatusCode, 200);+});++test("a retry is dropped once its envelope is deleted, even after a first try", async () => {+ const admin = await createAdmin();+ const { endpoint } = await addEndpoint(admin);+ const envelope = await createEnvelope(admin);++ answer = () => 503;+ await drainWebhookDeliveries({ database, env });++ const [tried] = await deliveriesFor(endpoint.id);++ assert.equal(tried!.status, "pending");+ assert.ok(tried!.payload);++ await database.query(`delete from envelopes where id = $1`, [envelope.id]);+ await database.query(+ `update webhook_deliveries set next_attempt_at = 0 where id = $1`,+ [tried!.id],+ );+ assert.equal((await drainWebhookDeliveries({ database, env })).dropped, 1);+ assert.equal(received.length, 1);++ // "Send again" does not bring it back either.+ assert.ok(await resendWebhookDelivery(tried!.id, database));+ assert.equal((await drainWebhookDeliveries({ database, env })).dropped, 1);+ assert.equal(received.length, 1);+});diff --git a/src/lib/webhooks/webhooks.test.ts b/src/lib/webhooks/webhooks.test.tsindex f3e77c2..ef84033 100644--- a/src/lib/webhooks/webhooks.test.ts+++ b/src/lib/webhooks/webhooks.test.ts@@ -3,7 +3,11 @@ import test from "node:test";import { MAX_ATTEMPTS, nextAttemptAt } from "./deliver.ts";import { parseWebhookEventTypes, webhookEventForAuditEvent } from "./events.ts";-import { parseWebhookUrl, privateWebhookUrlsAllowed } from "./safe-post.ts";+import {+ parseWebhookUrl,+ postWebhook,+ privateWebhookUrlsAllowed,+} from "./safe-post.ts";test("retries back off and stop after the last try", () => {assert.equal(MAX_ATTEMPTS, 8);@@ -77,3 +81,74 @@ test("private URLs are allowed only when asked for, and never on Vercel", () =>"http://127.0.0.1:4000/hook",);});++const publicAndPrivate = [+ { address: "203.0.113.10", family: 4 },+ { address: "127.0.0.1", family: 4 },+];++test("a name that resolves to a private address is never called", async () => {+ for (const addresses of [+ [{ address: "10.0.0.5", family: 4 }],+ [{ address: "169.254.169.254", family: 4 }],+ [{ address: "::1", family: 6 }],+ // One private answer among public ones is enough to refuse.+ publicAndPrivate,+ ]) {+ let asked = 0;+ const result = await postWebhook(+ "https://hooks.example.test/signudoc",+ { body: "{}", headers: {} },+ {+ env: {},+ lookup: (_hostname, callback) => {+ asked += 1;+ callback(null, addresses);+ },+ },+ );++ assert.equal(asked, 1);+ assert.equal(result.ok, false);+ assert.equal(result.status, null);+ assert.match(+ result.status === null ? result.error : "",+ /private address/,+ JSON.stringify(addresses),+ );+ }+});++test("the request goes to the address that was checked", async () => {+ const { createServer } = await import("node:http");+ const hosts: string[] = [];+ const server = createServer((request, response) => {+ hosts.push(request.headers.host ?? "");+ response.writeHead(204);+ response.end();+ });++ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));++ const { port } = server.address() as { port: number };++ try {+ // The name exists nowhere but in this lookup, so reaching the server+ // proves the connection used the address the guard was given.+ const result = await postWebhook(+ `http://hooks.example.test:${String(port)}/signudoc`,+ { body: "{}", headers: {} },+ {+ env: { WEBHOOK_ALLOW_PRIVATE_URLS: "1" },+ lookup: (_hostname, callback) => {+ callback(null, [{ address: "127.0.0.1", family: 4 }]);+ },+ },+ );++ assert.equal(result.status, 204);+ assert.deepEqual(hosts, [`hooks.example.test:${String(port)}`]);+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});