Skip to content

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

fix 500s

Thiago Araujo da Silvabb7a30d2f877
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 6e61bbdb57..8ec67fe170 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
@@ -138,14 +138,21 @@ const attachTlsCertAuth = (identityId: string, caCertificate: string, verifyClie
body: { caCertificate, verifyClientCertificateChain }
});
-const login = (identityId: string, chain: x509.X509Certificate[]) =>
+const loginWithHeader = (identityId: string, clientCertHeader: string) =>
testServer.inject({
method: "POST",
url: "/api/v1/auth/tls-cert-auth/login",
- headers: { "x-identity-tls-cert-auth-client-cert": encodeURIComponent(chain.map(toPem).join("")) },
+ headers: { "x-identity-tls-cert-auth-client-cert": clientCertHeader },
body: { identityId }
});
+const login = (identityId: string, chain: x509.X509Certificate[]) =>
+ loginWithHeader(identityId, encodeURIComponent(chain.map(toPem).join("")));
+
+// PEM markers around something that is not a certificate: the chain splitter accepts it and Node's
+// OpenSSL-backed parser is what rejects it.
+const UNDECODABLE_PEM = "-----BEGIN CERTIFICATE-----\nZm9vYmFy\n-----END CERTIFICATE-----\n";
+
/**
* Drives the real login route end to end: the CA certificate is stored through the API (KMS
* encrypted), and the client chain arrives in the header a TLS-terminating proxy would set.
@@ -335,4 +342,44 @@ describe("Identity TLS certificate auth v1", async () => {
});
});
});
+
+ // Certificate material the proxy forwards but nothing can parse. Each of these reached OpenSSL or
+ // decodeURIComponent unguarded and surfaced as a 500, which tells the caller nothing and keeps the
+ // attempt out of the audit log.
+ describe("malformed certificate material", async () => {
+ test("rejects a client certificate header that is not URL-encoded", async () => {
+ const ca = await makeRoot("Malformed Header CA");
+
+ await withIdentity({ caCertificate: ca.cert, verifyChain: false }, async (identityId) => {
+ const res = await loginWithHeader(identityId, "%zz-----BEGIN CERTIFICATE-----");
+ expect(res.statusCode).toBe(400);
+ expect(res.json().message).toContain("not valid URL-encoded data");
+ });
+ });
+
+ test("denies a client certificate that cannot be decoded", async () => {
+ const ca = await makeRoot("Undecodable Leaf CA");
+
+ await withIdentity({ caCertificate: ca.cert, verifyChain: false }, async (identityId) => {
+ const res = await loginWithHeader(identityId, encodeURIComponent(UNDECODABLE_PEM));
+ expect(res.statusCode).toBe(401);
+ expect(res.json().message).toContain("client certificate could not be decoded");
+ });
+ });
+
+ test("denies a presented chain carrying a certificate that cannot be decoded", async () => {
+ const root = await makeRoot("Undecodable Chain Root CA");
+ const intermediate = await makeIntermediate("Rotating Intermediate CA", root);
+ const leaf = await makeLeaf("workload", intermediate, { usages: [CLIENT_AUTH_EKU] });
+
+ await withIdentity({ caCertificate: root.cert, verifyChain: true }, async (identityId) => {
+ const res = await loginWithHeader(
+ identityId,
+ encodeURIComponent(toPem(leaf.cert) + toPem(intermediate.cert) + UNDECODABLE_PEM)
+ );
+ expect(res.statusCode).toBe(401);
+ expect(res.json().message).toContain("presented chain could not be decoded");
+ });
+ });
+ });
});
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 9947f0e838..e5c321fe6c 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
@@ -22,6 +22,7 @@ import {
UnauthorizedError
} from "@app/lib/errors";
import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
+import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
@@ -89,6 +90,55 @@ const nameConstraintsProblemMessage = (problem: TNameConstraintsProblem) => {
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.`;
};
+/**
+ * The chain arrives percent-encoded, because that is what a TLS-terminating proxy emits (nginx's
+ * `$ssl_client_escaped_cert`, and the equivalent in Envoy or HAProxy). A value that does not decode
+ * did not come from a proxy that encodes correctly, so it is the request that is malformed rather
+ * than the client's certificate that is untrusted.
+ */
+const decodeClientCertificateHeader = (clientCertificate: string) => {
+ try {
+ return decodeURIComponent(clientCertificate);
+ } catch {
+ throw new BadRequestError({
+ message:
+ "Malformed client certificate header: the value is not valid URL-encoded data. The TLS-terminating proxy must URL-encode the certificate chain it forwards."
+ });
+ }
+};
+
+/**
+ * Node's X509Certificate is OpenSSL-backed and rejects DER that carries the PEM markers but does not
+ * parse. Reading the certificate is what establishes who the client is, so a certificate that cannot
+ * be read has not established it and the login is denied, rather than failing the request as an
+ * internal error. Denying also keeps the attempt in the audit log, which only records
+ * `UnauthorizedError`, so a client probing the endpoint with junk stays visible.
+ *
+ * The OpenSSL reason is logged rather than returned, since it describes the encoding rather than
+ * anything the caller can act on.
+ */
+const parsePresentedCertificate = (
+ pem: string,
+ role: "leaf" | "chain",
+ detail: { identityId: string; orgId: string; identityName: string }
+) => {
+ try {
+ return new crypto.nativeCrypto.X509Certificate(pem);
+ } catch (err) {
+ logger.warn(
+ err,
+ `TLS certificate auth: a presented certificate could not be decoded [role=${role}] [identityId=${detail.identityId}]`
+ );
+ throw new UnauthorizedError({
+ message:
+ role === "leaf"
+ ? "Access denied: the client certificate could not be decoded."
+ : "Access denied: a CA certificate in the presented chain could not be decoded.",
+ detail: { reasonCode: "certificate_decode_failed", ...detail }
+ });
+ }
+};
+
/**
* Reject a CA certificate the moment it is configured, rather than at every login it would deny.
*
@@ -196,13 +246,15 @@ export const identityTlsCertAuthServiceFactory = ({
cipherTextBlob: identityTlsCertAuth.encryptedCaCertificate
}).toString();
- const presentedCertificates = extractX509CertFromChain(decodeURIComponent(clientCertificate));
+ const presentedCertificates = extractX509CertFromChain(decodeClientCertificateHeader(clientCertificate));
const leafCertificate = presentedCertificates?.[0];
if (!leafCertificate) {
throw new BadRequestError({ message: "Missing client certificate" });
}
- const clientCertificateX509 = new crypto.nativeCrypto.X509Certificate(leafCertificate);
+ const failureDetail = { identityId: identity.id, orgId: identity.orgId, identityName: identity.name };
+
+ const clientCertificateX509 = parsePresentedCertificate(leafCertificate, "leaf", failureDetail);
const caCertificateX509 = new crypto.nativeCrypto.X509Certificate(caCertificate);
if (identityTlsCertAuth.verifyClientCertificateChain) {
@@ -213,7 +265,7 @@ export const identityTlsCertAuthServiceFactory = ({
// long-lived root while the client presents the current intermediate alongside its leaf.
const presentedChain = presentedCertificates
.slice(1)
- .map((pem) => new crypto.nativeCrypto.X509Certificate(pem));
+ .map((pem) => parsePresentedCertificate(pem, "chain", failureDetail));
const chainResult = await verifyClientCertificateChain({
leaf: clientCertificateX509,