Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Answer the second review round on webhooks

Claudeb4cdc5bb5ca5
diff --git a/docs/api.md b/docs/api.md
index 5d464ce..4525658 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -333,8 +333,14 @@ import { createHmac, timingSafeEqual } from "node:crypto";
function isFromSignuDoc(headers, rawBody, secret) {
const id = headers["webhook-id"];
const timestamp = headers["webhook-timestamp"];
+ const signatures = headers["webhook-signature"];
- if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) {
+ if (!id || !timestamp || !signatures) {
+ return false;
+ }
+
+ // Written this way round so a timestamp that is not a number fails too.
+ if (!(Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300)) {
return false;
}
@@ -344,7 +350,7 @@ function isFromSignuDoc(headers, rawBody, secret) {
);
// During a secret rotation there are two signatures, space separated.
- return headers["webhook-signature"].split(" ").some((signature) => {
+ return signatures.split(" ").some((signature) => {
const given = Buffer.from(signature);
return given.length === expected.length && timingSafeEqual(given, expected);
@@ -354,7 +360,10 @@ function isFromSignuDoc(headers, rawBody, secret) {
"New secret" in Settings makes a new secret and shows it once. For 24 hours
after that, deliveries are signed with both the old and the new one, so you
-can switch without missing any.
+can switch without missing any. Another new secret can be made once those
+24 hours are over, so the old one always gets its full day. To replace a
+secret sooner, for example one that leaked, remove the endpoint and add it
+again.
### Answers and retries
@@ -374,8 +383,11 @@ day. On Pro you can run it more often by changing the schedule of
`/api/internal/webhooks` in `vercel.json`, for example to `*/5 * * * *`.
If your app was down, `GET /api/v1/webhook-deliveries?since=…` lists what
-it missed, with the same payloads. Deliveries are kept 30 days once
-delivered and 90 days otherwise.
+it missed, with the same payloads. Times are kept to the second, so a
+`since` with a fraction counts from the start of its second, and you may
+get a delivery you already have: skip it by its `webhook-id`. Deliveries
+are kept 30 days after they are delivered, and otherwise 90 days after
+their last try or "Send again".
### Safety
diff --git a/src/app/api/admin/webhooks/[id]/route.ts b/src/app/api/admin/webhooks/[id]/route.ts
index 0db586f..5ca8e7e 100644
--- a/src/app/api/admin/webhooks/[id]/route.ts
+++ b/src/app/api/admin/webhooks/[id]/route.ts
@@ -9,6 +9,7 @@ import { parseWebhookEventTypes } from "@/lib/webhooks/events";
import {
handleWebhookAdmin,
noStore,
+ notAJsonObject,
readJsonObject,
} from "@/lib/webhooks/admin-route";
@@ -23,6 +24,11 @@ export function PATCH(request: Request, context: RouteContext) {
async (actor) => {
const { id } = await context.params;
const body = await readJsonObject(request);
+
+ if (!body) {
+ return notAJsonObject();
+ }
+
const events =
body.events === undefined
? undefined
diff --git a/src/app/api/admin/webhooks/route.ts b/src/app/api/admin/webhooks/route.ts
index b2a9fc1..ba67d82 100644
--- a/src/app/api/admin/webhooks/route.ts
+++ b/src/app/api/admin/webhooks/route.ts
@@ -16,6 +16,7 @@ import {
import {
handleWebhookAdmin,
noStore,
+ notAJsonObject,
readJsonObject,
} from "@/lib/webhooks/admin-route";
@@ -53,6 +54,11 @@ export function POST(request: Request) {
}
const body = await readJsonObject(request);
+
+ if (!body) {
+ return notAJsonObject();
+ }
+
const events = parseWebhookEventTypes(body.events);
const description = parseWebhookDescription(body.description);
diff --git a/src/app/api/v1/webhook-deliveries/route.ts b/src/app/api/v1/webhook-deliveries/route.ts
index 16ecab8..4d6f3dc 100644
--- a/src/app/api/v1/webhook-deliveries/route.ts
+++ b/src/app/api/v1/webhook-deliveries/route.ts
@@ -8,11 +8,17 @@ import { listApiWebhookDeliveries } from "@/lib/webhooks/log";
// Webhook deliveries, newest first, with what each one carried. For an app
// that was down and wants to catch up: the payloads are the same ones its
-// endpoint was sent. Deliveries are kept 30 days once delivered, 90 if not.
+// endpoint was sent. Deliveries are kept 30 days once delivered, and
+// otherwise 90 days from their last change.
const querySchema = z.object({
cursor: z.string().max(200).optional(),
limit: z.coerce.number().int().min(1).max(100).default(25),
+ // Delivery times are kept to the second, so a time with a fraction
+ // counts from the start of its second. Rounding up instead could leave
+ // out a delivery made later in that same second; an app that catches up
+ // can more easily ignore one it already has (by its webhook-id) than
+ // find one that was never listed.
since: z
.string()
.datetime({ offset: true })
diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsx
index 98ccd32..104137e 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -119,6 +119,9 @@ function describeEvent(event: SystemAuditEvent): string {
case "webhook_endpoint_deleted":
return [
typeof metadata.url === "string" ? metadata.url : null,
+ Array.isArray(metadata.events)
+ ? `events: ${metadata.events.filter((type) => typeof type === "string").join(", ")}`
+ : null,
metadata.secretRotated === true ? "new signing secret" : null,
metadata.enabled === false
? "turned off"
diff --git a/src/components/settings/webhooks-panel.tsx b/src/components/settings/webhooks-panel.tsx
index e4c936b..567df87 100644
--- a/src/components/settings/webhooks-panel.tsx
+++ b/src/components/settings/webhooks-panel.tsx
@@ -113,6 +113,11 @@ function DeliveryLog({ endpointId }: { endpointId: string }) {
};
}, [endpointId, revision]);
+ function refresh() {
+ setError(null);
+ setRevision((value) => value + 1);
+ }
+
async function resend(id: string) {
setPendingId(id);
setError(null);
@@ -138,90 +143,102 @@ function DeliveryLog({ endpointId }: { endpointId: string }) {
}
}
- if (error) {
- return (
- <p className="notice notice-danger" role="alert">
- {error}
- </p>
- );
- }
-
- if (deliveries === null) {
- return <p className="text-sm text-(--secondary)">Loading...</p>;
- }
-
- if (deliveries.length === 0) {
- return <p className="text-sm text-(--secondary)">Nothing sent yet.</p>;
- }
-
+ // An error shows above the log rather than in its place, and Refresh is
+ // always there, so a failed refresh or "Send again" never hides what was
+ // already listed, and an empty or failed log can be read again.
return (
<div className="grid gap-2">
<div className="flex justify-end">
- <button
- className="btn-quiet"
- onClick={() => setRevision((value) => value + 1)}
- type="button"
- >
+ <button className="btn-quiet" onClick={refresh} type="button">
Refresh
</button>
</div>
- <ul aria-label="Recent deliveries" className="grid gap-2">
- {deliveries.map((delivery) => (
- <li
- className="grid gap-1 rounded-lg border border-(--border) px-3 py-2 text-sm"
- key={delivery.id}
- >
- <div className="flex flex-wrap items-center gap-2">
- <span className="font-mono text-(--fg)">
- {delivery.eventType}
- </span>
- <span className={`pill ${deliveryTone(delivery.status)}`}>
- {delivery.status === "pending" && delivery.attempts > 0
- ? "Retrying"
- : delivery.status === "pending"
- ? "Waiting"
- : delivery.status === "delivered"
- ? "Delivered"
- : "Failed"}
- </span>
- <span className="text-(--secondary)">
- {formatTime(delivery.createdAt)}
- {delivery.attempts > 1
- ? `, ${String(delivery.attempts)} tries`
- : ""}
- {delivery.lastStatusCode !== null
- ? `, answered ${String(delivery.lastStatusCode)}`
- : ""}
- </span>
- </div>
- {delivery.status !== "delivered" && delivery.lastError ? (
- <p className="break-all text-(--secondary)">
- {delivery.lastError}
- {delivery.status === "pending" && delivery.nextAttemptAt
- ? ` Next try around ${formatTime(delivery.nextAttemptAt) ?? ""}.`
- : ""}
- </p>
- ) : null}
- {delivery.status !== "pending" &&
- delivery.eventType !== "webhook.test" ? (
- <div>
- <button
- className="btn-quiet"
- disabled={pendingId !== null}
- onClick={() => void resend(delivery.id)}
- type="button"
- >
- {pendingId === delivery.id ? "Sending..." : "Send again"}
- </button>
- </div>
- ) : null}
- </li>
- ))}
- </ul>
+ {error ? (
+ <p className="notice notice-danger" role="alert">
+ {error}
+ </p>
+ ) : null}
+ {deliveries === null ? (
+ error ? null : (
+ <p className="text-sm text-(--secondary)">Loading...</p>
+ )
+ ) : deliveries.length === 0 ? (
+ <p className="text-sm text-(--secondary)">Nothing sent yet.</p>
+ ) : (
+ <DeliveryList
+ deliveries={deliveries}
+ onResend={(id) => void resend(id)}
+ pendingId={pendingId}
+ />
+ )}
</div>
);
}
+function DeliveryList({
+ deliveries,
+ onResend,
+ pendingId,
+}: {
+ deliveries: WebhookDeliverySummary[];
+ onResend: (id: string) => void;
+ pendingId: string | null;
+}) {
+ return (
+ <ul aria-label="Recent deliveries" className="grid gap-2">
+ {deliveries.map((delivery) => (
+ <li
+ className="grid gap-1 rounded-lg border border-(--border) px-3 py-2 text-sm"
+ key={delivery.id}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-mono text-(--fg)">{delivery.eventType}</span>
+ <span className={`pill ${deliveryTone(delivery.status)}`}>
+ {delivery.status === "pending" && delivery.attempts > 0
+ ? "Retrying"
+ : delivery.status === "pending"
+ ? "Waiting"
+ : delivery.status === "delivered"
+ ? "Delivered"
+ : "Failed"}
+ </span>
+ <span className="text-(--secondary)">
+ {formatTime(delivery.createdAt)}
+ {delivery.attempts > 1
+ ? `, ${String(delivery.attempts)} tries`
+ : ""}
+ {delivery.lastStatusCode !== null
+ ? `, answered ${String(delivery.lastStatusCode)}`
+ : ""}
+ </span>
+ </div>
+ {delivery.status !== "delivered" && delivery.lastError ? (
+ <p className="break-all text-(--secondary)">
+ {delivery.lastError}
+ {delivery.status === "pending" && delivery.nextAttemptAt
+ ? ` Next try around ${formatTime(delivery.nextAttemptAt) ?? ""}.`
+ : ""}
+ </p>
+ ) : null}
+ {delivery.status !== "pending" &&
+ delivery.eventType !== "webhook.test" ? (
+ <div>
+ <button
+ className="btn-quiet"
+ disabled={pendingId !== null}
+ onClick={() => onResend(delivery.id)}
+ type="button"
+ >
+ {pendingId === delivery.id ? "Sending..." : "Send again"}
+ </button>
+ </div>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
export function WebhooksPanel() {
const [endpoints, setEndpoints] = useState<WebhookEndpoint[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -241,6 +258,9 @@ export function WebhooksPanel() {
const [removingId, setRemovingId] = useState<string | null>(null);
const [openLogId, setOpenLogId] = useState<string | null>(null);
const [revision, setRevision] = useState(0);
+ // When the list was last read, for telling which endpoints are still in
+ // a secret switch-over.
+ const [now, setNow] = useState(0);
useEffect(() => {
let cancelled = false;
@@ -258,6 +278,7 @@ export function WebhooksPanel() {
return;
}
+ setNow(Math.floor(Date.now() / 1000));
setEndpoints(payload.endpoints);
} catch {
if (!cancelled) {
@@ -277,10 +298,15 @@ export function WebhooksPanel() {
}
async function createEndpoint() {
+ // A secret on screen stays until Done, so it is never lost to a second
+ // endpoint, made or not.
+ if (newSecret) {
+ return;
+ }
+
setIsCreating(true);
setError(null);
setNotice(null);
- setNewSecret(null);
try {
const { ok, payload } = await call("/api/admin/webhooks", {
@@ -308,6 +334,11 @@ export function WebhooksPanel() {
endpoint: WebhookEndpoint,
action: "delete" | "disable" | "enable" | "rotate" | "test",
) {
+ // The same for a new secret: it would take the place of one on screen.
+ if (action === "rotate" && newSecret) {
+ return;
+ }
+
setPendingId(endpoint.id);
setError(null);
setNotice(null);
@@ -459,7 +490,10 @@ export function WebhooksPanel() {
<button
className="btn-quiet min-h-12 px-5 text-sm"
disabled={
- isCreating || url.trim().length === 0 || events.length === 0
+ isCreating ||
+ newSecret !== null ||
+ url.trim().length === 0 ||
+ events.length === 0
}
onClick={() => void createEndpoint()}
type="button"
@@ -477,7 +511,8 @@ export function WebhooksPanel() {
>
<p className="text-sm font-semibold text-(--fg)">
Copy the signing secret for {newSecret.url} now. It is not shown
- again.
+ again. Press Done once it is copied, before adding another endpoint
+ or making another secret.
</p>
<code className="block overflow-x-auto rounded-lg border border-(--border) bg-(--paper) px-3 py-2 font-mono text-sm break-all text-(--fg)">
{newSecret.secret}
@@ -538,8 +573,9 @@ export function WebhooksPanel() {
{endpoint.events.length === webhookEventTypes.length
? "All events."
: `${endpoint.events.map((type) => EVENT_LABELS[type]).join(", ")}.`}
- {endpoint.previousSecretExpiresAt
- ? ` The old secret also signs until ${formatTime(endpoint.previousSecretExpiresAt) ?? ""}.`
+ {endpoint.previousSecretExpiresAt &&
+ endpoint.previousSecretExpiresAt > now
+ ? ` The old secret also signs until ${formatTime(endpoint.previousSecretExpiresAt) ?? ""}, and another new secret can be made after that.`
: ""}
</p>
<div className="flex flex-wrap items-center gap-2">
@@ -590,7 +626,12 @@ export function WebhooksPanel() {
</button>
<button
className="btn-quiet"
- disabled={pendingId !== null}
+ disabled={
+ pendingId !== null ||
+ newSecret !== null ||
+ (endpoint.previousSecretExpiresAt !== null &&
+ endpoint.previousSecretExpiresAt > now)
+ }
onClick={() => void act(endpoint, "rotate")}
type="button"
>
diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts
index af2d22b..4b73f29 100644
--- a/src/lib/api/openapi.ts
+++ b/src/lib/api/openapi.ts
@@ -310,6 +310,45 @@ export function buildOpenApiDocument(serverUrl: string) {
required: ["uploadId", "url", "method", "headers", "expiresAt"],
type: "object",
},
+ WebhookDelivery: {
+ properties: {
+ attempts: { type: "integer" },
+ createdAt: { format: "date-time", type: "string" },
+ deliveredAt: isoTime,
+ endpointId: { type: "string" },
+ envelopeId: { type: ["string", "null"] },
+ id: {
+ description: "The webhook-id header it was sent with.",
+ type: "string",
+ },
+ lastStatusCode: { type: ["integer", "null"] },
+ object: { const: "webhook_delivery", type: "string" },
+ payload: {
+ description:
+ "The JSON body it was sent with, or null before its first try.",
+ type: ["object", "null"],
+ },
+ status: {
+ enum: ["delivered", "failed", "pending"],
+ type: "string",
+ },
+ type: { enum: [...webhookEventTypes], type: "string" },
+ },
+ required: [
+ "object",
+ "id",
+ "type",
+ "status",
+ "attempts",
+ "endpointId",
+ "envelopeId",
+ "lastStatusCode",
+ "payload",
+ "createdAt",
+ "deliveredAt",
+ ],
+ type: "object",
+ },
},
securitySchemes: {
apiKey: {
@@ -658,7 +697,8 @@ export function buildOpenApiDocument(serverUrl: string) {
get: {
parameters: [
{
- description: "Only deliveries made at or after this time.",
+ description:
+ "Only deliveries made at or after this time. Times are kept to the second, so a time with a fraction counts from the start of its second.",
in: "query",
name: "since",
schema: { format: "date-time", type: "string" },
@@ -690,6 +730,22 @@ export function buildOpenApiDocument(serverUrl: string) {
],
responses: {
"200": {
+ content: {
+ "application/json": {
+ schema: {
+ properties: {
+ data: {
+ items: { $ref: "#/components/schemas/WebhookDelivery" },
+ type: "array",
+ },
+ nextCursor: { type: ["string", "null"] },
+ object: { const: "list", type: "string" },
+ },
+ required: ["object", "data", "nextCursor"],
+ type: "object",
+ },
+ },
+ },
description:
"Webhook deliveries to every endpoint, newest first, each with the payload it carried (null until its first try).",
},
diff --git a/src/lib/webhooks/admin-route.ts b/src/lib/webhooks/admin-route.ts
index cd4c8cb..b8b25eb 100644
--- a/src/lib/webhooks/admin-route.ts
+++ b/src/lib/webhooks/admin-route.ts
@@ -65,13 +65,25 @@ export async function handleWebhookAdmin(
}
}
-/** The JSON object in a request body, or an empty one. */
+/**
+ * The JSON object in a request body, or null when the body is not one
+ * (missing, cut off, or a list), so a route can refuse it instead of
+ * treating it as a request to change nothing.
+ */
export async function readJsonObject(
request: Request,
-): Promise<Record<string, unknown>> {
+): Promise<Record<string, unknown> | null> {
const parsed: unknown = await request.json().catch(() => null);
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
- : {};
+ : null;
+}
+
+/** The answer to a body readJsonObject could not read. */
+export function notAJsonObject(): Response {
+ return NextResponse.json(
+ { error: "Send the request as a JSON object." },
+ { headers: noStore, status: 400 },
+ );
}
diff --git a/src/lib/webhooks/deliver.ts b/src/lib/webhooks/deliver.ts
index ae7976f..2d2af80 100644
--- a/src/lib/webhooks/deliver.ts
+++ b/src/lib/webhooks/deliver.ts
@@ -137,6 +137,42 @@ export async function buildWebhookPayload(
};
}
+/** What sendOne needs of a delivery `c` and its endpoint `e`. */
+const CLAIMED_COLUMNS = `
+ c.id,
+ c.event_type AS "eventType",
+ c.envelope_id AS "envelopeId",
+ c.audit_event_id AS "auditEventId",
+ 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",
+ e.url,
+ e.secret_encrypted AS "secretEncrypted",
+ e.previous_secret_encrypted AS "previousSecretEncrypted",
+ e.previous_secret_expires_at AS "previousSecretExpiresAt"
+`;
+
+/**
+ * Marks failed a delivery whose last try was claimed but never finished
+ * (its function stopped mid-send), instead of sending it a ninth time.
+ */
+async function failAbandonedLastTries(database: DbExecutor, now: number) {
+ await database.query(
+ `
+ UPDATE webhook_deliveries
+ SET status = 'failed', next_attempt_at = NULL, locked_until = NULL,
+ last_error = 'The last try did not finish.', updated_at = $1
+ WHERE status = 'pending' AND attempts >= $2
+ AND (locked_until IS NULL OR locked_until <= $1)
+ `,
+ [now, MAX_ATTEMPTS],
+ );
+}
+
/** Takes up to `limit` due deliveries for this drain alone. */
async function claimDueDeliveries(
database: DbExecutor,
@@ -154,6 +190,7 @@ async function claimDueDeliveries(
WHERE d.status = 'pending'
AND d.next_attempt_at <= $1
AND (d.locked_until IS NULL OR d.locked_until <= $1)
+ AND d.attempts < $5
AND e.enabled
AND ($4::text IS NULL OR d.id = $4)
ORDER BY d.next_attempt_at, d.id
@@ -167,28 +204,13 @@ async function claimDueDeliveries(
WHERE d.id = due.id
RETURNING d.*
)
- SELECT
- c.id,
- c.event_type AS "eventType",
- c.envelope_id AS "envelopeId",
- c.audit_event_id AS "auditEventId",
- 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",
- e.url,
- e.secret_encrypted AS "secretEncrypted",
- e.previous_secret_encrypted AS "previousSecretEncrypted",
- e.previous_secret_expires_at AS "previousSecretExpiresAt"
+ SELECT ${CLAIMED_COLUMNS}
FROM claimed c
JOIN webhook_endpoints e ON e.id = c.endpoint_id
LEFT JOIN audit_events a ON a.id = c.audit_event_id
ORDER BY c.next_attempt_at, c.id
`,
- [now, limit, LEASE_SECONDS, onlyId ?? null],
+ [now, limit, LEASE_SECONDS, onlyId ?? null, MAX_ATTEMPTS],
);
}
@@ -413,6 +435,8 @@ export async function drainWebhookDeliveries(
skipped: 0,
};
+ await failAbandonedLastTries(database, nowInSeconds());
+
for (let batch = 0; batch < (options.maxBatches ?? 4); batch += 1) {
const claimed = await claimDueDeliveries(
database,
@@ -451,7 +475,11 @@ export async function drainWebhookDeliveries(
return summary;
}
-/** Whether anything is waiting, so callers can skip a drain cheaply. */
+/**
+ * Whether anything is waiting that a drain would send, so callers can skip
+ * one cheaply. The same tests as the claim: an endpoint that is off has
+ * nothing due.
+ */
export async function hasDueWebhookDeliveries(
database: DbExecutor = getDb(),
now: number = nowInSeconds(),
@@ -461,12 +489,16 @@ export async function hasDueWebhookDeliveries(
database,
`
SELECT EXISTS (
- SELECT 1 FROM webhook_deliveries
- WHERE status = 'pending' AND next_attempt_at <= $1
- AND (locked_until IS NULL OR locked_until <= $1)
+ SELECT 1
+ FROM webhook_deliveries d
+ JOIN webhook_endpoints e ON e.id = d.endpoint_id
+ WHERE d.status = 'pending' AND d.next_attempt_at <= $1
+ AND (d.locked_until IS NULL OR d.locked_until <= $1)
+ AND d.attempts < $2
+ AND e.enabled
) AS due
`,
- [now],
+ [now, MAX_ATTEMPTS],
);
return row?.due ?? false;
@@ -529,29 +561,46 @@ export async function sendTestWebhook(
type: WEBHOOK_TEST_EVENT,
};
- await database.query(
+ // Made already held by this request, so no other drain can take it
+ // and the answer read below is this try's. A test is tried once: it is
+ // made as its own last try.
+ const reserved = await queryOne<ClaimedDelivery>(
+ database,
`
- INSERT INTO webhook_deliveries (
- id, endpoint_id, event_type, payload, status, attempts,
- next_attempt_at, created_at, updated_at
- ) VALUES ($1, $2, $3, $4, 'pending', $5, $6, $6, $6)
+ WITH inserted AS (
+ INSERT INTO webhook_deliveries (
+ id, endpoint_id, event_type, payload, status, attempts,
+ next_attempt_at, locked_until, created_at, updated_at
+ )
+ SELECT $1::text, id, $3::text, $4::text, 'pending', $5::integer,
+ $6::bigint, $6::bigint + $7::bigint, $6::bigint, $6::bigint
+ FROM webhook_endpoints
+ WHERE id = $2::text AND enabled
+ RETURNING *
+ )
+ SELECT ${CLAIMED_COLUMNS}
+ FROM inserted c
+ JOIN webhook_endpoints e ON e.id = c.endpoint_id
+ LEFT JOIN audit_events a ON a.id = c.audit_event_id
`,
- // A test is tried once: it starts as if it were on its last try.
[
id,
endpointId,
WEBHOOK_TEST_EVENT,
JSON.stringify(payload),
- MAX_ATTEMPTS - 1,
+ MAX_ATTEMPTS,
now,
+ LEASE_SECONDS,
],
);
- await drainWebhookDeliveries({
- database,
- env: options.env,
- maxBatches: 1,
- onlyId: id,
- });
+
+ if (reserved) {
+ await sendOne(database, reserved, options.env ?? process.env).catch(
+ (error: unknown) => {
+ console.error(`[webhooks] Sending test delivery ${id} failed:`, error);
+ },
+ );
+ }
const row = await queryOne<{
id: string;
diff --git a/src/lib/webhooks/endpoints.ts b/src/lib/webhooks/endpoints.ts
index 5999f5a..ff8abd8 100644
--- a/src/lib/webhooks/endpoints.ts
+++ b/src/lib/webhooks/endpoints.ts
@@ -298,7 +298,10 @@ export async function updateWebhookEndpoint(
/**
* Makes a new secret. The old one keeps signing for a day as well, so a
- * receiver can switch without dropping deliveries.
+ * receiver can switch without dropping deliveries. Refused while an
+ * earlier switch-over is still running: a second new secret would drop
+ * the old one before its day was up, and receivers still on it would
+ * start refusing deliveries.
*/
export async function rotateWebhookSecret(
actor: WebhookActor,
@@ -321,6 +324,8 @@ export async function rotateWebhookSecret(
secret_encrypted = $3,
updated_at = $4
WHERE id = $1
+ AND (previous_secret_expires_at IS NULL
+ OR previous_secret_expires_at <= $4)
RETURNING ${ENDPOINT_COLUMNS}
`,
[
@@ -332,7 +337,25 @@ export async function rotateWebhookSecret(
);
if (!endpoint) {
- throw new WebhookEndpointError("That endpoint does not exist.", 404);
+ // Two rotations at once queue on the row, and the second then sees
+ // the first one's switch-over here.
+ const existing = await queryOne<{ previousSecretExpiresAt: number }>(
+ tx,
+ `
+ SELECT previous_secret_expires_at AS "previousSecretExpiresAt"
+ FROM webhook_endpoints WHERE id = $1
+ `,
+ [id],
+ );
+
+ if (!existing) {
+ throw new WebhookEndpointError("That endpoint does not exist.", 404);
+ }
+
+ throw new WebhookEndpointError(
+ `This endpoint's old secret still signs until ${new Date(existing.previousSecretExpiresAt * 1000).toISOString()}, so receivers can switch. Make another new secret after that, or remove the endpoint and add it again to replace its secret now.`,
+ 409,
+ );
}
await recordSystemAuditEvent(
diff --git a/src/lib/webhooks/log.ts b/src/lib/webhooks/log.ts
index d9f29a5..5e94056 100644
--- a/src/lib/webhooks/log.ts
+++ b/src/lib/webhooks/log.ts
@@ -62,6 +62,7 @@ export async function listEndpointDeliveries(
/**
* Puts a delivery back in line to be sent now, with a full set of tries.
+ * What its last try got is cleared, so it no longer reads as delivered.
* False when there is no such delivery or it is being sent this moment.
*/
export async function resendWebhookDelivery(
@@ -73,7 +74,8 @@ export async function resendWebhookDelivery(
`
UPDATE webhook_deliveries
SET status = 'pending', attempts = 0, next_attempt_at = $2,
- locked_until = NULL, updated_at = $2
+ locked_until = NULL, delivered_at = NULL, last_status_code = NULL,
+ last_error = NULL, updated_at = $2
WHERE id = $1 AND (locked_until IS NULL OR locked_until <= $2)
`,
[id, now],
@@ -188,7 +190,11 @@ export async function listApiWebhookDeliveries(
};
}
-/** For the daily cleanup. */
+/**
+ * For the daily cleanup. A delivered one goes 30 days after it was
+ * delivered, any other 90 days after it last changed, so one put back in
+ * line with "Send again" keeps its retries however old its event is.
+ */
export async function deleteOldWebhookDeliveries(
database: DbExecutor = getDb(),
now: number = Math.floor(Date.now() / 1000),
@@ -196,8 +202,9 @@ export async function deleteOldWebhookDeliveries(
const result = await database.query(
`
DELETE FROM webhook_deliveries
- WHERE (status = 'delivered' AND created_at <= $1)
- OR (status <> 'delivered' AND created_at <= $2)
+ WHERE (status = 'delivered'
+ AND COALESCE(delivered_at, created_at) <= $1)
+ OR (status <> 'delivered' AND updated_at <= $2)
`,
[now - DELIVERED_RETENTION_SECONDS, now - FAILED_RETENTION_SECONDS],
);
diff --git a/src/lib/webhooks/webhooks.dbtest.ts b/src/lib/webhooks/webhooks.dbtest.ts
index 3bab85c..4227212 100644
--- a/src/lib/webhooks/webhooks.dbtest.ts
+++ b/src/lib/webhooks/webhooks.dbtest.ts
@@ -23,6 +23,7 @@ import { issueSigningLink } from "../services/signing-links.ts";
import { getSigningPayloadForToken } from "../signing.ts";
import {
drainWebhookDeliveries,
+ hasDueWebhookDeliveries,
MAX_ATTEMPTS,
sendTestWebhook,
} from "./deliver.ts";
@@ -357,6 +358,7 @@ test("an endpoint removed while an event is recorded is skipped, and the change
const { endpoint } = await addEndpoint(admin, ["envelope.voided"]);
const envelope = await createEnvelope(admin);
const remover = await database.connect();
+ let recorded: Promise<unknown> | undefined;
try {
// An administrator removes the endpoint, not yet committed, just as
@@ -366,7 +368,7 @@ test("an endpoint removed while an event is recorded is skipped, and the change
endpoint.id,
]);
- const recorded = recordAuditEvent(
+ recorded = recordAuditEvent(
{
actorType: "sender",
envelopeId: envelope.id,
@@ -375,16 +377,23 @@ test("an endpoint removed while an event is recorded is skipped, and the change
},
database,
);
+ // Handled at once, so a failure before it waits is reported below
+ // instead of as an unhandled rejection.
+ recorded.catch(() => undefined);
await waitUntilBlockedBy(database, remover);
await remover.query("commit");
-
- // The change goes through; before, it failed on the foreign key.
- await recorded;
} finally {
+ // A no-op after the commit; otherwise the removal is let go, so the
+ // event can finish and the connection goes back clean.
+ await remover.query("rollback").catch(() => undefined);
+ await recorded?.catch(() => undefined);
remover.release();
}
+ // The change goes through; before, it failed on the foreign key.
+ await recorded;
+
assert.equal((await deliveriesFor(endpoint.id)).length, 0);
const voided = await database.query(
@@ -484,6 +493,67 @@ test("a failed try is retried later with the same payload, then given up", async
[row] = await deliveriesFor(endpoint.id);
assert.equal(row!.status, "delivered");
assert.equal(row!.attempts, 1);
+
+ // Sent again once delivered, it no longer reads as delivered until it is.
+ assert.ok(await resendWebhookDelivery(row!.id, database));
+
+ const reset = await database.query(
+ `
+ select status, delivered_at as "deliveredAt",
+ last_status_code as "lastStatusCode"
+ from webhook_deliveries where id = $1
+ `,
+ [row!.id],
+ );
+
+ assert.deepEqual(reset.rows[0], {
+ deliveredAt: null,
+ lastStatusCode: null,
+ status: "pending",
+ });
+});
+
+test("a last try that never finished is marked failed, not sent again", async () => {
+ const admin = await createAdmin();
+ const { endpoint } = await addEndpoint(admin);
+
+ await createEnvelope(admin);
+
+ const [row] = await deliveriesFor(endpoint.id);
+
+ // As if a drain claimed the last try and its function then stopped.
+ await database.query(
+ `
+ update webhook_deliveries
+ set attempts = $2, next_attempt_at = 0, locked_until = $3
+ where id = $1
+ `,
+ [row!.id, MAX_ATTEMPTS, Math.floor(Date.now() / 1000) - 1],
+ );
+ assert.equal(await hasDueWebhookDeliveries(database), false);
+ await drainWebhookDeliveries({ database, env });
+
+ const [after] = await deliveriesFor(endpoint.id);
+
+ assert.equal(received.length, 0);
+ assert.equal(after!.status, "failed");
+ assert.match(after!.lastError ?? "", /did not finish/);
+});
+
+test("deliveries waiting for an endpoint that is off are not due", async () => {
+ const admin = await createAdmin();
+ const { endpoint } = await addEndpoint(admin);
+
+ await createEnvelope(admin);
+ assert.equal(await hasDueWebhookDeliveries(database), true);
+
+ await updateWebhookEndpoint(
+ admin,
+ endpoint.id,
+ { enabled: false },
+ { database, env },
+ );
+ assert.equal(await hasDueWebhookDeliveries(database), false);
});
test("two drains at once never send the same delivery twice", async () => {
@@ -609,6 +679,48 @@ test("after a rotation both secrets sign, and an unreadable secret says so", asy
);
});
+test("a second new secret waits until the old one's day is over", async () => {
+ const admin = await createAdmin();
+ const { endpoint, secret: first } = await addEndpoint(admin);
+
+ await rotateWebhookSecret(admin, endpoint.id, { database, env });
+ await assert.rejects(
+ rotateWebhookSecret(admin, endpoint.id, { database, env }),
+ (error: unknown) =>
+ error instanceof WebhookEndpointError &&
+ error.statusCode === 409 &&
+ /old secret still signs until/.test(error.message),
+ );
+
+ // The secret from before the switch-over still signs.
+ await createEnvelope(admin);
+ await drainWebhookDeliveries({ database, env });
+
+ const [delivery] = received;
+
+ assert.ok(
+ verifyWebhook(first, {
+ body: delivery!.body,
+ id: delivery!.headers["webhook-id"] as string,
+ signatureHeader: delivery!.headers["webhook-signature"] as string,
+ timestamp: Number(delivery!.headers["webhook-timestamp"]),
+ }),
+ );
+
+ // Once that day is over, another new secret can be made.
+ await database.query(
+ `update webhook_endpoints set previous_secret_expires_at = $2 where id = $1`,
+ [endpoint.id, Math.floor(Date.now() / 1000) - 1],
+ );
+
+ const again = await rotateWebhookSecret(admin, endpoint.id, {
+ database,
+ env,
+ });
+
+ assert.ok(again.secret.startsWith("whsec_"));
+});
+
test("a test event is sent at once, tried once, and left out of the API list", async () => {
const admin = await createAdmin();
const { endpoint } = await addEndpoint(admin);
@@ -697,16 +809,30 @@ test("old deliveries are cleared, failed ones kept longer, and endpoints removed
const day = 24 * 60 * 60;
await database.query(
- `update webhook_deliveries set status = 'delivered', created_at = $2 where id = $1`,
+ `
+ update webhook_deliveries
+ set status = 'delivered', created_at = $2, delivered_at = $2, updated_at = $2
+ where id = $1
+ `,
[delivered!.id, now - 31 * day],
);
await database.query(
- `update webhook_deliveries set status = 'failed', created_at = $2 where id = $1`,
+ `
+ update webhook_deliveries
+ set status = 'failed', created_at = $2, updated_at = $2
+ where id = $1
+ `,
[failed!.id, now - 31 * day],
);
assert.equal(await deleteOldWebhookDeliveries(database, now), 1);
assert.equal((await deliveriesFor(endpoint.id)).length, 1);
- assert.equal(await deleteOldWebhookDeliveries(database, now + 60 * day), 1);
+ assert.equal(await deleteOldWebhookDeliveries(database, now + 58 * day), 0);
+
+ // Sent again, it keeps its retries however old its event is: the 90 days
+ // count from its last change.
+ assert.ok(await resendWebhookDelivery(failed!.id, database, now));
+ assert.equal(await deleteOldWebhookDeliveries(database, now + 60 * day), 0);
+ assert.equal(await deleteOldWebhookDeliveries(database, now + 91 * day), 1);
await createEnvelope(admin);
await deleteWebhookEndpoint(admin, endpoint.id, database);