Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(pki): add OCSP responder for internal certificate authorities

Carlos Monastyrski492951db71e7
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 1548de24be..5b7dfd3ba1 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -851,6 +851,69 @@ logger.error({ sessionId, err }, "Failed to get connection details");
Note that `logger.ts` also has a `redactedKeys` list applied to structured-object fields up to depth three. It only matches by key name, so it does **not** help with a secret embedded in a `url` field.
+### Certificate revocation: CRL and OCSP
+
+Internal CAs publish revocation two ways, both unauthenticated public endpoints under
+`/api/v1/cert-manager`. CRL is `ee/services/certificate-authority-crl`; OCSP
+([RFC 6960](https://www.rfc-editor.org/rfc/rfc6960)) is `ee/services/certificate-authority-ocsp`, opt-in
+per CA via `internal_certificate_authorities.isOcspEnabled` and gated on the `pkiOcsp` plan flag.
+
+The responder answers a status question for one certificate, so the things that bite are freshness and
+what an anonymous caller can cost us.
+
+- **Serials have two forms and the database knows one.** `certificates.serialNumber` is 40 lowercase hex
+ as issued, and `createSerialNumber` clears the top bit, so ~1 in 8 begins with `0`. A CertID carries a
+ DER INTEGER that may also carry a sign byte. `parseOcspRequest` keeps `rawSerialNumber` and the
+ zero-stripped `serialNumber`, and `$resolveStatuses` queries both. Querying one silently answers
+ `unknown` for every certificate whose serial starts with a zero byte, revoked ones included.
+- **Every read on the revocation path goes to a primary, in Redis and in Postgres.** `keyStore.getItem`
+ and `ormify().find` both default to a replica. Under lag either one re-caches a pre-revocation `good`
+ for the full validity window. Use `getItemPrimary` and pass `certificateDAL.primaryNode()` as the `tx`.
+- **The cache must be reaped wherever a status can change**: revoke, delete, and toggling the flag. A miss
+ leaves a revoked certificate reading `good` for up to an hour. Only single-certID responses are cached;
+ multi-certID requests are answered but never cached, so there is one key scheme to invalidate.
+- **Concurrent misses coalesce into one signing.** `inFlightResponses` keys on the cache key plus the
+ generation counter. The generation is what stops a request arriving after a revoke from joining a flight
+ that began before it. Nonced requests are exempt for free, because their cache key is `null`.
+- **Never take the hash OID out of a CertID without checking `OCSP_HASH_NAME_BY_OID` first.** An OID is an
+ unbounded dotted-decimal string and it keys the per-CA issuer-hash memo, so an unvalidated one is
+ unbounded attacker-controlled heap.
+- **Signing is concurrency-capped globally and per CA and sheds with `tryLater`.** The per-CA tier stops
+ one tenant's traffic shedding everyone else's. Both are per process, so the rate limiter is the outer
+ bound, and it is only registered under `isProductionMode && isCloud`.
+- **Do not log per request on this path.** The endpoint is unauthenticated and the rate limiter is only
+ registered under `isProductionMode && isCloud`, so on self-hosted an anonymous caller sets the log
+ volume. Malformed and unauthorized results are counted by `ocsp.result` and logged nowhere; the
+ saturation warning is interval-guarded because shedding is by definition high volume.
+- **Protocol shape, not REST.** HTTP 200 with the error in the DER body, and a wildcard GET path carrying
+ url-encoded base64. Required by RFC 6960 appendix A.1. Both routes also carry an `errorHandler`, because
+ a body over `bodyLimit` or a missing `Content-Type` never reaches the handler and would otherwise return
+ a JSON 500 an OCSP client cannot parse.
+- **The responder never consults the plan.** Entitlement gates enabling OCSP, never answering, per
+ `CODE_QUALITY.md`. Note the managed CRL URL beside it *does* re-check at issuance; that asymmetry is
+ deliberate on the OCSP side and should not be "fixed" by copying the CRL pattern.
+- **The response metric keeps those two states on separate dimensions.** `ocsp.status` is the envelope
+ and `ocsp.cert_status` is the per-certificate answer, which only exists inside a `successful` envelope
+ and is `none` otherwise. Flattening them onto one label made `unknown` and `unauthorized` look like
+ siblings when they come from different enumerations. Both names, plus `ocsp.cache`, have to be in
+ `INFISICAL_CORE_METER_ATTRIBUTES`: an attribute missing from that allowlist is dropped by the SDK View
+ with no error, so `ocsp-metric-attributes.test.ts` pins them.
+- **The two "I can't answer" states are different, and RFC 6960 picks between them.** `unauthorized`
+ (2.3, unsigned) is "not capable of responding authoritatively": no such CA, no active CA certificate,
+ issuer hashes that belong to someone else, and OCSP switched off for that CA. `unknown` (2.2, signed,
+ inside a successful response) is "I serve this issuer but have no record of this certificate", which is
+ a serial this CA never issued. Do not answer a disabled CA with `unknown`: we hold a record for those
+ certificates, so it is a false assertion signed with the CA key, and it would make the off switch still
+ cost a signature per request. `unknown` responses carry a short validity window, since their serial is
+ caller-chosen.
+
+**`signTbs` must DER-encode ECDSA itself.** WebCrypto returns raw `r||s`; X.509 and OCSP need the DER
+`ECDSA-Sig-Value` SEQUENCE. The certificate, CSR and CRL generators convert internally, so nothing above
+them ever had to. Without it every ECDSA CA's OCSP responses fail verification in openssl, Go and Windows,
+and nothing on our side errors. `TCaSigner` (`services/certificate-authority/ca-signer.ts`) gained
+`signTbs` for this and abstracts over software, HSM and PQC CAs. PQC needs no special case beyond taking
+the signature OID from `pqcNameToOid`.
+
### Enterprise (EE) Features
Enterprise code lives in `src/ee/`:
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index c5ffb1aec0..76d04e01ea 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -16,6 +16,7 @@ import { TAuditLogServiceFactory, TCreateAuditLogDTO } from "@app/ee/services/au
import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";
import { TAuditReportServiceFactory } from "@app/ee/services/audit-report/audit-report-service";
import { TCertificateAuthorityCrlServiceFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-types";
+import { TCertificateAuthorityOcspServiceFactory } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-types";
import { TCertificateEstServiceFactory } from "@app/ee/services/certificate-est/certificate-est-service";
import { TDynamicSecretServiceFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-types";
import { TDynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-types";
@@ -375,6 +376,7 @@ declare module "fastify" {
certManagerExport: TCertManagerExportServiceFactory;
certificateAuthority: TCertificateAuthorityServiceFactory;
certificateAuthorityCrl: TCertificateAuthorityCrlServiceFactory;
+ certificateAuthorityOcsp: TCertificateAuthorityOcspServiceFactory;
certificateEst: TCertificateEstServiceFactory;
pkiAcme: TPkiAcmeServiceFactory;
pkiScep: TPkiScepServiceFactory;
diff --git a/backend/src/db/migrations/20260921143512_add-ca-ocsp.ts b/backend/src/db/migrations/20260921143512_add-ca-ocsp.ts
new file mode 100644
index 0000000000..c615541387
--- /dev/null
+++ b/backend/src/db/migrations/20260921143512_add-ca-ocsp.ts
@@ -0,0 +1,29 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasTable = await knex.schema.hasTable(TableName.InternalCertificateAuthority);
+ if (!hasTable) return;
+
+ const hasColumn = await knex.schema.hasColumn(TableName.InternalCertificateAuthority, "isOcspEnabled");
+
+ if (!hasColumn) {
+ await knex.schema.alterTable(TableName.InternalCertificateAuthority, (t) => {
+ t.boolean("isOcspEnabled").defaultTo(false).notNullable();
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasTable = await knex.schema.hasTable(TableName.InternalCertificateAuthority);
+ if (!hasTable) return;
+
+ const hasColumn = await knex.schema.hasColumn(TableName.InternalCertificateAuthority, "isOcspEnabled");
+
+ if (hasColumn) {
+ await knex.schema.alterTable(TableName.InternalCertificateAuthority, (t) => {
+ t.dropColumn("isOcspEnabled");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/internal-certificate-authorities.ts b/backend/src/db/schemas/internal-certificate-authorities.ts
index 70bd018697..d1895efdca 100644
--- a/backend/src/db/schemas/internal-certificate-authorities.ts
+++ b/backend/src/db/schemas/internal-certificate-authorities.ts
@@ -32,7 +32,8 @@ export const InternalCertificateAuthoritiesSchema = z.object({
lastRenewalMessage: z.string().nullable().optional(),
lastRenewalAt: z.date().nullable().optional(),
crlDistributionPointUrls: z.string().array().nullable().optional(),
- disableManagedCrlDistributionPointUrl: z.boolean().default(false)
+ disableManagedCrlDistributionPointUrl: z.boolean().default(false),
+ isOcspEnabled: z.boolean().default(false)
});
export type TInternalCertificateAuthorities = z.infer<typeof InternalCertificateAuthoritiesSchema>;
diff --git a/backend/src/ee/routes/v1/certificate-authority-ocsp-router.ts b/backend/src/ee/routes/v1/certificate-authority-ocsp-router.ts
new file mode 100644
index 0000000000..7cd72a09c8
--- /dev/null
+++ b/backend/src/ee/routes/v1/certificate-authority-ocsp-router.ts
@@ -0,0 +1,129 @@
+import { z } from "zod";
+
+import {
+ OCSP_MAX_REQUEST_BYTES,
+ OCSP_REQUEST_CONTENT_TYPE,
+ OCSP_RESPONSE_CONTENT_TYPE,
+ OcspResponseStatus
+} from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums";
+import { buildOcspErrorResponse } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns";
+import { RateLimitError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { recordOcspResponseMetric, TOcspStatusLabel } from "@app/lib/telemetry/metrics";
+import { ocspLimit } from "@app/server/config/rateLimiter";
+
+const decodeGetRequest = (encoded: string): Buffer => {
+ let candidate = encoded;
+ if (candidate.includes("%")) {
+ try {
+ candidate = decodeURIComponent(candidate);
+ } catch {
+ return Buffer.alloc(0);
+ }
+ }
+ return Buffer.from(candidate, "base64");
+};
+
+export const registerCaOcspRouter = async (server: FastifyZodProvider) => {
+ server.addContentTypeParser(
+ OCSP_REQUEST_CONTENT_TYPE,
+ { parseAs: "buffer", bodyLimit: OCSP_MAX_REQUEST_BYTES },
+ (_, body, done) => {
+ done(null, body);
+ }
+ );
+
+ const sendPreHandlerError = (
+ error: unknown,
+ _req: unknown,
+ res: Parameters<Parameters<typeof server.route>[0]["handler"]>[1]
+ ) => {
+ const statusCode = (error as { statusCode?: number })?.statusCode;
+ const isRateLimited = statusCode === 429 || error instanceof RateLimitError;
+ const isClientError = typeof statusCode === "number" && statusCode >= 400 && statusCode < 500;
+
+ let status = OcspResponseStatus.InternalError;
+ let statusLabel: TOcspStatusLabel = "internal_error";
+
+ if (isRateLimited) {
+ status = OcspResponseStatus.TryLater;
+ statusLabel = "try_later";
+ } else if (isClientError) {
+ status = OcspResponseStatus.MalformedRequest;
+ statusLabel = "malformed_request";
+ } else {
+ logger.error(error, "OCSP request failed before the handler ran");
+ }
+
+ recordOcspResponseMetric({ status: statusLabel, certStatus: "none", cache: "skipped" });
+ void res.header("Content-Type", OCSP_RESPONSE_CONTENT_TYPE);
+ void res.status(200).send(Buffer.from(buildOcspErrorResponse(status)));
+ };
+
+ const sendResponse = async (
+ caId: string,
+ requestDer: Buffer,
+ res: Parameters<Parameters<typeof server.route>[0]["handler"]>[1],
+ allowCaching: boolean
+ ) => {
+ void res.header("Content-Type", OCSP_RESPONSE_CONTENT_TYPE);
+
+ if (requestDer.length === 0 || requestDer.length > OCSP_MAX_REQUEST_BYTES) {
+ recordOcspResponseMetric({ status: "malformed_request", certStatus: "none", cache: "skipped" });
+ return Buffer.from(buildOcspErrorResponse(OcspResponseStatus.MalformedRequest));
+ }
+
+ try {
+ const { response, maxAgeSeconds } = await server.services.certificateAuthorityOcsp.getOcspResponse({
+ caId,
+ requestDer
+ });
+
+ if (allowCaching && maxAgeSeconds > 0) {
+ void res.header("Cache-Control", `public, max-age=${maxAgeSeconds}`);
+ }
+
+ return Buffer.from(response);
+ } catch (error) {
+ logger.error(error, `Failed to build OCSP response [caId=${caId}]`);
+ recordOcspResponseMetric({ status: "internal_error", certStatus: "none", cache: "skipped" });
+ return Buffer.from(buildOcspErrorResponse(OcspResponseStatus.InternalError));
+ }
+ };
+
+ server.route({
+ method: "POST",
+ url: "/:caId",
+ config: { rateLimit: ocspLimit },
+ schema: {
+ hide: true,
+ params: z.object({
+ caId: z.string().uuid()
+ }),
+ response: {
+ 200: z.instanceof(Buffer)
+ }
+ },
+ errorHandler: sendPreHandlerError,
+ handler: async (req, res) =>
+ sendResponse(req.params.caId, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), res, false)
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:caId/*",
+ config: { rateLimit: ocspLimit },
+ schema: {
+ hide: true,
+ params: z.object({
+ caId: z.string().uuid(),
+ "*": z.string().trim().min(1).max(OCSP_MAX_REQUEST_BYTES)
+ }),
+ response: {
+ 200: z.instanceof(Buffer)
+ }
+ },
+ errorHandler: sendPreHandlerError,
+ handler: async (req, res) => sendResponse(req.params.caId, decodeGetRequest(req.params["*"]), res, true)
+ });
+};
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index 0776e0d729..2cc8d0a103 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -9,6 +9,7 @@ import { registerAgentVaultRouters } from "./agent-vault-routers";
import { registerAssumePrivilegeRouter } from "./assume-privilege-router";
import { AUDIT_LOG_STREAM_REGISTER_ROUTER_MAP, registerAuditLogStreamRouter } from "./audit-log-stream-routers";
import { registerCaCrlRouter } from "./certificate-authority-crl-router";
+import { registerCaOcspRouter } from "./certificate-authority-ocsp-router";
import { registerDeprecatedProjectRoleRouter } from "./deprecated-project-role-router";
import { registerDeprecatedProjectRouter } from "./deprecated-project-router";
import { registerDeprecatedSecretApprovalPolicyRouter } from "./deprecated-secret-approval-policy-router";
@@ -115,6 +116,7 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
await pkiRouter.register(injectCertManagerProjectId);
await pkiRouter.register(registerCaCrlRouter, { prefix: "/crl" });
+ await pkiRouter.register(registerCaOcspRouter, { prefix: "/ocsp" });
await pkiRouter.register(registerPkiAcmeRouter, { prefix: "/acme" });
await pkiRouter.register(registerPkiDiscoveryRouter, { prefix: "/discovery-jobs" });
await pkiRouter.register(registerPkiInstallationRouter, { prefix: "/installations" });
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 4255a9f7f8..6584754247 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -2946,6 +2946,7 @@ interface CreateCa {
dn?: string;
keySource?: string;
hsmConnectorId?: string;
+ isOcspEnabled?: boolean;
};
}
@@ -2972,6 +2973,7 @@ interface UpdateCa {
name: string;
dn?: string;
status: CaStatus;
+ isOcspEnabled?: boolean;
};
}
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-coalescing.test.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-coalescing.test.ts
new file mode 100644
index 0000000000..e043436bb5
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-coalescing.test.ts
@@ -0,0 +1,226 @@
+import { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+import * as pkijs from "pkijs";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
+import { buildHsmCaSigner } from "@app/services/certificate-authority/ca-signer";
+
+import { OCSP_NONCE_OID } from "./certificate-authority-ocsp-enums";
+
+const getCaSignerMock = vi.fn();
+
+vi.mock("@app/services/certificate-authority/certificate-authority-fns", () => ({
+ getCaSigner: (...args: unknown[]) => getCaSignerMock(...args) as unknown
+}));
+
+vi.mock("@app/services/project/project-fns", () => ({
+ getProjectKmsCertificateKeyId: vi.fn().mockResolvedValue("kms-key-id")
+}));
+
+// eslint-disable-next-line import/first
+import { certificateAuthorityOcspServiceFactory } from "./certificate-authority-ocsp-service";
+
+const buildKeyStore = () => {
+ const store = new Map<string, string>();
+ return {
+ getItemPrimary: vi.fn(async (key: string) => store.get(key) ?? null),
+ setItemWithExpiry: vi.fn(async (key: string, _ttl: number, value: string) => {
+ store.set(key, value);
+ return "OK" as const;
+ }),
+ deleteItemsByKeyIn: vi.fn(async (keys: string[]) => {
+ keys.forEach((key) => store.delete(key));
+ return keys.length;
+ }),
+ incrementSeededWithExpiry: vi.fn(async (key: string, seed: number) => {
+ const next = store.has(key) ? Number(store.get(key)) + 1 : seed + 1;
+ store.set(key, String(next));
+ return next;
+ })
+ };
+};
+
+type THarness = Awaited<ReturnType<typeof buildHarness>>;
+
+let caCounter = 0;
+
+const buildHarness = async () => {
+ caCounter += 1;
+ const caId = `ca-${caCounter}`;
+ const caCertId = `ca-cert-${caCounter}`;
+
+ const keys = (await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
+ "sign",
+ "verify"
+ ])) as CryptoKeyPair;
+
+ const caCert = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name: `CN=Coalescing Root ${caCounter}`,
+ notBefore: new Date(Date.now() - 86_400_000),
+ notAfter: new Date(Date.now() + 86_400_000),
+ signingAlgorithm: { name: "ECDSA", hash: "SHA-256" },
+ keys,
+ extensions: [new x509.BasicConstraintsExtension(true, 2, true)]
+ });
+
+ let signCount = 0;
+ let releaseGate: () => void = () => {};
+ const gate = new Promise<void>((resolve) => {
+ releaseGate = resolve;
+ });
+
+ const signer = buildHsmCaSigner({
+ caPublicKey: keys.publicKey,
+ keyAlgorithm: CertKeyAlgorithm.ECDSA_P256,
+ sign: async (tbs) => {
+ signCount += 1;
+ await gate;
+ return Buffer.from(await webcrypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, keys.privateKey, tbs));
+ }
+ });
+
+ getCaSignerMock.mockResolvedValue({ signer });
+
+ const keyStore = buildKeyStore();
+
+ const service = certificateAuthorityOcspServiceFactory({
+ certificateAuthorityDAL: {
+ findByIdWithAssociatedCa: vi.fn(async () => ({
+ id: caId,
+ projectId: "project-1",
+ internalCa: { id: "internal-1", isOcspEnabled: true, activeCaCertId: caCertId }
+ }))
+ } as never,
+ certificateAuthorityCertDAL: {
+ findById: vi.fn(async () => ({ id: caCertId, encryptedCertificate: Buffer.from("ignored") }))
+ } as never,
+ certificateAuthoritySecretDAL: { findOne: vi.fn() } as never,
+ certificateDAL: { find: vi.fn(async () => []), primaryNode: vi.fn(() => undefined) } as never,
+ projectDAL: { findById: vi.fn(), findOne: vi.fn(), updateById: vi.fn(), transaction: vi.fn() } as never,
+ kmsService: {
+ decryptWithKmsKey: vi.fn(async () => async () => Buffer.from(caCert.rawData)),
+ generateKmsKey: vi.fn()
+ } as never,
+ hsmConnectorService: { sign: vi.fn() } as never,
+ keyStore: keyStore as never
+ });
+
+ const buildRequestDer = async (nonce?: Buffer) => {
+ const request = new pkijs.OCSPRequest();
+ await request.createForCertificate(pkijs.Certificate.fromBER(caCert.rawData), {
+ hashAlgorithm: "SHA-256",
+ issuerCertificate: pkijs.Certificate.fromBER(caCert.rawData)
+ });
+
+ if (nonce) {
+ request.tbsRequest.requestExtensions = [
+ new pkijs.Extension({
+ extnID: OCSP_NONCE_OID,
+ critical: false,
+ extnValue: new (await import("asn1js")).OctetString({ valueHex: nonce }).toBER(false)
+ })
+ ];
+ }
+
+ return Buffer.from(request.toSchema(true).toBER(false));
+ };
+
+ return {
+ caId,
+ service,
+ buildRequestDer,
+ keyStore,
+ getSignCount: () => signCount,
+ releaseGate: () => releaseGate()
+ };
+};
+
+beforeAll(() => {
+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+ pkijs.setEngine("coalescing-test", new pkijs.CryptoEngine({ crypto: webcrypto as unknown as Crypto }));
+});
+
+beforeEach(() => {
+ getCaSignerMock.mockReset();
+});
+
+describe("OCSP single-flight coalescing", () => {
+ it("should sign once for concurrent identical nonce-free requests and hand every caller the same bytes", async () => {
+ const harness: THarness = await buildHarness();
+ const requestDer = await harness.buildRequestDer();
+
+ const inFlight = Array.from({ length: 6 }, () =>
+ harness.service.getOcspResponse({ caId: harness.caId, requestDer })
+ );
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 20);
+ });
+ harness.releaseGate();
+
+ const results = await Promise.all(inFlight);
+
+ expect(harness.getSignCount()).toBe(1);
+ const [first] = results;
+ for (const result of results) {
+ expect(result.response.equals(first.response)).toBe(true);
+ expect(result.maxAgeSeconds).toBeGreaterThan(0);
+ }
+ });
+
+ it("should sign per request when a nonce is present so no caller receives another caller's nonce", async () => {
+ const harness: THarness = await buildHarness();
+ const requestDers = await Promise.all([
+ harness.buildRequestDer(Buffer.alloc(16, 1)),
+ harness.buildRequestDer(Buffer.alloc(16, 2)),
+ harness.buildRequestDer(Buffer.alloc(16, 3))
+ ]);
+
+ const inFlight = requestDers.map((requestDer) =>
+ harness.service.getOcspResponse({ caId: harness.caId, requestDer })
+ );
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 20);
+ });
+ harness.releaseGate();
+
+ const results = await Promise.all(inFlight);
+
+ expect(harness.getSignCount()).toBe(3);
+ expect(results[0].response.equals(results[1].response)).toBe(false);
+ for (const result of results) {
+ expect(result.maxAgeSeconds).toBe(0);
+ }
+ });
+});
+
+describe("revocation during an in-flight signing", () => {
+ it("should not hand a request that arrived after the revocation the pre-revocation response", async () => {
+ const harness: THarness = await buildHarness();
+ const requestDer = await harness.buildRequestDer();
+
+ const leader = harness.service.getOcspResponse({ caId: harness.caId, requestDer });
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 20);
+ });
+
+ await harness.service.invalidateCachedResponse({ caId: harness.caId, serialNumber: "01" });
+
+ const follower = harness.service.getOcspResponse({ caId: harness.caId, requestDer });
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 20);
+ });
+ harness.releaseGate();
+
+ const [leaderResult, followerResult] = await Promise.all([leader, follower]);
+
+ expect(harness.getSignCount()).toBe(2);
+ expect(followerResult.response.equals(leaderResult.response)).toBe(false);
+ });
+});
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums.ts
new file mode 100644
index 0000000000..f597a037ae
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-enums.ts
@@ -0,0 +1,43 @@
+export enum OcspResponseStatus {
+ Successful = 0,
+ MalformedRequest = 1,
+ InternalError = 2,
+ TryLater = 3,
+ SigRequired = 5,
+ Unauthorized = 6
+}
+
+export enum OcspCertStatus {
+ Good = "good",
+ Revoked = "revoked",
+ Unknown = "unknown"
+}
+
+export const OCSP_BASIC_RESPONSE_OID = "1.3.6.1.5.5.7.48.1.1";
+export const OCSP_NONCE_OID = "1.3.6.1.5.5.7.48.1.2";
+
+export const OCSP_HASH_NAME_BY_OID: Record<string, string> = {
+ "1.3.14.3.2.26": "sha1",
+ "2.16.840.1.101.3.4.2.1": "sha256",
+ "2.16.840.1.101.3.4.2.2": "sha384",
+ "2.16.840.1.101.3.4.2.3": "sha512"
+};
+
+export const OCSP_REQUEST_CONTENT_TYPE = "application/ocsp-request";
+export const OCSP_RESPONSE_CONTENT_TYPE = "application/ocsp-response";
+
+export const OCSP_MAX_REQUEST_BYTES = 16 * 1024;
+export const OCSP_MAX_CERT_IDS_PER_REQUEST = 32;
+export const OCSP_MAX_SERIAL_HEX_LENGTH = 42;
+export const OCSP_MAX_NONCE_BYTES = 32;
+export const OCSP_RESPONSE_VALIDITY_SECONDS = 60 * 60;
+export const OCSP_UNKNOWN_RESPONSE_VALIDITY_SECONDS = 60;
+export const OCSP_GENERATION_TTL_SECONDS = 24 * 60 * 60;
+export const STORED_SERIAL_HEX_LENGTH = 40;
+export const OCSP_MAX_CONCURRENT_SIGNATURES = 8;
+export const OCSP_MAX_CONCURRENT_SIGNATURES_PER_CA = 4;
+export const OCSP_SIGNING_QUEUE_TIMEOUT_MS = 5_000;
+export const OCSP_SIGNING_MAX_QUEUE_DEPTH = 64;
+export const OCSP_MAX_TRACKED_CA_LIMITERS = 256;
+export const OCSP_MAX_CACHED_CA_CERTIFICATES = 256;
+export const OCSP_SATURATION_LOG_INTERVAL_MS = 10_000;
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns.test.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns.test.ts
new file mode 100644
index 0000000000..134b9e8866
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns.test.ts
@@ -0,0 +1,387 @@
+import { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+import * as asn1js from "asn1js";
+import * as pkijs from "pkijs";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { TCaSigner } from "@app/services/certificate-authority/ca-signer";
+
+import {
+ OCSP_HASH_NAME_BY_OID,
+ OCSP_NONCE_OID,
+ OcspCertStatus,
+ OcspResponseStatus
+} from "./certificate-authority-ocsp-enums";
+import {
+ buildOcspErrorResponse,
+ buildSignedOcspResponse,
+ getCaOcspIdentifiers,
+ normalizeSerialNumber,
+ parseOcspRequest,
+ resolveOcspSignatureAlgorithm
+} from "./certificate-authority-ocsp-fns";
+
+const RSA_ALG: RsaHashedKeyGenParams = {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: "SHA-256",
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: 2048
+};
+
+const LEAF_SERIAL = "4f2a9c1b33";
+
+let caKeys: CryptoKeyPair;
+let caCert: x509.X509Certificate;
+let leafCert: x509.X509Certificate;
+let signer: TCaSigner;
+
+const buildClientRequest = async (serialHex?: string, withNonce = false) => {
+ const request = new pkijs.OCSPRequest();
+ await request.createForCertificate(pkijs.Certificate.fromBER(leafCert.rawData), {
+ hashAlgorithm: "SHA-1",
+ issuerCertificate: pkijs.Certificate.fromBER(caCert.rawData)
+ });
+
+ if (serialHex) {
+ request.tbsRequest.requestList[0].reqCert.serialNumber = new asn1js.Integer({
+ valueHex: Buffer.from(serialHex, "hex")
+ });
+ }
+
+ if (withNonce) {
+ request.tbsRequest.requestExtensions = [
+ new pkijs.Extension({
+ extnID: OCSP_NONCE_OID,
+ extnValue: new asn1js.OctetString({ valueHex: Buffer.from("0102030405060708", "hex") }).toBER()
+ })
+ ];
+ }
+
+ return Buffer.from(request.toSchema(true).toBER(false));
+};
+
+beforeAll(async () => {
+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+ pkijs.setEngine("test", new pkijs.CryptoEngine({ crypto: webcrypto as unknown as Crypto }));
+
+ caKeys = (await webcrypto.subtle.generateKey(RSA_ALG, true, ["sign", "verify"])) as CryptoKeyPair;
+
+ caCert = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name: "CN=Unit Test Root CA, O=Example Inc",
+ notBefore: new Date(Date.now() - 86_400_000),
+ notAfter: new Date(Date.now() + 86_400_000),
+ signingAlgorithm: RSA_ALG,
+ keys: caKeys,
+ extensions: [new x509.BasicConstraintsExtension(true, 2, true)]
+ });
+
+ const leafKeys = (await webcrypto.subtle.generateKey(RSA_ALG, true, ["sign", "verify"])) as CryptoKeyPair;
+ leafCert = await x509.X509CertificateGenerator.create({
+ serialNumber: LEAF_SERIAL,
+ subject: "CN=api.corp.internal",
+ issuer: caCert.subject,
+ notBefore: new Date(Date.now() - 3_600_000),
+ notAfter: new Date(Date.now() + 3_600_000),
+ signingKey: caKeys.privateKey,
+ publicKey: leafKeys.publicKey,
+ signingAlgorithm: RSA_ALG
+ });
+
+ signer = {
+ caPublicKey: caKeys.publicKey,
+ signingAlgorithm: RSA_ALG,
+ createCertificate: () => {
+ throw new Error("not used");
+ },
+ createCsr: () => {
+ throw new Error("not used");
+ },
+ createCrl: () => {
+ throw new Error("not used");
+ },
+ signTbs: (tbs: Buffer) => webcrypto.subtle.sign(RSA_ALG, caKeys.privateKey, tbs)
+ } as unknown as TCaSigner;
+});
+
+describe("normalizeSerialNumber", () => {
+ it("should lowercase and strip the DER sign-padding byte", () => {
+ expect(normalizeSerialNumber("00FF2A")).toBe("ff2a");
+ });
+
+ it("should leave an already-normalized serial untouched", () => {
+ expect(normalizeSerialNumber("4f2a9c1b33")).toBe("4f2a9c1b33");
+ });
+
+ it("should not collapse a zero serial to an empty string", () => {
+ expect(normalizeSerialNumber("00")).toBe("0");
+ });
+});
+
+describe("resolveOcspSignatureAlgorithm", () => {
+ it.each([
+ ["SHA-256", "1.2.840.113549.1.1.11"],
+ ["SHA-384", "1.2.840.113549.1.1.12"],
+ ["SHA-512", "1.2.840.113549.1.1.13"]
+ ])("should map RSA with %s", (hash, oid) => {
+ expect(resolveOcspSignatureAlgorithm({ name: "RSASSA-PKCS1-v1_5", hash } as Algorithm).algorithmId).toBe(oid);
+ });
+
+ it.each([
+ ["SHA-256", "1.2.840.10045.4.3.2"],
+ ["SHA-384", "1.2.840.10045.4.3.3"]
+ ])("should map ECDSA with %s", (hash, oid) => {
+ expect(resolveOcspSignatureAlgorithm({ name: "ECDSA", hash } as Algorithm).algorithmId).toBe(oid);
+ });
+
+ it.each([
+ ["ML-DSA-44", "2.16.840.1.101.3.4.3.17"],
+ ["ML-DSA-65", "2.16.840.1.101.3.4.3.18"],
+ ["ML-DSA-87", "2.16.840.1.101.3.4.3.19"],
+ ["SLH-DSA-SHA2-128s", "2.16.840.1.101.3.4.3.20"],
+ ["SLH-DSA-SHAKE-256f", "2.16.840.1.101.3.4.3.31"]
+ ])("should map the post-quantum algorithm %s", (name, oid) => {
+ const resolved = resolveOcspSignatureAlgorithm({ name } as Algorithm);
+
+ expect(resolved.algorithmId).toBe(oid);
+ expect(resolved.algorithmParams).toBeUndefined();
+ });
+
+ it("should reject an algorithm the responder cannot sign with", () => {
+ expect(() => resolveOcspSignatureAlgorithm({ name: "Ed25519" } as Algorithm)).toThrow(/not supported/i);
+ });
+});
+
+describe("parseOcspRequest", () => {
+ it("should extract the CertID and normalize the serial", async () => {
+ const parsed = parseOcspRequest(await buildClientRequest());
+
+ expect(parsed).not.toBeNull();
+ expect(parsed?.entries).toHaveLength(1);
+ expect(parsed?.entries[0].serialNumber).toBe(LEAF_SERIAL);
+ expect(parsed?.entries[0].rawSerialNumber).toBe(LEAF_SERIAL);
+ expect(parsed?.entries[0].hashAlgorithmOid).toBe("1.3.14.3.2.26");
+ expect(parsed?.nonce).toBeUndefined();
+ });
+
+ it("should unwrap the nonce extension", async () => {
+ const parsed = parseOcspRequest(await buildClientRequest(undefined, true));
+
+ expect(parsed?.nonce?.toString("hex")).toBe("0102030405060708");
+ });
+
+ it("should return null for a body that is not an OCSP request", () => {
+ expect(parseOcspRequest(Buffer.from("definitely not asn1"))).toBeNull();
+ });
+
+ it("should return null for an empty body", () => {
+ expect(parseOcspRequest(Buffer.alloc(0))).toBeNull();
+ });
+
+ it("should keep the raw serial alongside the normalized one when it has a leading zero byte", async () => {
+ const parsed = parseOcspRequest(await buildClientRequest("0a2c3d4e"));
+
+ expect(parsed?.entries[0].rawSerialNumber).toBe("0a2c3d4e");
+ expect(parsed?.entries[0].serialNumber).toBe("a2c3d4e");
+ });
+
+ it("should reject a serial longer than RFC 5280 allows", async () => {
+ expect(parseOcspRequest(await buildClientRequest("00".repeat(64)))).toBeNull();
+ });
+
+ it("should reject a nonce longer than RFC 8954 allows", async () => {
+ const request = new pkijs.OCSPRequest();
+ await request.createForCertificate(pkijs.Certificate.fromBER(leafCert.rawData), {
+ hashAlgorithm: "SHA-1",
+ issuerCertificate: pkijs.Certificate.fromBER(caCert.rawData)
+ });
+ request.tbsRequest.requestExtensions = [
+ new pkijs.Extension({
+ extnID: OCSP_NONCE_OID,
+ extnValue: new asn1js.OctetString({ valueHex: Buffer.alloc(33, 7) }).toBER()
+ })
+ ];
+
+ expect(parseOcspRequest(Buffer.from(request.toSchema(true).toBER(false)))).toBeNull();
+ });
+});
+
+describe("getCaOcspIdentifiers", () => {
+ it("should derive hashes that match what a client computes", async () => {
+ const parsed = parseOcspRequest(await buildClientRequest());
+ const identifiers = getCaOcspIdentifiers(caCert, "1.3.14.3.2.26");
+
+ expect(identifiers?.issuerNameHash.equals(parsed!.entries[0].issuerNameHash)).toBe(true);
+ expect(identifiers?.issuerKeyHash.equals(parsed!.entries[0].issuerKeyHash)).toBe(true);
+ });
+
+ it("should return null for a hash algorithm we do not support", () => {
+ expect(getCaOcspIdentifiers(caCert, "1.2.3.4.5")).toBeNull();
+ });
+});
+
+describe("buildOcspErrorResponse", () => {
+ it.each([
+ [OcspResponseStatus.MalformedRequest, 1],
+ [OcspResponseStatus.InternalError, 2],
+ [OcspResponseStatus.Unauthorized, 6]
+ ])("should encode %s with no responseBytes", (status, expected) => {
+ const parsed = pkijs.OCSPResponse.fromBER(buildOcspErrorResponse(status));
+
+ expect(parsed.responseStatus.valueBlock.valueDec).toBe(expected);
+ expect(parsed.responseBytes).toBeUndefined();
+ });
+});
+
+describe("buildSignedOcspResponse", () => {
+ const thisUpdate = new Date("2026-09-21T13:00:00.000Z");
+ const nextUpdate = new Date("2026-09-21T14:00:00.000Z");
+
+ const build = async (
+ status: Parameters<typeof buildSignedOcspResponse>[0]["statuses"][number]["status"],
+ serialHex?: string
+ ) => {
+ const parsed = parseOcspRequest(await buildClientRequest(serialHex));
+ return buildSignedOcspResponse({
+ signer,
+ caCertificate: caCert,
+ statuses: [{ entry: parsed!.entries[0], status }],
+ thisUpdate,
+ nextUpdate
+ });
+ };
+
+ const readBasic = (der: Buffer) => {
+ const response = pkijs.OCSPResponse.fromBER(der);
+ expect(response.responseStatus.valueBlock.valueDec).toBe(OcspResponseStatus.Successful);
+ return new pkijs.BasicOCSPResponse({
+ schema: asn1js.fromBER(response.responseBytes!.response.valueBlock.valueHexView).result
+ });
+ };
+
+ it("should produce a good response whose signature verifies against the CA key", async () => {
+ const basic = readBasic(await build({ kind: OcspCertStatus.Good }));
+
+ expect(basic.tbsResponseData.responses).toHaveLength(1);
+ expect((basic.tbsResponseData.responses[0].certStatus as asn1js.BaseBlock).idBlock.tagNumber).toBe(0);
+ await expect(basic.verify({ trustedCerts: [pkijs.Certificate.fromBER(caCert.rawData)] })).resolves.toBe(true);
+ });
+
+ it("should encode revoked with its reason", async () => {
+ const revokedAt = new Date("2026-09-20T10:00:00.000Z");
+ const basic = readBasic(await build({ kind: OcspCertStatus.Revoked, revokedAt, reason: 1 }));
+
+ const certStatus = basic.tbsResponseData.responses[0].certStatus as asn1js.Constructed;
+ expect(certStatus.idBlock.tagNumber).toBe(1);
+ expect((certStatus.valueBlock.value[0] as asn1js.GeneralizedTime).toDate().toISOString()).toBe(
+ revokedAt.toISOString()
+ );
+ });
+
+ it("should truncate a revocation time carrying milliseconds, which DER forbids", async () => {
+ const revokedAt = new Date("2026-09-20T10:00:00.360Z");
+ const basic = readBasic(await build({ kind: OcspCertStatus.Revoked, revokedAt, reason: 1 }));
+
+ const certStatus = basic.tbsResponseData.responses[0].certStatus as asn1js.Constructed;
+ const encoded = Buffer.from((certStatus.valueBlock.value[0] as asn1js.GeneralizedTime).toBER(false));
+
+ // a fractional part here makes Go's encoding/asn1 reject the whole response
+ expect(encoded.subarray(2).toString("ascii")).toBe("20260920100000Z");
+ });
+
+ it("should encode unknown", async () => {
+ const basic = readBasic(await build({ kind: OcspCertStatus.Unknown }));
+
+ expect((basic.tbsResponseData.responses[0].certStatus as asn1js.BaseBlock).idBlock.tagNumber).toBe(2);
+ });
+
+ it("should carry thisUpdate and nextUpdate through", async () => {
+ const basic = readBasic(await build({ kind: OcspCertStatus.Good }));
+ const single = basic.tbsResponseData.responses[0];
+
+ expect(single.thisUpdate.toISOString()).toBe(thisUpdate.toISOString());
+ expect(single.nextUpdate?.toISOString()).toBe(nextUpdate.toISOString());
+ });
+
+ it("should emit a canonical CertID rather than echoing a non-minimal serial", async () => {
+ const padded = readBasic(await build({ kind: OcspCertStatus.Good }, `0000${LEAF_SERIAL}`));
+ const honest = readBasic(await build({ kind: OcspCertStatus.Good }, LEAF_SERIAL));
+
+ const serialOf = (basic: pkijs.BasicOCSPResponse) =>
+ Buffer.from(basic.tbsResponseData.responses[0].certID.serialNumber.valueBlock.valueHexView).toString("hex");
+
+ expect(serialOf(padded)).toBe(serialOf(honest));
+ expect(serialOf(padded)).toBe(LEAF_SERIAL);
+ });
+
+ it("should echo the nonce when the request carried one", async () => {
+ const parsed = parseOcspRequest(await buildClientRequest(undefined, true));
+ const basic = readBasic(
+ await buildSignedOcspResponse({
+ signer,
+ caCertificate: caCert,
+ statuses: [{ entry: parsed!.entries[0], status: { kind: OcspCertStatus.Good } }],
+ nonce: parsed!.nonce,
+ thisUpdate,
+ nextUpdate
+ })
+ );
+
+ const echoed = basic.tbsResponseData.responseExtensions?.find((ext) => ext.extnID === OCSP_NONCE_OID);
+ expect(echoed).toBeDefined();
+ expect(Buffer.from((echoed!.parsedValue as asn1js.OctetString).valueBlock.valueHexView).toString("hex")).toBe(
+ "0102030405060708"
+ );
+ });
+});
+
+describe("nonce extension hardening", () => {
+ it("should reject a nonce whose inner DER is not an OCTET STRING rather than throwing", async () => {
+ const request = new pkijs.OCSPRequest();
+ await request.createForCertificate(pkijs.Certificate.fromBER(leafCert.rawData), {
+ hashAlgorithm: "SHA-1",
+ issuerCertificate: pkijs.Certificate.fromBER(caCert.rawData)
+ });
+ request.tbsRequest.requestExtensions = [
+ new pkijs.Extension({
+ extnID: OCSP_NONCE_OID,
+ extnValue: new asn1js.Sequence({ value: [new asn1js.Integer({ value: 1 })] }).toBER()
+ })
+ ];
+
+ expect(() => parseOcspRequest(Buffer.from(request.toSchema(true).toBER(false)))).not.toThrow();
+ expect(parseOcspRequest(Buffer.from(request.toSchema(true).toBER(false)))).toBeNull();
+ });
+});
+
+describe("hash algorithm allowlist", () => {
+ const buildRequestWithOid = (oid: string) => {
+ const certId = new asn1js.Sequence({
+ value: [
+ new asn1js.Sequence({ value: [new asn1js.ObjectIdentifier({ value: oid }), new asn1js.Null()] }),
+ new asn1js.OctetString({ valueHex: new Uint8Array(20).fill(0xaa) }),
+ new asn1js.OctetString({ valueHex: new Uint8Array(20).fill(0xbb) }),
+ new asn1js.Integer({ value: 1 })
+ ]
+ });
+ const tbs = new asn1js.Sequence({
+ value: [new asn1js.Sequence({ value: [new asn1js.Sequence({ value: [certId] })] })]
+ });
+ return Buffer.from(new asn1js.Sequence({ value: [tbs] }).toBER(false));
+ };
+
+ it.each(Object.keys(OCSP_HASH_NAME_BY_OID))("should accept the supported hash OID %s", (oid) => {
+ expect(parseOcspRequest(buildRequestWithOid(oid))).not.toBeNull();
+ });
+
+ it("should reject an unsupported hash OID rather than carrying it downstream", () => {
+ expect(parseOcspRequest(buildRequestWithOid("1.2.840.113549.2.5"))).toBeNull();
+ });
+
+ it("should reject an arbitrarily long attacker-chosen OID", () => {
+ const longOid = `1.3.6.1.4.1.${Array.from({ length: 4000 }, (_, i) => (i % 9) + 1).join(".")}`;
+ expect(longOid.length).toBeGreaterThan(7000);
+ expect(parseOcspRequest(buildRequestWithOid(longOid))).toBeNull();
+ });
+});
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns.ts
new file mode 100644
index 0000000000..0dab1f9a1c
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-fns.ts
@@ -0,0 +1,254 @@
+import * as x509 from "@peculiar/x509";
+import * as asn1js from "asn1js";
+import * as pkijs from "pkijs";
+
+import { crypto } from "@app/lib/crypto/cryptography";
+import { pqcNameToOid } from "@app/lib/crypto/pqc/pqc-utils";
+import { BadRequestError } from "@app/lib/errors";
+import { TCaSigner } from "@app/services/certificate-authority/ca-signer";
+
+import {
+ OCSP_BASIC_RESPONSE_OID,
+ OCSP_HASH_NAME_BY_OID,
+ OCSP_MAX_CERT_IDS_PER_REQUEST,
+ OCSP_MAX_NONCE_BYTES,
+ OCSP_MAX_SERIAL_HEX_LENGTH,
+ OCSP_NONCE_OID,
+ OcspCertStatus,
+ OcspResponseStatus
+} from "./certificate-authority-ocsp-enums";
+import { TOcspCertStatus, TParsedOcspRequest, TParsedOcspRequestEntry } from "./certificate-authority-ocsp-types";
+
+const RSA_SIGNATURE_OID_BY_HASH: Record<string, string> = {
+ "SHA-256": "1.2.840.113549.1.1.11",
+ "SHA-384": "1.2.840.113549.1.1.12",
+ "SHA-512": "1.2.840.113549.1.1.13"
+};
+
+const ECDSA_SIGNATURE_OID_BY_HASH: Record<string, string> = {
+ "SHA-256": "1.2.840.10045.4.3.2",
+ "SHA-384": "1.2.840.10045.4.3.3",
+ "SHA-512": "1.2.840.10045.4.3.4"
+};
+
+const toArrayBuffer = (view: Uint8Array): ArrayBuffer =>
+ view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
+
+export const normalizeSerialNumber = (hex: string): string => {
+ let out = hex.toLowerCase();
+ while (out.length > 1 && out.startsWith("0")) out = out.slice(1);
+ return out;
+};
+
+const toMinimalSerialBytes = (hex: string): Buffer => {
+ let bytes = Buffer.from(hex.length % 2 === 0 ? hex : `0${hex}`, "hex");
+ let start = 0;
+ while (start < bytes.length - 1 && bytes[start] === 0) start += 1;
+ bytes = bytes.subarray(start);
+ // eslint-disable-next-line no-bitwise
+ return bytes[0] & 0x80 ? Buffer.concat([Buffer.from([0]), bytes]) : Buffer.from(bytes);
+};
+
+const algorithmHashName = (alg: Algorithm): string | undefined => {
+ const { hash } = alg as { hash?: string | { name?: string } };
+ return typeof hash === "string" ? hash : hash?.name;
+};
+
+export const resolveOcspSignatureAlgorithm = (
+ signingAlgorithm: Algorithm
+): { algorithmId: string; algorithmParams?: asn1js.Null } => {
+ const hash = algorithmHashName(signingAlgorithm);
+ const name = signingAlgorithm.name.toUpperCase();
+
+ const pqcAlgorithmId = pqcNameToOid(signingAlgorithm.name);
+ if (pqcAlgorithmId) return { algorithmId: pqcAlgorithmId };
+
+ if (name === "RSASSA-PKCS1-V1_5") {
+ const algorithmId = hash ? RSA_SIGNATURE_OID_BY_HASH[hash] : undefined;
+ if (algorithmId) return { algorithmId, algorithmParams: new asn1js.Null() };
+ }
+
+ if (name === "ECDSA") {
+ const algorithmId = hash ? ECDSA_SIGNATURE_OID_BY_HASH[hash] : undefined;
+ if (algorithmId) return { algorithmId };
+ }
+
+ throw new BadRequestError({
+ message: `OCSP responses cannot be signed with ${signingAlgorithm.name}${
+ hash ? ` and ${hash}` : ""
+ }. This certificate authority's key algorithm is not supported by the OCSP responder.`
+ });
+};
+
+const digestForOcsp = (hashAlgorithmOid: string, data: Buffer): Buffer | null => {
+ const hashName = OCSP_HASH_NAME_BY_OID[hashAlgorithmOid];
+ if (!hashName) return null;
+ return crypto.nativeCrypto.createHash(hashName).update(data).digest();
+};
+
+export const parseOcspRequest = (der: Buffer): TParsedOcspRequest | null => {
+ let request: pkijs.OCSPRequest;
+ try {
+ request = pkijs.OCSPRequest.fromBER(toArrayBuffer(new Uint8Array(der)));
+ } catch {
+ return null;
+ }
+
+ const requestList = request.tbsRequest.requestList ?? [];
+ if (requestList.length === 0 || requestList.length > OCSP_MAX_CERT_IDS_PER_REQUEST) return null;
+
+ const entries: TParsedOcspRequestEntry[] = [];
+ for (const item of requestList) {
+ const { reqCert } = item;
+ if (!reqCert) return null;
+
+ const { algorithmId: hashAlgorithmOid } = reqCert.hashAlgorithm;
+ if (!OCSP_HASH_NAME_BY_OID[hashAlgorithmOid]) return null;
+
+ const rawSerialNumber = Buffer.from(reqCert.serialNumber.valueBlock.valueHexView).toString("hex").toLowerCase();
+ if (rawSerialNumber.length === 0 || rawSerialNumber.length > OCSP_MAX_SERIAL_HEX_LENGTH) return null;
+
+ entries.push({
+ hashAlgorithmOid,
+ issuerNameHash: Buffer.from(reqCert.issuerNameHash.valueBlock.valueHexView),
+ issuerKeyHash: Buffer.from(reqCert.issuerKeyHash.valueBlock.valueHexView),
+ rawSerialNumber,
+ serialNumber: normalizeSerialNumber(rawSerialNumber)
+ });
+ }
+
+ let nonce: Buffer | undefined;
+ const nonceExtension = request.tbsRequest.requestExtensions?.find((ext) => ext.extnID === OCSP_NONCE_OID);
+ if (nonceExtension) {
+ const rawExtnValue = new Uint8Array(nonceExtension.extnValue.valueBlock.valueHexView);
+ const decoded = asn1js.fromBER(toArrayBuffer(rawExtnValue));
+ if (decoded.offset !== -1 && !(decoded.result instanceof asn1js.OctetString)) return null;
+ const candidate =
+ decoded.offset === -1
+ ? Buffer.from(rawExtnValue)
+ : Buffer.from((decoded.result as asn1js.OctetString).valueBlock.valueHexView);
+
+ if (candidate.length === 0 || candidate.length > OCSP_MAX_NONCE_BYTES) return null;
+ nonce = candidate;
+ }
+
+ return { entries, nonce };
+};
+
+export const buildOcspErrorResponse = (status: OcspResponseStatus): Buffer => {
+ const response = new pkijs.OCSPResponse({ responseStatus: new asn1js.Enumerated({ value: status }) });
+ return Buffer.from(response.toSchema().toBER(false));
+};
+
+const buildCertStatus = (status: TOcspCertStatus): asn1js.BaseBlock => {
+ if (status.kind === OcspCertStatus.Good) {
+ return new asn1js.Primitive({ idBlock: { tagClass: 3, tagNumber: 0 } });
+ }
+
+ if (status.kind === OcspCertStatus.Revoked) {
+ // RFC 5280 4.1.2.5.2 forbids fractional seconds in GeneralizedTime, and Go's encoding/asn1
+ // rejects the whole response rather than just this field. revokedAt comes from the database
+ // with milliseconds, unlike thisUpdate/nextUpdate which the caller already truncates.
+ const revokedAt = new Date(status.revokedAt);
+ revokedAt.setMilliseconds(0);
+
+ const revokedInfo: asn1js.BaseBlock[] = [new asn1js.GeneralizedTime({ valueDate: revokedAt })];
+ if (typeof status.reason === "number") {
+ revokedInfo.push(
+ new asn1js.Constructed({
+ idBlock: { tagClass: 3, tagNumber: 0 },
+ value: [new asn1js.Enumerated({ value: status.reason })]
+ })
+ );
+ }
+ return new asn1js.Constructed({ idBlock: { tagClass: 3, tagNumber: 1 }, value: revokedInfo });
+ }
+
+ return new asn1js.Primitive({ idBlock: { tagClass: 3, tagNumber: 2 } });
+};
+
+export const buildSignedOcspResponse = async ({
+ signer,
+ caCertificate,
+ statuses,
+ nonce,
+ thisUpdate,
+ nextUpdate
+}: {
+ signer: TCaSigner;
+ caCertificate: x509.X509Certificate;
+ statuses: { entry: TParsedOcspRequestEntry; status: TOcspCertStatus }[];
+ nonce?: Buffer;
+ thisUpdate: Date;
+ nextUpdate: Date;
+}): Promise<Buffer> => {
+ const caCert = pkijs.Certificate.fromBER(caCertificate.rawData);
+ const signatureAlgorithm = resolveOcspSignatureAlgorithm(signer.signingAlgorithm);
+
+ const basicResponse = new pkijs.BasicOCSPResponse();
+ basicResponse.tbsResponseData.responderID = caCert.subject;
+ basicResponse.tbsResponseData.producedAt = thisUpdate;
+ basicResponse.tbsResponseData.responses = statuses.map(({ entry, status }) => {
+ const single = new pkijs.SingleResponse();
+ single.certID = new pkijs.CertID({
+ hashAlgorithm: new pkijs.AlgorithmIdentifier({
+ algorithmId: entry.hashAlgorithmOid,
+ algorithmParams: new asn1js.Null()
+ }),
+ issuerNameHash: new asn1js.OctetString({ valueHex: toArrayBuffer(new Uint8Array(entry.issuerNameHash)) }),
+ issuerKeyHash: new asn1js.OctetString({ valueHex: toArrayBuffer(new Uint8Array(entry.issuerKeyHash)) }),
+ serialNumber: new asn1js.Integer({
+ valueHex: toArrayBuffer(new Uint8Array(toMinimalSerialBytes(entry.serialNumber)))
+ })
+ });
+ single.certStatus = buildCertStatus(status);
+ single.thisUpdate = thisUpdate;
+ single.nextUpdate = nextUpdate;
+ return single;
+ });
+
+ if (nonce) {
+ basicResponse.tbsResponseData.responseExtensions = [
+ new pkijs.Extension({
+ extnID: OCSP_NONCE_OID,
+ extnValue: new asn1js.OctetString({ valueHex: toArrayBuffer(new Uint8Array(nonce)) }).toBER()
+ })
+ ];
+ }
+
+ basicResponse.signatureAlgorithm = new pkijs.AlgorithmIdentifier(signatureAlgorithm);
+
+ const tbsSchema = basicResponse.tbsResponseData.toSchema(true) as asn1js.Sequence;
+ const tbs = Buffer.from(tbsSchema.toBER(false));
+ const signature = await signer.signTbs(tbs);
+
+ basicResponse.tbsResponseData.tbsView = new Uint8Array(tbs);
+ basicResponse.signature = new asn1js.BitString({ valueHex: signature });
+ basicResponse.certs = [caCert];
+
+ const response = new pkijs.OCSPResponse({
+ responseStatus: new asn1js.Enumerated({ value: OcspResponseStatus.Successful }),
+ responseBytes: new pkijs.ResponseBytes({
+ responseType: OCSP_BASIC_RESPONSE_OID,
+ response: new asn1js.OctetString({ valueHex: basicResponse.toSchema().toBER(false) })
+ })
+ });
+
+ return Buffer.from(response.toSchema().toBER(false));
+};
+
+export const getCaOcspIdentifiers = (
+ caCertificate: x509.X509Certificate,
+ hashAlgorithmOid: string
+): { issuerNameHash: Buffer; issuerKeyHash: Buffer } | null => {
+ const caCert = pkijs.Certificate.fromBER(caCertificate.rawData);
+
+ const subjectDer = Buffer.from(caCert.subject.toSchema().toBER(false));
+ const publicKeyBits = Buffer.from(caCert.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView);
+
+ const issuerNameHash = digestForOcsp(hashAlgorithmOid, subjectDer);
+ const issuerKeyHash = digestForOcsp(hashAlgorithmOid, publicKeyBits);
+ if (!issuerNameHash || !issuerKeyHash) return null;
+
+ return { issuerNameHash, issuerKeyHash };
+};
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-hsm.test.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-hsm.test.ts
new file mode 100644
index 0000000000..3b46ae7ae4
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-hsm.test.ts
@@ -0,0 +1,100 @@
+import { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+import * as asn1js from "asn1js";
+import * as pkijs from "pkijs";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
+import { buildHsmCaSigner } from "@app/services/certificate-authority/ca-signer";
+
+import { OcspCertStatus, OcspResponseStatus } from "./certificate-authority-ocsp-enums";
+import { buildSignedOcspResponse, parseOcspRequest } from "./certificate-authority-ocsp-fns";
+
+type TCase = {
+ keyAlgorithm: CertKeyAlgorithm;
+ gen: RsaHashedKeyGenParams | EcKeyGenParams;
+ sign: AlgorithmIdentifier | EcdsaParams;
+ isEcdsa: boolean;
+};
+
+const CASES: TCase[] = [
+ {
+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,
+ gen: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256", publicExponent: new Uint8Array([1, 0, 1]), modulusLength: 2048 },
+ sign: { name: "RSASSA-PKCS1-v1_5" },
+ isEcdsa: false
+ },
+ {
+ keyAlgorithm: CertKeyAlgorithm.ECDSA_P256,
+ gen: { name: "ECDSA", namedCurve: "P-256" },
+ sign: { name: "ECDSA", hash: "SHA-256" },
+ isEcdsa: true
+ },
+ {
+ keyAlgorithm: CertKeyAlgorithm.ECDSA_P384,
+ gen: { name: "ECDSA", namedCurve: "P-384" },
+ sign: { name: "ECDSA", hash: "SHA-384" },
+ isEcdsa: true
+ }
+];
+
+beforeAll(() => {
+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+ pkijs.setEngine("hsm-test", new pkijs.CryptoEngine({ crypto: webcrypto as unknown as Crypto }));
+});
+
+describe.each(CASES)("HSM-backed OCSP signing: $keyAlgorithm", (testCase) => {
+ it("should produce a response whose signature verifies against the CA public key", async () => {
+ const keys = (await webcrypto.subtle.generateKey(testCase.gen, true, ["sign", "verify"])) as CryptoKeyPair;
+
+ const caCert = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name: "CN=HSM Stand-in Root",
+ notBefore: new Date(Date.now() - 86_400_000),
+ notAfter: new Date(Date.now() + 86_400_000),
+ signingAlgorithm: testCase.gen as Algorithm,
+ keys,
+ extensions: [new x509.BasicConstraintsExtension(true, 2, true)]
+ });
+
+ const signer = buildHsmCaSigner({
+ caPublicKey: keys.publicKey,
+ keyAlgorithm: testCase.keyAlgorithm,
+ sign: async (tbs) => Buffer.from(await webcrypto.subtle.sign(testCase.sign, keys.privateKey, tbs))
+ });
+
+ const request = new pkijs.OCSPRequest();
+ await request.createForCertificate(pkijs.Certificate.fromBER(caCert.rawData), {
+ hashAlgorithm: "SHA-1",
+ issuerCertificate: pkijs.Certificate.fromBER(caCert.rawData)
+ });
+ const parsed = parseOcspRequest(Buffer.from(request.toSchema(true).toBER(false)));
+ expect(parsed).not.toBeNull();
+
+ const thisUpdate = new Date();
+ thisUpdate.setMilliseconds(0);
+
+ const der = await buildSignedOcspResponse({
+ signer,
+ caCertificate: caCert,
+ statuses: [{ entry: parsed!.entries[0], status: { kind: OcspCertStatus.Good } }],
+ thisUpdate,
+ nextUpdate: new Date(thisUpdate.getTime() + 3_600_000)
+ });
+
+ const response = pkijs.OCSPResponse.fromBER(der);
+ expect(response.responseStatus.valueBlock.valueDec).toBe(OcspResponseStatus.Successful);
+
+ const basic = new pkijs.BasicOCSPResponse({
+ schema: asn1js.fromBER(response.responseBytes!.response.valueBlock.valueHexView).result
+ });
+
+ if (testCase.isEcdsa) {
+ const sig = Buffer.from(basic.signature.valueBlock.valueHexView);
+ expect(sig[0]).toBe(0x30);
+ }
+
+ await expect(basic.verify({ trustedCerts: [pkijs.Certificate.fromBER(caCert.rawData)] })).resolves.toBe(true);
+ });
+});
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-limiter.test.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-limiter.test.ts
new file mode 100644
index 0000000000..9f0f6ce0eb
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-limiter.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it } from "vitest";
+
+import { createOcspSigningLimiter, createOcspSigningLimiterRegistry } from "./certificate-authority-ocsp-limiter";
+
+const deferred = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+};
+
+describe("createOcspSigningLimiter", () => {
+ it("should run work immediately while under the limit", async () => {
+ const limiter = createOcspSigningLimiter(2, 1000, 64);
+
+ await expect(limiter.run(async () => "done")).resolves.toBe("done");
+ expect(limiter.getActiveCount()).toBe(0);
+ });
+
+ it("should never exceed the concurrency limit", async () => {
+ const limiter = createOcspSigningLimiter(2, 5000, 64);
+ const gate = deferred();
+ let peak = 0;
+
+ const inFlight = Array.from({ length: 6 }, () =>
+ limiter.run(async () => {
+ peak = Math.max(peak, limiter.getActiveCount());
+ await gate.promise;
+ return true;
+ })
+ );
+
+ await new Promise((r) => {
+ setTimeout(r, 20);
+ });
+ expect(limiter.getActiveCount()).toBe(2);
+
+ gate.resolve();
+ await Promise.all(inFlight);
+ expect(peak).toBeLessThanOrEqual(2);
+ });
+
+ it("should hand a freed slot to a queued caller", async () => {
+ const limiter = createOcspSigningLimiter(1, 5000, 64);
+ const first = deferred();
+ const order: string[] = [];
+
+ const a = limiter.run(async () => {
+ await first.promise;
+ order.push("a");
+ });
+ const b = limiter.run(async () => {
+ order.push("b");
+ });
+
+ first.resolve();
+ await Promise.all([a, b]);
+
+ expect(order).toEqual(["a", "b"]);
+ expect(limiter.getActiveCount()).toBe(0);
+ expect(limiter.getQueueDepth()).toBe(0);
+ });
+
+ it("should return null rather than queueing forever when saturated", async () => {
+ const limiter = createOcspSigningLimiter(1, 30, 64);
+ const gate = deferred();
+
+ const holder = limiter.run(async () => {
+ await gate.promise;
+ });
+
+ await expect(limiter.run(async () => "never")).resolves.toBeNull();
+
+ gate.resolve();
+ await holder;
+ expect(limiter.getQueueDepth()).toBe(0);
+ });
+
+ it("should release the slot when the work throws", async () => {
+ const limiter = createOcspSigningLimiter(1, 1000, 64);
+
+ await expect(
+ limiter.run(async () => {
+ throw new Error("boom");
+ })
+ ).rejects.toThrow("boom");
+
+ expect(limiter.getActiveCount()).toBe(0);
+ await expect(limiter.run(async () => "recovered")).resolves.toBe("recovered");
+ });
+});
+
+describe("createOcspSigningLimiterRegistry", () => {
+ it("should reject immediately once the queue is full rather than admitting every caller to a wait", async () => {
+ const limiter = createOcspSigningLimiter(1, 5000, 1);
+ const gate = deferred();
+
+ const holder = limiter.run(async () => {
+ await gate.promise;
+ });
+ const queued = limiter.run(async () => "queued");
+
+ await expect(limiter.run(async () => "rejected")).resolves.toBeNull();
+
+ gate.resolve();
+ await Promise.all([holder, queued]);
+ });
+
+ it("should stop one CA from consuming the whole global budget", async () => {
+ const registry = createOcspSigningLimiterRegistry({
+ globalLimit: 8,
+ perCaLimit: 2,
+ maxWaitMs: 5000,
+ maxQueueDepth: 64,
+ maxTrackedCas: 8
+ });
+ const gate = deferred();
+ let noisyPeak = 0;
+ let noisyActive = 0;
+
+ const noisy = Array.from({ length: 6 }, () =>
+ registry.runForCa("noisy-ca", async () => {
+ noisyActive += 1;
+ noisyPeak = Math.max(noisyPeak, noisyActive);
+ await gate.promise;
+ noisyActive -= 1;
+ })
+ );
+
+ await new Promise((r) => {
+ setTimeout(r, 20);
+ });
+
+ // the quiet CA still gets served while the noisy one is saturated
+ const quiet = await registry.runForCa("quiet-ca", async () => "served");
+
+ gate.resolve();
+ await Promise.all(noisy);
+
+ expect(noisyPeak).toBeLessThanOrEqual(2);
+ expect(quiet).toBe("served");
+ });
+
+ it("should prune idle per-CA limiters rather than growing without bound", async () => {
+ const registry = createOcspSigningLimiterRegistry({
+ globalLimit: 8,
+ perCaLimit: 2,
+ maxWaitMs: 1000,
+ maxQueueDepth: 64,
+ maxTrackedCas: 3
+ });
+
+ for (let i = 0; i < 10; i += 1) {
+ // eslint-disable-next-line no-await-in-loop -- pruning only reclaims idle limiters, so these must not overlap
+ await registry.runForCa(`ca-${i}`, () => Promise.resolve(i));
+ }
+
+ expect(registry.getTrackedCaCount()).toBeLessThanOrEqual(4);
+ });
+});
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-limiter.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-limiter.ts
new file mode 100644
index 0000000000..2ba770d83b
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-limiter.ts
@@ -0,0 +1,97 @@
+type TWaiter = {
+ admit: () => void;
+ timer: NodeJS.Timeout;
+};
+
+export const createOcspSigningLimiter = (limit: number, maxWaitMs: number, maxQueueDepth: number) => {
+ let active = 0;
+ const queue: TWaiter[] = [];
+
+ const releaseSlot = () => {
+ const waiter = queue.shift();
+ if (!waiter) {
+ active -= 1;
+ return;
+ }
+ clearTimeout(waiter.timer);
+ waiter.admit();
+ };
+
+ const run = async <T>(fn: () => Promise<T>): Promise<T | null> => {
+ if (active < limit) {
+ active += 1;
+ } else {
+ if (queue.length >= maxQueueDepth) return null;
+
+ const admitted = await new Promise<boolean>((resolve) => {
+ const timer = setTimeout(() => {
+ const index = queue.findIndex((waiter) => waiter.timer === timer);
+ if (index >= 0) queue.splice(index, 1);
+ resolve(false);
+ }, maxWaitMs);
+
+ queue.push({ admit: () => resolve(true), timer });
+ });
+
+ if (!admitted) return null;
+ }
+
+ try {
+ return await fn();
+ } finally {
+ releaseSlot();
+ }
+ };
+
+ const isIdle = () => active === 0 && queue.length === 0;
+
+ return { run, isIdle, getActiveCount: () => active, getQueueDepth: () => queue.length };
+};
+
+export type TOcspSigningLimiter = ReturnType<typeof createOcspSigningLimiter>;
+
+export const createOcspSigningLimiterRegistry = ({
+ globalLimit,
+ perCaLimit,
+ maxWaitMs,
+ maxQueueDepth,
+ maxTrackedCas
+}: {
+ globalLimit: number;
+ perCaLimit: number;
+ maxWaitMs: number;
+ maxQueueDepth: number;
+ maxTrackedCas: number;
+}) => {
+ const globalLimiter = createOcspSigningLimiter(globalLimit, maxWaitMs, maxQueueDepth);
+ const perCaLimiters = new Map<string, TOcspSigningLimiter>();
+
+ const pruneIdle = () => {
+ if (perCaLimiters.size <= maxTrackedCas) return;
+ for (const [caId, limiter] of perCaLimiters) {
+ if (limiter.isIdle()) perCaLimiters.delete(caId);
+ if (perCaLimiters.size <= maxTrackedCas) return;
+ }
+ };
+
+ const runForCa = async <T>(caId: string, fn: () => Promise<T>): Promise<T | null> => {
+ let caLimiter = perCaLimiters.get(caId);
+ if (!caLimiter) {
+ pruneIdle();
+ caLimiter = createOcspSigningLimiter(perCaLimit, maxWaitMs, maxQueueDepth);
+ perCaLimiters.set(caId, caLimiter);
+ }
+
+ return caLimiter.run(() => globalLimiter.run(fn));
+ };
+
+ return {
+ runForCa,
+ getGlobalActiveCount: () => globalLimiter.getActiveCount(),
+ getGlobalQueueDepth: () => globalLimiter.getQueueDepth(),
+ getCaQueueDepth: (caId: string) => perCaLimiters.get(caId)?.getQueueDepth() ?? 0,
+ getTrackedCaCount: () => perCaLimiters.size
+ };
+};
+
+export type TOcspSigningLimiterRegistry = ReturnType<typeof createOcspSigningLimiterRegistry>;
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service.ts
new file mode 100644
index 0000000000..7555f80951
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service.ts
@@ -0,0 +1,376 @@
+import * as x509 from "@peculiar/x509";
+
+import { TKeyStoreFactory } from "@app/keystore/keystore";
+import { NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import {
+ recordOcspResponseMetric,
+ recordOcspSigningDurationMetric,
+ TOcspCertStatusLabel,
+ TOcspStatusLabel
+} from "@app/lib/telemetry/metrics";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { CertStatus } from "@app/services/certificate/certificate-types";
+import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
+import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
+import { getCaSigner } from "@app/services/certificate-authority/certificate-authority-fns";
+import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
+import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import {
+ OCSP_GENERATION_TTL_SECONDS,
+ OCSP_HASH_NAME_BY_OID,
+ OCSP_MAX_CACHED_CA_CERTIFICATES,
+ OCSP_MAX_CONCURRENT_SIGNATURES,
+ OCSP_MAX_CONCURRENT_SIGNATURES_PER_CA,
+ OCSP_MAX_TRACKED_CA_LIMITERS,
+ OCSP_RESPONSE_VALIDITY_SECONDS,
+ OCSP_SATURATION_LOG_INTERVAL_MS,
+ OCSP_SIGNING_MAX_QUEUE_DEPTH,
+ OCSP_SIGNING_QUEUE_TIMEOUT_MS,
+ OCSP_UNKNOWN_RESPONSE_VALIDITY_SECONDS,
+ OcspCertStatus,
+ OcspResponseStatus,
+ STORED_SERIAL_HEX_LENGTH
+} from "./certificate-authority-ocsp-enums";
+import {
+ buildOcspErrorResponse,
+ buildSignedOcspResponse,
+ getCaOcspIdentifiers,
+ normalizeSerialNumber,
+ parseOcspRequest
+} from "./certificate-authority-ocsp-fns";
+import { createOcspSigningLimiterRegistry } from "./certificate-authority-ocsp-limiter";
+import {
+ TCertificateAuthorityOcspServiceFactory,
+ TOcspCertStatus,
+ TOcspResponseResult,
+ TParsedOcspRequestEntry
+} from "./certificate-authority-ocsp-types";
+
+type TCertificateAuthorityOcspServiceFactoryDep = {
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;
+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
+ certificateDAL: Pick<TCertificateDALFactory, "find" | "primaryNode">;
+ projectDAL: Pick<TProjectDALFactory, "findById" | "findOne" | "updateById" | "transaction">;
+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
+ keyStore: Pick<
+ TKeyStoreFactory,
+ "getItemPrimary" | "setItemWithExpiry" | "deleteItemsByKeyIn" | "incrementSeededWithExpiry"
+ >;
+};
+
+const OCSP_CACHE_PREFIX = "ocsp-response";
+const OCSP_GENERATION_PREFIX = "ocsp-generation";
+
+const buildCacheKey = (caCertId: string, hashAlgorithmOid: string, serialNumber: string) =>
+ `${OCSP_CACHE_PREFIX}:${caCertId}:${hashAlgorithmOid}:${serialNumber}`;
+
+const buildGenerationKey = (caId: string) => `${OCSP_GENERATION_PREFIX}:${caId}`;
+
+type TCaOcspIdentifiers = ReturnType<typeof getCaOcspIdentifiers>;
+
+type TResolvedCaCertificate = {
+ id: string;
+ certificate: x509.X509Certificate;
+ caId: string;
+ kmsKeyId: string;
+ identifiers: Map<string, TCaOcspIdentifiers>;
+};
+
+const caCertificateCache = new Map<string, TResolvedCaCertificate>();
+
+type TOcspOutcome = { result: TOcspResponseResult; status: TOcspStatusLabel; certStatus: TOcspCertStatusLabel };
+
+const inFlightResponses = new Map<string, Promise<TOcspOutcome>>();
+
+let lastSaturationLogAt = 0;
+
+const signingLimiters = createOcspSigningLimiterRegistry({
+ globalLimit: OCSP_MAX_CONCURRENT_SIGNATURES,
+ perCaLimit: OCSP_MAX_CONCURRENT_SIGNATURES_PER_CA,
+ maxWaitMs: OCSP_SIGNING_QUEUE_TIMEOUT_MS,
+ maxQueueDepth: OCSP_SIGNING_MAX_QUEUE_DEPTH,
+ maxTrackedCas: OCSP_MAX_TRACKED_CA_LIMITERS
+});
+
+export const certificateAuthorityOcspServiceFactory = ({
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateAuthoritySecretDAL,
+ certificateDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService,
+ keyStore
+}: TCertificateAuthorityOcspServiceFactoryDep): TCertificateAuthorityOcspServiceFactory => {
+ const $getActiveCaCertificate = async (caId: string, projectId: string, activeCaCertId: string) => {
+ const cached = caCertificateCache.get(activeCaCertId);
+ if (cached) return cached;
+
+ const caCert = await certificateAuthorityCertDAL.findById(activeCaCertId);
+ if (!caCert) return null;
+
+ const keyId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });
+ const kmsDecryptor = await kmsService.decryptWithKmsKey({ kmsId: keyId });
+ const decryptedCaCert = await kmsDecryptor({ cipherTextBlob: caCert.encryptedCertificate });
+
+ const resolved: TResolvedCaCertificate = {
+ id: caCert.id,
+ certificate: new x509.X509Certificate(decryptedCaCert),
+ caId,
+ kmsKeyId: keyId,
+ identifiers: new Map()
+ };
+
+ if (caCertificateCache.size >= OCSP_MAX_CACHED_CA_CERTIFICATES) {
+ const oldest = caCertificateCache.keys().next().value as string | undefined;
+ if (oldest) caCertificateCache.delete(oldest);
+ }
+ caCertificateCache.set(activeCaCertId, resolved);
+
+ return resolved;
+ };
+
+ const $getIdentifiers = (caCertificate: TResolvedCaCertificate, hashAlgorithmOid: string) => {
+ if (caCertificate.identifiers.has(hashAlgorithmOid)) {
+ return caCertificate.identifiers.get(hashAlgorithmOid) ?? null;
+ }
+
+ const identifiers = getCaOcspIdentifiers(caCertificate.certificate, hashAlgorithmOid);
+ caCertificate.identifiers.set(hashAlgorithmOid, identifiers);
+
+ return identifiers;
+ };
+
+ const $resolveStatuses = async (caId: string, entries: TParsedOcspRequestEntry[]) => {
+ const serialNumbers = [
+ ...new Set(
+ entries.flatMap((entry) => [
+ entry.rawSerialNumber,
+ entry.serialNumber,
+ entry.serialNumber.padStart(STORED_SERIAL_HEX_LENGTH, "0")
+ ])
+ )
+ ];
+ const certificates = await certificateDAL.find(
+ { caId, $in: { serialNumber: serialNumbers } },
+ { tx: certificateDAL.primaryNode() }
+ );
+
+ const bySerial = new Map(
+ certificates.map((certificate) => [normalizeSerialNumber(certificate.serialNumber), certificate])
+ );
+
+ return entries.map((entry) => {
+ const certificate = bySerial.get(entry.serialNumber);
+
+ if (!certificate) return { entry, status: { kind: OcspCertStatus.Unknown } as TOcspCertStatus };
+
+ if (certificate.status === CertStatus.REVOKED) {
+ return {
+ entry,
+ status: {
+ kind: OcspCertStatus.Revoked,
+ revokedAt: certificate.revokedAt ?? new Date(0),
+ ...(typeof certificate.revocationReason === "number" ? { reason: certificate.revocationReason } : {})
+ } as TOcspCertStatus
+ };
+ }
+
+ return { entry, status: { kind: OcspCertStatus.Good } as TOcspCertStatus };
+ });
+ };
+
+ const $toCertStatusLabel = (kinds: OcspCertStatus[]): TOcspCertStatusLabel => {
+ if (kinds.some((kind) => kind === OcspCertStatus.Revoked)) return "revoked";
+ if (kinds.some((kind) => kind === OcspCertStatus.Unknown)) return "unknown";
+ return "good";
+ };
+
+ const getOcspResponse: TCertificateAuthorityOcspServiceFactory["getOcspResponse"] = async ({ caId, requestDer }) => {
+ const parsed = parseOcspRequest(requestDer);
+ if (!parsed) {
+ recordOcspResponseMetric({ status: "malformed_request", certStatus: "none", cache: "skipped" });
+ return { response: buildOcspErrorResponse(OcspResponseStatus.MalformedRequest), maxAgeSeconds: 0 };
+ }
+
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId).catch((error) => {
+ if (error instanceof NotFoundError) return null;
+ throw error;
+ });
+
+ if (!ca?.internalCa?.id || !ca.internalCa.isOcspEnabled || !ca.internalCa.activeCaCertId) {
+ recordOcspResponseMetric({ status: "unauthorized", certStatus: "none", cache: "skipped" });
+ return { response: buildOcspErrorResponse(OcspResponseStatus.Unauthorized), maxAgeSeconds: 0 };
+ }
+
+ const activeCaCert = await $getActiveCaCertificate(ca.id, ca.projectId, ca.internalCa.activeCaCertId);
+ if (!activeCaCert) {
+ recordOcspResponseMetric({ status: "unauthorized", certStatus: "none", cache: "skipped" });
+ return { response: buildOcspErrorResponse(OcspResponseStatus.Unauthorized), maxAgeSeconds: 0 };
+ }
+
+ for (const entry of parsed.entries) {
+ const identifiers = $getIdentifiers(activeCaCert, entry.hashAlgorithmOid);
+ if (
+ !identifiers ||
+ !identifiers.issuerNameHash.equals(entry.issuerNameHash) ||
+ !identifiers.issuerKeyHash.equals(entry.issuerKeyHash)
+ ) {
+ recordOcspResponseMetric({ status: "unauthorized", certStatus: "none", cache: "skipped" });
+ return { response: buildOcspErrorResponse(OcspResponseStatus.Unauthorized), maxAgeSeconds: 0 };
+ }
+ }
+
+ const generationKey = buildGenerationKey(ca.id);
+ const generationAtStart = (await keyStore.getItemPrimary(generationKey)) ?? "0";
+
+ const cacheKey =
+ parsed.nonce || parsed.entries.length !== 1
+ ? null
+ : buildCacheKey(activeCaCert.id, parsed.entries[0].hashAlgorithmOid, parsed.entries[0].serialNumber);
+
+ if (cacheKey) {
+ const cached = await keyStore.getItemPrimary(cacheKey);
+ if (cached) {
+ const { der, expiresAt, certStatus } = JSON.parse(cached) as {
+ der: string;
+ expiresAt: number;
+ certStatus: TOcspCertStatusLabel;
+ };
+ const remaining = Math.floor((expiresAt - Date.now()) / 1000);
+ if (remaining > 0) {
+ recordOcspResponseMetric({ status: "successful", certStatus, cache: "hit" });
+ return { response: Buffer.from(der, "base64"), maxAgeSeconds: remaining };
+ }
+ }
+ }
+
+ const $produce = async (): Promise<TOcspOutcome> => {
+ const thisUpdate = new Date();
+ thisUpdate.setMilliseconds(0);
+
+ const signingStartedAt = Date.now();
+ let resolvedCertStatus: TOcspCertStatusLabel = "unknown";
+ let validitySeconds = OCSP_RESPONSE_VALIDITY_SECONDS;
+ let nextUpdate = new Date(thisUpdate.getTime() + validitySeconds * 1000);
+
+ const response = await signingLimiters.runForCa(ca.id, async () => {
+ const statuses = await $resolveStatuses(ca.id, parsed.entries);
+ resolvedCertStatus = $toCertStatusLabel(statuses.map(({ status }) => status.kind));
+
+ if (resolvedCertStatus === "unknown") {
+ validitySeconds = OCSP_UNKNOWN_RESPONSE_VALIDITY_SECONDS;
+ nextUpdate = new Date(thisUpdate.getTime() + validitySeconds * 1000);
+ }
+
+ const { signer } = await getCaSigner({
+ caId: ca.id,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService,
+ prefetched: { kmsKeyId: activeCaCert.kmsKeyId }
+ });
+
+ return buildSignedOcspResponse({
+ signer,
+ caCertificate: activeCaCert.certificate,
+ statuses,
+ thisUpdate,
+ nextUpdate,
+ ...(parsed.nonce ? { nonce: parsed.nonce } : {})
+ });
+ });
+
+ if (!response) {
+ if (Date.now() - lastSaturationLogAt > OCSP_SATURATION_LOG_INTERVAL_MS) {
+ lastSaturationLogAt = Date.now();
+ logger.warn(
+ `OCSP responder saturated, shedding request [caId=${ca.id}] [caQueueDepth=${signingLimiters.getCaQueueDepth(
+ ca.id
+ )}] [globalQueueDepth=${signingLimiters.getGlobalQueueDepth()}]`
+ );
+ }
+ recordOcspResponseMetric({ status: "try_later", certStatus: "none", cache: cacheKey ? "miss" : "skipped" });
+ return {
+ result: { response: buildOcspErrorResponse(OcspResponseStatus.TryLater), maxAgeSeconds: 0 },
+ status: "try_later",
+ certStatus: "none"
+ };
+ }
+
+ recordOcspSigningDurationMetric({ durationMs: Date.now() - signingStartedAt });
+ recordOcspResponseMetric({
+ status: "successful",
+ certStatus: resolvedCertStatus,
+ cache: cacheKey ? "miss" : "skipped"
+ });
+
+ if (cacheKey) {
+ const generationNow = (await keyStore.getItemPrimary(generationKey)) ?? "0";
+ if (generationNow === generationAtStart) {
+ await keyStore.setItemWithExpiry(
+ cacheKey,
+ validitySeconds,
+ JSON.stringify({
+ der: response.toString("base64"),
+ expiresAt: nextUpdate.getTime(),
+ certStatus: resolvedCertStatus
+ })
+ );
+ }
+ }
+
+ return {
+ result: { response, maxAgeSeconds: parsed.nonce ? 0 : validitySeconds },
+ status: "successful",
+ certStatus: resolvedCertStatus
+ };
+ };
+
+ if (!cacheKey) return (await $produce()).result;
+
+ const inFlightKey = `${cacheKey}:${generationAtStart}`;
+
+ const inFlight = inFlightResponses.get(inFlightKey);
+ if (inFlight) {
+ const { result, status, certStatus } = await inFlight;
+ recordOcspResponseMetric({ status, certStatus, cache: "coalesced" });
+ return result;
+ }
+
+ const pending = $produce();
+ inFlightResponses.set(inFlightKey, pending);
+
+ try {
+ return (await pending).result;
+ } finally {
+ inFlightResponses.delete(inFlightKey);
+ }
+ };
+
+ const invalidateCachedResponse: TCertificateAuthorityOcspServiceFactory["invalidateCachedResponse"] = async ({
+ caId,
+ serialNumber
+ }) => {
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ const activeCaCertId = ca?.internalCa?.activeCaCertId;
+ if (!activeCaCertId) return;
+
+ const normalized = normalizeSerialNumber(serialNumber);
+ const keys = Object.keys(OCSP_HASH_NAME_BY_OID).map((oid) => buildCacheKey(activeCaCertId, oid, normalized));
+
+ await keyStore.incrementSeededWithExpiry(buildGenerationKey(caId), Date.now(), OCSP_GENERATION_TTL_SECONDS);
+ await keyStore.deleteItemsByKeyIn(keys);
+ };
+
+ return { getOcspResponse, invalidateCachedResponse };
+};
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-types.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-types.ts
new file mode 100644
index 0000000000..108a40b4ab
--- /dev/null
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-types.ts
@@ -0,0 +1,39 @@
+import { OcspCertStatus } from "./certificate-authority-ocsp-enums";
+
+export type TOcspCertStatus =
+ | { kind: OcspCertStatus.Good }
+ | { kind: OcspCertStatus.Revoked; revokedAt: Date; reason?: number }
+ | { kind: OcspCertStatus.Unknown };
+
+export type TParsedOcspRequestEntry = {
+ hashAlgorithmOid: string;
+ issuerNameHash: Buffer;
+ issuerKeyHash: Buffer;
+ rawSerialNumber: string;
+ serialNumber: string;
+};
+
+export type TParsedOcspRequest = {
+ entries: TParsedOcspRequestEntry[];
+ nonce?: Buffer;
+};
+
+export type TGetOcspResponseDTO = {
+ caId: string;
+ requestDer: Buffer;
+};
+
+export type TInvalidateOcspCacheDTO = {
+ caId: string;
+ serialNumber: string;
+};
+
+export type TOcspResponseResult = {
+ response: Buffer;
+ maxAgeSeconds: number;
+};
+
+export type TCertificateAuthorityOcspServiceFactory = {
+ getOcspResponse: (dto: TGetOcspResponseDTO) => Promise<TOcspResponseResult>;
+ invalidateCachedResponse: (dto: TInvalidateOcspCacheDTO) => Promise<void>;
+};
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index 8c65c36121..5ddff88d5a 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -118,6 +118,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
pkiScep: false,
pkiPqc: false,
caCrl: true,
+ pkiOcsp: false,
pkiEnterpriseCaIntegrations: false,
pkiExternalIntermediateCa: false,
pkiDiscovery: false,
diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts
index 729f7b194e..8041395e49 100644
--- a/backend/src/ee/services/license/license-types.ts
+++ b/backend/src/ee/services/license/license-types.ts
@@ -108,6 +108,7 @@ export type TFeatureSet = {
// caCrl defaults on, so self-hosted OSS keeps it; the License Server's free-plan default is what
// withholds it on cloud.
caCrl: boolean;
+ pkiOcsp: false;
pkiEnterpriseCaIntegrations: false;
pkiExternalIntermediateCa: false;
pkiDiscovery: false;
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 5bb96903ae..04eaa5cd48 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2764,7 +2764,9 @@ export const CertificateAuthorities = {
crlDistributionPointUrls:
"Additional CRL Distribution Point URLs (HTTP/HTTPS) embedded in every certificate issued by this CA. Up to 4 URLs; the Infisical-managed CRL endpoint is included by default unless disabled.",
disableManagedCrlDistributionPointUrl:
- "When set to true, the Infisical-managed CRL endpoint URL will not be embedded in certificates issued by this CA. Only custom CRL Distribution Point URLs (if any) will be included."
+ "When set to true, the Infisical-managed CRL endpoint URL will not be embedded in certificates issued by this CA. Only custom CRL Distribution Point URLs (if any) will be included.",
+ isOcspEnabled:
+ "When set to true, certificates issued by this CA carry the Infisical-managed OCSP responder URL in their Authority Information Access extension, and that responder answers revocation status queries for them. Applies to certificates issued after it is enabled."
}
}
};
diff --git a/backend/src/lib/csr/pkcs11-algorithm-map.test.ts b/backend/src/lib/csr/pkcs11-algorithm-map.test.ts
new file mode 100644
index 0000000000..eb04de0b5d
--- /dev/null
+++ b/backend/src/lib/csr/pkcs11-algorithm-map.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from "vitest";
+
+import { ecdsaRawRsToDer } from "./pkcs11-algorithm-map";
+
+const parseDerLength = (der: Buffer) => {
+ expect(der[0]).toBe(0x30);
+ if (der[1] <= 0x7f) return { headerBytes: 2, length: der[1] };
+ expect(der[1]).toBe(0x81);
+ return { headerBytes: 3, length: der[2] };
+};
+
+describe("ecdsaRawRsToDer", () => {
+ it("should use the short form when the body fits in 127 bytes (P-256)", () => {
+ const der = ecdsaRawRsToDer(Buffer.alloc(64, 0x11));
+ const { headerBytes, length } = parseDerLength(der);
+
+ expect(headerBytes).toBe(2);
+ expect(der.length).toBe(headerBytes + length);
+ });
+
+ it("should use the long form when the body exceeds 127 bytes (P-521)", () => {
+ const der = ecdsaRawRsToDer(Buffer.alloc(132, 0x7f));
+ const { headerBytes, length } = parseDerLength(der);
+
+ expect(headerBytes).toBe(3);
+ expect(length).toBeGreaterThan(0x7f);
+ expect(der.length).toBe(headerBytes + length);
+ });
+
+ it("should sign-pad a component whose high bit is set", () => {
+ const der = ecdsaRawRsToDer(Buffer.alloc(64, 0xff));
+ const { headerBytes } = parseDerLength(der);
+
+ expect(der[headerBytes]).toBe(0x02);
+ expect(der[headerBytes + 2]).toBe(0x00);
+ });
+
+ it("should reject an odd-length raw signature", () => {
+ expect(() => ecdsaRawRsToDer(Buffer.alloc(65, 0x11))).toThrow();
+ });
+});
diff --git a/backend/src/lib/csr/pkcs11-algorithm-map.ts b/backend/src/lib/csr/pkcs11-algorithm-map.ts
index cd737ec27f..aa3bb1ab87 100644
--- a/backend/src/lib/csr/pkcs11-algorithm-map.ts
+++ b/backend/src/lib/csr/pkcs11-algorithm-map.ts
@@ -105,7 +105,9 @@ export const ecdsaRawRsToDer = (raw: Buffer): Buffer => {
const rTlv = Buffer.concat([Buffer.from([0x02, rPadded.length]), rPadded]);
const sTlv = Buffer.concat([Buffer.from([0x02, sPadded.length]), sPadded]);
const seqBody = Buffer.concat([rTlv, sTlv]);
- return Buffer.concat([Buffer.from([0x30, seqBody.length]), seqBody]);
+ const seqHeader =
+ seqBody.length <= 0x7f ? Buffer.from([0x30, seqBody.length]) : Buffer.from([0x30, 0x81, seqBody.length]);
+ return Buffer.concat([seqHeader, seqBody]);
};
export const bufferToArrayBuffer = (buf: Buffer): ArrayBuffer => {
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index bf26cb3ce3..bb005d2e9d 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -929,3 +929,40 @@ export const recordLegacyRootKeyUsageMetric = (params: {
});
});
};
+
+export type TOcspStatusLabel = "successful" | "malformed_request" | "internal_error" | "try_later" | "unauthorized";
+
+export type TOcspCertStatusLabel = "good" | "revoked" | "unknown" | "none";
+
+export const ocspResponseCounter = infisicalCoreMeter.createCounter("infisical.ocsp.response.count", {
+ description:
+ "OCSP responses by response status, certificate status and cache outcome. cert_status is 'none' when the response carries no certificate status, which is every status other than successful. A rising try_later means the signing budget is saturated.",
+ unit: "{response}"
+});
+
+export const ocspSigningDurationHistogram = infisicalCoreMeter.createHistogram("infisical.ocsp.signing.duration", {
+ description: "Time spent resolving status and signing a fresh OCSP response, excluding cache hits.",
+ unit: "ms"
+});
+
+export const recordOcspResponseMetric = (params: {
+ status: TOcspStatusLabel;
+ certStatus: TOcspCertStatusLabel;
+ cache: "hit" | "miss" | "skipped" | "coalesced";
+}) => {
+ safely(() => {
+ if (!isTelemetryEnabled()) return;
+ ocspResponseCounter.add(1, {
+ "ocsp.status": params.status,
+ "ocsp.cert_status": params.certStatus,
+ "ocsp.cache": params.cache
+ });
+ });
+};
+
+export const recordOcspSigningDurationMetric = (params: { durationMs: number }) => {
+ safely(() => {
+ if (!isTelemetryEnabled()) return;
+ ocspSigningDurationHistogram.record(params.durationMs);
+ });
+};
diff --git a/backend/src/lib/telemetry/ocsp-metric-attributes.test.ts b/backend/src/lib/telemetry/ocsp-metric-attributes.test.ts
new file mode 100644
index 0000000000..d638ffc3bf
--- /dev/null
+++ b/backend/src/lib/telemetry/ocsp-metric-attributes.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import { INFISICAL_CORE_METER_ATTRIBUTES } from "./telemetry-attributes";
+
+// An attribute missing from the allowlist is dropped by the SDK View without erroring, so the
+// only thing standing between a typo and silently unlabelled data is a check like this one.
+describe("OCSP metric attributes", () => {
+ it.each(["ocsp.status", "ocsp.cert_status", "ocsp.cache"])(
+ "should carry %s on the InfisicalCore allowlist",
+ (attribute) => {
+ expect(INFISICAL_CORE_METER_ATTRIBUTES).toContain(attribute);
+ }
+ );
+
+ it("should no longer carry the flattened ocsp.result attribute", () => {
+ expect(INFISICAL_CORE_METER_ATTRIBUTES).not.toContain("ocsp.result");
+ });
+
+ it("should keep every attribute bounded, with no per-tenant or per-actor identifier", () => {
+ const ocspAttributes = INFISICAL_CORE_METER_ATTRIBUTES.filter((a) => a.startsWith("ocsp."));
+
+ expect(ocspAttributes).toHaveLength(3);
+ for (const attribute of ocspAttributes) {
+ expect(attribute).not.toMatch(/id$|org|project|actor|user|ip|serial/i);
+ }
+ });
+});
diff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.ts
index 676eb63496..d522c0e476 100644
--- a/backend/src/lib/telemetry/telemetry-attributes.ts
+++ b/backend/src/lib/telemetry/telemetry-attributes.ts
@@ -41,6 +41,9 @@ export const INFISICAL_CORE_METER_ATTRIBUTES = [
"cache.result",
"cache.if_none_match",
"cache.etag_miss_reason",
+ "ocsp.status",
+ "ocsp.cert_status",
+ "ocsp.cache",
"rate_limit.bucket",
"provider",
"destination",
diff --git a/backend/src/server/config/rateLimiter.ts b/backend/src/server/config/rateLimiter.ts
index b3ce5b45b4..ca5ee0f63f 100644
--- a/backend/src/server/config/rateLimiter.ts
+++ b/backend/src/server/config/rateLimiter.ts
@@ -38,6 +38,18 @@ export const writeLimit: RateLimitOptions = {
keyGenerator: (req) => req.realIp
};
+// OCSP is per-handshake traffic, so readLimit is the wrong budget: a mutual TLS fleet behind one NAT
+// address would spend it on revocation checks alone and read the resulting tryLater as the responder
+// being down. The endpoint is unauthenticated, so the IP is all there is to key on, and
+// OCSP_MAX_CONCURRENT_SIGNATURES is what caps the expensive work; this only has to stop one address
+// flooding us with cache hits.
+export const ocspLimit: RateLimitOptions = {
+ timeWindow: 60 * 1000,
+ hook: "preValidation",
+ max: 6000,
+ keyGenerator: (req) => req.realIp
+};
+
// Gateways report load every 10s (6/min each), so 10 leaves room for tick drift and a restart
// landing in the same window without leaving headroom for a flood. Keyed by the reporting gateway
// rather than by IP, because the write limiter's IP key is shared: ~100 gateways behind one NAT
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 6ca7dae75b..7f34ce05f9 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -54,6 +54,7 @@ import { auditReportQueueServiceFactory } from "@app/ee/services/audit-report/au
import { auditReportServiceFactory } from "@app/ee/services/audit-report/audit-report-service";
import { certificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { certificateAuthorityCrlServiceFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-service";
+import { certificateAuthorityOcspServiceFactory } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service";
import { certificateEstServiceFactory } from "@app/ee/services/certificate-est/certificate-est-service";
import { dynamicSecretDALFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-dal";
import { dynamicSecretServiceFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-service";
@@ -3483,6 +3484,17 @@ export const registerRoutes = async (
gatewayPoolService
});
+ const certificateAuthorityOcspService = certificateAuthorityOcspServiceFactory({
+ certificateAuthorityDAL,
+ certificateAuthorityCertDAL,
+ certificateAuthoritySecretDAL,
+ certificateDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService,
+ keyStore
+ });
+
const internalCertificateAuthorityService = internalCertificateAuthorityServiceFactory({
certificateAuthorityDAL,
certificateAuthorityCertDAL,
@@ -3636,7 +3648,8 @@ export const registerRoutes = async (
certificatePolicyService,
licenseService,
usageMeteringService,
- hsmConnectorService
+ hsmConnectorService,
+ certificateAuthorityOcspService
});
const godaddyCaFns = GoDaddyCertificateAuthorityFns({
@@ -4298,6 +4311,7 @@ export const registerRoutes = async (
certManagerInstance: certManagerInstanceService,
certManagerExport: certManagerExportService,
certificateAuthorityCrl: certificateAuthorityCrlService,
+ certificateAuthorityOcsp: certificateAuthorityOcspService,
certificateEst: certificateEstService,
pkiAcme: pkiAcmeService,
pkiScep: pkiScepService,
diff --git a/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts b/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts
index fbf26b52f9..add47dcaee 100644
--- a/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts
+++ b/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts
@@ -146,6 +146,7 @@ export const registerCertificateAuthorityEndpoints = <
projectId?: string;
configuration?: { keySource?: string; hsmConnectorId?: string };
};
+ const createdOcspSetting = (body as { configuration?: { isOcspEnabled?: boolean } }).configuration?.isOcspEnabled;
const certificateAuthority = (await server.services.certificateAuthority.createCertificateAuthority(
{ ...req.body, projectId: body.projectId ?? req.internalCertManagerProjectId, type: caType },
req.permission
@@ -160,7 +161,8 @@ export const registerCertificateAuthorityEndpoints = <
name: certificateAuthority.name,
caId: certificateAuthority.id,
keySource: body.configuration?.keySource,
- hsmConnectorId: body.configuration?.hsmConnectorId
+ hsmConnectorId: body.configuration?.hsmConnectorId,
+ ...(typeof createdOcspSetting === "boolean" && { isOcspEnabled: createdOcspSetting })
}
}
});
@@ -201,6 +203,8 @@ export const registerCertificateAuthorityEndpoints = <
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
const { id } = req.params;
+ const updatedOcspSetting = (req.body as { configuration?: { isOcspEnabled?: boolean } }).configuration
+ ?.isOcspEnabled;
const certificateAuthority = (await server.services.certificateAuthority.updateCertificateAuthority(
{
@@ -219,7 +223,8 @@ export const registerCertificateAuthorityEndpoints = <
metadata: {
name: certificateAuthority.name,
caId: certificateAuthority.id,
- status: certificateAuthority.status
+ status: certificateAuthority.status,
+ ...(typeof updatedOcspSetting === "boolean" && { isOcspEnabled: updatedOcspSetting })
}
}
});
diff --git a/backend/src/services/certificate-authority/ca-signer.ts b/backend/src/services/certificate-authority/ca-signer.ts
index 5e831d5664..dff05bcdda 100644
--- a/backend/src/services/certificate-authority/ca-signer.ts
+++ b/backend/src/services/certificate-authority/ca-signer.ts
@@ -27,6 +27,7 @@ export type TCaSigner = {
createCertificate: (params: TCaCertificateParams) => Promise<x509.X509Certificate>;
createCsr: (params: TCaCsrParams) => Promise<x509.Pkcs10CertificateRequest>;
createCrl: (params: TCaCrlParams) => Promise<x509.X509Crl>;
+ signTbs: (tbs: Buffer) => Promise<ArrayBuffer>;
};
export type TCaExternalSignFn = (tbs: Buffer, mechanism: string, isDigest: boolean) => Promise<Buffer>;
@@ -117,7 +118,14 @@ export const buildLocalCaSigner = ({
keys: { privateKey, publicKey },
signingAlgorithm
}),
- createCrl: (params) => x509.X509CrlGenerator.create({ ...params, signingKey: privateKey, signingAlgorithm })
+ createCrl: (params) => x509.X509CrlGenerator.create({ ...params, signingKey: privateKey, signingAlgorithm }),
+ signTbs: async (tbs) => {
+ const signature = await x509.cryptoProvider
+ .get()
+ .subtle.sign(signingAlgorithm, privateKey, bufferToArrayBuffer(tbs));
+ if (signingAlgorithm.name !== "ECDSA") return signature;
+ return bufferToArrayBuffer(ecdsaRawRsToDer(Buffer.from(signature)));
+ }
});
const HSM_MECHANISM_BY_HASH: Record<"rsa" | "ecdsa", Record<string, string>> = {
@@ -217,6 +225,7 @@ export const buildHsmCaSigner = ({
const crl = AsnConvert.parse(built.rawData, CertificateList);
crl.signature = await signTbs(Buffer.from(AsnConvert.serialize(crl.tbsCertList)));
return new x509.X509Crl(AsnConvert.serialize(crl));
- }
+ },
+ signTbs
};
};
diff --git a/backend/src/services/certificate-authority/certificate-authority-dal.ts b/backend/src/services/certificate-authority/certificate-authority-dal.ts
index f2346b67cf..d8bebc6b34 100644
--- a/backend/src/services/certificate-authority/certificate-authority-dal.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-dal.ts
@@ -58,7 +58,8 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
db
.ref("disableManagedCrlDistributionPointUrl")
.withSchema(TableName.InternalCertificateAuthority)
- .as("internalDisableManagedCrlDistributionPointUrl")
+ .as("internalDisableManagedCrlDistributionPointUrl"),
+ db.ref("isOcspEnabled").withSchema(TableName.InternalCertificateAuthority).as("internalIsOcspEnabled")
)
.select(
db.ref("id").withSchema(TableName.ExternalCertificateAuthority).as("externalCaId"),
@@ -95,7 +96,8 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
notAfter: result.internalNotAfter?.toISOString(),
activeCaCertId: result.internalActiveCaCertId,
crlDistributionPointUrls: result.internalCrlDistributionPointUrls ?? [],
- disableManagedCrlDistributionPointUrl: result.internalDisableManagedCrlDistributionPointUrl ?? false
+ disableManagedCrlDistributionPointUrl: result.internalDisableManagedCrlDistributionPointUrl ?? false,
+ isOcspEnabled: result.internalIsOcspEnabled ?? false
}
: undefined,
externalCa: result
@@ -152,7 +154,8 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
db
.ref("disableManagedCrlDistributionPointUrl")
.withSchema(TableName.InternalCertificateAuthority)
- .as("internalDisableManagedCrlDistributionPointUrl")
+ .as("internalDisableManagedCrlDistributionPointUrl"),
+ db.ref("isOcspEnabled").withSchema(TableName.InternalCertificateAuthority).as("internalIsOcspEnabled")
)
.select(
db.ref("id").withSchema(TableName.ExternalCertificateAuthority).as("externalCaId"),
@@ -192,7 +195,8 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
notAfter: result.internalNotAfter?.toISOString(),
activeCaCertId: result.internalActiveCaCertId,
crlDistributionPointUrls: result.internalCrlDistributionPointUrls ?? [],
- disableManagedCrlDistributionPointUrl: result.internalDisableManagedCrlDistributionPointUrl ?? false
+ disableManagedCrlDistributionPointUrl: result.internalDisableManagedCrlDistributionPointUrl ?? false,
+ isOcspEnabled: result.internalIsOcspEnabled ?? false
}
: undefined,
externalCa: result
@@ -290,7 +294,8 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
db
.ref("disableManagedCrlDistributionPointUrl")
.withSchema(TableName.InternalCertificateAuthority)
- .as("internalDisableManagedCrlDistributionPointUrl")
+ .as("internalDisableManagedCrlDistributionPointUrl"),
+ db.ref("isOcspEnabled").withSchema(TableName.InternalCertificateAuthority).as("internalIsOcspEnabled")
)
.select(
db.ref("id").withSchema(TableName.ExternalCertificateAuthority).as("externalCaId"),
@@ -346,7 +351,8 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
notAfter: ca.internalNotAfter?.toISOString(),
activeCaCertId: ca.internalActiveCaCertId,
crlDistributionPointUrls: ca.internalCrlDistributionPointUrls ?? [],
- disableManagedCrlDistributionPointUrl: ca.internalDisableManagedCrlDistributionPointUrl ?? false
+ disableManagedCrlDistributionPointUrl: ca.internalDisableManagedCrlDistributionPointUrl ?? false,
+ isOcspEnabled: ca.internalIsOcspEnabled ?? false
}
: undefined,
externalCa: ca
diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.test.ts b/backend/src/services/certificate-authority/certificate-authority-fns.test.ts
index 3e8bb1915e..60eaddc945 100644
--- a/backend/src/services/certificate-authority/certificate-authority-fns.test.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-fns.test.ts
@@ -4,7 +4,9 @@ import { describe, expect, it } from "vitest";
import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
import {
+ buildAuthorityInfoAccessExtension,
buildCrlDistributionPointUrls,
+ buildOcspResponderUrl,
createDistinguishedName,
extractDnParts,
signatureAlgorithmToAlgCfg
@@ -315,3 +317,40 @@ describe("extractDnParts", () => {
expect(parts.domainComponents).toEqual(["corp", "com"]);
});
});
+
+describe("buildOcspResponderUrl", () => {
+ it("should build the managed responder URL from the site URL and CA id", () => {
+ expect(buildOcspResponderUrl("https://app.infisical.com", "ca-123")).toBe(
+ "https://app.infisical.com/api/v1/cert-manager/ocsp/ca-123"
+ );
+ });
+});
+
+describe("buildAuthorityInfoAccessExtension", () => {
+ const caIssuerUrl = "https://app.infisical.com/api/v1/cert-manager/ca/internal/ca-123/certificates/c-1/der";
+ const ocspResponderUrl = "https://app.infisical.com/api/v1/cert-manager/ocsp/ca-123";
+
+ it("should emit only caIssuers when no responder URL is given", () => {
+ const parsed = new x509.AuthorityInfoAccessExtension(buildAuthorityInfoAccessExtension({ caIssuerUrl }).rawData);
+
+ expect(parsed.caIssuers?.map((name) => name.value)).toEqual([caIssuerUrl]);
+ expect(parsed.ocsp ?? []).toHaveLength(0);
+ });
+
+ it("should emit both accessMethods when a responder URL is given", () => {
+ const parsed = new x509.AuthorityInfoAccessExtension(
+ buildAuthorityInfoAccessExtension({ caIssuerUrl, ocspResponderUrl }).rawData
+ );
+
+ expect(parsed.caIssuers?.map((name) => name.value)).toEqual([caIssuerUrl]);
+ expect(parsed.ocsp?.map((name) => name.value)).toEqual([ocspResponderUrl]);
+ });
+
+ it("should treat a null responder URL the same as omitting it", () => {
+ const parsed = new x509.AuthorityInfoAccessExtension(
+ buildAuthorityInfoAccessExtension({ caIssuerUrl, ocspResponderUrl: null }).rawData
+ );
+
+ expect(parsed.ocsp ?? []).toHaveLength(0);
+ });
+});
diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.ts
index f9e60d359b..823687a5d8 100644
--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts
@@ -394,12 +394,13 @@ export const getCaCredentials = async ({
certificateAuthoritySecretDAL,
projectDAL,
kmsService,
- signatureAlgorithm
+ signatureAlgorithm,
+ prefetched
}: TGetCaCredentialsDTO) => {
- const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ const ca = prefetched?.ca ?? (await certificateAuthorityDAL.findByIdWithAssociatedCa(caId));
if (!ca?.internalCa?.id) throw new NotFoundError({ message: `Internal CA with ID '${caId}' not found` });
- const caSecret = await certificateAuthoritySecretDAL.findOne({ caId });
+ const caSecret = prefetched?.caSecret ?? (await certificateAuthoritySecretDAL.findOne({ caId }));
if (!caSecret) throw new NotFoundError({ message: `CA secret for CA with ID '${caId}' not found` });
if (!caSecret.encryptedPrivateKey) {
throw new BadRequestError({
@@ -407,11 +408,16 @@ export const getCaCredentials = async ({
});
}
- const keyId = await getProjectKmsCertificateKeyId({
- projectId: ca.projectId,
- projectDAL,
- kmsService
- });
+ // getProjectKmsCertificateKeyId opens a transaction even on its read-only path, so a caller that
+ // already resolved the key skips it. That matters on the OCSP signing path, where the concurrency
+ // cap would otherwise hold one transaction per in-flight signature against a ten-connection pool.
+ const keyId =
+ prefetched?.kmsKeyId ??
+ (await getProjectKmsCertificateKeyId({
+ projectId: ca.projectId,
+ projectDAL,
+ kmsService
+ }));
const kmsDecryptor = await kmsService.decryptWithKmsKey({
kmsId: keyId
@@ -474,7 +480,8 @@ export const getCaSigner = async ({
projectDAL,
kmsService,
hsmConnectorService,
- signatureAlgorithm
+ signatureAlgorithm,
+ prefetched
}: TGetCaSignerDTO): Promise<{
caSecret: Awaited<ReturnType<typeof getCaCredentials>>["caSecret"];
signer: TCaSigner;
@@ -527,7 +534,8 @@ export const getCaSigner = async ({
certificateAuthoritySecretDAL,
projectDAL,
kmsService,
- signatureAlgorithm
+ signatureAlgorithm,
+ prefetched: { ca, caSecret, kmsKeyId: prefetched?.kmsKeyId }
});
const signingAlgorithm = signatureAlgorithm || keyAlgorithmToAlgCfg(keyAlgorithm);
const signer = buildLocalCaSigner({ privateKey: caPrivateKey, publicKey: caPublicKey, signingAlgorithm });
@@ -724,6 +732,21 @@ export const normalizeUrlForComparison = (url: string) => {
}
};
+export const buildOcspResponderUrl = (siteUrl: string, caId: string): string =>
+ `${siteUrl}/api/v1/cert-manager/ocsp/${caId}`;
+
+export const buildAuthorityInfoAccessExtension = ({
+ caIssuerUrl,
+ ocspResponderUrl
+}: {
+ caIssuerUrl: string;
+ ocspResponderUrl?: string | null;
+}): x509.AuthorityInfoAccessExtension =>
+ new x509.AuthorityInfoAccessExtension({
+ caIssuers: new x509.GeneralName("url", caIssuerUrl),
+ ...(ocspResponderUrl ? { ocsp: new x509.GeneralName("url", ocspResponderUrl) } : {})
+ });
+
export const buildCrlDistributionPointUrls = (
managedUrl: string,
customUrls: string[] | null | undefined,
diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts
index c3b55c04ea..65b9bd1a90 100644
--- a/backend/src/services/certificate-authority/certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts
@@ -795,7 +795,11 @@ export const certificateAuthorityServiceFactory = ({
}
const internalConfig = configuration as
- | { crlDistributionPointUrls?: string[]; disableManagedCrlDistributionPointUrl?: boolean }
+ | {
+ crlDistributionPointUrls?: string[];
+ disableManagedCrlDistributionPointUrl?: boolean;
+ isOcspEnabled?: boolean;
+ }
| undefined;
const updatedCa = await internalCertificateAuthorityService.updateCaById({
@@ -804,7 +808,8 @@ export const certificateAuthorityServiceFactory = ({
status,
name,
crlDistributionPointUrls: internalConfig?.crlDistributionPointUrls,
- disableManagedCrlDistributionPointUrl: internalConfig?.disableManagedCrlDistributionPointUrl
+ disableManagedCrlDistributionPointUrl: internalConfig?.disableManagedCrlDistributionPointUrl,
+ isOcspEnabled: internalConfig?.isOcspEnabled
});
if (!updatedCa.internalCa) {
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
index 1d39a70887..2f79a7818c 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
@@ -38,6 +38,7 @@ type TInternalCertificateAuthorityConfiguration = {
activeCaCertId?: string | null;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
+ isOcspEnabled?: boolean;
};
export const InternalCertificateAuthorityConfigurationSchema = z
@@ -82,7 +83,12 @@ export const InternalCertificateAuthorityConfigurationSchema = z
.boolean()
.optional()
.default(false)
- .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.disableManagedCrlDistributionPointUrl)
+ .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.disableManagedCrlDistributionPointUrl),
+ isOcspEnabled: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.isOcspEnabled)
})
.refine(
(data) => {
@@ -116,7 +122,8 @@ export const UpdateInternalCertificateAuthorityConfigurationSchema = z.object({
disableManagedCrlDistributionPointUrl: z
.boolean()
.optional()
- .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.disableManagedCrlDistributionPointUrl)
+ .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.disableManagedCrlDistributionPointUrl),
+ isOcspEnabled: z.boolean().optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.isOcspEnabled)
});
export const UpdateInternalCertificateAuthoritySchema = GenericUpdateCertificateAuthorityFieldsSchema(
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index 4d1832f67e..ac843d5bdb 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -73,7 +73,9 @@ import { TCertificateAuthorityCertDALFactory } from "../certificate-authority-ce
import { TCertificateAuthorityDALFactory, TCertificateAuthorityWithAssociatedCa } from "../certificate-authority-dal";
import { CaStatus, InternalCaType } from "../certificate-authority-enums";
import {
+ buildAuthorityInfoAccessExtension,
buildCrlDistributionPointUrls,
+ buildOcspResponderUrl,
createDistinguishedName,
createSerialNumber,
expandInternalCa,
@@ -186,6 +188,14 @@ export const internalCertificateAuthorityServiceFactory = ({
return plan.caCrl;
};
+ const $isOcspAllowed = async (projectId: string) => {
+ const project = await projectDAL.findById(projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+
+ const plan = await licenseService.getPlan(project.orgId);
+ return plan.pkiOcsp;
+ };
+
// Root CAs: only keyCertSign + cRLSign (they don't perform end-entity operations)
const ROOT_CA_KEY_USAGES = x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign;
// PQC root CAs also need digitalSignature per FIPS 204/205
@@ -320,6 +330,7 @@ export const internalCertificateAuthorityServiceFactory = ({
name,
crlDistributionPointUrls,
disableManagedCrlDistributionPointUrl,
+ isOcspEnabled,
...dto
}: TCreateCaDTO) => {
let projectId: string;
@@ -375,6 +386,15 @@ export const internalCertificateAuthorityServiceFactory = ({
});
}
+ if (isOcspEnabled) {
+ if (!(await $isOcspAllowed(projectId))) {
+ throw new BadRequestError({
+ message:
+ "Failed to create certificate authority with OCSP enabled due to plan restriction. Upgrade plan to use OCSP."
+ });
+ }
+ }
+
const dn = createDistinguishedName({
commonName,
organization,
@@ -578,6 +598,7 @@ export const internalCertificateAuthorityServiceFactory = ({
keyAlgorithm,
crlDistributionPointUrls: crlDistributionPointUrls ?? [],
disableManagedCrlDistributionPointUrl: disableManagedCrlDistributionPointUrl ?? false,
+ isOcspEnabled: isOcspEnabled ?? false,
...(type === InternalCaType.ROOT && {
maxPathLength,
...(notAfter && {
@@ -674,6 +695,7 @@ export const internalCertificateAuthorityServiceFactory = ({
name,
crlDistributionPointUrls,
disableManagedCrlDistributionPointUrl,
+ isOcspEnabled,
...dto
}: TUpdateCaDTO) => {
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
@@ -706,17 +728,30 @@ export const internalCertificateAuthorityServiceFactory = ({
});
}
+ if (isOcspEnabled && !ca.internalCa.isOcspEnabled) {
+ if (!(await $isOcspAllowed(ca.projectId))) {
+ throw new BadRequestError({
+ message: "Failed to enable OCSP due to plan restriction. Upgrade plan to use OCSP."
+ });
+ }
+ }
+
const updatedCa = await certificateAuthorityDAL.transaction(async (tx) => {
if (status !== undefined || name !== undefined) {
await certificateAuthorityDAL.updateById(ca.id, { status, name }, tx);
}
- if (crlDistributionPointUrls !== undefined || disableManagedCrlDistributionPointUrl !== undefined) {
+ if (
+ crlDistributionPointUrls !== undefined ||
+ disableManagedCrlDistributionPointUrl !== undefined ||
+ isOcspEnabled !== undefined
+ ) {
await internalCertificateAuthorityDAL.update(
{ caId: ca.id },
{
...(crlDistributionPointUrls !== undefined && { crlDistributionPointUrls }),
- ...(disableManagedCrlDistributionPointUrl !== undefined && { disableManagedCrlDistributionPointUrl })
+ ...(disableManagedCrlDistributionPointUrl !== undefined && { disableManagedCrlDistributionPointUrl }),
+ ...(isOcspEnabled !== undefined && { isOcspEnabled })
},
tx
);
@@ -1525,9 +1560,7 @@ export const internalCertificateAuthorityServiceFactory = ({
await x509.AuthorityKeyIdentifierExtension.create(caCertObj, false),
await x509.SubjectKeyIdentifierExtension.create(csrObj.publicKey),
...(cdpUrls.length > 0 ? [new x509.CRLDistributionPointsExtension(cdpUrls)] : []),
- new x509.AuthorityInfoAccessExtension({
- caIssuers: new x509.GeneralName("url", caIssuerUrl)
- })
+ buildAuthorityInfoAccessExtension({ caIssuerUrl })
]
});
@@ -2074,6 +2107,9 @@ export const internalCertificateAuthorityServiceFactory = ({
ca.internalCa.disableManagedCrlDistributionPointUrl || !(await $isManagedCrlDistributionAllowed(ca.projectId))
);
+ const ocspResponderUrl =
+ ca.internalCa.isOcspEnabled && appCfg.SITE_URL ? buildOcspResponderUrl(appCfg.SITE_URL, ca.id) : null;
+
const basicConstraintsExtension = $createBasicConstraintsExtension({
basicConstraints,
pathLength,
@@ -2085,9 +2121,7 @@ export const internalCertificateAuthorityServiceFactory = ({
...(cdpUrls.length > 0 ? [new x509.CRLDistributionPointsExtension(cdpUrls)] : []),
await x509.AuthorityKeyIdentifierExtension.create(caCertObj, false),
await x509.SubjectKeyIdentifierExtension.create(csrObj.publicKey),
- new x509.AuthorityInfoAccessExtension({
- caIssuers: new x509.GeneralName("url", caIssuerUrl)
- }),
+ buildAuthorityInfoAccessExtension({ caIssuerUrl, ocspResponderUrl }),
new x509.CertificatePolicyExtension(["2.5.29.32.0"]) // anyPolicy
];
@@ -2500,6 +2534,9 @@ export const internalCertificateAuthorityServiceFactory = ({
ca.internalCa.disableManagedCrlDistributionPointUrl || !(await $isManagedCrlDistributionAllowed(ca.projectId))
);
+ const ocspResponderUrl =
+ ca.internalCa.isOcspEnabled && appCfg.SITE_URL ? buildOcspResponderUrl(appCfg.SITE_URL, ca.id) : null;
+
const basicConstraintsExtension = $createBasicConstraintsExtension({
basicConstraints,
pathLength,
@@ -2511,9 +2548,7 @@ export const internalCertificateAuthorityServiceFactory = ({
await x509.AuthorityKeyIdentifierExtension.create(caCertObj, false),
await x509.SubjectKeyIdentifierExtension.create(csrObj.publicKey),
...(cdpUrls.length > 0 ? [new x509.CRLDistributionPointsExtension(cdpUrls)] : []),
- new x509.AuthorityInfoAccessExtension({
- caIssuers: new x509.GeneralName("url", caIssuerUrl)
- }),
+ buildAuthorityInfoAccessExtension({ caIssuerUrl, ocspResponderUrl }),
new x509.CertificatePolicyExtension(["2.5.29.32.0"]) // anyPolicy
];
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
index eda4274685..b44b1a60fe 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
@@ -58,6 +58,7 @@ export type TCreateCaDTO =
hsmConnectorId?: string;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
+ isOcspEnabled?: boolean;
}
| ({
isInternal: false;
@@ -80,6 +81,7 @@ export type TCreateCaDTO =
hsmConnectorId?: string;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
+ isOcspEnabled?: boolean;
} & Omit<TProjectPermission, "projectId">);
export type TGetCaDTO = {
@@ -94,6 +96,7 @@ export type TUpdateCaDTO =
status?: CaStatus;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
+ isOcspEnabled?: boolean;
}
| ({
isInternal: false;
@@ -102,6 +105,7 @@ export type TUpdateCaDTO =
status?: CaStatus;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
+ isOcspEnabled?: boolean;
} & Omit<TProjectPermission, "projectId">);
export type TDeleteCaDTO = {
@@ -341,6 +345,11 @@ export type TGetCaCredentialsDTO = {
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
signatureAlgorithm?: RsaHashedImportParams | EcKeyImportParams;
+ prefetched?: {
+ ca?: Awaited<ReturnType<TCertificateAuthorityDALFactory["findByIdWithAssociatedCa"]>>;
+ caSecret?: Awaited<ReturnType<TCertificateAuthoritySecretDALFactory["findOne"]>>;
+ kmsKeyId?: string;
+ };
};
export type TGetCaSignerDTO = {
@@ -351,6 +360,7 @@ export type TGetCaSignerDTO = {
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
signatureAlgorithm?: RsaHashedImportParams | EcKeyImportParams;
+ prefetched?: { kmsKeyId?: string };
};
export type TGetCaCertChainsDTO = {
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index 4f168ce0c6..cc6dfab468 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -430,7 +430,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-123",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
},
name: "Test CA",
status: "ACTIVE",
@@ -494,7 +495,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-123",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
}
};
@@ -604,7 +606,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-123",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
},
name: "Test CA",
status: "ACTIVE",
@@ -948,7 +951,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-123",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
},
name: "Test CA",
status: "ACTIVE",
@@ -1063,7 +1067,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-123",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
}
};
@@ -1233,7 +1238,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-123",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
},
name: "Test CA",
status: "ACTIVE",
@@ -1280,7 +1286,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-123",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
}
};
@@ -1696,7 +1703,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-1",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
};
@@ -1869,7 +1877,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-1",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
};
@@ -2042,7 +2051,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-1",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
};
@@ -2215,7 +2225,8 @@ describe("CertificateV3Service", () => {
activeCaCertId: "cert-123",
caId: "ca-1",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
};
@@ -2456,7 +2467,8 @@ describe("CertificateV3Service", () => {
dn: "CN=Test CA,O=Test Org,OU=Test OU,C=US",
serialNumber: "123456789",
crlDistributionPointUrls: [],
- disableManagedCrlDistributionPointUrl: false
+ disableManagedCrlDistributionPointUrl: false,
+ isOcspEnabled: false
}
};
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index beb69ce95a..3ecd7919b1 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -5,6 +5,7 @@ import * as x509 from "@peculiar/x509";
import { ActionProjectType, ProjectMembershipRole, ResourceType } from "@app/db/schemas";
import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
+import { TCertificateAuthorityOcspServiceFactory } from "@app/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
@@ -160,6 +161,7 @@ type TCertificateServiceFactoryDep = {
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
+ certificateAuthorityOcspService: Pick<TCertificateAuthorityOcspServiceFactory, "invalidateCachedResponse">;
};
export type TCertificateServiceFactory = ReturnType<typeof certificateServiceFactory>;
@@ -194,7 +196,8 @@ export const certificateServiceFactory = ({
usageCounterDAL,
keyStore,
usageMeteringService,
- hsmConnectorService
+ hsmConnectorService,
+ certificateAuthorityOcspService
}: TCertificateServiceFactoryDep) => {
const $canActOnCertViaApplication = async (
cert: { applicationId?: string | null; projectId: string },
@@ -536,6 +539,20 @@ export const certificateServiceFactory = ({
throw err;
}
+ if (cert.caId) {
+ try {
+ await certificateAuthorityOcspService.invalidateCachedResponse({
+ caId: cert.caId,
+ serialNumber: cert.serialNumber
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to invalidate OCSP cache after deletion [caId=${cert.caId}] [serialNumber=${cert.serialNumber}]`
+ );
+ }
+ }
+
await triggerSyncsForDeletedCertificate(
cert.id,
pkiSyncIdsHoldingCertificate,
@@ -746,6 +763,18 @@ export const certificateServiceFactory = ({
// rebuild CRL (TODO: move to interval-based cron job)
// Only rebuild CRL for internal CAs - external CAs manage their own CRLs
if (!ca.externalCa?.id) {
+ try {
+ await certificateAuthorityOcspService.invalidateCachedResponse({
+ caId: ca.id,
+ serialNumber: cert.serialNumber
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to invalidate OCSP cache after revocation [caId=${ca.id}] [serialNumber=${cert.serialNumber}]`
+ );
+ }
+
await rebuildCaCrl({
caId: ca.id,
certificateAuthorityDAL,
diff --git a/backend/src/services/license-client/feature-mapping.ts b/backend/src/services/license-client/feature-mapping.ts
index 5893f36c45..c80529ca0f 100644
--- a/backend/src/services/license-client/feature-mapping.ts
+++ b/backend/src/services/license-client/feature-mapping.ts
@@ -250,6 +250,10 @@ const certManagerMappings: TFeatureMapping[] = [
v2Key: "ca_crl",
v1Field: "caCrl"
},
+ {
+ v2Key: "pki_ocsp",
+ v1Field: "pkiOcsp"
+ },
{
v2Key: "pki_est",
v1Field: "pkiEst"
diff --git a/docs/docs.json b/docs/docs.json
index 20e8e16cbb..d7b3231363 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -599,7 +599,8 @@
"pages": [
"documentation/platform/pki/ca/private-ca",
"documentation/platform/pki/ca/ca-renewal",
- "documentation/platform/pki/ca/crl-distribution"
+ "documentation/platform/pki/ca/crl-distribution",
+ "documentation/platform/pki/ca/ocsp"
]
},
{
diff --git a/docs/documentation/platform/pki/ca/ocsp.mdx b/docs/documentation/platform/pki/ca/ocsp.mdx
new file mode 100644
index 0000000000..05cf9aabaa
--- /dev/null
+++ b/docs/documentation/platform/pki/ca/ocsp.mdx
@@ -0,0 +1,126 @@
+---
+title: "OCSP"
+sidebarTitle: "OCSP"
+description: "Answer certificate revocation checks in real time with the Online Certificate Status Protocol."
+---
+
+A CRL tells a validator every certificate an internal CA has ever revoked, and the validator downloads the whole list to check one certificate. The Online Certificate Status Protocol (OCSP, [RFC 6960](https://www.rfc-editor.org/rfc/rfc6960)) answers a narrower question: is this one certificate revoked right now. Infisical runs an OCSP responder for each internal CA that has OCSP enabled.
+
+Load balancers, VPN concentrators, and mutual TLS gateways often check OCSP while ignoring CRLs entirely.
+
+<Info>
+ OCSP is available for internal CAs. A certificate from an external CA such as ACME, DigiCert, AWS Private CA, or Venafi carries its own issuer's responder URL, and only that issuer can answer for it.
+</Info>
+
+## How it works
+
+- Every end-entity certificate issued while OCSP is enabled carries the responder URL in its Authority Information Access extension, which is where validators read it from. Certificates for intermediate CAs aren't covered.
+- A validator sends the certificate's serial number and two hashes identifying the issuer, then receives a signed answer of `good`, `revoked`, or `unknown`.
+- The CA signs the response, so a validator can verify it without trusting the transport.
+- Revoking a certificate changes the answer Infisical returns straight away. How soon a validator sees the change depends on how long it caches the previous response.
+- A serial the CA never issued returns `unknown` rather than `good`.
+
+<Note>
+ Only certificates issued **after** OCSP is enabled carry the responder URL. Enabling OCSP doesn't change certificates that already exist, so reissue one if it needs to be checkable over OCSP.
+</Note>
+
+## Prerequisites
+
+- An internal CA with a certificate installed.
+- The Enterprise plan.
+- A responder URL your validators can reach. Infisical builds it from the instance URL, so a self-hosted instance that validators can't resolve needs a reachable address configured first.
+
+## Enable OCSP
+
+<Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step title="Open the CA">
+ Go to **Certificate Authorities** and select the internal CA.
+ </Step>
+ <Step title="Edit the OCSP card">
+ Select the pencil icon on the **OCSP** card.
+ </Step>
+ <Step title="Turn OCSP on">
+ Turn on **Enable OCSP**, then select **Save**.
+ </Step>
+ <Step title="Copy the responder URL">
+ The **OCSP** card now shows the responder URL. Certificates issued from this point carry it.
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ Set `isOcspEnabled` under `configuration` when you create or update an internal CA.
+
+ ### Enable on an existing CA
+
+ ```bash
+ curl --location --request PATCH 'https://app.infisical.com/api/v1/cert-manager/ca/internal/<ca-id>' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "configuration": {
+ "isOcspEnabled": true
+ }
+ }'
+ ```
+
+ ### Enable at creation
+
+ ```bash
+ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal' \
+ --header 'Authorization: Bearer <access-token>' \
+ --header 'Content-Type: application/json' \
+ --data-raw '{
+ "name": "my-internal-ca",
+ "configuration": {
+ "type": "root",
+ "commonName": "My Root CA",
+ "keyAlgorithm": "RSA_2048",
+ "isOcspEnabled": true
+ }
+ }'
+ ```
+
+ Turning `isOcspEnabled` off stops the responder answering for this CA and removes the URL from certificates issued afterwards. Certificates already carrying the URL get an `unauthorized` response, which RFC 6960 defines for a responder that can no longer answer authoritatively. Validators that require a status treat those certificates as uncheckable, so turn OCSP off only once you no longer need revocation checking for the certificates you have already issued.
+ </Tab>
+</Tabs>
+
+## Verify the responder
+
+Use `openssl` with the certificate and its issuer:
+
+```bash
+openssl ocsp -issuer ca.pem -cert certificate.pem \
+ -url https://app.infisical.com/api/v1/cert-manager/ocsp/<ca-id> \
+ -CAfile ca.pem
+```
+
+A working responder prints `Response verify OK` followed by the status:
+
+```
+Response verify OK
+certificate.pem: good
+ This Update: Sep 21 13:29:42 2026 GMT
+ Next Update: Sep 21 14:29:42 2026 GMT
+```
+
+## OCSP stapling
+
+OCSP stapling allows a server to include the OCSP response for its own certificate in the TLS handshake, so clients receive the revocation status without querying the responder themselves.
+
+Stapling is optional and is configured on the server that presents the certificate, not in Infisical. Enabling it reduces handshake latency and keeps connections working during a brief responder outage.
+
+```nginx
+ssl_stapling on;
+ssl_stapling_verify on;
+resolver 1.1.1.1 8.8.8.8 valid=300s;
+```
+
+<Note>
+ Stapling only applies to certificates a server presents. When a server validates a client certificate, such as in mutual TLS, stapling doesn't apply and each check queries the responder directly.
+</Note>
+
+## Limitations
+
+- Certificates issued before OCSP was enabled don't carry the responder URL.
diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.ts
index 6c2af91dcb..103bd8afa7 100644
--- a/frontend/src/hooks/api/ca/types.ts
+++ b/frontend/src/hooks/api/ca/types.ts
@@ -168,6 +168,7 @@ export type TInternalCertificateAuthority = {
activeCaCertId?: string;
crlDistributionPointUrls?: string[];
disableManagedCrlDistributionPointUrl?: boolean;
+ isOcspEnabled?: boolean;
};
};
diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.ts
index 555d58f2bd..908ea223ea 100644
--- a/frontend/src/hooks/api/subscriptions/types.ts
+++ b/frontend/src/hooks/api/subscriptions/types.ts
@@ -66,6 +66,7 @@ export type SubscriptionPlan = {
pkiScep: boolean;
pkiPqc: boolean;
caCrl: boolean;
+ pkiOcsp: boolean;
pkiEnterpriseCaIntegrations: boolean;
pkiExternalIntermediateCa: boolean;
pkiDiscovery: boolean;
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
index 0f527504ba..01a4668c2b 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
@@ -38,6 +38,7 @@ import {
CaDistributionPointsSection,
CaGenerateRootCertModal,
CaIssuerUrlSection,
+ CaOcspSection,
CaRenewalModal,
CaSigningConfigSection
} from "./components";
@@ -193,6 +194,7 @@ const Page = () => {
<CaIssuerUrlSection caId={data.id} />
<CaCrlsSection caId={data.id} />
<CaDistributionPointsSection caId={data.id} />
+ <CaOcspSection caId={data.id} />
</div>
</div>
</div>
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaOcspSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaOcspSection.tsx
new file mode 100644
index 0000000000..2416722411
--- /dev/null
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaOcspSection.tsx
@@ -0,0 +1,203 @@
+import { Controller, useForm } from "react-hook-form";
+import { subject } from "@casl/ability";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { PencilIcon } from "lucide-react";
+import { z } from "zod";
+
+import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
+import { createNotification } from "@app/components/notifications";
+import { ProjectPermissionCan } from "@app/components/permissions";
+import {
+ Button as ButtonV2,
+ FormControl,
+ Modal,
+ ModalClose,
+ ModalContent,
+ Switch
+} from "@app/components/v2";
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Detail,
+ DetailGroup,
+ DetailLabel,
+ DetailValue,
+ IconButton
+} from "@app/components/v3";
+import {
+ ProjectPermissionCertificateAuthorityActions,
+ ProjectPermissionSub,
+ useSubscription
+} from "@app/context";
+import { CaType, useGetCa, useUpdateCa } from "@app/hooks/api";
+import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";
+import { usePopUp } from "@app/hooks/usePopUp";
+
+type Props = {
+ caId: string;
+};
+
+const editSchema = z.object({
+ isOcspEnabled: z.boolean().default(false)
+});
+
+type EditFormData = z.infer<typeof editSchema>;
+
+export const CaOcspSection = ({ caId }: Props) => {
+ const { popUp, handlePopUpToggle } = usePopUp(["editOcsp", "upgradePlan"] as const);
+ const { subscription } = useSubscription();
+
+ const { data } = useGetCa({ caId, type: CaType.INTERNAL });
+ const ca = data as TInternalCertificateAuthority | undefined;
+
+ const { mutateAsync: updateCa } = useUpdateCa();
+
+ const {
+ control,
+ handleSubmit,
+ reset,
+ formState: { isSubmitting }
+ } = useForm<EditFormData>({
+ resolver: zodResolver(editSchema),
+ values: {
+ isOcspEnabled: ca?.configuration.isOcspEnabled ?? false
+ }
+ });
+
+ if (!ca) return null;
+
+ const isOcspEnabled = ca.configuration.isOcspEnabled ?? false;
+ const ocspResponderUrl = `${window.origin}/api/v1/cert-manager/ocsp/${ca.id}`;
+
+ const handleEdit = () => {
+ if (!isOcspEnabled && !subscription.pkiOcsp) {
+ handlePopUpToggle("upgradePlan", true);
+ return;
+ }
+ handlePopUpToggle("editOcsp", true);
+ };
+
+ const onEditSubmit = async (values: EditFormData) => {
+ try {
+ await updateCa({
+ id: ca.id,
+ type: CaType.INTERNAL,
+ configuration: {
+ isOcspEnabled: values.isOcspEnabled
+ } as TInternalCertificateAuthority["configuration"]
+ });
+ createNotification({
+ text: values.isOcspEnabled ? "OCSP enabled" : "OCSP disabled",
+ type: "success"
+ });
+ handlePopUpToggle("editOcsp", false);
+ } catch {
+ createNotification({
+ text: "Failed to update OCSP",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <>
+ <Card className="w-full">
+ <CardHeader className="border-b">
+ <CardTitle>OCSP</CardTitle>
+ <CardDescription>Answer revocation status checks for issued certificates</CardDescription>
+ <CardAction>
+ <ProjectPermissionCan
+ I={ProjectPermissionCertificateAuthorityActions.Edit}
+ a={subject(ProjectPermissionSub.CertificateAuthorities, { name: ca.name })}
+ >
+ {(isAllowed) => (
+ <IconButton
+ variant="outline"
+ size="xs"
+ isDisabled={!isAllowed}
+ onClick={handleEdit}
+ >
+ <PencilIcon />
+ </IconButton>
+ )}
+ </ProjectPermissionCan>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ <DetailGroup>
+ <Detail>
+ <DetailLabel>Status</DetailLabel>
+ <DetailValue>{isOcspEnabled ? "Enabled" : "Disabled"}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Responder URL</DetailLabel>
+ <DetailValue>
+ {isOcspEnabled ? (
+ <span className="break-all">{ocspResponderUrl}</span>
+ ) : (
+ <span className="text-muted">—</span>
+ )}
+ </DetailValue>
+ </Detail>
+ </DetailGroup>
+ </CardContent>
+ </Card>
+
+ <Modal
+ isOpen={popUp.editOcsp.isOpen}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("editOcsp", isOpen);
+ if (!isOpen) reset();
+ }}
+ >
+ <ModalContent title="Edit OCSP">
+ <form onSubmit={handleSubmit(onEditSubmit)}>
+ <Controller
+ control={control}
+ name="isOcspEnabled"
+ render={({ field: { value, onChange } }) => (
+ <FormControl helperText="Only certificates issued after OCSP is enabled carry the responder URL.">
+ <Switch
+ id="isOcspEnabled"
+ className="bg-muted/80 shadow-inner data-[state=checked]:bg-success/80"
+ thumbClassName="bg-surface-raised"
+ isChecked={value}
+ onCheckedChange={onChange}
+ >
+ Enable OCSP
+ </Switch>
+ </FormControl>
+ )}
+ />
+ <div className="flex w-full justify-between gap-4 pt-4">
+ <ModalClose asChild>
+ <ButtonV2 colorSchema="secondary" variant="plain">
+ Cancel
+ </ButtonV2>
+ </ModalClose>
+ <ButtonV2
+ type="submit"
+ colorSchema="secondary"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ Save
+ </ButtonV2>
+ </div>
+ </form>
+ </ModalContent>
+ </Modal>
+
+ <UpgradePlanModal
+ paywallKey="cert-manager.ca-ocsp"
+ isOpen={popUp.upgradePlan.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
+ text="OCSP is available on Infisical's Enterprise plan."
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
index 2e859e78dd..3f1e8639a9 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/index.tsx
@@ -5,5 +5,6 @@ export { CaDetailsSection } from "./CaDetailsSection";
export { CaDistributionPointsSection } from "./CaDistributionPointsSection";
export { CaGenerateRootCertModal } from "./CaGenerateRootCertModal";
export { CaIssuerUrlSection } from "./CaIssuerUrlSection";
+export { CaOcspSection } from "./CaOcspSection";
export { CaRenewalModal } from "./CaRenewalModal";
export { CaSigningConfigSection } from "./CaSigningConfigSection";