Skip to content

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

fix hostname constrain

Thiago Araujo da Silva60bcfecb4ee2
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.ts
index 9342d8043b..6e61bbdb57 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
@@ -38,6 +38,17 @@ const permittedDnsConstraint = (permitted: string[]) =>
.toBER(false)
);
+const permittedUriConstraint = (permitted: string[]) =>
+ new x509.Extension(
+ "2.5.29.30",
+ true,
+ new NameConstraints({
+ permittedSubtrees: permitted.map((uri) => new GeneralSubtree({ base: new GeneralName({ type: 6, value: uri }) }))
+ })
+ .toSchema()
+ .toBER(false)
+ );
+
const makeRoot = async (name: string, extraExtensions: x509.Extension[] = []): Promise<TIssued> => {
const keys = await generateKeys();
const cert = await x509.X509CertificateGenerator.createSelfSigned({
@@ -75,7 +86,7 @@ const makeIntermediate = async (
const makeLeaf = async (
name: string,
issuer: TIssued,
- opts?: { usages?: string[]; dnsName?: string }
+ opts?: { usages?: string[]; dnsName?: string; uri?: string }
): Promise<TIssued> => {
const keys = await generateKeys();
const cert = await x509.X509CertificateGenerator.create({
@@ -90,7 +101,8 @@ const makeLeaf = async (
extensions: [
new x509.BasicConstraintsExtension(false),
...(opts?.usages ? [ekuExtension(opts.usages)] : []),
- ...(opts?.dnsName ? [new x509.SubjectAlternativeNameExtension([{ type: "dns", value: opts.dnsName }])] : [])
+ ...(opts?.dnsName ? [new x509.SubjectAlternativeNameExtension([{ type: "dns", value: opts.dnsName }])] : []),
+ ...(opts?.uri ? [new x509.SubjectAlternativeNameExtension([{ type: "url", value: opts.uri }])] : [])
]
});
return { cert, keys };
@@ -191,6 +203,34 @@ describe("Identity TLS certificate auth v1", async () => {
await deleteIdentity(identity.id);
}
});
+
+ // A URI name constraint restricts the host, so one written the way a SPIFFE ID looks matches
+ // nothing and would deny every login. Refusing it at attach names the CA as the problem.
+ test("refuses to attach a CA whose URI name constraint is not a domain", async () => {
+ const ca = await makeRoot("Scheme URI CA", [permittedUriConstraint(["spiffe://example.org"])]);
+ const identity = await createIdentity(`tls-cert-auth-${nextSerial()}`);
+
+ try {
+ const res = await attachTlsCertAuth(identity.id, toPem(ca.cert), false);
+ expect(res.statusCode).toBe(400);
+ expect(res.json().message).toContain("is not a fully qualified domain name");
+ } finally {
+ await deleteIdentity(identity.id);
+ }
+ });
+
+ test("attaches a CA whose URI name constraint is a domain", async () => {
+ const ca = await makeRoot("Domain URI CA", [permittedUriConstraint(["example.org"])]);
+ const leaf = await makeLeaf("workload", ca, {
+ usages: [CLIENT_AUTH_EKU],
+ uri: "spiffe://example.org/ns/default/sa/svc"
+ });
+
+ await withIdentity({ caCertificate: ca.cert, verifyChain: false }, async (identityId) => {
+ const res = await login(identityId, [leaf.cert]);
+ expect(res.statusCode).toBe(200);
+ });
+ });
});
describe("trust anchor mode", async () => {
@@ -237,6 +277,25 @@ describe("Identity TLS certificate auth v1", async () => {
});
});
+ // The anchor is screened when it is configured, but a presented intermediate is not, so the
+ // login has to report the CA rather than the client's name.
+ test("denies a chain through an intermediate whose URI name constraint is not a domain", async () => {
+ const root = await makeRoot("Stable Root CA");
+ const constrained = await makeIntermediate("Scheme URI Intermediate CA", root, {
+ extraExtensions: [permittedUriConstraint(["spiffe://example.org"])]
+ });
+ const leaf = await makeLeaf("workload", constrained, {
+ usages: [CLIENT_AUTH_EKU],
+ uri: "spiffe://example.org/ns/default/sa/svc"
+ });
+
+ await withIdentity({ caCertificate: root.cert, verifyChain: true }, async (identityId) => {
+ const res = await login(identityId, [leaf.cert, constrained.cert]);
+ expect(res.statusCode).toBe(401);
+ expect(res.json().message).toContain("is not a fully qualified domain name");
+ });
+ });
+
test("denies a chain deeper than a CA's path length permits", async () => {
const root = await makeRoot("Stable Root CA");
const limited = await makeIntermediate("PathLen Zero CA", root, { pathLength: 0 });
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.ts
index 71d7a1f9b7..8f5161482e 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
@@ -6,6 +6,7 @@ import { GeneralName, GeneralSubtree, NameConstraints } from "pkijs";
import { beforeAll, describe, expect, test, vi } from "vitest";
import {
+ findNameConstraintsProblem,
isSubjectAltNameAllowed,
isValidAllowedSubjectAltNameEntry,
normalizeAllowedSubjectAltName,
@@ -372,6 +373,33 @@ const schemaMismatchedNameConstraint = () =>
const undecodableNameConstraint = () => new x509.Extension("2.5.29.30", true, new Uint8Array([0x99, 0x99, 0x99]));
+// eslint-disable-next-line no-bitwise
+const NON_SIGNING_KEY_USAGE = x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.cRLSign;
+
+const uriConstraint = (subtrees: { permitted?: string[]; excluded?: string[] }) =>
+ new x509.Extension(
+ "2.5.29.30",
+ true,
+ new NameConstraints({
+ ...(subtrees.permitted
+ ? {
+ permittedSubtrees: subtrees.permitted.map(
+ (uri) => new GeneralSubtree({ base: new GeneralName({ type: 6, value: uri }) })
+ )
+ }
+ : {}),
+ ...(subtrees.excluded
+ ? {
+ excludedSubtrees: subtrees.excluded.map(
+ (uri) => new GeneralSubtree({ base: new GeneralName({ type: 6, value: uri }) })
+ )
+ }
+ : {})
+ })
+ .toSchema()
+ .toBER(false)
+ );
+
describe("verifyDirectlyIssuedClientCertificate", () => {
const alg: RsaHashedKeyGenParams = {
name: "RSASSA-PKCS1-v1_5",
@@ -431,6 +459,25 @@ describe("verifyDirectlyIssuedClientCertificate", () => {
return { cert, keys };
};
+ const makeLeafWithUriSan = async (issuer: { cert: x509.X509Certificate; keys: CryptoKeyPair }, uri: 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: "url", value: uri }])
+ ]
+ });
+ return { cert, keys };
+ };
+
const permittedDnsConstraint = (permitted: string[]) =>
new x509.Extension(
"2.5.29.30",
@@ -469,7 +516,7 @@ describe("verifyDirectlyIssuedClientCertificate", () => {
expect(
await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })
- ).toEqual({ ok: false, reasonCode: "certificate_expired" });
+ ).toEqual({ ok: false, reasonCode: "issuer_certificate_expired" });
});
test("rejects when the configured CA's extended key usage excludes client authentication", async () => {
@@ -501,6 +548,19 @@ describe("verifyDirectlyIssuedClientCertificate", () => {
).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
});
+ test("rejects a leaf that is not yet valid", 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: new Date("2026-05-01T00:00:00Z")
+ })
+ ).toEqual({ ok: false, reasonCode: "certificate_not_yet_valid" });
+ });
+
// 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 () => {
@@ -541,6 +601,226 @@ describe("verifyDirectlyIssuedClientCertificate", () => {
await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })
).toEqual({ ok: true });
});
+
+ // The rule above holds whether or not the CA also asserts name constraints. Evaluating those
+ // constraints must not quietly import a CA:TRUE requirement the mode does not have.
+ test("accepts a name-constrained configured CA that omits basic constraints", async () => {
+ const ca = await makeCa("Constraint-less Constrained CA", {
+ omitBasicConstraints: true,
+ extensions: [permittedDnsConstraint(["example.com"])]
+ });
+ 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 });
+ });
+
+ test("still enforces the constraints of a configured CA that omits basic constraints", async () => {
+ const ca = await makeCa("Constraint-less Constrained CA", {
+ omitBasicConstraints: true,
+ 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" });
+ });
+
+ // OpenSSL reports `ca === false` for a key usage without keyCertSign, so the path builder rejects
+ // such an issuer and always has. Single-hop does not consult that flag on the configured CA, so
+ // asserting name constraints alongside it must not become grounds for rejection either.
+ test("accepts a name-constrained CA whose key usage omits keyCertSign", async () => {
+ const ca = await makeCa("No KeyCertSign CA", {
+ extensions: [new x509.KeyUsagesExtension(NON_SIGNING_KEY_USAGE, true), 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("still enforces the constraints of a CA whose key usage omits keyCertSign", async () => {
+ const ca = await makeCa("No KeyCertSign CA", {
+ extensions: [
+ new x509.KeyUsagesExtension(NON_SIGNING_KEY_USAGE, true),
+ 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" });
+ });
+
+ test("accepts a leaf permitted by a URI name constraint written as a domain", async () => {
+ const ca = await makeCa("URI Constrained CA", { extensions: [uriConstraint({ permitted: ["example.org"] })] });
+ const leaf = await makeLeafWithUriSan(ca, "spiffe://example.org/ns/default/sa/svc");
+
+ expect(
+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })
+ ).toEqual({ ok: true });
+ });
+
+ // The constraint has to be a hostname, so this one matches nothing and no reissued certificate
+ // could satisfy it. Reporting a name violation would send the operator after the client's SAN
+ // instead of the CA that has to be fixed.
+ test("rejects a scheme-qualified URI name constraint rather than blaming the client's name", async () => {
+ const ca = await makeCa("Scheme URI CA", {
+ extensions: [uriConstraint({ permitted: ["spiffe://example.org"] })]
+ });
+ const leaf = await makeLeafWithUriSan(ca, "spiffe://example.org/ns/default/sa/svc");
+
+ expect(
+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })
+ ).toEqual({ ok: false, reasonCode: "unsupported_name_constraint" });
+ });
+
+ test("rejects a URI name constraint carrying a path instead of widening it to the host", async () => {
+ const ca = await makeCa("Path URI CA", {
+ extensions: [uriConstraint({ permitted: ["spiffe://example.org/team-a"] })]
+ });
+ const leaf = await makeLeafWithUriSan(ca, "spiffe://example.org/team-a/svc");
+
+ expect(
+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })
+ ).toEqual({ ok: false, reasonCode: "unsupported_name_constraint" });
+ });
+
+ // An exclusion that matches nothing excludes nothing, so it has to fail closed rather than let
+ // through the namespace the CA meant to fence off.
+ test("rejects a scheme-qualified URI exclusion", async () => {
+ const ca = await makeCa("Excluding CA", { extensions: [uriConstraint({ excluded: ["spiffe://evil.org"] })] });
+ const leaf = await makeLeafWithUriSan(ca, "spiffe://example.org/ns/default/sa/svc");
+
+ expect(
+ await verifyDirectlyIssuedClientCertificate({ leaf: toNative(leaf.cert), ca: toNative(ca.cert), now: NOW })
+ ).toEqual({ ok: false, reasonCode: "unsupported_name_constraint" });
+ });
+});
+
+// The engine no longer re-verifies signatures, which is what used to need an Ed25519 shim: pkijs's
+// own algorithm table covers only RSA and ECDSA, so an Ed25519 chain came back unbuildable rather
+// than as a constraint decision.
+describe("name constraints on an Ed25519 chain", () => {
+ const alg = { name: "Ed25519" };
+
+ const toNative = (cert: x509.X509Certificate) => new crypto.X509Certificate(Buffer.from(cert.rawData));
+
+ 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 generateKeys = () =>
+ crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]) as Promise<CryptoKeyPair>;
+
+ const build = async (permitted: string[], dnsName: string) => {
+ const caKeys = await generateKeys();
+ const ca = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name: "CN=Ed25519 Root CA",
+ notBefore: NOT_BEFORE,
+ notAfter: FAR_FUTURE,
+ keys: caKeys,
+ signingAlgorithm: alg,
+ extensions: [
+ new x509.BasicConstraintsExtension(true, undefined, true),
+ 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)
+ )
+ ]
+ });
+
+ const leafKeys = await generateKeys();
+ const leaf = await x509.X509CertificateGenerator.create({
+ serialNumber: "02",
+ subject: "CN=workload",
+ issuer: ca.subject,
+ notBefore: NOT_BEFORE,
+ notAfter: FAR_FUTURE,
+ signingKey: caKeys.privateKey,
+ publicKey: leafKeys.publicKey,
+ signingAlgorithm: alg,
+ extensions: [
+ new x509.BasicConstraintsExtension(false),
+ new x509.SubjectAlternativeNameExtension([{ type: "dns", value: dnsName }])
+ ]
+ });
+
+ return { ca: toNative(ca), leaf: toNative(leaf) };
+ };
+
+ test("accepts a leaf inside the permitted namespace", async () => {
+ const { ca, leaf } = await build(["example.com"], "workload.example.com");
+
+ expect(await verifyDirectlyIssuedClientCertificate({ leaf, ca, now: NOW })).toEqual({ ok: true });
+ });
+
+ test("rejects a leaf outside the permitted namespace", async () => {
+ const { ca, leaf } = await build(["allowed.example.com"], "workload.elsewhere.com");
+
+ expect(await verifyDirectlyIssuedClientCertificate({ leaf, ca, now: NOW })).toEqual({
+ ok: false,
+ reasonCode: "name_constraint_violation"
+ });
+ });
+});
+
+describe("findNameConstraintsProblem", () => {
+ const alg: RsaHashedKeyGenParams = {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: "SHA-256",
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: 2048
+ };
+
+ const toNative = (cert: x509.X509Certificate) => new crypto.X509Certificate(Buffer.from(cert.rawData));
+
+ const makeCa = async (name: string, extensions: x509.Extension[]) => {
+ const keys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
+ return x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "01",
+ name: `CN=${name}`,
+ notBefore: new Date("2026-06-01T00:00:00Z"),
+ notAfter: new Date("2030-01-01T00:00:00Z"),
+ keys,
+ extensions: [new x509.BasicConstraintsExtension(true, undefined, true), ...extensions]
+ });
+ };
+
+ test("reports nothing for a CA that asserts no name constraints", async () => {
+ expect(findNameConstraintsProblem(toNative(await makeCa("Plain CA", [])))).toBeNull();
+ });
+
+ test("reports nothing for a URI constraint written as a domain", async () => {
+ const ca = await makeCa("Domain URI CA", [uriConstraint({ permitted: ["example.org"] })]);
+ expect(findNameConstraintsProblem(toNative(ca))).toBeNull();
+ });
+
+ test("reports the offending constraint for a scheme-qualified URI subtree", async () => {
+ const ca = await makeCa("Scheme URI CA", [uriConstraint({ permitted: ["spiffe://example.org"] })]);
+ expect(findNameConstraintsProblem(toNative(ca))).toEqual({
+ kind: "unsupported_uri_subtree",
+ constraint: "spiffe://example.org"
+ });
+ });
+
+ test("reports a malformed name constraints extension", async () => {
+ const ca = await makeCa("Malformed NC CA", [schemaMismatchedNameConstraint()]);
+ expect(findNameConstraintsProblem(toNative(ca))).toEqual({ kind: "unreadable_extension" });
+ });
});
describe("verifyClientCertificateChain", () => {
@@ -577,14 +857,20 @@ describe("verifyClientCertificateChain", () => {
const makeIntermediate = async (
name: string,
issuer: TIssued,
- opts?: { notAfter?: Date; serialNumber?: string; pathLength?: number; extraExtensions?: x509.Extension[] }
+ opts?: {
+ notBefore?: Date;
+ notAfter?: Date;
+ serialNumber?: string;
+ pathLength?: number;
+ extraExtensions?: x509.Extension[];
+ }
): Promise<TIssued> => {
const keys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
const cert = await x509.X509CertificateGenerator.create({
serialNumber: opts?.serialNumber ?? "02",
subject: `CN=${name}`,
issuer: issuer.cert.subject,
- notBefore: NOT_BEFORE,
+ notBefore: opts?.notBefore ?? NOT_BEFORE,
notAfter: opts?.notAfter ?? FAR_FUTURE,
signingKey: issuer.keys.privateKey,
publicKey: keys.publicKey,
@@ -1175,7 +1461,21 @@ describe("verifyClientCertificateChain", () => {
trustAnchor: toNative(root.cert),
now: NOW
});
- expect(result).toEqual({ ok: false, reasonCode: "certificate_expired" });
+ expect(result).toEqual({ ok: false, reasonCode: "issuer_certificate_expired" });
+ });
+
+ test("rejects when the intermediate is not yet valid", async () => {
+ const futureIntermediate = await makeIntermediate("Future Intermediate", root, {
+ notBefore: new Date("2026-07-01T00:00:00Z")
+ });
+ const leaf = await makeLeaf("workload", futureIntermediate);
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(futureIntermediate.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "issuer_certificate_not_yet_valid" });
});
describe("Ed25519", () => {
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.ts
index 31f9304b60..14b2b75d27 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
@@ -1,7 +1,7 @@
import { webcrypto } from "node:crypto";
import * as x509 from "@peculiar/x509";
-import { Certificate, CertificateChainValidationEngine, CryptoEngine, NameConstraints } from "pkijs";
+import { Certificate, CertificateChainValidationEngine, CryptoEngine, GeneralSubtree, NameConstraints } from "pkijs";
import { crypto } from "@app/lib/crypto/cryptography";
import { logger } from "@app/lib/logger";
@@ -20,9 +20,12 @@ export type TVerifyClientCertificateChainResult =
| "ca_verification_failed"
| "certificate_expired"
| "certificate_not_yet_valid"
+ | "issuer_certificate_expired"
+ | "issuer_certificate_not_yet_valid"
| "issuer_client_auth_usage_not_allowed"
| "name_constraint_violation"
- | "path_length_exceeded";
+ | "path_length_exceeded"
+ | "unsupported_name_constraint";
};
type TVerificationFailure = Extract<TVerifyClientCertificateChainResult, { ok: false }>;
@@ -35,51 +38,67 @@ const ANY_PURPOSE_EKU_OID = CERT_EXTENDED_KEY_USAGES[CertExtendedKeyUsageType.AN
const PERMITTED_SUBTREE_VIOLATION_CODE = 41;
const EXCLUDED_SUBTREE_VIOLATION_CODE = 42;
+const URI_GENERAL_NAME_TYPE = 6;
+
// Caps on how much of a presented chain the path search will explore. See `explore` below.
const MAX_CANDIDATE_PATHS = 8;
const MAX_SEARCH_PATH_STEPS = 2000;
-const ED25519_SIGNATURE_OID = "1.3.101.112";
+const pkiCryptoEngine = new CryptoEngine({ name: "identity-tls-cert-auth", crypto: webcrypto as Crypto });
/**
- * pkijs re-verifies every signature on the path with its own crypto engine, and that engine's
- * algorithm table covers only RSA and ECDSA. An Ed25519 chain Node already verified therefore comes
- * back from pkijs as unbuildable rather than as a constraint decision, which would deny a valid
- * client the moment its CA asserts name constraints. Node's WebCrypto does implement Ed25519, so
- * route that one algorithm to it and leave every other signature to pkijs.
+ * pkijs's validation engine builds the path itself before it will evaluate name constraints, and
+ * that path building carries structural opinions of its own: it re-verifies every signature with
+ * pkijs's software crypto, re-checks validity windows, and requires every issuer to assert `CA:TRUE`
+ * and, when a key usage is present, `keyCertSign`.
+ *
+ * None of that is wanted here, because all of it is already settled by `issuedBy`, `validityFailure`
+ * and the `candidate.ca` gate, against OpenSSL rather than a second implementation. Letting it run
+ * again turned pkijs's opinions into authentication failures: a configured CA that omits basic
+ * constraints is deliberately accepted in single-hop mode, and a CA whose key usage omits
+ * `keyCertSign` has never been rejected here, yet both were denied as soon as their certificate also
+ * asserted name constraints.
+ *
+ * Overriding `sort` hands the engine the path this code already established, so only the subtree
+ * matching runs. It also removes a subtler mismatch: pkijs rebuilt the path from the certificates it
+ * was given and evaluated the shortest one it found, which for a cross-signed chain could be a
+ * different path than the candidate under consideration, skipping the constraints of a CA that was
+ * on it.
*
- * Ed448 is deliberately not routed here: Node still marks it experimental, and this is an
- * authentication path. Such a chain keeps failing closed, with the reason logged.
+ * @param orderedPath leaf first, then each issuer in turn, trust anchor last
*/
-class ChainCryptoEngine extends CryptoEngine {
- async verifyWithPublicKey(...args: Parameters<CryptoEngine["verifyWithPublicKey"]>): Promise<boolean> {
- const [data, signature, publicKeyInfo, signatureAlgorithm] = args;
- if (signatureAlgorithm.algorithmId !== ED25519_SIGNATURE_OID) {
- return super.verifyWithPublicKey(...args);
- }
+class NameConstraintsEngine extends CertificateChainValidationEngine {
+ private readonly orderedPath: Certificate[];
- const algorithm = { name: "Ed25519" };
- const publicKey = await webcrypto.subtle.importKey("spki", publicKeyInfo.toSchema().toBER(false), algorithm, true, [
- "verify"
- ]);
- return webcrypto.subtle.verify(algorithm, publicKey, signature.valueBlock.valueHexView, data);
+ constructor(orderedPath: Certificate[]) {
+ super({ trustedCerts: [orderedPath[orderedPath.length - 1]], certs: orderedPath.slice(0, -1).reverse() });
+ this.orderedPath = orderedPath;
}
-}
-const pkiCryptoEngine = new ChainCryptoEngine({ name: "identity-tls-cert-auth", crypto: webcrypto as Crypto });
+ sort(): Promise<Certificate[]> {
+ return Promise.resolve(this.orderedPath);
+ }
+}
const isWithinValidityWindow = (cert: TNativeX509, at: Date): boolean =>
new Date(cert.validFrom) <= at && at <= new Date(cert.validTo);
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"
- };
+/**
+ * The reason codes distinguish the presented leaf from a CA above it, because the two are the
+ * client's problem in different ways: an expired leaf is reissued by the client, an expired CA is
+ * the operator's to rotate, and a caller that cannot tell them apart cannot act on either.
+ */
+const validityFailure = (cert: TNativeX509, at: Date, role: "leaf" | "issuer"): TVerificationFailure | null => {
+ if (isWithinValidityWindow(cert, at)) return null;
+
+ const notYetValid = at < new Date(cert.validFrom);
+ if (role === "leaf") {
+ return { ok: false, reasonCode: notYetValid ? "certificate_not_yet_valid" : "certificate_expired" };
+ }
+ return { ok: false, reasonCode: notYetValid ? "issuer_certificate_not_yet_valid" : "issuer_certificate_expired" };
+};
/**
* Returns true when `issuer` issued `child`.
@@ -155,22 +174,71 @@ const nameConstraintsOf = (cert: Certificate): TNameConstraintsState => {
return { status: "present", constraints };
};
+const uriSubtreeValue = (subtree: GeneralSubtree): string | null =>
+ subtree.base.type === URI_GENERAL_NAME_TYPE && typeof subtree.base.value === "string" ? subtree.base.value : null;
+
+/**
+ * RFC 5280 4.2.1.10: a URI name constraint applies to the host part of the name and has to be a
+ * fully qualified domain name, such as `example.org` or `.example.org`. A constraint written the way
+ * the names themselves look, `spiffe://example.org`, is not a hostname, and neither is one carrying
+ * a path. Go's crypto/x509 and pkijs both read it that way, so such a constraint matches nothing:
+ * as a permitted subtree it denies every client, and as an excluded subtree it excludes none.
+ *
+ * Returning it rather than evaluating it keeps both halves honest. Letting the match run would deny
+ * every client while naming the client's certificate as the problem, when the certificate cannot be
+ * changed to satisfy it. Skipping it would let a CA that meant to restrict its subordinates certify
+ * anything. Note that the host is not extracted and reused: for a constraint like
+ * `spiffe://example.org/team-a`, treating it as `example.org` would permit `team-b` as well, which
+ * is wider than what the CA asserted.
+ */
+const unsupportedUriSubtree = (constraints: NameConstraints): string | null => {
+ const subtrees = [...(constraints.permittedSubtrees ?? []), ...(constraints.excludedSubtrees ?? [])];
+ return subtrees.map(uriSubtreeValue).find((uri) => uri !== null && /[:/]/.test(uri)) ?? null;
+};
+
+export type TNameConstraintsProblem =
+ | { kind: "unparseable_certificate" }
+ | { kind: "unreadable_extension" }
+ | { kind: "unsupported_uri_subtree"; constraint: string };
+
+/**
+ * Why a certificate's name constraints could never permit a client, so an operator hears about it
+ * when they configure the CA rather than at every login it would deny. Null when the certificate
+ * asserts no constraints, or asserts ones that can be evaluated.
+ */
+export const findNameConstraintsProblem = (cert: TNativeX509): TNameConstraintsProblem | null => {
+ let state: TNameConstraintsState;
+ try {
+ state = nameConstraintsOf(Certificate.fromBER(cert.raw));
+ } catch (err) {
+ logger.warn(err, `TLS certificate auth: certificate could not be decoded [subject=${cert.subject}]`);
+ return { kind: "unparseable_certificate" };
+ }
+
+ if (state.status === "absent") return null;
+ if (state.status === "unreadable") return { kind: "unreadable_extension" };
+
+ const constraint = unsupportedUriSubtree(state.constraints);
+ return constraint === null ? null : { kind: "unsupported_uri_subtree", constraint };
+};
+
/**
* RFC 5280 6.1.4 (g): a CA may restrict the namespace its subordinates can certify. Without this,
* the holder of a constrained sub-CA under the configured anchor could mint a leaf for any name and
* authenticate as any identity pinned to that anchor.
*
* Subtree matching (DNS/IP/email/URI/directory-name semantics, permitted and excluded) is delegated
- * to pkijs rather than reimplemented. pkijs applies constraints carried by certificates on the path
- * but not by the trust anchor itself, so the anchor's own constraints are supplied separately as the
- * RFC's initial-permitted/excluded-subtrees inputs. That matters because operators may pin a
- * constrained sub-CA directly rather than the root above it.
+ * to pkijs rather than reimplemented, and only that: see `NameConstraintsEngine` for why the engine
+ * is not allowed to rebuild or re-validate the path. pkijs applies constraints carried by
+ * certificates on the path but not by the trust anchor itself, so the anchor's own constraints are
+ * supplied separately as the RFC's initial-permitted/excluded-subtrees inputs. That matters because
+ * operators may pin a constrained sub-CA directly rather than the root above it.
*
* Only runs when some certificate on the path actually asserts constraints, so a chain that has
* none is validated exactly as before. A CA asserting constraints that cannot be read denies before
* that point; see `nameConstraintsOf`.
*/
-const enforceNameConstraints = async (orderedPath: TNativeX509[], now: Date): Promise<TVerificationFailure | null> => {
+const enforceNameConstraints = async (orderedPath: TNativeX509[]): Promise<TVerificationFailure | null> => {
if (orderedPath.length < 2) return null;
const parsedPath = orderedPath.map((cert) => Certificate.fromBER(cert.raw));
@@ -184,20 +252,26 @@ const enforceNameConstraints = async (orderedPath: TNativeX509[], now: Date): Pr
return { ok: false, reasonCode: "ca_verification_failed" };
}
+ const unsupportedIssuer = pathConstraints
+ .map((state, idx) => ({
+ subject: orderedPath[idx].subject,
+ constraint: idx > 0 && state.status === "present" ? unsupportedUriSubtree(state.constraints) : null
+ }))
+ .find(({ constraint }) => constraint !== null);
+
+ if (unsupportedIssuer) {
+ logger.warn(
+ `TLS certificate auth: a CA on the chain asserts a URI name constraint that no certificate can satisfy [subject=${unsupportedIssuer.subject}] [constraint=${unsupportedIssuer.constraint}]`
+ );
+ return { ok: false, reasonCode: "unsupported_name_constraint" };
+ }
+
if (!pathConstraints.some((state) => state.status === "present")) return null;
- const anchor = parsedPath[parsedPath.length - 1];
const anchorState = pathConstraints[pathConstraints.length - 1];
const anchorConstraints = anchorState.status === "present" ? anchorState.constraints : null;
- const engine = new CertificateChainValidationEngine({
- trustedCerts: [anchor],
- // pkijs takes the chain end-entity last.
- certs: parsedPath.slice(0, -1).reverse(),
- checkDate: now
- });
-
- const { result, resultCode, resultMessage } = await engine.verify(
+ const { result, resultCode, resultMessage } = await new NameConstraintsEngine(parsedPath).verify(
{
initialPermittedSubtreesSet: anchorConstraints?.permittedSubtrees ?? [],
initialExcludedSubtreesSet: anchorConstraints?.excludedSubtrees ?? []
@@ -250,8 +324,9 @@ export const permitsClientAuth = (cert: TNativeX509): boolean => {
* 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.
+ * a client in either mode; a leaf outside the namespace its CA is permitted to certify is outside it
+ * whether or not intermediates were presented; and a leaf outside its own validity window is no more
+ * usable here than on a longer path.
*
* 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
@@ -271,13 +346,14 @@ export const verifyDirectlyIssuedClientCertificate = async ({
}): Promise<TVerifyClientCertificateChainResult> => {
if (!issuedBy(leaf, ca)) return { ok: false, reasonCode: "ca_verification_failed" };
- const caFailure =
- validityFailure(ca, now) ??
+ const failure =
+ validityFailure(leaf, now, "leaf") ??
+ validityFailure(ca, now, "issuer") ??
(permitsClientAuth(ca) ? null : ({ ok: false, reasonCode: "issuer_client_auth_usage_not_allowed" } as const));
- if (caFailure) return caFailure;
+ if (failure) return failure;
try {
- return (await enforceNameConstraints([leaf, ca], now)) ?? { ok: true };
+ return (await enforceNameConstraints([leaf, ca])) ?? { ok: true };
} catch {
return { ok: false, reasonCode: "ca_verification_failed" };
}
@@ -368,10 +444,10 @@ export const verifyClientCertificateChain = async ({
* purpose against the whole chain rather than the leaf alone.
*/
const issuerFailure = (issuer: TNativeX509): TVerificationFailure | null =>
- validityFailure(issuer, now) ??
+ validityFailure(issuer, now, "issuer") ??
(issuerPermitsClientAuth(issuer) ? null : { ok: false, reasonCode: "issuer_client_auth_usage_not_allowed" });
- const leafFailure = validityFailure(leaf, now);
+ const leafFailure = validityFailure(leaf, now, "leaf");
if (leafFailure) return leafFailure;
const candidateIssuers: TNativeX509[] = [];
@@ -449,7 +525,7 @@ export const verifyClientCertificateChain = async ({
try {
const pathLengthFailure = enforcePathLength(path);
// eslint-disable-next-line no-await-in-loop -- stop at the first path that validates
- failure = pathLengthFailure ?? (await enforceNameConstraints(path, now));
+ failure = pathLengthFailure ?? (await enforceNameConstraints(path));
} catch (err) {
logger.warn(
err,
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.ts
index 12158e4bf6..9947f0e838 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
@@ -44,12 +44,14 @@ import { TOrgDALFactory } from "../org/org-dal";
import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";
import { TIdentityTlsCertAuthDALFactory } from "./identity-tls-cert-auth-dal";
import {
+ findNameConstraintsProblem,
isSubjectAltNameAllowed,
parseAllowedSubjectAltNames,
parseSubjectDetails,
permitsClientAuth,
readSubjectAltNames,
serializeAllowedSubjectAltNames,
+ TNameConstraintsProblem,
TVerifyClientCertificateChainResult,
verifyClientCertificateChain,
verifyDirectlyIssuedClientCertificate
@@ -61,17 +63,32 @@ const CHAIN_FAILURE_MESSAGES: Record<
string
> = {
ca_verification_failed: "Access denied: Certificate chain could not be validated against the provided CA.",
- certificate_expired: "Access denied: A certificate in the chain is outside its validity period.",
- certificate_not_yet_valid: "Access denied: A certificate in the chain is outside its validity period.",
+ certificate_expired: "Access denied: Certificate has expired.",
+ certificate_not_yet_valid: "Access denied: Certificate not yet valid.",
+ issuer_certificate_expired: "Access denied: A CA certificate that issued the client certificate has expired.",
+ issuer_certificate_not_yet_valid:
+ "Access denied: A CA certificate that issued the client certificate is not yet valid.",
issuer_client_auth_usage_not_allowed:
"Access denied: A CA in the certificate chain is not permitted to issue client authentication certificates.",
name_constraint_violation:
"Access denied: The client certificate's name is outside the namespace its issuing CA is permitted to certify.",
- path_length_exceeded: "Access denied: The certificate chain has more intermediate CAs than a CA in it permits."
+ path_length_exceeded: "Access denied: The certificate chain has more intermediate CAs than a CA in it permits.",
+ unsupported_name_constraint:
+ "Access denied: A CA in the certificate chain restricts a URI name that is not a fully qualified domain name, so no client certificate can satisfy it."
};
const normalizeCaCertificate = (caCertificate: string) => caCertificate.replace(/\s+/g, "");
+const nameConstraintsProblemMessage = (problem: TNameConstraintsProblem) => {
+ if (problem.kind === "unparseable_certificate")
+ return "CA certificate could not be decoded. Provide a PEM-encoded X.509 certificate that conforms to RFC 5280.";
+
+ if (problem.kind === "unreadable_extension")
+ return "CA certificate's name constraints extension is malformed, so the namespace it restricts cannot be honored and no certificate it issues could be used to log in. Provide a CA certificate whose name constraints are well-formed.";
+
+ return `CA certificate restricts the URI name "${problem.constraint}", which is not a fully qualified domain name, so no certificate it issues could be used to log in. A URI name constraint restricts the host only, such as "example.org". To restrict individual workload identities, use allowed subject alternative names instead.`;
+};
+
/**
* Reject a CA certificate the moment it is configured, rather than at every login it would deny.
*
@@ -102,6 +119,10 @@ const validateCaCertificateUsable = (caCertificate: string) => {
"CA certificate's extended key usage does not include client authentication, so no certificate it issues could be used to log in. Provide a CA certificate that permits client authentication."
});
}
+
+ const nameConstraintsProblem = findNameConstraintsProblem(caCertificateX509);
+ if (nameConstraintsProblem)
+ throw new BadRequestError({ message: nameConstraintsProblemMessage(nameConstraintsProblem) });
};
type TIdentityTlsCertAuthServiceFactoryDep = {
@@ -263,30 +284,6 @@ export const identityTlsCertAuthServiceFactory = ({
});
}
- if (new Date(clientCertificateX509.validTo) < new Date()) {
- throw new UnauthorizedError({
- message: "Access denied: Certificate has expired.",
- detail: {
- reasonCode: "certificate_expired",
- identityId: identity.id,
- orgId: identity.orgId,
- identityName: identity.name
- }
- });
- }
-
- if (new Date(clientCertificateX509.validFrom) > new Date()) {
- throw new UnauthorizedError({
- message: "Access denied: Certificate not yet valid.",
- detail: {
- reasonCode: "certificate_not_yet_valid",
- identityId: identity.id,
- orgId: identity.orgId,
- identityName: identity.name
- }
- });
- }
-
const subjectDetails = parseSubjectDetails(clientCertificateX509.subject);
if (identityTlsCertAuth.allowedCommonNames) {
const isValidCommonName = identityTlsCertAuth.allowedCommonNames.split(",").includes(subjectDetails.CN);
diff --git a/docs/documentation/platform/identities/tls-cert-auth.mdx b/docs/documentation/platform/identities/tls-cert-auth.mdx
index 5019719339..50f5ad7bd6 100644
--- a/docs/documentation/platform/identities/tls-cert-auth.mdx
+++ b/docs/documentation/platform/identities/tls-cert-auth.mdx
@@ -93,7 +93,7 @@ Now create a new TLS Certificate Auth Method.
Here's some information about each field:
-- **CA Certificate:** A PEM encoded CA Certificate used to validate incoming TLS request client certificate. Both the CA Certificate and the client certificate must permit client authentication: a certificate that lists an Extended Key Usage without `clientAuth` (or `anyExtendedKeyUsage`) is rejected, since a CA's key usages also limit what the certificates beneath it may be used for. A certificate that lists no Extended Key Usage is unrestricted and is accepted.
+- **CA Certificate:** A PEM encoded CA Certificate used to validate incoming TLS request client certificate. Any name constraints it asserts are honored, so a client certificate whose name falls outside the namespace the CA may certify is rejected. Both the CA Certificate and the client certificate must permit client authentication: a certificate that lists an Extended Key Usage without `clientAuth` (or `anyExtendedKeyUsage`) is rejected, since a CA's key usages also limit what the certificates beneath it may be used for. A certificate that lists no Extended Key Usage is unrestricted and is accepted.
- **Verify Client Certificate Chain (default is disabled):** By default, the CA Certificate must be the **direct issuer** of the client's leaf certificate. Enable this to instead treat the CA Certificate as a **trust anchor** and accept any client whose presented chain (leaf followed by intermediates) builds a valid path up to it. This is helpful when the issuing intermediate rotates beneath a long-lived root, such as a **SPIRE X.509-SVID**: you can pin the stable root here once and let the workload present its current intermediate alongside its leaf, rather than updating the CA Certificate on every rotation. Either way the trust anchor is the only certificate trusted, the client certificate must still be an end-entity certificate, and the Common Name and Subject Alternative Name checks below still apply to the leaf. Restrictions that the CAs on the path place on their subordinates are honored: a client certificate whose name falls outside an issuing CA's name constraints is rejected, as is a chain with more intermediates than a CA's path length permits, or one that passes through a CA whose Extended Key Usage does not permit client authentication.
- **Allowed Common Names:** A comma separated list of client certificate common names allowed.
- **Allowed Subject Alternative Names:** A comma separated list of client certificate subject alternative names (SANs) allowed. This is useful when the client certificate carries its identity in a SAN rather than the Subject Common Name, such as a SPIFFE X.509-SVID whose identity is a URI SAN (`spiffe://trust-domain/path`) with an empty Subject. Matching is type-aware, so an entry only matches a SAN of the same type:
@@ -106,6 +106,18 @@ Here's some information about each field:
- **Access Token Max Number of Uses (default is `0`):** The maximum number of times that an access token can be used; a value of `0` implies an infinite number of uses.
- **Access Token Trusted IPs:** The IPs or CIDR ranges that access tokens can be used from. By default, each token is given the `0.0.0.0/0`, allowing usage from any network address.
+<Note>
+ If your CA restricts the namespace it may certify through the X.509 **name constraints** extension,
+ those restrictions are enforced on every login, in both single-hop and chain mode. A URI name
+ constraint restricts the **host** only and must be a fully qualified domain name, such as
+ `example.org` or `.example.org`. Writing it the way the identity itself looks, such as
+ `spiffe://example.org`, or writing one that carries a path, is not a hostname, so no client
+ certificate can satisfy it and every login is denied. Infisical rejects such a CA Certificate when you save it.
+
+ Name constraints cannot scope individual workloads, because a URI constraint applies to the host
+ and ignores the path. Use **Allowed Subject Alternative Names** for that.
+</Note>
+
### Adding an identity to a project
In order to allow an identity to access project-level resources such as secrets, you must add it to the relevant projects.