Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Cache revocation answers only while current, and stop lookups out of time
Claude508add92ac4a
diff --git a/src/lib/services/pdf-ltv.test.ts b/src/lib/services/pdf-ltv.test.tsindex d6698cc..9832404 100644--- a/src/lib/services/pdf-ltv.test.ts+++ b/src/lib/services/pdf-ltv.test.ts@@ -410,6 +410,8 @@ test("a self-made seal without a timestamp is left as it is", async () => {});test("a certificate authority that does not answer is given up on in time", async () => {+ const signals: (AbortSignal | undefined)[] = [];+await withPki(async (pki) => {const sealed = await sealedWith(pki, { timestamp: false });const started = Date.now();@@ -417,12 +419,86 @@ test("a certificate authority that does not answer is given up on in time", asynfindSignatures(sealed).map((signature) => signature.contents),{budget: createLookupBudget(300),- fetch: () => new Promise<Buffer>(() => {}),+ fetch: (_url, _request, options) => {+ signals.push(options?.signal);+ return new Promise<Buffer>(() => {});+ },},);assert.ok(Date.now() - started < 3_000);assert.match(data.problems.join(" "), /Ran out of time/);+ // Each lookup still under way was told to stop.+ assert.ok(signals.length > 0);+ assert.ok(signals.every((signal) => signal?.aborted));+ });+});++test("a lookup told to stop closes its connection", async () => {+ let closed = false;+ const server = createServer((request) => {+ // Never answers.+ request.on("close", () => {+ closed = true;+ });+ });++ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));++ try {+ const address = server.address();+ const port = typeof address === "object" && address ? address.port : 0;+ const controller = new AbortController();+ const lookup = createValidationFetch({+ allowPrivateAddresses: true,+ timeoutMs: 10_000,+ })(`http://127.0.0.1:${String(port)}/ocsp`, undefined, {+ signal: controller.signal,+ });++ setTimeout(() => controller.abort(), 100);++ const started = Date.now();++ await assert.rejects(lookup);+ assert.ok(Date.now() - started < 2_000);++ for (let wait = 0; wait < 20 && !closed; wait += 1) {+ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ assert.equal(closed, true);+ } finally {+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});++test("an answer without a next update is kept only while it is current", async () => {+ await withPki(async (pki) => {+ // A day old, less a moment: still current, but not for long.+ pki.state.ocspNextUpdate = false;+ pki.state.staleByMs = 24 * 60 * 60 * 1000 - 1500;++ const signatures = findSignatures(+ await sealedWith(pki, { timestamp: false }),+ ).map((signature) => signature.contents);+ const first = await collectValidationData(signatures, {+ fetch: localFetch,+ });+ const asked = pki.state.ocspRequests;++ assert.equal(first.ocsps.length, 1);+ await new Promise((resolve) => setTimeout(resolve, 1700));++ // The cached answer is past its age now, so the responder is asked+ // again instead.+ const second = await collectValidationData(signatures, {+ fetch: localFetch,+ });++ assert.equal(pki.state.ocspRequests, asked + 1);+ assert.equal(second.ocsps.length, 1);});});diff --git a/src/lib/services/pdf-ltv.ts b/src/lib/services/pdf-ltv.tsindex c621205..c22474a 100644--- a/src/lib/services/pdf-ltv.ts+++ b/src/lib/services/pdf-ltv.ts@@ -333,6 +333,8 @@ function cmsCertificates(cms: Uint8Array, depth = 0): Buffer[] {export type ValidationFetch = (url: string,request?: { body: Buffer; contentType: string },+ /** Aborted when the document's lookup time runs out. */+ options?: { signal?: AbortSignal },) => Promise<Buffer>;function isPrivateAddress(host: string): boolean {@@ -454,8 +456,14 @@ function fetchOnce({lookup,maxBytes,+ signal,timeoutMs,- }: { lookup: LookupFunction; maxBytes: number; timeoutMs: number },+ }: {+ lookup: LookupFunction;+ maxBytes: number;+ signal?: AbortSignal;+ timeoutMs: number;+ },): Promise<FetchedResponse> {return new Promise((resolve, reject) => {const send = target.protocol === "https:" ? httpsRequest : httpRequest;@@ -472,7 +480,9 @@ function fetchOnce(: {},lookup,method: request ? "POST" : "GET",- signal: AbortSignal.timeout(timeoutMs),+ signal: signal+ ? AbortSignal.any([AbortSignal.timeout(timeoutMs), signal])+ : AbortSignal.timeout(timeoutMs),},(response: IncomingMessage) => {const status = response.statusCode ?? 0;@@ -541,10 +551,14 @@ export function createValidationFetch({} = {}): ValidationFetch {const lookup = guardedLookup(resolve, allowPrivateAddresses);- return async (url, request) => {+ return async (url, request, { signal } = {}) => {let target = new URL(url);for (let hop = 0; hop < 4; hop += 1) {+ if (signal?.aborted) {+ throw new LongTermValidationError("Ran out of time for lookups.");+ }+if (target.protocol !== "http:" && target.protocol !== "https:") {throw new LongTermValidationError(`Refused to fetch ${target.protocol} URL.`,@@ -561,6 +575,7 @@ export function createValidationFetch({const response = await fetchOnce(target, request, {lookup,maxBytes,+ signal,timeoutMs,});@@ -637,10 +652,22 @@ type RevocationAnswer = {/** Certificates the answer came with, such as a delegated OCSP responder. */extraCertificates: Buffer[];kind: "crl" | "ocsp";- nextUpdate: Date | null;+ /**+ * When the answer stops being current: its next update, or without one,+ * the most its age may be.+ */+ staleAt: Date;status: "good" | "revoked";};+function staleAt(+ thisUpdate: Date,+ nextUpdate: Date | null,+ maxAgeMs: number,+): Date {+ return nextUpdate ?? new Date(thisUpdate.getTime() + maxAgeMs);+}+function hashName(oid: string): string | null {return oid === OIDS.sha1 ? "sha1" : oid === OIDS.sha256 ? "sha256" : null;}@@ -846,12 +873,11 @@ export function readOcspResponse(data: elementBytes(body, response),extraCertificates,kind: "ocsp",- nextUpdate: match.nextUpdate,+ staleAt: staleAt(match.thisUpdate, match.nextUpdate, OCSP_MAX_AGE_MS),status: match.status,};}-/** Reads a revocation list from `issuer`, and whether it lists `certificate`. *//** The CRL extensions this reader understands, critical or not. */const KNOWN_CRL_EXTENSIONS = new Set<string>([OIDS.authorityKeyIdentifier,@@ -958,6 +984,7 @@ function assertCompleteList(}}+/** Reads a revocation list from `issuer`, and whether it lists `certificate`. */export function readCrl(body: Buffer,certificate: Certificate,@@ -1019,7 +1046,7 @@ export function readCrl(data: elementBytes(body, list),extraCertificates: [],kind: "crl",- nextUpdate,+ staleAt: staleAt(thisUpdate, nextUpdate, CRL_MAX_AGE_MS),status: listed ? "revoked" : "good",};}@@ -1042,13 +1069,11 @@ function revocationLifetime(answer: RevocationAnswer | null): number {return 0;}- if (!answer.nextUpdate) {- return REVOCATION_CACHE_MS;- }-+ // Kept no longer than it stays current, so a cached answer is never+ // older than one that would be refused fresh.return Math.max(0,- Math.min(REVOCATION_CACHE_MS, answer.nextUpdate.getTime() - Date.now()),+ Math.min(REVOCATION_CACHE_MS, answer.staleAt.getTime() - Date.now()),);}@@ -1059,10 +1084,14 @@ export function createLookupBudget(budgetMs = LOOKUP_BUDGET_MS): LookupBudget {return { deadline: Date.now() + budgetMs, fetches: 0 };}-/** Runs `task`, giving up when the document's lookup time runs out. */+/**+ * Runs `task`, giving up when the document's lookup time runs out. The+ * task is told through `signal`, so a request still under way is stopped+ * instead of left running.+ */async function withinBudget<T>(budget: LookupBudget,- task: () => Promise<T>,+ task: (signal: AbortSignal) => Promise<T>,): Promise<T> {const remaining = budget.deadline - Date.now();@@ -1070,17 +1099,17 @@ async function withinBudget<T>(throw new LongTermValidationError("Ran out of time for lookups.");}+ const controller = new AbortController();let timer: NodeJS.Timeout | undefined;try {return await Promise.race([- task(),+ task(controller.signal),new Promise<never>((_, reject) => {- timer = setTimeout(- () =>- reject(new LongTermValidationError("Ran out of time for lookups.")),- remaining,- );+ timer = setTimeout(() => {+ controller.abort();+ reject(new LongTermValidationError("Ran out of time for lookups."));+ }, remaining);}),]);} finally {@@ -1120,7 +1149,9 @@ export async function collectValidationData(throw new LongTermValidationError("Too many lookups for one document.");}- return withinBudget(budget, () => fetchFrom(url, request));+ return withinBudget(budget, (signal) =>+ fetchFrom(url, request, { signal }),+ );};const addToPool = (certificate: Certificate) => {if (!pool.has(certificate.fingerprint)) {diff --git a/src/lib/services/pki-test-support.ts b/src/lib/services/pki-test-support.tsindex 8a33881..a613168 100644--- a/src/lib/services/pki-test-support.ts+++ b/src/lib/services/pki-test-support.ts@@ -181,6 +181,8 @@ export type TestPki = {revoked: Set<string>;/** How long ago the revocation answers say they were made. */staleByMs: number;+ /** False: OCSP answers come without a next update. */+ ocspNextUpdate: boolean;timestampRequests: number;};timestampUrl: string;@@ -299,6 +301,7 @@ export async function startTestPki(): Promise<TestPki> {ocspSigner: "ca",revoked: new Set(),staleByMs: 0,+ ocspNextUpdate: true,timestampRequests: 0,};let tokenSerial = 1;@@ -321,7 +324,14 @@ export async function startTestPki(): Promise<TestPki> {certId,revoked ? encode(0xa1, generalizedTime(now)) : encode(0x80),generalizedTime(now),- encode(0xa0, generalizedTime(new Date(now.getTime() + 60 * 60 * 1000))),+ ...(state.ocspNextUpdate+ ? [+ encode(+ 0xa0,+ generalizedTime(new Date(now.getTime() + 60 * 60 * 1000)),+ ),+ ]+ : []),);const signer =state.ocspSigner === "delegated"