Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
validate single hop
Thiago Araujo da Silva8b0f170e3359
diff --git a/backend/e2e-test/routes/v1/identity-tls-cert-auth.spec.ts b/backend/e2e-test/routes/v1/identity-tls-cert-auth.spec.tsindex 8923523a17..4f943b56a3 100644--- a/backend/e2e-test/routes/v1/identity-tls-cert-auth.spec.ts+++ b/backend/e2e-test/routes/v1/identity-tls-cert-auth.spec.ts@@ -67,10 +67,7 @@ const makeIntermediate = async (signingKey: issuer.keys.privateKey,publicKey: keys.publicKey,signingAlgorithm: SIGNING_ALGORITHM,- extensions: [- new x509.BasicConstraintsExtension(true, opts?.pathLength, true),- ...(opts?.extraExtensions ?? [])- ]+ extensions: [new x509.BasicConstraintsExtension(true, opts?.pathLength, true), ...(opts?.extraExtensions ?? [])]});return { cert, keys };};@@ -121,11 +118,7 @@ const deleteIdentity = async (identityId: string) => {expect(res.statusCode).toBe(200);};-const attachTlsCertAuth = async (- identityId: string,- caCertificate: string,- verifyClientCertificateChain: boolean-) => {+const attachTlsCertAuth = async (identityId: string, caCertificate: string, verifyClientCertificateChain: boolean) => {const res = await testServer.inject({method: "POST",url: `/api/v1/auth/tls-cert-auth/identities/${identityId}`,diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.tsindex f1946d3e42..4706fb0c82 100644--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.ts+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.ts@@ -13,7 +13,8 @@ import {permitsClientAuth,readSubjectAltNames,TCertificateSanItem,- verifyClientCertificateChain+ verifyClientCertificateChain,+ verifyDirectlyIssuedClientCertificate} from "./identity-tls-cert-auth-fns";// The singleton logger is only initialized by the server bootstrap, so it is undefined under vitest.@@ -357,6 +358,143 @@ describe("readSubjectAltNames", () => {});});+describe("verifyDirectlyIssuedClientCertificate", () => {+ const alg: RsaHashedKeyGenParams = {+ name: "RSASSA-PKCS1-v1_5",+ hash: "SHA-256",+ publicExponent: new Uint8Array([1, 0, 1]),+ modulusLength: 2048+ };++ x509.cryptoProvider.set(crypto.webcrypto as Crypto);++ const NOW = new Date("2026-06-24T12:00:00Z");+ const NOT_BEFORE = new Date("2026-06-01T00:00:00Z");+ const FAR_FUTURE = new Date("2030-01-01T00:00:00Z");++ const toNative = (cert: x509.X509Certificate) => new crypto.X509Certificate(Buffer.from(cert.rawData));++ const makeCa = async (+ name: string,+ opts?: { notAfter?: Date; extensions?: x509.Extension[]; omitBasicConstraints?: boolean }+ ) => {+ const keys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);+ const cert = await x509.X509CertificateGenerator.createSelfSigned({+ serialNumber: "01",+ name: `CN=${name}`,+ notBefore: NOT_BEFORE,+ notAfter: opts?.notAfter ?? FAR_FUTURE,+ keys,+ extensions: [+ ...(opts?.omitBasicConstraints ? [] : [new x509.BasicConstraintsExtension(true, undefined, true)]),+ ...(opts?.extensions ?? [])+ ]+ });+ return { cert, keys };+ };++ const makeLeaf = async (issuer: { cert: x509.X509Certificate; keys: CryptoKeyPair }, dnsName: string) => {+ const keys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);+ const cert = await x509.X509CertificateGenerator.create({+ serialNumber: "02",+ subject: "CN=workload",+ issuer: issuer.cert.subject,+ notBefore: NOT_BEFORE,+ notAfter: FAR_FUTURE,+ signingKey: issuer.keys.privateKey,+ publicKey: keys.publicKey,+ signingAlgorithm: alg,+ extensions: [+ new x509.BasicConstraintsExtension(false),+ new x509.SubjectAlternativeNameExtension([{ type: "dns", value: dnsName }])+ ]+ });+ return { cert, keys };+ };++ const permittedDnsConstraint = (permitted: string[]) =>+ new x509.Extension(+ "2.5.29.30",+ true,+ new NameConstraints({+ permittedSubtrees: permitted.map(+ (dns) => new GeneralSubtree({ base: new GeneralName({ type: 2, value: dns }) })+ )+ })+ .toSchema()+ .toBER(false)+ );++ test("accepts a leaf the configured CA issued", async () => {+ const ca = await makeCa("Root CA");+ const leaf = await makeLeaf(ca, "workload.example.com");++ expect(+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })+ ).toEqual({ ok: true });+ });++ test("rejects a leaf a different CA issued", async () => {+ const ca = await makeCa("Root CA");+ const otherCa = await makeCa("Other CA");+ const leaf = await makeLeaf(otherCa, "workload.example.com");++ expect(+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })+ ).toEqual({ ok: false, reasonCode: "ca_verification_failed" });+ });++ test("rejects when the configured CA has expired", async () => {+ const ca = await makeCa("Expired CA", { notAfter: new Date("2026-06-10T00:00:00Z") });+ const leaf = await makeLeaf(ca, "workload.example.com");++ expect(+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })+ ).toEqual({ ok: false, reasonCode: "certificate_expired" });+ });++ test("rejects when the configured CA's extended key usage excludes client authentication", async () => {+ const ca = await makeCa("ServerAuth CA", {+ extensions: [new x509.ExtendedKeyUsageExtension(["1.3.6.1.5.5.7.3.1"], true)]+ });+ const leaf = await makeLeaf(ca, "workload.example.com");++ expect(+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })+ ).toEqual({ ok: false, reasonCode: "issuer_client_auth_usage_not_allowed" });+ });++ test("accepts a leaf inside the namespace its CA is permitted to certify", async () => {+ const ca = await makeCa("Constrained CA", { extensions: [permittedDnsConstraint(["example.com"])] });+ const leaf = await makeLeaf(ca, "workload.example.com");++ expect(+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })+ ).toEqual({ ok: true });+ });++ test("rejects a leaf outside the namespace its CA is permitted to certify", async () => {+ const ca = await makeCa("Constrained CA", { extensions: [permittedDnsConstraint(["allowed.example.com"])] });+ const leaf = await makeLeaf(ca, "workload.elsewhere.com");++ expect(+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })+ ).toEqual({ ok: false, reasonCode: "name_constraint_violation" });+ });++ // Single-hop has always accepted a configured CA that omits basic constraints, unlike the path+ // builder, which will not walk through a certificate that does not assert CA:TRUE.+ test("accepts a configured CA that omits basic constraints", async () => {+ const ca = await makeCa("Constraint-less CA", { omitBasicConstraints: true });+ const leaf = await makeLeaf(ca, "workload.example.com");++ expect(toNative(ca.cert).ca).toBe(false);+ expect(+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })+ ).toEqual({ ok: true });+ });+});+describe("verifyClientCertificateChain", () => {const alg: RsaHashedKeyGenParams = {name: "RSASSA-PKCS1-v1_5",diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.tsindex 4dd5fd9305..d4df4e1fdc 100644--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.ts+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.ts@@ -73,6 +73,39 @@ const isWithinValidityWindow = (cert: TNativeX509, at: Date): boolean =>const isSelfIssued = (cert: TNativeX509): boolean => cert.subject === cert.issuer;+const validityFailure = (cert: TNativeX509, at: Date): TVerificationFailure | null =>+ isWithinValidityWindow(cert, at)+ ? null+ : {+ ok: false,+ reasonCode: at < new Date(cert.validFrom) ? "certificate_not_yet_valid" : "certificate_expired"+ };++/**+ * Returns true when `issuer` issued `child`.+ *+ * The name check compares the OpenSSL-formatted DN strings returned by Node's X509Certificate+ * (`child.issuer === issuer.subject`). This is a fast pre-filter before the cryptographic `verify`,+ * and assumes both sides of the chain share the same PKI-level DN encoding conventions, i.e. the+ * same string types (PrintableString vs UTF8String) and attribute ordering for equivalent names.+ * That holds within a single PKI (SPIRE emits the leaf and the rotating intermediate from one CA+ * with consistent encoding), which is the supported case here.+ *+ * It can yield a false negative in a heterogeneous PKI where the issuer and subject encode the same+ * logical DN differently (e.g. one cert uses PrintableString and the other UTF8String for an+ * attribute, or they differ in attribute ordering). In that situation a cryptographically valid+ * issuer relationship is rejected and validation fails with `ca_verification_failed`. A full+ * RFC 5280 name comparison (per-RDN, encoding-insensitive) would be required to support that.+ */+const issuedBy = (child: TNativeX509, issuer: TNativeX509): boolean => {+ if (child.issuer !== issuer.subject) return false;+ try {+ return child.verify(issuer.publicKey);+ } catch {+ return false;+ }+};+const basicConstraintsPathLength = (cert: TNativeX509): number | undefined =>new x509.X509Certificate(cert.raw).getExtension(x509.BasicConstraintsExtension)?.pathLength;@@ -176,6 +209,46 @@ export const permitsClientAuth = (cert: TNativeX509): boolean => {return usages.some((oid) => oid === CLIENT_AUTH_EKU_OID || oid === ANY_PURPOSE_EKU_OID);};+/**+ * Validate a client certificate the configured CA is expected to have issued directly.+ *+ * This is the default mode, where no intermediates are involved: the configured CA either signed+ * the presented leaf or it did not. It still applies every rule the path-building mode applies to a+ * one-hop path, because the rules belong to the CA rather than to the length of the path. A CA that+ * has expired, or whose extended key usage does not cover client authentication, cannot authenticate+ * a client in either mode, and a leaf outside the namespace its CA is permitted to certify is+ * outside it whether or not intermediates were presented.+ *+ * Unlike the path-building mode, the anchor is not required to assert `CA:TRUE`. It is configured by+ * an operator rather than presented by the client, and a self-signed certificate that omits basic+ * constraints entirely has always been accepted here.+ *+ * @param leaf the end-entity certificate presented by the client+ * @param ca the configured CA certificate that must have issued it+ */+export const verifyDirectlyIssuedClientCertificate = async ({+ leaf,+ ca,+ now = new Date()+}: {+ leaf: TNativeX509;+ ca: TNativeX509;+ now?: Date;+}): Promise<TVerifyClientCertificateChainResult> => {+ if (!issuedBy(leaf, ca)) return { ok: false, reasonCode: "ca_verification_failed" };++ const caFailure =+ validityFailure(ca, now) ??+ (permitsClientAuth(ca) ? null : ({ ok: false, reasonCode: "issuer_client_auth_usage_not_allowed" } as const));+ if (caFailure) return caFailure;++ try {+ return (await enforceNameConstraints([leaf, ca], now)) ?? { ok: true };+ } catch {+ return { ok: false, reasonCode: "ca_verification_failed" };+ }+};+/*** Validate the presented client certificate chain against a configured trust anchor.*@@ -201,7 +274,7 @@ export const permitsClientAuth = (cert: TNativeX509): boolean => {** NOTE: each hop's issuer/subject match is a string comparison of the OpenSSL-formatted DN strings,* so this assumes every certificate on the path shares the same PKI-level DN encoding conventions- * (string types and attribute ordering). See `issuedBy` below for the heterogeneous-PKI caveat.+ * (string types and attribute ordering). See `issuedBy` above for the heterogeneous-PKI caveat.** @param leaf the end-entity certificate presented by the client (chain[0])* @param presentedChain intermediates presented by the client (chain[1..n]); order-independent@@ -230,39 +303,13 @@ export const verifyClientCertificateChain = async ({const anchorId = certificateId(trustAnchor);const isAnchor = (cert: TNativeX509): boolean => certificateId(cert) === anchorId;- /**- * Returns true when `issuer` issued `child`.- *- * The name check compares the OpenSSL-formatted DN strings returned by Node's X509Certificate- * (`child.issuer === issuer.subject`). This is a fast pre-filter before the cryptographic- * `verify`, and assumes both sides of the chain share the same PKI-level DN encoding- * conventions, i.e. the same string types (PrintableString vs UTF8String) and attribute- * ordering for equivalent names. That holds within a single PKI (SPIRE emits the leaf and the- * rotating intermediate from one CA with consistent encoding), which is the supported case here.- *- * It can yield a false negative in a heterogeneous PKI where the issuer and subject encode the- * same logical DN differently (e.g. one cert uses PrintableString and the other UTF8String for an- * attribute, or they differ in attribute ordering). In that situation a cryptographically valid- * issuer relationship is rejected and chain validation fails with `ca_verification_failed`. A- * full RFC 5280 name comparison (per-RDN, encoding-insensitive) would be required to support that.- *- * Results are cached per (child, issuer) pair, so overlapping paths through a shared issuer cost- * one signature verification rather than one per path.- */const signatureResults = new Map<string, boolean>();- const issuedBy = (child: TNativeX509, issuer: TNativeX509): boolean => {- if (child.issuer !== issuer.subject) return false;-+ const issuedByCached = (child: TNativeX509, issuer: TNativeX509): boolean => {const pairId = `${certificateId(child)}:${certificateId(issuer)}`;const cached = signatureResults.get(pairId);if (cached !== undefined) return cached;- let verified: boolean;- try {- verified = child.verify(issuer.publicKey);- } catch {- verified = false;- }+ const verified = issuedBy(child, issuer);signatureResults.set(pairId, verified);return verified;};@@ -277,14 +324,6 @@ export const verifyClientCertificateChain = async ({return permitted;};- const validityFailure = (cert: TNativeX509): TVerificationFailure | null =>- isWithinValidityWindow(cert, now)- ? null- : {- ok: false,- reasonCode: now < new Date(cert.validFrom) ? "certificate_not_yet_valid" : "certificate_expired"- };-/*** The gate every issuer clears before it may extend a path. Both properties belong to the* certificate alone rather than to the path it sits on, so failing one rules out this branch@@ -295,10 +334,10 @@ export const verifyClientCertificateChain = async ({* purpose against the whole chain rather than the leaf alone.*/const issuerFailure = (issuer: TNativeX509): TVerificationFailure | null =>- validityFailure(issuer) ??+ validityFailure(issuer, now) ??(issuerPermitsClientAuth(issuer) ? null : { ok: false, reasonCode: "issuer_client_auth_usage_not_allowed" });- const leafFailure = validityFailure(leaf);+ const leafFailure = validityFailure(leaf, now);if (leafFailure) return leafFailure;const candidateIssuers: TNativeX509[] = [];@@ -333,14 +372,16 @@ export const verifyClientCertificateChain = async ({return;}- if (trustAnchor.ca && issuedBy(current, trustAnchor)) {+ if (trustAnchor.ca && issuedByCached(current, trustAnchor)) {const anchorFailure = issuerFailure(trustAnchor);if (anchorFailure) search.prunedFailure ??= anchorFailure;else completePaths.push([...path, trustAnchor]);}candidateIssuers- .filter((candidate) => !visited.has(certificateId(candidate)) && candidate.ca && issuedBy(current, candidate))+ .filter(+ (candidate) => !visited.has(certificateId(candidate)) && candidate.ca && issuedByCached(current, candidate)+ ).forEach((candidate) => {const candidateFailure = issuerFailure(candidate);if (candidateFailure) {diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.tsindex 540d1aa6ce..d0caac9c11 100644--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts@@ -51,7 +51,8 @@ import {readSubjectAltNames,serializeAllowedSubjectAltNames,TVerifyClientCertificateChainResult,- verifyClientCertificateChain+ verifyClientCertificateChain,+ verifyDirectlyIssuedClientCertificate} from "./identity-tls-cert-auth-fns";import { TIdentityTlsCertAuthServiceFactory } from "./identity-tls-cert-auth-types";@@ -179,23 +180,19 @@ export const identityTlsCertAuthServiceFactory = ({}} else {// Single-hop mode (default): the configured CA must be the direct issuer of the leaf.- const isValidCertificate = clientCertificateX509.verify(caCertificateX509.publicKey);- if (!isValidCertificate)- throw new UnauthorizedError({- message: "Access denied: Certificate not issued by the provided CA.",- detail: {- reasonCode: "ca_verification_failed",- identityId: identity.id,- orgId: identity.orgId,- identityName: identity.name- }- });+ const directResult = await verifyDirectlyIssuedClientCertificate({+ leaf: clientCertificateX509,+ ca: caCertificateX509+ });- if (!permitsClientAuth(caCertificateX509)) {+ if (!directResult.ok) {throw new UnauthorizedError({- message: CHAIN_FAILURE_MESSAGES.issuer_client_auth_usage_not_allowed,+ message:+ directResult.reasonCode === "ca_verification_failed"+ ? "Access denied: Certificate not issued by the provided CA."+ : CHAIN_FAILURE_MESSAGES[directResult.reasonCode],detail: {- reasonCode: "issuer_client_auth_usage_not_allowed",+ reasonCode: directResult.reasonCode,identityId: identity.id,orgId: identity.orgId,identityName: identity.name