From a245ccd4a0904db5ef510090801e18bb0844ba62 Mon Sep 17 00:00:00 2001 From: Sam Ottenhoff Date: Mon, 26 Oct 2026 10:29:56 -0400 Subject: [PATCH] feat(verification): cache public documents with bounded freshness --- .../src/badges/revocation-status.ts | 3 + .../src/credential-download.test.ts | 2 +- .../src/http/response-cache-policy.ts | 3 + .../src/routes/credential-routes.ts | 6 +- apps/api-worker/src/routes/did-routes.ts | 5 + apps/api-worker/src/routes/oid4vci-routes.ts | 3 +- .../public-document-cache.integration.test.ts | 160 ++++++++++++++++++ .../src/status-list-revocation.test.ts | 2 +- docs/SELF_HOST_DOCKER_RUNBOOK.md | 33 ++++ 9 files changed, 212 insertions(+), 5 deletions(-) create mode 100644 apps/api-worker/src/routes/public-document-cache.integration.test.ts diff --git a/apps/api-worker/src/badges/revocation-status.ts b/apps/api-worker/src/badges/revocation-status.ts index 3cd31ff6..14517a61 100644 --- a/apps/api-worker/src/badges/revocation-status.ts +++ b/apps/api-worker/src/badges/revocation-status.ts @@ -2,6 +2,8 @@ import type { JsonObject } from "@credtrail/core-domain"; import { bytesToBase64Url } from "../utils/crypto"; const BITSTRING_STATUS_LIST_CONTEXT = "https://www.w3.org/ns/credentials/status/v1"; +/** Status-list refresh interval, in milliseconds as required by the credential format. */ +export const REVOCATION_STATUS_LIST_TTL_MS = 600_000; const MINIMUM_STATUS_LIST_ENTRIES = 131_072; const MINIMUM_STATUS_LIST_BYTES = MINIMUM_STATUS_LIST_ENTRIES / 8; @@ -157,6 +159,7 @@ export const buildRevocationStatusListCredential = async ( id: `${statusListCredentialUrl}#list`, type: "BitstringStatusList", statusPurpose: "revocation", + ttl: REVOCATION_STATUS_LIST_TTL_MS, encodedList, }, }, diff --git a/apps/api-worker/src/credential-download.test.ts b/apps/api-worker/src/credential-download.test.ts index 81b3c50a..82a2370e 100644 --- a/apps/api-worker/src/credential-download.test.ts +++ b/apps/api-worker/src/credential-download.test.ts @@ -426,7 +426,7 @@ describe("GET /credentials/v1/:credentialId/jsonld", () => { const body = await response.text(); expect(response.status).toBe(200); - expect(response.headers.get("cache-control")).toBe("no-store"); + expect(response.headers.get("cache-control")).toBe("public, max-age=1800"); expect(response.headers.get("content-type")).toContain("application/vc+ld+json"); expect(response.headers.get("content-disposition")).toBeNull(); expect(response.headers.get("x-credtrail-credential-state")).toBe("active"); diff --git a/apps/api-worker/src/http/response-cache-policy.ts b/apps/api-worker/src/http/response-cache-policy.ts index a6837d9f..41245430 100644 --- a/apps/api-worker/src/http/response-cache-policy.ts +++ b/apps/api-worker/src/http/response-cache-policy.ts @@ -1,3 +1,6 @@ +/** Public issuer and credential documents may be reused for 30 minutes. */ +export const PUBLIC_DOCUMENT_CACHE_CONTROL = "public, max-age=1800"; + const hasExplicitPublicCachePolicy = (responseHeaders: Headers): boolean => { const cacheControl = responseHeaders.get("cache-control"); diff --git a/apps/api-worker/src/routes/credential-routes.ts b/apps/api-worker/src/routes/credential-routes.ts index 744945c4..7f1b758f 100644 --- a/apps/api-worker/src/routes/credential-routes.ts +++ b/apps/api-worker/src/routes/credential-routes.ts @@ -11,10 +11,12 @@ import { import { parseCredentialPathParams, parseTenantPathParams } from "@credtrail/validation"; import type { Hono } from "hono"; import type { AppBindings, AppContext, AppEnv } from "../app/types"; +import { REVOCATION_STATUS_LIST_TTL_MS } from "../badges/revocation-status"; import type { BadgePdfDocumentInput, BadgePdfDocumentResult } from "../badges/pdf"; import { loadOrRenderBadgePdf } from "../badges/pdf-cache"; import type { ResolveDatabase } from "../app/route-deps"; import { canonicalAppRequestUrl } from "../http/canonical-app-url"; +import { PUBLIC_DOCUMENT_CACHE_CONTROL } from "../http/response-cache-policy"; import type { PublicResourceNetwork } from "../http/public-resource-network"; import { VC_JSON_LD_CONTENT_TYPE } from "../http/vc-media-types"; @@ -455,7 +457,7 @@ export const registerCredentialRoutes = < model: VerificationViewModel, download: boolean, ): Response => { - c.header("Cache-Control", "no-store"); + c.header("Cache-Control", download ? "no-store" : PUBLIC_DOCUMENT_CACHE_CONTROL); c.header("Content-Type", VC_JSON_LD_CONTENT_TYPE); const checkedAt = new Date().toISOString(); const baseLifecycle = summarizeCredentialLifecycleVerification( @@ -637,7 +639,7 @@ export const registerCredentialRoutes = < ); } - c.header("Cache-Control", "no-store"); + c.header("Cache-Control", `public, max-age=${REVOCATION_STATUS_LIST_TTL_MS / 1_000}`); c.header("Content-Type", VC_JSON_LD_CONTENT_TYPE); return c.body(JSON.stringify(signedStatusListCredential.credential, null, 2)); }); diff --git a/apps/api-worker/src/routes/did-routes.ts b/apps/api-worker/src/routes/did-routes.ts index 7bc467b5..6ae4fb40 100644 --- a/apps/api-worker/src/routes/did-routes.ts +++ b/apps/api-worker/src/routes/did-routes.ts @@ -2,6 +2,7 @@ import type { JsonObject } from "@credtrail/core-domain"; import type { Hono } from "hono"; import type { TenantSigningRegistryEntry } from "@credtrail/validation"; import type { AppContext, AppEnv } from "../app/types"; +import { PUBLIC_DOCUMENT_CACHE_CONTROL } from "../http/response-cache-policy"; interface SigningKeyLike { keyId: string; @@ -67,6 +68,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => { ); } + c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL); return c.json(didDocument); }); @@ -100,6 +102,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => { ); } + c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL); return c.json(didDocument); }); @@ -117,6 +120,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => { ); } + c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL); return c.json( jwksDocumentForSigningEntry({ signingEntry, @@ -140,6 +144,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => { ); } + c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL); return c.json( jwksDocumentForSigningEntry({ signingEntry, diff --git a/apps/api-worker/src/routes/oid4vci-routes.ts b/apps/api-worker/src/routes/oid4vci-routes.ts index f28caabc..5a281fa2 100644 --- a/apps/api-worker/src/routes/oid4vci-routes.ts +++ b/apps/api-worker/src/routes/oid4vci-routes.ts @@ -14,6 +14,7 @@ import type { ResolveDatabase } from "../app/route-deps"; import type { PublicBadgeViewModel, VerificationViewModel } from "../badges/public-badge-model"; import { VC_DATA_MODEL_CONTEXT_URL } from "../credentials/verification-checks"; import { canonicalAppRequestUrl } from "../http/canonical-app-url"; +import { PUBLIC_DOCUMENT_CACHE_CONTROL } from "../http/response-cache-policy"; const PRE_AUTHORIZED_CODE_GRANT = "urn:ietf:params:oauth:grant-type:pre-authorized_code"; const OID4VCI_TOKEN_ENDPOINT_PATH = "/credentials/v1/token"; @@ -460,7 +461,7 @@ export const registerOid4vciRoutes = (input: RegisterOid4vciRoutesInput): void = }; app.get("/.well-known/openid-credential-issuer", (c) => { - c.header("Cache-Control", "no-store"); + c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL); return c.json(buildIssuerMetadata(publicRequestUrl(c))); }); diff --git a/apps/api-worker/src/routes/public-document-cache.integration.test.ts b/apps/api-worker/src/routes/public-document-cache.integration.test.ts new file mode 100644 index 00000000..0621822f --- /dev/null +++ b/apps/api-worker/src/routes/public-document-cache.integration.test.ts @@ -0,0 +1,160 @@ +import { afterEach, expect, it } from "vitest"; +import { + generateTenantDidSigningMaterial, + immutableCredentialObjectKey, + type ImmutableCredentialStore, +} from "@credtrail/core-domain"; +import { + cleanupTestResources, + createBadgeRuleIntegrationFixture, + createTestPostgresDatabase, + describeDbIntegration, + seedAssertion, +} from "../../../../packages/db/src/postgres-test-support"; +import { app } from "../app"; +import type { AppBindings } from "../app/types"; +import { decodedRevocationStatusBit } from "../badges/revocation-status"; + +const tenantIds: string[] = []; +const userIds: string[] = []; +afterEach(async () => { + if (tenantIds.length === 0) return; + await cleanupTestResources(createTestPostgresDatabase(), { tenantIds, userIds }); + tenantIds.length = 0; + userIds.length = 0; +}); + +describeDbIntegration("public verification document caching", () => { + it("caches public documents, aligns status refresh with HTTP freshness, and keeps errors and downloads private", async () => { + const fixture = await createBadgeRuleIntegrationFixture(); + tenantIds.push(fixture.tenantId); + userIds.push(fixture.userId); + const tenantId = fixture.tenantId; + const assertionId = `${tenantId}:assertion`; + const publicId = crypto.randomUUID(); + await seedAssertion(fixture.db, { + tenantId, + badgeTemplateId: fixture.badgeTemplateId, + id: assertionId, + publicId, + recipientIdentity: "learner@example.edu", + issuedAt: "2026-10-26T12:00:00.000Z", + statusListIndex: 0, + }); + const credential = { + "@context": ["https://www.w3.org/ns/credentials/v2"], + type: ["VerifiableCredential", "OpenBadgeCredential"], + id: `https://credtrail.org/credentials/v1/${encodeURIComponent(assertionId)}`, + issuer: { id: `did:web:credtrail.org:${tenantId}`, name: "Example University" }, + credentialSubject: { id: "mailto:learner@example.edu", achievement: { name: "Foundations" } }, + }; + const objects = new Map([ + [immutableCredentialObjectKey({ tenantId, assertionId }), JSON.stringify(credential)], + ]); + const store: ImmutableCredentialStore = { + head: async (key) => (objects.has(key) ? { key } : null), + get: async (key) => { + const text = objects.get(key); + return text === undefined ? null : { size: text.length, text: async () => text }; + }, + put: async (key, value) => { + if (objects.has(key)) return null; + objects.set(key, value); + return { key, etag: "test", version: "1", size: value.length, uploaded: new Date() }; + }, + delete: async (key) => { + objects.delete(key); + }, + }; + const signing = await generateTenantDidSigningMaterial({ + did: "did:web:credtrail.org", + keyId: "cache-test", + }); + const env: AppBindings = { + APP_ENV: "test", + DATABASE_URL: process.env.TEST_DATABASE_URL ?? "", + PLATFORM_DOMAIN: "credtrail.org", + PUBLIC_APP_ORIGIN: "https://credtrail.org", + BADGE_OBJECTS: store, + TENANT_SIGNING_REGISTRY_JSON: JSON.stringify({ + "did:web:credtrail.org": { + keyId: signing.keyId, + publicJwk: signing.publicJwk, + privateJwk: signing.privateJwk, + tenantId, + }, + [`did:web:credtrail.org:${tenantId}`]: { + keyId: signing.keyId, + publicJwk: signing.publicJwk, + privateJwk: signing.privateJwk, + tenantId, + }, + }), + }; + const request = async (path: string): Promise => + app.request(`https://credtrail.org${path}`, undefined, env); + for (const path of [ + "/.well-known/did.json", + "/.well-known/jwks.json", + `/${tenantId}/did.json`, + `/${tenantId}/jwks.json`, + "/.well-known/openid-credential-issuer", + `/badges/${publicId}/jsonld`, + `/credentials/v1/${encodeURIComponent(assertionId)}/jsonld`, + ]) { + const response = await request(path); + expect(response.status).toBe(200); + expect(response.headers.get("cache-control")).toBe("public, max-age=1800"); + expect(response.headers.has("set-cookie")).toBe(false); + } + for (const path of [ + `/badges/${publicId}/jsonld`, + `/credentials/v1/${encodeURIComponent(assertionId)}/jsonld`, + ]) { + expect(await (await request(path)).json()).toEqual(credential); + } + for (const suffix of ["/download", "/download.pdf"]) { + for (const base of [ + `/badges/${publicId}`, + `/credentials/v1/${encodeURIComponent(assertionId)}`, + ]) { + const response = await request(`${base}${suffix}`); + expect(response.status).toBe(200); + expect(response.headers.get("cache-control")).toBe("no-store"); + } + } + for (const path of [ + "/missing/did.json", + "/missing/jwks.json", + "/badges/missing/jsonld", + `/credentials/v1/${encodeURIComponent(`${tenantId}:missing`)}/jsonld`, + "/credentials/v1/status-lists/missing/revocation", + ]) { + const response = await request(path); + expect(response.status).toBe(404); + expect(response.headers.get("cache-control")).toBe("no-store"); + } + const statusPath = `/credentials/v1/status-lists/${tenantId}/revocation`; + const statusList = await request(statusPath); + const active = await statusList.json<{ + credentialSubject: { ttl: number; encodedList: string }; + proof: unknown; + }>(); + expect(statusList.status).toBe(200); + expect(statusList.headers.get("cache-control")).toBe("public, max-age=600"); + expect(active.credentialSubject.ttl).toBe(600_000); + expect(active.proof).toBeDefined(); + expect(await decodedRevocationStatusBit(active.credentialSubject.encodedList, 0)).toBe(false); + await fixture.db + .prepare("UPDATE assertions SET revoked_at = ? WHERE tenant_id = ? AND id = ?") + .bind("2026-10-26T13:00:00.000Z", tenantId, assertionId) + .run(); + const updated = await request(statusPath); + const revoked = await updated.json<{ + credentialSubject: { ttl: number; encodedList: string }; + }>(); + expect(updated.headers.get("cache-control")).toBe("public, max-age=600"); + expect(revoked.credentialSubject.ttl).toBe(600_000); + expect(await decodedRevocationStatusBit(revoked.credentialSubject.encodedList, 0)).toBe(true); + }); +}); diff --git a/apps/api-worker/src/status-list-revocation.test.ts b/apps/api-worker/src/status-list-revocation.test.ts index c512fb71..4390f595 100644 --- a/apps/api-worker/src/status-list-revocation.test.ts +++ b/apps/api-worker/src/status-list-revocation.test.ts @@ -207,7 +207,7 @@ describe("GET /credentials/v1/status-lists/:tenantId/revocation", () => { const encodedList = asString(credentialSubject?.encodedList); expect(response.status).toBe(200); - expect(response.headers.get("cache-control")).toBe("no-store"); + expect(response.headers.get("cache-control")).toBe("public, max-age=600"); expect(response.headers.get("content-type")).toContain("application/vc+ld+json"); expect(asString(credential.id)).toBe( "https://credtrail.test/credentials/v1/status-lists/tenant_123/revocation", diff --git a/docs/SELF_HOST_DOCKER_RUNBOOK.md b/docs/SELF_HOST_DOCKER_RUNBOOK.md index d79a4efc..47470399 100644 --- a/docs/SELF_HOST_DOCKER_RUNBOOK.md +++ b/docs/SELF_HOST_DOCKER_RUNBOOK.md @@ -374,6 +374,39 @@ Validation checks: - logical backup: `pg_dump --format=custom --file=credtrail.dump "$DATABASE_URL"` - restore: `pg_restore --clean --if-exists --dbname "$DATABASE_URL" credtrail.dump` +## Cache public verification documents + +CredTrail sends these cache policies on successful public document responses: + +| Document | Routes | `Cache-Control` | +| --- | --- | --- | +| DID documents and public keys | `/.well-known/did.json`, `/.well-known/jwks.json`, `/:tenantSlug/did.json`, `/:tenantSlug/jwks.json` | `public, max-age=1800` | +| Credential issuer metadata | `/.well-known/openid-credential-issuer` | `public, max-age=1800` | +| Credential JSON-LD | `/badges/:badgeIdentifier/jsonld`, `/credentials/v1/:credentialId/jsonld` | `public, max-age=1800` | +| Revocation status lists | `/credentials/v1/status-lists/:tenantId/revocation` | `public, max-age=600` | + +Status lists also contain `credentialSubject.ttl: 600000`, in milliseconds, to align +verifier refresh guidance with the ten-minute HTTP freshness period. This policy does +not guarantee that every verifier observes a revocation within ten minutes. Verifiers +can keep their own caches or check status less often. Lifecycle headers on cached +credential JSON-LD can also lag; use the status list to check revocation. + +In Cloudflare, create Cache Rules that make only these public document routes eligible +for caching and respect the origin `Cache-Control` header. Cloudflare does not cache +JSON or extensionless document routes by default. Match only `GET` and `HEAD` requests +for the listed paths. Do not override `no-store` or cache responses that set cookies. +Verification responses, credential downloads, wallet exchanges, authentication, and +administrator routes retain their existing cache policies. See +[Cloudflare's default cache behavior](https://developers.cloudflare.com/cache/concepts/default-cache-behavior/). + +Plan key rotation around the thirty-minute DID/JWKS freshness period. A verifier with +an older cached key document can reject credentials signed with a newly activated +key. CredTrail currently publishes only the active key in DID documents; it does not +provide a separate step to publish the next DID key before signing with it. Account +for this possible verification gap when scheduling a rotation. Keep historical public +keys available in JWKS for existing credentials. Emergency key removal also cannot +recall copies already held by caches or verifiers. + ## TLS Termination Terminate TLS at your edge/load balancer (ALB, NGINX, Traefik, ingress controller).