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(pit-service): implement secret policy violation scanning in processNewCommitRaw
Victor Hugo dos Santosa52c72218e0a
diff --git a/backend/src/ee/services/pit/pit-service.test.ts b/backend/src/ee/services/pit/pit-service.test.tsindex e3f83d92b3..9560629aba 100644--- a/backend/src/ee/services/pit/pit-service.test.ts+++ b/backend/src/ee/services/pit/pit-service.test.ts@@ -1,10 +1,15 @@import { vi } from "vitest";+import { BadRequestError } from "@app/lib/errors";import { ActorType } from "@app/services/auth/auth-type";import { ChangeType, ResourceType } from "@app/services/folder-commit/folder-commit-service";+import { scanSecretPolicyViolations } from "../secret-scanning-v2/secret-scanning-v2-fns";import { pitServiceFactory } from "./pit-service";+vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));+vi.mock("../secret-scanning-v2/secret-scanning-v2-fns", () => ({ scanSecretPolicyViolations: vi.fn() }));+const buildService = ({ commitFolderId = "folder-1" }: { commitFolderId?: string } = {}) => {const getChangeVersions = vi.fn().mockResolvedValue([]);const compareFolderStates = vi.fn().mockResolvedValue([@@ -114,3 +119,105 @@ describe("compareCommitChanges", () => {expect(getChangeVersions).not.toHaveBeenCalled();});});++describe("processNewCommitRaw", () => {+ const TRX = { isTx: true };+ const approval = { id: "request-1", policyId: "policy-1", commits: [{ id: "commit-1" }] };+ const build = ({ withPolicy = true } = {}) => {+ const policy = withPolicy ? { id: "policy-1", bypassForMachineIdentities: false } : undefined;+ const deps = {+ secretApprovalPolicyService: { getSecretApprovalPolicy: vi.fn().mockResolvedValue(policy) },+ projectDAL: {+ findById: vi.fn().mockResolvedValue({ id: "project-1", secretDetectionIgnoreValues: ["ignored"] })+ },+ folderCommitDAL: { transaction: vi.fn((fn: (tx: unknown) => Promise<unknown>) => fn(TRX)) },+ folderDAL: { findBySecretPath: vi.fn().mockResolvedValue({ id: "folder-1" }) },+ secretApprovalRequestService: {+ generateSecretApprovalRequestV2Bridge: vi.fn().mockResolvedValue(approval),+ createSecretApprovalSideEffects: vi.fn().mockResolvedValue(undefined)+ },+ secretV2BridgeService: {+ createManySecret: vi.fn().mockResolvedValue([]),+ updateManySecret: vi.fn().mockResolvedValue([])+ }+ };+ const service = pitServiceFactory(deps as unknown as Parameters<typeof pitServiceFactory>[0]);+ const run = (secrets: object) =>+ service.processNewCommitRaw({+ actor: ActorType.USER,+ actorId: "user-1",+ actorOrgId: "org-1",+ actorAuthMethod: null,+ projectId: "project-1",+ environment: "dev",+ secretPath: "/",+ message: "",+ changes: { secrets, folders: {} } as unknown as Parameters<typeof service.processNewCommitRaw>[0]["changes"]+ });+ return { deps, run };+ };++ test("scans created and updated values before opening the transaction when a policy applies", async () => {+ const { deps, run } = build();+ const scan = vi.mocked(scanSecretPolicyViolations);+ scan.mockReset();+ scan.mockImplementationOnce(() => {+ throw new BadRequestError({ message: "Secret value detected in TOKEN." });+ });++ await expect(+ run({ create: [{ secretKey: "TOKEN", secretValue: "leak" }], update: [{ secretKey: "OTHER", secretValue: "v" }] })+ ).rejects.toThrow("Secret value detected in TOKEN.");++ expect(scan).toHaveBeenCalledWith(+ "project-1",+ "/",+ [+ { secretKey: "TOKEN", secretValue: "leak" },+ { secretKey: "OTHER", secretValue: "v" }+ ],+ ["ignored"]+ );+ expect(deps.folderCommitDAL.transaction).not.toHaveBeenCalled();+ expect(deps.secretApprovalRequestService.generateSecretApprovalRequestV2Bridge).not.toHaveBeenCalled();+ });++ test("leaves direct updates to updateManySecret's own scan when no policy applies", async () => {+ const { run } = build({ withPolicy: false });+ const scan = vi.mocked(scanSecretPolicyViolations);+ scan.mockReset();++ await run({ update: [{ secretKey: "OTHER", secretValue: "v" }] });++ expect(scan).not.toHaveBeenCalled();+ });++ test("opens the request in the caller's transaction and notifies approvers only after it commits", async () => {+ const { deps, run } = build();+ vi.mocked(scanSecretPolicyViolations).mockReset();++ const result = await run({ update: [{ secretKey: "OTHER", secretValue: "v" }] });++ expect(deps.secretApprovalRequestService.generateSecretApprovalRequestV2Bridge).toHaveBeenCalledWith(+ expect.objectContaining({ trx: TRX, skipPostProcessing: true })+ );+ expect(deps.secretApprovalRequestService.createSecretApprovalSideEffects).toHaveBeenCalledWith(+ expect.objectContaining({ secretApprovalRequest: approval, secretKeys: ["OTHER"] })+ );+ const sideEffectsOrder =+ deps.secretApprovalRequestService.createSecretApprovalSideEffects.mock.invocationCallOrder[0];+ const transactionOrder = deps.folderCommitDAL.transaction.mock.invocationCallOrder[0];+ expect(sideEffectsOrder).toBeGreaterThan(transactionOrder);+ expect(result).toMatchObject({ approvalId: "request-1" });+ });++ test("a failed notification does not fail the save", async () => {+ const { deps, run } = build();+ vi.mocked(scanSecretPolicyViolations).mockReset();+ deps.secretApprovalRequestService.createSecretApprovalSideEffects.mockRejectedValueOnce(new Error("smtp down"));++ await expect(run({ update: [{ secretKey: "OTHER", secretValue: "v" }] })).resolves.toMatchObject({+ approvalId: "request-1"+ });+ });+});diff --git a/backend/src/ee/services/pit/pit-service.ts b/backend/src/ee/services/pit/pit-service.tsindex f163dbec2c..f1365a50fb 100644--- a/backend/src/ee/services/pit/pit-service.ts+++ b/backend/src/ee/services/pit/pit-service.ts@@ -34,6 +34,7 @@ import { shouldApplyPolicy } from "../secret-approval-policy/secret-approval-polimport { TSecretApprovalPolicyServiceFactory } from "../secret-approval-policy/secret-approval-policy-service";import { TSecretApprovalRequestServiceFactory } from "../secret-approval-request/secret-approval-request-service";import { TCreateSecretApprovalSideEffectsDTO } from "../secret-approval-request/secret-approval-request-types";+import { scanSecretPolicyViolations } from "../secret-scanning-v2/secret-scanning-v2-fns";type TPitServiceFactoryDep = {folderCommitService: TFolderCommitServiceFactory;@@ -687,6 +688,21 @@ export const pitServiceFactory = ({}}+ // Secret detection is skipped for writes made inside a caller's transaction (the change request and+ // createManySecret below), so it runs here first. updateManySecret scans the direct updates itself.+ const secretsToScan = [+ ...(changes.secrets?.create ?? []),+ ...(shouldApplyPolicy(policy, actor) ? (changes.secrets?.update ?? []).filter((el) => el.secretValue) : [])+ ];+ if (secretsToScan.length) {+ await scanSecretPolicyViolations(+ projectId,+ secretPath,+ secretsToScan.map((el) => ({ secretKey: el.secretKey, secretValue: el.secretValue as string })),+ project.secretDetectionIgnoreValues || []+ );+ }+// Notifying approvers reaches Slack, Teams and SMTP, so it waits until the request has committedlet approvalSideEffects: TCreateSecretApprovalSideEffectsDTO | undefined;const response = await folderCommitDAL.transaction(async (trx) => {