Skip to content

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

fix policyMappings error

Thiago Araujo da Silva96ccf7c37e1b
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 8ddf7ed964..1a12256388 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
@@ -2,7 +2,16 @@ import crypto from "node:crypto";
import * as x509 from "@peculiar/x509";
import * as asn1js from "asn1js";
-import { GeneralName, GeneralSubtree, NameConstraints } from "pkijs";
+import {
+ CertificatePolicies,
+ GeneralName,
+ GeneralSubtree,
+ NameConstraints,
+ PolicyConstraints,
+ PolicyInformation,
+ PolicyMapping,
+ PolicyMappings
+} from "pkijs";
import { beforeAll, describe, expect, test, vi } from "vitest";
import {
@@ -400,6 +409,30 @@ const uriConstraint = (subtrees: { permitted?: string[]; excluded?: string[] })
.toBER(false)
);
+const dnsConstraint = (subtrees: { permitted?: string[]; excluded?: string[] }) =>
+ new x509.Extension(
+ "2.5.29.30",
+ true,
+ new NameConstraints({
+ ...(subtrees.permitted
+ ? {
+ permittedSubtrees: subtrees.permitted.map(
+ (dns) => new GeneralSubtree({ base: new GeneralName({ type: 2, value: dns }) })
+ )
+ }
+ : {}),
+ ...(subtrees.excluded
+ ? {
+ excludedSubtrees: subtrees.excluded.map(
+ (dns) => new GeneralSubtree({ base: new GeneralName({ type: 2, value: dns }) })
+ )
+ }
+ : {})
+ })
+ .toSchema()
+ .toBER(false)
+ );
+
describe("verifyDirectlyIssuedClientCertificate", () => {
const alg: RsaHashedKeyGenParams = {
name: "RSASSA-PKCS1-v1_5",
@@ -1005,7 +1038,13 @@ describe("verifyClientCertificateChain", () => {
const makeLeaf = async (
name: string,
issuer: TIssued,
- opts?: { notBefore?: Date; notAfter?: Date; dnsName?: string; sans?: x509.JsonGeneralName[] }
+ opts?: {
+ notBefore?: Date;
+ notAfter?: Date;
+ dnsName?: string;
+ sans?: x509.JsonGeneralName[];
+ extraExtensions?: x509.Extension[];
+ }
) => {
const keys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
const sans: x509.JsonGeneralName[] = opts?.sans ?? (opts?.dnsName ? [{ type: "dns", value: opts.dnsName }] : []);
@@ -1020,7 +1059,8 @@ describe("verifyClientCertificateChain", () => {
signingAlgorithm: alg,
extensions: [
new x509.BasicConstraintsExtension(false),
- ...(sans.length ? [new x509.SubjectAlternativeNameExtension(sans)] : [])
+ ...(sans.length ? [new x509.SubjectAlternativeNameExtension(sans)] : []),
+ ...(opts?.extraExtensions ?? [])
]
});
return { cert, keys };
@@ -1375,6 +1415,166 @@ describe("verifyClientCertificateChain", () => {
expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
});
+ // RFC 5280 6.1.4 (g) intersects the permitted subtrees at every hop, so a name has to satisfy
+ // every CA above it. Each of these passes if the sets are unioned instead, which lets the widest
+ // CA on the path decide and hands a constrained sub-CA a way out of its own namespace.
+ describe("intersects the permitted subtrees of every CA on the path", () => {
+ test("rejects a name only the wider CA permits", async () => {
+ const wide = await makeIntermediate("Corp CA", root, {
+ serialNumber: "80",
+ extraExtensions: [permittedDnsConstraint(["corp.example.com"])]
+ });
+ const narrow = await makeIntermediate("Team A CA", wide, {
+ serialNumber: "81",
+ extraExtensions: [permittedDnsConstraint(["team-a.corp.example.com"])]
+ });
+ const leaf = await makeLeaf("admin", narrow, { dnsName: "admin.corp.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(wide.cert), toNative(narrow.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ test("accepts a name every CA on the path permits", async () => {
+ const wide = await makeIntermediate("Corp CA", root, {
+ serialNumber: "82",
+ extraExtensions: [permittedDnsConstraint(["corp.example.com"])]
+ });
+ const narrow = await makeIntermediate("Team A CA", wide, {
+ serialNumber: "83",
+ extraExtensions: [permittedDnsConstraint(["team-a.corp.example.com"])]
+ });
+ const leaf = await makeLeaf("svc", narrow, { dnsName: "svc.team-a.corp.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(wide.cert), toNative(narrow.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: true });
+ });
+
+ // The escalation the intersection exists to stop: a sub-CA writes what it issues, so if a
+ // subordinate's wider subtrees counted, the holder of a restricted CA could issue itself one.
+ test("rejects a leaf a constrained sub-CA reached by issuing a wider sub-CA", async () => {
+ const teamA = await makeIntermediate("Team A CA", root, {
+ serialNumber: "84",
+ extraExtensions: [permittedDnsConstraint(["team-a.example.com"])]
+ });
+ const widened = await makeIntermediate("Team A Widened CA", teamA, {
+ serialNumber: "85",
+ extraExtensions: [permittedDnsConstraint(["example.com"])]
+ });
+ const leaf = await makeLeaf("admin", widened, { dnsName: "admin.corp.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(teamA.cert), toNative(widened.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ // Two CAs whose subtrees do not overlap permit nothing at all between them, so a leaf matching
+ // either one is still outside the intersection.
+ test("rejects every name when two CAs on the path permit disjoint namespaces", async () => {
+ const first = await makeIntermediate("Example Com CA", root, {
+ serialNumber: "86",
+ extraExtensions: [permittedDnsConstraint(["example.com"])]
+ });
+ const second = await makeIntermediate("Example Net CA", first, {
+ serialNumber: "87",
+ extraExtensions: [permittedDnsConstraint(["other.example.net"])]
+ });
+ const leaf = await makeLeaf("svc", second, { dnsName: "svc.other.example.net" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(first.cert), toNative(second.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ test("holds a CA below the configured anchor to the anchor's own subtrees", async () => {
+ // Operators may pin a constrained sub-CA directly, so the anchor's constraints have to bind
+ // the CAs presented beneath it rather than only the leaf.
+ const pinned = await makeIntermediate("Pinned Constrained CA", root, {
+ serialNumber: "88",
+ extraExtensions: [permittedDnsConstraint(["team-a.example.com"])]
+ });
+ const widened = await makeIntermediate("Widening CA", pinned, {
+ serialNumber: "89",
+ extraExtensions: [permittedDnsConstraint(["example.com"])]
+ });
+ const leaf = await makeLeaf("svc", widened, { dnsName: "svc.team-b.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(widened.cert)],
+ trustAnchor: toNative(pinned.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ // Excluded subtrees accumulate rather than narrow, so a subordinate permitting what an ancestor
+ // excluded must not re-open it.
+ test("rejects a name a lower CA permits but a higher CA excludes", async () => {
+ const excluding = await makeIntermediate("Excluding CA", root, {
+ serialNumber: "8a",
+ extraExtensions: [dnsConstraint({ excluded: ["secret.example.com"] })]
+ });
+ const permitting = await makeIntermediate("Permitting CA", excluding, {
+ serialNumber: "8b",
+ extraExtensions: [permittedDnsConstraint(["secret.example.com"])]
+ });
+ const leaf = await makeLeaf("svc", permitting, { dnsName: "svc.secret.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(excluding.cert), toNative(permitting.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ test("still evaluates each name of a multi-name leaf against every CA on the path", async () => {
+ // The per-name pass and the per-CA pass have to compose: one in-scope name must not carry an
+ // out-of-scope one past the narrower CA.
+ const wide = await makeIntermediate("Corp CA", root, {
+ serialNumber: "8c",
+ extraExtensions: [permittedDnsConstraint(["corp.example.com"])]
+ });
+ const narrow = await makeIntermediate("Team A CA", wide, {
+ serialNumber: "8d",
+ extraExtensions: [permittedDnsConstraint(["team-a.corp.example.com"])]
+ });
+ const leaf = await makeLeaf("svc", narrow, {
+ sans: [
+ { type: "dns", value: "svc.team-a.corp.example.com" },
+ { type: "dns", value: "admin.corp.example.com" }
+ ]
+ });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(wide.cert), toNative(narrow.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+ });
+
test("rejects a chain deeper than a CA's pathLenConstraint permits", async () => {
const limited = await makeIntermediate("PathLen Zero CA", root, { serialNumber: "30", pathLength: 0 });
const extra = await makeIntermediate("Extra Intermediate CA", limited, { serialNumber: "31" });
@@ -1710,6 +1910,116 @@ describe("verifyClientCertificateChain", () => {
expect(result).toEqual({ ok: false, reasonCode: "issuer_certificate_not_yet_valid" });
});
+ // Nothing here validates certificate policies, so a chain carrying policy extensions has to be
+ // decided by its name constraints alone. pkijs's engine runs its policy processing first and
+ // returns on the first problem it finds, which denied valid logins and masked real namespace
+ // violations until those extensions were kept out of its view.
+ describe("certificate policy extensions", () => {
+ const policyMappings = () =>
+ new x509.Extension(
+ "2.5.29.33",
+ false,
+ new PolicyMappings({
+ mappings: [
+ new PolicyMapping({ issuerDomainPolicy: "1.3.6.1.4.1.1.1", subjectDomainPolicy: "1.3.6.1.4.1.1.2" })
+ ]
+ })
+ .toSchema()
+ .toBER(false)
+ );
+
+ const requireExplicitPolicy = () =>
+ new x509.Extension(
+ "2.5.29.36",
+ true,
+ new PolicyConstraints({ requireExplicitPolicy: 0 }).toSchema().toBER(false)
+ );
+
+ const certificatePolicies = (oid: string) =>
+ new x509.Extension(
+ "2.5.29.32",
+ false,
+ new CertificatePolicies({ certificatePolicies: [new PolicyInformation({ policyIdentifier: oid })] })
+ .toSchema()
+ .toBER(false)
+ );
+
+ // pkijs reads the policy mappings of one certificate against the policy list of the certificate
+ // below it, which only has a certificate below it on a chain of three or more.
+ const threeHopChain = async (leafName: string, upperExtensions: x509.Extension[]) => {
+ const upper = await makeIntermediate("Upper Intermediate CA", root, {
+ serialNumber: "40",
+ extraExtensions: [permittedDnsConstraint(["team-a.example.com"]), ...upperExtensions]
+ });
+ const lower = await makeIntermediate("Lower Intermediate CA", upper, { serialNumber: "41" });
+ const leaf = await makeLeaf(leafName, lower, { dnsName: leafName });
+ return { presentedChain: [toNative(lower.cert), toNative(upper.cert)], leaf: toNative(leaf.cert) };
+ };
+
+ test("accepts an in-namespace leaf under a CA asserting policy mappings", async () => {
+ const { leaf, presentedChain } = await threeHopChain("team-a.example.com", [policyMappings()]);
+
+ const result = await verifyClientCertificateChain({
+ leaf,
+ presentedChain,
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: true });
+ });
+
+ test("reports a namespace violation under a CA asserting policy mappings", async () => {
+ const { leaf, presentedChain } = await threeHopChain("victim.example.com", [policyMappings()]);
+
+ const result = await verifyClientCertificateChain({
+ leaf,
+ presentedChain,
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ test("accepts an in-namespace leaf under a CA requiring an explicit policy", async () => {
+ const constrained = await makeIntermediate("Explicit Policy CA", root, {
+ serialNumber: "42",
+ extraExtensions: [permittedDnsConstraint(["team-a.example.com"]), requireExplicitPolicy()]
+ });
+ const leaf = await makeLeaf("team-a.example.com", constrained, { dnsName: "team-a.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(constrained.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: true });
+ });
+
+ test("accepts an in-namespace leaf whose certificate policies do not chain", async () => {
+ const constrained = await makeIntermediate("Disjoint Policy CA", root, {
+ serialNumber: "43",
+ extraExtensions: [
+ permittedDnsConstraint(["team-a.example.com"]),
+ requireExplicitPolicy(),
+ certificatePolicies("1.3.6.1.4.1.1.1")
+ ]
+ });
+ const leaf = await makeLeaf("team-a.example.com", constrained, {
+ dnsName: "team-a.example.com",
+ extraExtensions: [certificatePolicies("1.3.6.1.4.1.2.1")]
+ });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(constrained.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: true });
+ });
+ });
+
describe("Ed25519", () => {
const edAlg = { name: "Ed25519" } as unknown as EcKeyGenParams;
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 f7541baab9..108ec06ec8 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
@@ -7,6 +7,10 @@ import {
CertificateChainValidationEngine,
CryptoEngine,
GeneralSubtree,
+ id_CertificatePolicies,
+ id_InhibitAnyPolicy,
+ id_PolicyConstraints,
+ id_PolicyMappings,
NameConstraints
} from "pkijs";
@@ -156,17 +160,79 @@ const parseCertificate = (cert: TNativeX509): x509.X509Certificate => {
return parsed;
};
+const POLICY_EXTENSION_OIDS = new Set<string>([
+ id_CertificatePolicies,
+ id_PolicyMappings,
+ id_PolicyConstraints,
+ id_InhibitAnyPolicy
+]);
+
+/**
+ * pkijs's validation engine runs RFC 5280's certificate policy processing before it will look at
+ * name constraints, and returns on the first policy problem it finds. Nothing here validates
+ * policies, so each of those outcomes is a login denied over something the caller never asked about:
+ * a chain whose CAs assert `requireExplicitPolicy` over policy identifiers that do not chain fails
+ * outright, and a `policyMappings` on an intermediate of a three-certificate chain reads a policy
+ * list the certificate below it does not carry, which the engine catches and reports as a generic
+ * failure. Both land before the subtree matching, so a chain that also violates a name constraint is
+ * reported as `ca_verification_failed` instead of `name_constraint_violation`.
+ *
+ * Dropping the policy extensions leaves that pass with nothing to process and no way to fail, so
+ * every chain reaches the stage this parse exists for. Only pkijs loses sight of them: these objects
+ * feed the name constraints engine and the subject alternative name reads, and the @peculiar parse
+ * that the extended key usage gate, the path length check and the identity's allow-list go through
+ * still sees the certificate whole.
+ */
+const parsePkiCertificate = (raw: BufferSource): Certificate => {
+ const parsed = Certificate.fromBER(raw);
+ if (parsed.extensions) {
+ parsed.extensions = parsed.extensions.filter((ext) => !POLICY_EXTENSION_OIDS.has(ext.extnID));
+ }
+ return parsed;
+};
+
const pkiCertificates = new WeakMap<TNativeX509, Certificate>();
const toPkiCertificate = (cert: TNativeX509): Certificate => {
const cached = pkiCertificates.get(cert);
if (cached) return cached;
- const parsed = Certificate.fromBER(cert.raw);
+ const parsed = parsePkiCertificate(cert.raw);
pkiCertificates.set(cert, parsed);
return parsed;
};
+const parseWithoutNameConstraints = (raw: BufferSource): Certificate => {
+ const parsed = parsePkiCertificate(raw);
+ if (parsed.extensions) {
+ parsed.extensions = parsed.extensions.filter((ext) => ext.extnID !== NAME_CONSTRAINTS_EXTENSION_OID);
+ }
+ return parsed;
+};
+
+const nameConstraintFreeCertificates = new WeakMap<TNativeX509, Certificate>();
+
+/**
+ * The certificate as pkijs sees it with its own name constraints extension removed, so that a path
+ * built from these carries no constraints at all and the only ones in play are the single
+ * certificate's worth `enforceNameConstraints` supplies to each pass. See there for why every
+ * constraint has to be handed over that way rather than left on the path.
+ *
+ * A certificate that asserts none needs no copy, so the shared parse is returned unchanged and the
+ * ordinary chain that constrains nothing pays nothing here.
+ */
+const toNameConstraintFreeCertificate = (cert: TNativeX509): Certificate => {
+ const shared = toPkiCertificate(cert);
+ if (!shared.extensions?.some((ext) => ext.extnID === NAME_CONSTRAINTS_EXTENSION_OID)) return shared;
+
+ const cached = nameConstraintFreeCertificates.get(cert);
+ if (cached) return cached;
+
+ const parsed = parseWithoutNameConstraints(cert.raw);
+ nameConstraintFreeCertificates.set(cert, parsed);
+ return parsed;
+};
+
const basicConstraintsPathLength = (cert: TNativeX509): number | undefined =>
parseCertificate(cert).getExtension(x509.BasicConstraintsExtension)?.pathLength;
@@ -288,11 +354,9 @@ const subjectAltNamesOf = (cert: Certificate): AltName[] =>
ext.extnID === SUBJECT_ALT_NAME_EXTENSION_OID && ext.parsedValue instanceof AltName ? [ext.parsedValue] : []
);
-const permittedSubtreeTypes = (states: TNameConstraintsState[]): Set<number> =>
+const permittedSubtreeTypes = (constraints: NameConstraints[]): Set<number> =>
new Set(
- states.flatMap((state) =>
- state.status === "present" ? (state.constraints.permittedSubtrees ?? []).map((subtree) => subtree.base.type) : []
- )
+ constraints.flatMap((constraint) => (constraint.permittedSubtrees ?? []).map((subtree) => subtree.base.type))
);
/**
@@ -318,6 +382,9 @@ type TPerNameEvaluation = { certificate: Certificate; rounds: number; selectRoun
* identity's allow-list included, still has to see all of its names. It is also only made once the
* shared parse has shown a copy is needed, so the ordinary certificate naming one workload does not
* pay for a second decode.
+ *
+ * Its own name constraints are dropped for the same reason the rest of the path drops them: this
+ * copy is substituted into a path that must carry no constraints of its own.
*/
const perNameEvaluation = (
cert: TNativeX509,
@@ -328,7 +395,7 @@ const perNameEvaluation = (
const rounds = roundsToCoverEveryName(shared.map((name) => name.type).filter((type) => constrainedTypes.has(type)));
if (rounds < 2) return null;
- const certificate = Certificate.fromBER(cert.raw);
+ const certificate = parseWithoutNameConstraints(cert.raw);
const extensions = subjectAltNamesOf(certificate);
if (!extensions.length) return null;
const names = extensions.map((altName) => altName.altNames);
@@ -356,12 +423,25 @@ const perNameEvaluation = (
*
* Subtree matching (DNS/IP/email/URI/directory-name semantics, permitted and excluded) is delegated
* 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.
+ * is not allowed to rebuild or re-validate the path.
+ *
+ * What is not delegated is how the constraints of different certificates combine. 6.1.4 (g) narrows
+ * the permitted set at every hop, by intersection, so a name has to sit inside what *every* CA above
+ * it permits. pkijs unions them instead: it collects the subtrees it meets into one list and lets a
+ * name match any entry. So the widest CA on the path decided the outcome, and a CA could be escaped
+ * by one below it asserting something broader. That is not a corner case, because a sub-CA writes
+ * the certificates it issues: the holder of a CA restricted to `team-a.example.com` could issue
+ * itself a sub-CA permitting `example.com` and mint a leaf for any name under it.
+ *
+ * Since a name is inside an intersection exactly when it is inside each of its members, this runs
+ * one pass per constraining CA and denies if any of them denies. Each pass covers the path from the
+ * leaf up to that CA, and only that CA's constraints are in play: they are handed over as the RFC's
+ * initial-permitted/excluded-subtrees inputs, and every certificate on the path is substituted for a
+ * copy without its own name constraints extension so pkijs has nothing left to union them with. The
+ * initial inputs are also what lets a constrained CA that is itself the anchor be honored, since
+ * pkijs never reads the constraints of the certificate it treats as the trust anchor.
*
- * What is not delegated is how the names of one certificate combine. pkijs decides a permitted
+ * How the names of a single certificate combine is not delegated either. pkijs decides a permitted
* subtree group by OR-ing every name of that type, so one name inside the permitted subtree carries
* the rest, whereas 6.1.4 (g) requires every name of a constrained type to be within a permitted
* subtree. Left alone, the holder of a constrained sub-CA could mint a leaf pairing one in-scope
@@ -404,16 +484,17 @@ const enforceNameConstraints = async (orderedPath: TNativeX509[]): Promise<TVeri
return { ok: false, reasonCode: "unsupported_name_constraint" };
}
- if (!pathConstraints.some((state) => state.status === "present")) return null;
-
- const anchorState = pathConstraints[pathConstraints.length - 1];
- const anchorConstraints = anchorState.status === "present" ? anchorState.constraints : null;
+ // A leaf's own constraints restrict nothing below it, so only the CAs above it constrain the path.
+ const constrainingCertificates = pathConstraints.flatMap((state, idx) =>
+ idx > 0 && state.status === "present" ? [{ idx, constraints: state.constraints }] : []
+ );
+ if (!constrainingCertificates.length) return null;
- const evaluate = async (path: Certificate[]): Promise<TVerificationFailure | null> => {
+ const evaluate = async (path: Certificate[], constraints: NameConstraints): Promise<TVerificationFailure | null> => {
const { result, resultCode, resultMessage } = await new NameConstraintsEngine(path).verify(
{
- initialPermittedSubtreesSet: anchorConstraints?.permittedSubtrees ?? [],
- initialExcludedSubtreesSet: anchorConstraints?.excludedSubtrees ?? []
+ initialPermittedSubtreesSet: constraints.permittedSubtrees ?? [],
+ initialExcludedSubtreesSet: constraints.excludedSubtrees ?? []
},
pkiCryptoEngine
);
@@ -429,30 +510,39 @@ const enforceNameConstraints = async (orderedPath: TNativeX509[]): Promise<TVeri
return { ok: false, reasonCode: "ca_verification_failed" };
};
- const failure = await evaluate(parsedPath);
- if (failure) return failure;
+ const constrainedTypes = permittedSubtreeTypes(constrainingCertificates.map(({ constraints }) => constraints));
- const constrainedTypes = permittedSubtreeTypes(pathConstraints);
- if (!constrainedTypes.size) return null;
+ const perName = constrainedTypes.size
+ ? orderedPath.slice(0, -1).flatMap((cert, idx) => {
+ const evaluation = perNameEvaluation(cert, parsedPath[idx], constrainedTypes);
+ return evaluation ? [{ idx, evaluation }] : [];
+ })
+ : [];
- const perName = orderedPath.slice(0, -1).flatMap((cert, idx) => {
- const evaluation = perNameEvaluation(cert, parsedPath[idx], constrainedTypes);
- return evaluation ? [{ idx, evaluation }] : [];
- });
+ const constraintFreePath = orderedPath.map(toNameConstraintFreeCertificate);
- const rounds = Math.max(0, ...perName.map(({ evaluation }) => evaluation.rounds));
+ for (const { idx: constrainingIdx, constraints } of constrainingCertificates) {
+ const basePath = constraintFreePath.slice(0, constrainingIdx + 1);
- for (let round = 0; round < rounds; round += 1) {
- const path = [...parsedPath];
- perName.forEach(({ idx, evaluation }) => {
- if (evaluation.rounds <= round) return;
- evaluation.selectRound(round);
- path[idx] = evaluation.certificate;
- });
+ // eslint-disable-next-line no-await-in-loop -- stop at the first CA whose namespace the path leaves
+ const failure = await evaluate(basePath, constraints);
+ if (failure) return failure;
- // eslint-disable-next-line no-await-in-loop -- stop at the first name the path does not permit
- const roundFailure = await evaluate(path);
- if (roundFailure) return roundFailure;
+ const perNameBelow = perName.filter(({ idx }) => idx < constrainingIdx);
+ const rounds = Math.max(0, ...perNameBelow.map(({ evaluation }) => evaluation.rounds));
+
+ for (let round = 0; round < rounds; round += 1) {
+ const path = [...basePath];
+ perNameBelow.forEach(({ idx, evaluation }) => {
+ if (evaluation.rounds <= round) return;
+ evaluation.selectRound(round);
+ path[idx] = evaluation.certificate;
+ });
+
+ // eslint-disable-next-line no-await-in-loop -- stop at the first name the path does not permit
+ const roundFailure = await evaluate(path, constraints);
+ if (roundFailure) return roundFailure;
+ }
}
return null;