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
feat(secret-rotation): add Stripe JWE secret decryption
Calvin8b899e4ae56b
diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-jwe.test.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-jwe.test.tsnew file mode 100644index 0000000000..55c387d23c--- /dev/null+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-jwe.test.ts@@ -0,0 +1,100 @@+import crypto from "node:crypto";++import { describe, expect, it } from "vitest";++import { decryptStripeJwe, generateStripeEncryptionKeyPair, readStripeSecret } from "./stripe-api-key-jwe";++/** Builds the compact JWE Stripe would return, so the test proves the real unwrap path. */+const encryptJwe = (+ plaintext: string,+ publicKeyPem: string,+ { alg = "RSA-OAEP", enc = "A256GCM" }: { alg?: string; enc?: string } = {}+) => {+ const header = Buffer.from(JSON.stringify({ alg, enc })).toString("base64url");+ const contentKey = crypto.randomBytes(32);+ const wrapped = crypto.publicEncrypt(+ {+ key: publicKeyPem,+ padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,+ oaepHash: alg === "RSA-OAEP" ? "sha1" : "sha256"+ },+ contentKey+ );+ const iv = crypto.randomBytes(12);+ const cipher = crypto.createCipheriv("aes-256-gcm", contentKey, iv);+ cipher.setAAD(Buffer.from(header, "ascii"));+ const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);++ return [+ header,+ wrapped.toString("base64url"),+ iv.toString("base64url"),+ ciphertext.toString("base64url"),+ cipher.getAuthTag().toString("base64url")+ ].join(".");+};++describe("decryptStripeJwe", () => {+ it("round-trips both algorithms Stripe may use, under FIPS", async () => {+ // The unit suite runs with --force-fips. OAEP with SHA-1 is the algorithm Stripe returns as+ // `RSA-OAEP`, and this assertion is what stops a toolchain bump from breaking live mode silently.+ expect(crypto.getFips()).toBe(1);++ const { publicKey, privateKey } = await generateStripeEncryptionKeyPair();++ for (const alg of ["RSA-OAEP", "RSA-OAEP-256"]) {+ const jwe = encryptJwe("rk_live_secret", publicKey, { alg });+ expect(decryptStripeJwe(jwe, privateKey)).toBe("rk_live_secret");+ }+ });++ it("rejects a JWE without exactly five segments", async () => {+ const { privateKey } = await generateStripeEncryptionKeyPair();++ expect(() => decryptStripeJwe("a.b.c", privateKey)).toThrow(/5 segments, got 3/);+ });++ it("names an unsupported key algorithm rather than guessing", async () => {+ const { publicKey, privateKey } = await generateStripeEncryptionKeyPair();+ const jwe = encryptJwe("rk_live_secret", publicKey, { alg: "RSA1_5" });++ expect(() => decryptStripeJwe(jwe, privateKey)).toThrow(/RSA1_5/);+ });++ it("rejects an unsupported content encryption algorithm", async () => {+ const { publicKey, privateKey } = await generateStripeEncryptionKeyPair();+ const jwe = encryptJwe("rk_live_secret", publicKey, { enc: "A128GCM" });++ expect(() => decryptStripeJwe(jwe, privateKey)).toThrow(/A128GCM/);+ });++ it("fails a tampered ciphertext", async () => {+ const { publicKey, privateKey } = await generateStripeEncryptionKeyPair();+ const segments = encryptJwe("rk_live_secret", publicKey).split(".");+ segments[4] = Buffer.alloc(16).toString("base64url");++ expect(() => decryptStripeJwe(segments.join("."), privateKey)).toThrow();+ });+});++describe("readStripeSecret", () => {+ it("prefers the plaintext token test mode returns", async () => {+ const { privateKey } = await generateStripeEncryptionKeyPair();++ expect(readStripeSecret({ token: "rk_test_plain", encrypted_secret: null }, privateKey)).toBe("rk_test_plain");+ });++ it("decrypts the JWE live mode returns", async () => {+ const { publicKey, privateKey } = await generateStripeEncryptionKeyPair();+ const jwe = encryptJwe("rk_live_secret", publicKey);++ expect(readStripeSecret({ encrypted_secret: { ciphertext: jwe } }, privateKey)).toBe("rk_live_secret");+ });++ it("throws when Stripe returns neither", async () => {+ const { privateKey } = await generateStripeEncryptionKeyPair();++ expect(() => readStripeSecret({}, privateKey)).toThrow(/without a secret/);+ expect(() => readStripeSecret(undefined, privateKey)).toThrow(/without a secret/);+ });+});diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-jwe.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-jwe.tsnew file mode 100644index 0000000000..caa7d64448--- /dev/null+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-jwe.ts@@ -0,0 +1,95 @@+import crypto from "node:crypto";++import { BadRequestError } from "@app/lib/errors";++export type TStripeSecretKeyField = {+ token?: string | null;+ encrypted_secret?: { ciphertext?: string | null } | null;+};++// Stripe names OAEP with SHA-1 `RSA-OAEP`, which is the JOSE spelling. Both are accepted by the+// FIPS provider for key transport, so neither needs a fallback.+const SUPPORTED_KEY_ALGORITHMS: Record<string, "sha1" | "sha256"> = {+ "RSA-OAEP": "sha1",+ "RSA-OAEP-256": "sha256"+};++const SUPPORTED_CONTENT_ALGORITHM = "A256GCM";++export const generateStripeEncryptionKeyPair = async () =>+ new Promise<{ publicKey: string; privateKey: string }>((resolve, reject) => {+ crypto.generateKeyPair(+ "rsa",+ {+ modulusLength: 2048,+ publicKeyEncoding: { type: "spki", format: "pem" },+ privateKeyEncoding: { type: "pkcs8", format: "pem" }+ },+ (error, publicKey, privateKey) => (error ? reject(error) : resolve({ publicKey, privateKey }))+ );+ });++export const decryptStripeJwe = (jwe: string, privateKeyPem: string): string => {+ const segments = jwe.split(".");++ if (segments.length !== 5) {+ throw new BadRequestError({+ message: `Stripe returned a malformed encrypted secret: expected a compact JWE with 5 segments, got ${segments.length}.`+ });+ }++ const [protectedHeader, wrappedKey, iv, ciphertext, authTag] = segments;++ let header: { alg?: string; enc?: string };++ try {+ header = JSON.parse(Buffer.from(protectedHeader, "base64url").toString()) as typeof header;+ } catch {+ throw new BadRequestError({+ message: "Stripe returned an encrypted secret whose JWE header could not be parsed."+ });+ }++ const oaepHash = header.alg ? SUPPORTED_KEY_ALGORITHMS[header.alg] : undefined;++ if (!oaepHash) {+ throw new BadRequestError({+ message: `Stripe encrypted the secret with an unsupported key algorithm '${header.alg ?? "none"}'. Infisical supports RSA-OAEP and RSA-OAEP-256.`+ });+ }++ if (header.enc !== SUPPORTED_CONTENT_ALGORITHM) {+ throw new BadRequestError({+ message: `Stripe encrypted the secret with an unsupported content algorithm '${header.enc ?? "none"}'. Infisical supports ${SUPPORTED_CONTENT_ALGORITHM}.`+ });+ }++ const contentKey = crypto.privateDecrypt(+ { key: privateKeyPem, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash },+ Buffer.from(wrappedKey, "base64url")+ );++ const decipher = crypto.createDecipheriv("aes-256-gcm", contentKey, Buffer.from(iv, "base64url"));+ decipher.setAAD(Buffer.from(protectedHeader, "ascii"));+ decipher.setAuthTag(Buffer.from(authTag, "base64url"));++ return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64url")), decipher.final()]).toString();+};++/**+ * Test and sandbox accounts return the secret in plaintext, live accounts return a JWE. Both shapes+ * are real, and the one we develop against is not the one that matters.+ */+export const readStripeSecret = (secretKey: TStripeSecretKeyField | undefined, privateKeyPem: string): string => {+ if (secretKey?.token) return secretKey.token;++ const ciphertext = secretKey?.encrypted_secret?.ciphertext;++ if (!ciphertext) {+ throw new BadRequestError({+ message: "Stripe returned an API key without a secret. The key may need to be created again."+ });+ }++ return decryptStripeJwe(ciphertext, privateKeyPem);+};