Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/api-worker/src/badges/revocation-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -157,6 +159,7 @@ export const buildRevocationStatusListCredential = async (
id: `${statusListCredentialUrl}#list`,
type: "BitstringStatusList",
statusPurpose: "revocation",
ttl: REVOCATION_STATUS_LIST_TTL_MS,
encodedList,
},
},
Expand Down
2 changes: 1 addition & 1 deletion apps/api-worker/src/credential-download.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
3 changes: 3 additions & 0 deletions apps/api-worker/src/http/response-cache-policy.ts
Original file line number Diff line number Diff line change
@@ -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");

Expand Down
6 changes: 4 additions & 2 deletions apps/api-worker/src/routes/credential-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -455,7 +457,7 @@ export const registerCredentialRoutes = <
model: VerificationViewModel<AssertionValue, CredentialValue>,
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(
Expand Down Expand Up @@ -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));
});
Expand Down
5 changes: 5 additions & 0 deletions apps/api-worker/src/routes/did-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -67,6 +68,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => {
);
}

c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL);
return c.json(didDocument);
});

Expand Down Expand Up @@ -100,6 +102,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => {
);
}

c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL);
return c.json(didDocument);
});

Expand All @@ -117,6 +120,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => {
);
}

c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL);
return c.json(
jwksDocumentForSigningEntry({
signingEntry,
Expand All @@ -140,6 +144,7 @@ export const registerDidRoutes = (input: RegisterDidRoutesInput): void => {
);
}

c.header("Cache-Control", PUBLIC_DOCUMENT_CACHE_CONTROL);
return c.json(
jwksDocumentForSigningEntry({
signingEntry,
Expand Down
3 changes: 2 additions & 1 deletion apps/api-worker/src/routes/oid4vci-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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)));
});

Expand Down
160 changes: 160 additions & 0 deletions apps/api-worker/src/routes/public-document-cache.integration.test.ts
Original file line number Diff line number Diff line change
@@ -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<Response> =>
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);
});
});
2 changes: 1 addition & 1 deletion apps/api-worker/src/status-list-revocation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
33 changes: 33 additions & 0 deletions docs/SELF_HOST_DOCKER_RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down