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
refactor: update Azure Key Vault connection handling and add tests for client assertion generation
Victor Hugo dos Santosbf5fb7c86fe9
diff --git a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.tsindex c135e61164..e38835b3e4 100644--- a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts+++ b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts@@ -4,7 +4,6 @@ import { AxiosError, AxiosResponse } from "axios";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";import { BadRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import {decryptAppConnectionCredentials,encryptAppConnectionCredentials,@@ -371,10 +370,6 @@ export const validateAzureKeyVaultConnectionCredentials = async (config: TAzureK} else if (e instanceof BadRequestError) {throw e;} else {- logger.error(- e,- "validateAzureKeyVaultConnectionCredentials: Failed to get access token using certificate authentication"- );throw new InternalServerError({message: "Failed to get access token"});diff --git a/backend/src/services/app-connection/shared/azure/generate-client-assertion.test.ts b/backend/src/services/app-connection/shared/azure/generate-client-assertion.test.tsnew file mode 100644index 0000000000..87e88c44c2--- /dev/null+++ b/backend/src/services/app-connection/shared/azure/generate-client-assertion.test.ts@@ -0,0 +1,117 @@+import { createPublicKey, createVerify, generateKeyPairSync } from "crypto";++import { BadRequestError } from "@app/lib/errors";++import { generateClientAssertion } from "./generate-client-assertion";++const CLIENT_ID = "11111111-2222-3333-4444-555555555555";+const TENANT_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";++const decodeBase64Url = (segment: string): Buffer => Buffer.from(segment, "base64url");+const decodeJsonSegment = <T>(segment: string): T => JSON.parse(decodeBase64Url(segment).toString("utf8")) as T;++// Generate a real RSA keypair + a base64-wrapped "certificate" body once for the suite.+// generateClientAssertion only base64-decodes the certificate body and SHA-1s it, so any+// PEM-wrapped base64 blob works as the certificate input — no X.509 ASN.1 needed.+const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });+const privateKeyPem = privateKey.export({ format: "pem", type: "pkcs8" }) as string;+const privateKeyDerBase64 = privateKey.export({ format: "der", type: "pkcs8" }).toString("base64");+const publicKeyDerBase64 = publicKey.export({ format: "der", type: "spki" }).toString("base64");+const certificatePem = `-----BEGIN CERTIFICATE-----\n${publicKeyDerBase64.match(/.{1,64}/g)!.join("\n")}\n-----END CERTIFICATE-----`;++describe("generateClientAssertion", () => {+ test("returns a three-segment JWT with the expected header and claims", () => {+ const jwt = generateClientAssertion(CLIENT_ID, TENANT_ID, privateKeyPem, certificatePem);++ const segments = jwt.split(".");+ expect(segments).toHaveLength(3);++ const header = decodeJsonSegment<{ alg: string; typ: string; x5t: string }>(segments[0]);+ expect(header.alg).toBe("RS256");+ expect(header.typ).toBe("JWT");+ expect(header.x5t).toMatch(/^[A-Za-z0-9_-]+$/); // base64url, non-empty++ const payload = decodeJsonSegment<{+ aud: string;+ exp: number;+ iss: string;+ jti: string;+ nbf: number;+ sub: string;+ }>(segments[1]);+ expect(payload.aud).toBe(`https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`);+ expect(payload.iss).toBe(CLIENT_ID);+ expect(payload.sub).toBe(CLIENT_ID);+ expect(payload.jti).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);+ expect(payload.exp - payload.nbf).toBe(600);+ });++ test("signature verifies against the matching public key (PEM input)", () => {+ const jwt = generateClientAssertion(CLIENT_ID, TENANT_ID, privateKeyPem, certificatePem);+ const [headerSeg, payloadSeg, signatureSeg] = jwt.split(".");++ const verifier = createVerify("RSA-SHA256");+ verifier.update(`${headerSeg}.${payloadSeg}`);+ verifier.end();+ expect(verifier.verify(publicKey, decodeBase64Url(signatureSeg))).toBe(true);+ });++ test("signature verifies when private key is provided as bare base64 DER (no PEM wrapper)", () => {+ const jwt = generateClientAssertion(CLIENT_ID, TENANT_ID, privateKeyDerBase64, certificatePem);+ const [headerSeg, payloadSeg, signatureSeg] = jwt.split(".");++ const verifier = createVerify("RSA-SHA256");+ verifier.update(`${headerSeg}.${payloadSeg}`);+ verifier.end();+ expect(verifier.verify(publicKey, decodeBase64Url(signatureSeg))).toBe(true);+ });++ test("strips PEM markers and whitespace before computing the thumbprint", () => {+ const messyCertificate = certificatePem+ .replace("-----BEGIN CERTIFICATE-----", " -----BEGIN CERTIFICATE-----\r\n")+ .replace("-----END CERTIFICATE-----", "\r\n-----END CERTIFICATE----- ");++ const cleanJwt = generateClientAssertion(CLIENT_ID, TENANT_ID, privateKeyPem, certificatePem);+ const messyJwt = generateClientAssertion(CLIENT_ID, TENANT_ID, privateKeyPem, messyCertificate);++ const cleanX5t = decodeJsonSegment<{ x5t: string }>(cleanJwt.split(".")[0]).x5t;+ const messyX5t = decodeJsonSegment<{ x5t: string }>(messyJwt.split(".")[0]).x5t;+ expect(messyX5t).toBe(cleanX5t);+ });++ test("issues a fresh jti per call", () => {+ const a = generateClientAssertion(CLIENT_ID, TENANT_ID, privateKeyPem, certificatePem);+ const b = generateClientAssertion(CLIENT_ID, TENANT_ID, privateKeyPem, certificatePem);+ const jtiA = decodeJsonSegment<{ jti: string }>(a.split(".")[1]).jti;+ const jtiB = decodeJsonSegment<{ jti: string }>(b.split(".")[1]).jti;+ expect(jtiA).not.toBe(jtiB);+ });++ test("throws BadRequestError when the private key is unparseable text", () => {+ expect(() => generateClientAssertion(CLIENT_ID, TENANT_ID, "not-a-real-private-key", certificatePem)).toThrow(+ BadRequestError+ );+ expect(() => generateClientAssertion(CLIENT_ID, TENANT_ID, "not-a-real-private-key", certificatePem)).toThrow(+ /Invalid private key format/+ );+ });++ test("throws BadRequestError when a PEM-wrapped private key has corrupted contents", () => {+ const corruptPem = "-----BEGIN PRIVATE KEY-----\nnotvalidbase64!!!\n-----END PRIVATE KEY-----";+ expect(() => generateClientAssertion(CLIENT_ID, TENANT_ID, corruptPem, certificatePem)).toThrow(BadRequestError);+ });++ test("throws BadRequestError when the bare base64 DER fallback path receives garbage", () => {+ // No "BEGIN PRIVATE KEY" → falls through to the DER fallback, which fails to parse.+ expect(() => generateClientAssertion(CLIENT_ID, TENANT_ID, "garbage-not-base64-der", certificatePem)).toThrow(+ BadRequestError+ );+ });++ // Sanity check that the suite's keypair fixture is sound — guards against future+ // node-crypto changes that could silently break the assumptions above.+ test("test fixture: regenerated public key from the private key matches the keypair public", () => {+ const recovered = createPublicKey(privateKeyPem);+ expect(recovered.export({ format: "der", type: "spki" }).toString("base64")).toBe(publicKeyDerBase64);+ });+});diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsxindex 76b4ba8240..6166d3c135 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx@@ -10,9 +10,9 @@ import {FormControl,Input,ModalClose,+ SecretInput,Select,- SelectItem,- TextArea+ SelectItem} from "@app/components/v2";import {APP_CONNECTION_MAP,@@ -390,17 +390,18 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit, projectId<Controllername="credentials.certificateBody"control={control}- render={({ field, fieldState: { error } }) => (+ render={({ field: { value, onChange }, fieldState: { error } }) => (<FormControlisError={Boolean(error?.message)}label="Certificate"errorText={error?.message}tooltipText="The PEM-encoded public certificate uploaded to your Azure App Registration.">- <TextArea- {...field}- className="h-[6rem] resize-none!"- placeholder={"-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"}+ <SecretInput+ containerClassName="text-gray-400 group-focus-within:border-primary-400/50! border border-mineshaft-500 bg-mineshaft-900 px-2.5 py-1.5"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder="-----BEGIN CERTIFICATE-----..."/></FormControl>)}@@ -408,17 +409,18 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit, projectId<Controllername="credentials.privateKey"control={control}- render={({ field, fieldState: { error } }) => (+ render={({ field: { value, onChange }, fieldState: { error } }) => (<FormControlisError={Boolean(error?.message)}label="Private Key"errorText={error?.message}tooltipText="The PEM-encoded private key matching the certificate. The private key is never transmitted to Azure; it is only used locally to sign the client assertion.">- <TextArea- {...field}- className="h-[6rem] resize-none!"- placeholder={"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"}+ <SecretInput+ containerClassName="text-gray-400 group-focus-within:border-primary-400/50! border border-mineshaft-500 bg-mineshaft-900 px-2.5 py-1.5"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder="-----BEGIN PRIVATE KEY-----..."/></FormControl>)}