Skip to content

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

feat: add side effects into the bridge service

adilson1236e754c9dd
diff --git a/backend/e2e-test/routes/v1/secret-approval-request-move-bridge.spec.ts b/backend/e2e-test/routes/v1/secret-approval-request-move-bridge.spec.ts
index a656c80f1a..4e7d4ca431 100644
--- a/backend/e2e-test/routes/v1/secret-approval-request-move-bridge.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-approval-request-move-bridge.spec.ts
@@ -4,10 +4,10 @@ import { Knex } from "knex";
import { SecretType, TableName } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
+import { ApprovalPolicyType, ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;
-const BRIDGE_MESSAGE = "Secret change requests on the approval system are not available yet.";
const projectId = seedData1.projectV3.id;
const envSlug = seedData1.environment.slug;
const SOURCE_FOLDER = "sar-move-bridge-source";
@@ -103,6 +103,12 @@ describe("Secret move under a secret approval policy", () => {
afterAll(async () => {
const db = getDb();
await db(TableName.SecretApprovalRequest).whereIn("folderId", Object.values(folderIds)).del();
+ await db(TableName.ApprovalRequests)
+ .whereIn(
+ "id",
+ db(TableName.SecretChangeRequests).select("approvalRequestId").whereIn("folderId", Object.values(folderIds))
+ )
+ .del();
await db(TableName.SecretApprovalPolicy).where({ id: legacyPolicyId }).del();
await db(TableName.ApprovalPolicies).where({ id: bridgePolicyId }).del();
await deleteTag(tagId);
@@ -154,17 +160,47 @@ describe("Secret move under a secret approval policy", () => {
expect(tagRows).toMatchObject([{ secretId: commit.id, tagId }]);
});
- test("a move into a path governed by a policy on the approval system is refused by the bridge", async () => {
+ test("a move into a path governed by a policy on the global approval system opens a request there", async () => {
const createRes = await createSecret(`/${SOURCE_FOLDER}`, "MOVE_TO_BRIDGE");
expect(createRes.statusCode).toBe(200);
const secretId = createRes.json().secret.id as string;
const moveRes = await moveSecrets(`/${BRIDGE_FOLDER}`, [secretId]);
- expect(moveRes.statusCode).toBe(400);
- expect(moveRes.json().message).toBe(BRIDGE_MESSAGE);
+ expect(moveRes.statusCode).toBe(200);
+ expect(moveRes.json()).toMatchObject({ isSourceUpdated: true, isDestinationUpdated: false });
expect(await requestsForFolder(folderIds[BRIDGE_FOLDER])).toHaveLength(0);
- const sourceSecret = await getDb()(TableName.SecretV2).where({ id: secretId }).first();
- expect(sourceSecret?.folderId).toBe(folderIds[SOURCE_FOLDER]);
+ const changeRequests = await getDb()(TableName.SecretChangeRequests).where({ folderId: folderIds[BRIDGE_FOLDER] });
+ expect(changeRequests).toHaveLength(1);
+ const [changeRequest] = changeRequests;
+ expect(changeRequest).toMatchObject({ hasMerged: false, isReplicated: null });
+ expect(
+ await getDb()(TableName.ApprovalRequests).where({ id: changeRequest.approvalRequestId }).first()
+ ).toMatchObject({
+ type: ApprovalPolicyType.SecretChange,
+ status: ApprovalRequestStatus.Open,
+ policyId: bridgePolicyId,
+ requesterId: seedData1.id
+ });
+ expect(
+ await getDb()(TableName.SecretApprovalRequestSecretV2).where({ secretChangeId: changeRequest.id })
+ ).toMatchObject([{ key: "MOVE_TO_BRIDGE", op: "create", requestId: null }]);
+
+ const detailsRes = await testServer.inject({
+ method: "GET",
+ url: `/api/v1/secret-approval-requests/${changeRequest.approvalRequestId}`,
+ headers: authHeaders()
+ });
+ expect(detailsRes.statusCode).toBe(200);
+ expect(detailsRes.json().approval).toMatchObject({
+ policy: { id: bridgePolicyId },
+ isReplicated: null,
+ commits: [{ secretKey: "MOVE_TO_BRIDGE", op: "create" }]
+ });
+
+ expect(await getDb()(TableName.SecretV2).where({ id: secretId }).first()).toBeUndefined();
+ expect(
+ await getDb()(TableName.SecretV2).where({ folderId: folderIds[BRIDGE_FOLDER], key: "MOVE_TO_BRIDGE" })
+ ).toHaveLength(0);
});
});
diff --git a/backend/src/db/migrations/20261002193921_secret-change-requests.ts b/backend/src/db/migrations/20261002193921_secret-change-requests.ts
index 5753bf6f38..32c8a43b9c 100644
--- a/backend/src/db/migrations/20261002193921_secret-change-requests.ts
+++ b/backend/src/db/migrations/20261002193921_secret-change-requests.ts
@@ -27,6 +27,7 @@ export async function up(knex: Knex): Promise<void> {
t.jsonb("conflicts").nullable();
t.text("commitMessage").nullable();
t.text("bypassReason").nullable();
+ t.boolean("isReplicated").nullable();
t.timestamps(true, true, true);
});
diff --git a/backend/src/db/schemas/secret-change-requests.ts b/backend/src/db/schemas/secret-change-requests.ts
index 9a429d36a1..22f80b349c 100644
--- a/backend/src/db/schemas/secret-change-requests.ts
+++ b/backend/src/db/schemas/secret-change-requests.ts
@@ -17,6 +17,7 @@ export const SecretChangeRequestsSchema = z.object({
conflicts: z.unknown().nullable().optional(),
commitMessage: z.string().nullable().optional(),
bypassReason: z.string().nullable().optional(),
+ isReplicated: z.boolean().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date()
});
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.ts
index 53a4e79c2b..5f67056782 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.test.ts
@@ -1,3 +1,4 @@
+import { Knex } from "knex";
import { describe, expect, test, vi } from "vitest";
import { TSecretApprovalPolicies } from "@app/db/schemas";
@@ -10,18 +11,34 @@ const POLICY_ID = "policy-1";
const build = () => {
const permissionService = { getProjectPermission: vi.fn() };
- const secretApprovalRequestDAL = { create: vi.fn() };
+ const secretApprovalRequestDAL = { create: vi.fn(), findById: vi.fn().mockResolvedValue(null) };
const secretChangePolicyBridgeService = {
findSecretChangePolicy: vi.fn().mockResolvedValue({ id: POLICY_ID })
};
+ const secretChangeRequestBridgeService = {
+ findSecretChangeRequest: vi.fn().mockResolvedValue(null),
+ createSecretChangeRequestSideEffects: vi.fn().mockResolvedValue(undefined)
+ };
+ const userDAL = { findById: vi.fn().mockResolvedValue({ id: "user-1", email: "[email protected]" }) };
+ const projectDAL = { findById: vi.fn().mockResolvedValue(null) };
const service = secretApprovalRequestServiceFactory({
permissionService,
secretApprovalRequestDAL,
- secretChangePolicyBridgeService
+ secretChangePolicyBridgeService,
+ secretChangeRequestBridgeService,
+ userDAL,
+ projectDAL
} as unknown as Parameters<typeof secretApprovalRequestServiceFactory>[0]);
- return { service, permissionService, secretApprovalRequestDAL, secretChangePolicyBridgeService };
+ return {
+ service,
+ permissionService,
+ secretApprovalRequestDAL,
+ secretChangePolicyBridgeService,
+ secretChangeRequestBridgeService,
+ projectDAL
+ };
};
describe("generateSecretApprovalRequest", () => {
@@ -51,3 +68,38 @@ describe("generateSecretApprovalRequest", () => {
expect(secretApprovalRequestDAL.create).not.toHaveBeenCalled();
});
});
+
+describe("createSecretApprovalSideEffects", () => {
+ const TX = { isTx: true } as unknown as Knex;
+ const dto = {
+ secretApprovalRequest: { id: "request-1", policyId: POLICY_ID, commits: [{ id: "commit-1" }] },
+ projectId: "project-1",
+ environment: "dev",
+ secretPath: "/",
+ secretKeys: ["KEY"],
+ actor: ActorType.USER,
+ actorId: "user-1",
+ actorOrgId: "org-1",
+ tx: TX
+ };
+
+ test("hands a request stored on the global approval system to the bridge, through the caller's transaction", async () => {
+ const { service, secretChangeRequestBridgeService, projectDAL } = build();
+ secretChangeRequestBridgeService.findSecretChangeRequest.mockResolvedValueOnce({ id: "request-1" });
+
+ await service.createSecretApprovalSideEffects(dto);
+
+ expect(secretChangeRequestBridgeService.findSecretChangeRequest).toHaveBeenCalledWith("request-1", TX);
+ expect(secretChangeRequestBridgeService.createSecretChangeRequestSideEffects).toHaveBeenCalledWith(dto);
+ expect(projectDAL.findById).not.toHaveBeenCalled();
+ });
+
+ test("keeps a legacy request on the legacy path", async () => {
+ const { service, secretChangeRequestBridgeService, projectDAL } = build();
+
+ await expect(service.createSecretApprovalSideEffects(dto)).rejects.toThrow();
+
+ expect(secretChangeRequestBridgeService.createSecretChangeRequestSideEffects).not.toHaveBeenCalled();
+ expect(projectDAL.findById).toHaveBeenCalledWith("project-1");
+ });
+});
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
index 64fc77bda1..e7a57fd1be 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
@@ -168,6 +168,7 @@ type TSecretApprovalRequestServiceFactoryDep = {
| "getSecretChangeRequestById"
| "listSecretChangeRequests"
| "countSecretChangeRequests"
+ | "createSecretChangeRequestSideEffects"
>;
};
@@ -236,8 +237,8 @@ export const secretApprovalRequestServiceFactory = ({
smtpService
});
- const $useSecretChangeRequestBridge = async (requestId: string) =>
- Boolean(await secretChangeRequestBridgeService.findSecretChangeRequest(requestId));
+ const $useSecretChangeRequestBridge = async (requestId: string, tx?: Knex) =>
+ Boolean(await secretChangeRequestBridgeService.findSecretChangeRequest(requestId, tx));
const requestCount = async ({
projectId,
@@ -1623,17 +1624,13 @@ export const secretApprovalRequestServiceFactory = ({
return secretApprovalRequest;
};
- const createSecretApprovalSideEffects = async ({
- secretApprovalRequest,
- projectId,
- environment,
- secretPath,
- secretKeys,
- actor,
- actorId,
- actorOrgId,
- tx
- }: TCreateSecretApprovalSideEffectsDTO) => {
+ const createSecretApprovalSideEffects = async (dto: TCreateSecretApprovalSideEffectsDTO) => {
+ if (await $useSecretChangeRequestBridge(dto.secretApprovalRequest.id, dto.tx)) {
+ return secretChangeRequestBridgeService.createSecretChangeRequestSideEffects(dto);
+ }
+
+ const { secretApprovalRequest, projectId, environment, secretPath, secretKeys, actor, actorId, actorOrgId, tx } =
+ dto;
const user =
actor === ActorType.IDENTITY
? undefined
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.test.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.test.ts
index 03ccd0c6e2..9b75c8c51a 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.test.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.test.ts
@@ -107,7 +107,11 @@ describe("toSecretChangeRequest", () => {
requesterId: null,
machineIdentityId: "identity-1"
}),
- secretChangeRequest: secretChangeRequest({ statusChangedByUserId: "user-2", bypassReason: "hotfix" }),
+ secretChangeRequest: secretChangeRequest({
+ statusChangedByUserId: "user-2",
+ bypassReason: "hotfix",
+ isReplicated: true
+ }),
commits: []
});
@@ -116,7 +120,8 @@ describe("toSecretChangeRequest", () => {
committerUserId: null,
committerIdentityId: "identity-1",
statusChangedByUserId: "user-2",
- bypassReason: "hotfix"
+ bypassReason: "hotfix",
+ isReplicated: true
});
expect(result.status).toBe("close");
});
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.ts
index 90d0a11c92..a61d48de10 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-fns.ts
@@ -103,7 +103,7 @@ export const toSecretChangeRequestBase = ({
folderId: secretChangeRequest.folderId,
createdAt: approvalRequest.createdAt,
updatedAt: approvalRequest.updatedAt,
- isReplicated: null,
+ isReplicated: secretChangeRequest.isReplicated ?? null,
committerUserId: approvalRequest.requesterId ?? null,
committerIdentityId: approvalRequest.machineIdentityId ?? null,
statusChangedByUserId: secretChangeRequest.statusChangedByUserId ?? null,
@@ -473,6 +473,7 @@ export const toSecretChangeRequestListItem = ({
conflicts: row.conflicts,
commitMessage: row.commitMessage,
bypassReason: row.bypassReason,
+ isReplicated: row.isReplicated,
statusChangedByUserId: row.statusChangedByUserId,
createdAt: row.createdAt,
updatedAt: row.updatedAt
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts
index 0b4cd72e29..8f2f8c6e92 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.test.ts
@@ -1383,3 +1383,171 @@ describe("secretChangeRequestBridge listSecretChangeRequests and countSecretChan
expect(deps.secretChangeRequestDAL.countByProjectId).toHaveBeenCalledWith("project-1", "approver-1", "policy-1");
});
});
+
+describe("secretChangeRequestBridge createSecretChangeRequest", () => {
+ const CREATE_DTO = {
+ policy: { id: "policy-1" },
+ folderId: "folder-1",
+ actor: ActorType.USER,
+ actorId: "user-1",
+ isReplicated: true,
+ commitMessage: "moved",
+ commits: [
+ { op: SecretOperations.Create, key: "NEW_KEY", encryptedValue: Buffer.from("v"), tagIds: ["tag-1"] },
+ { op: SecretOperations.Delete, key: "OLD_KEY", secretId: "secret-2", secretVersion: "version-2" }
+ ]
+ };
+
+ beforeEach(() => {
+ resolveRequester.mockReset().mockResolvedValue(REQUESTER);
+ runSecretChangeRequestSideEffects.mockClear();
+ });
+
+ const create = (service: ReturnType<typeof buildService>["service"], tx?: Knex) =>
+ service.createSecretChangeRequest(
+ CREATE_DTO as unknown as Parameters<ReturnType<typeof buildService>["service"]["createSecretChangeRequest"]>[0],
+ tx
+ );
+
+ test("writes the request envelope, change row, commits and tags in the caller's transaction", async () => {
+ const { service, deps } = buildService();
+ deps.secretChangePolicyBridgeService.findSecretChangePolicyById.mockResolvedValue({
+ ...POLICY,
+ projectId: "project-1"
+ });
+
+ const result = await create(service, CALLER_TX);
+
+ expect(deps.approvalRequestDAL.transaction).not.toHaveBeenCalled();
+ expect(deps.secretChangePolicyBridgeService.findSecretChangePolicyById).toHaveBeenCalledWith("policy-1", CALLER_TX);
+ expect(deps.projectDAL.findById).toHaveBeenCalledWith("project-1", CALLER_TX);
+ expect(resolveRequester).toHaveBeenCalledWith(ActorType.USER, "user-1", CALLER_TX);
+ expect(deps.approvalRequestDAL.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ projectId: "project-1",
+ organizationId: "org-1",
+ policyId: "policy-1",
+ type: ApprovalPolicyType.SecretChange,
+ status: ApprovalRequestStatus.Open,
+ requesterId: "user-1"
+ }),
+ CALLER_TX
+ );
+ expect(deps.secretChangeRequestDAL.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ approvalRequestId: "request-1",
+ folderId: "folder-1",
+ hasMerged: false,
+ commitMessage: "moved",
+ isReplicated: true
+ }),
+ CALLER_TX
+ );
+ expect(deps.secretApprovalRequestSecretDAL.insertV2Bridge).toHaveBeenCalledWith(
+ [
+ expect.objectContaining({ key: "NEW_KEY", op: SecretOperations.Create, secretChangeId: "change-1" }),
+ expect.objectContaining({ key: "OLD_KEY", op: SecretOperations.Delete, secretChangeId: "change-1" })
+ ],
+ CALLER_TX
+ );
+ const [insertedCommits] = deps.secretApprovalRequestSecretDAL.insertV2Bridge.mock.calls[0];
+ expect(insertedCommits[0]).not.toHaveProperty("tagIds");
+ expect(deps.secretApprovalRequestSecretDAL.insertApprovalSecretV2Tags).toHaveBeenCalledWith(
+ [{ secretId: "commit-0", tagId: "tag-1" }],
+ CALLER_TX
+ );
+ expect(runSecretChangeRequestSideEffects).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ id: "request-1",
+ policyId: "policy-1",
+ status: ApprovalRequestStatus.Open,
+ folderId: "folder-1",
+ isReplicated: true,
+ committerUserId: "user-1",
+ commits: [expect.objectContaining({ key: "NEW_KEY" }), expect.objectContaining({ key: "OLD_KEY" })]
+ });
+ });
+
+ test("opens its own transaction when the caller has none and skips the tag insert without tags", async () => {
+ const { service, deps } = buildService();
+ deps.secretChangePolicyBridgeService.findSecretChangePolicyById.mockResolvedValue({
+ ...POLICY,
+ projectId: "project-1"
+ });
+
+ await service.createSecretChangeRequest({
+ ...CREATE_DTO,
+ commits: [{ op: SecretOperations.Delete, key: "OLD_KEY", secretId: "secret-2" }]
+ } as unknown as Parameters<ReturnType<typeof buildService>["service"]["createSecretChangeRequest"]>[0]);
+
+ expect(deps.approvalRequestDAL.transaction).toHaveBeenCalledTimes(1);
+ expect(deps.secretChangeRequestDAL.create).toHaveBeenCalledWith(expect.anything(), OWN_TX);
+ expect(deps.secretApprovalRequestSecretDAL.insertApprovalSecretV2Tags).not.toHaveBeenCalled();
+ });
+
+ test("writes nothing when the policy is gone or has no approval step", async () => {
+ const { service, deps } = buildService({ steps: [] });
+ deps.secretChangePolicyBridgeService.findSecretChangePolicyById.mockResolvedValueOnce(null);
+ await expect(create(service, CALLER_TX)).rejects.toBeInstanceOf(NotFoundError);
+
+ deps.secretChangePolicyBridgeService.findSecretChangePolicyById.mockResolvedValueOnce({
+ ...POLICY,
+ projectId: "project-1"
+ });
+ await expect(create(service, CALLER_TX)).rejects.toThrow("has no approval step configured");
+ expect(deps.approvalRequestDAL.create).not.toHaveBeenCalled();
+ });
+});
+
+describe("secretChangeRequestBridge createSecretChangeRequestSideEffects", () => {
+ const SIDE_EFFECTS_DTO = {
+ secretApprovalRequest: { id: "request-1", policyId: "policy-1", commits: [{ id: "commit-1" }] },
+ projectId: "project-1",
+ environment: "dev",
+ secretPath: "/app",
+ secretKeys: ["NEW_KEY"],
+ actor: ActorType.USER,
+ actorId: "user-1",
+ actorOrgId: "org-1"
+ };
+
+ beforeEach(() => {
+ runSecretChangeRequestSideEffects.mockClear();
+ });
+
+ test("runs the bridge side effects for the stored request through the caller's transaction", async () => {
+ const { service, deps } = buildService();
+
+ await service.createSecretChangeRequestSideEffects({ ...SIDE_EFFECTS_DTO, tx: CALLER_TX });
+
+ expect(deps.approvalRequestDAL.findById).toHaveBeenCalledWith("request-1", CALLER_TX);
+ expect(deps.secretChangeRequestDAL.findOne).toHaveBeenCalledWith({ approvalRequestId: "request-1" }, CALLER_TX);
+ expect(deps.secretChangePolicyBridgeService.findSecretChangePolicyById).toHaveBeenCalledWith("policy-1", CALLER_TX);
+ expect(deps.projectDAL.findById).toHaveBeenCalledWith("project-1", CALLER_TX);
+ expect(runSecretChangeRequestSideEffects).toHaveBeenCalledWith({
+ approvalRequest: APPROVAL_REQUEST,
+ secretChangeRequest: SECRET_CHANGE_REQUEST,
+ policy: POLICY,
+ project: PROJECT,
+ commits: [{ id: "commit-1" }],
+ environment: "dev",
+ secretPath: "/app",
+ secretKeys: ["NEW_KEY"],
+ actor: ActorType.USER,
+ actorId: "user-1",
+ actorOrgId: "org-1",
+ tx: CALLER_TX
+ });
+ });
+
+ test("reads an unknown request as not found and refuses one whose policy is gone", async () => {
+ const { service, deps } = buildService();
+
+ deps.approvalRequestDAL.findById.mockResolvedValueOnce(null);
+ await expect(service.createSecretChangeRequestSideEffects(SIDE_EFFECTS_DTO)).rejects.toBeInstanceOf(NotFoundError);
+
+ deps.secretChangePolicyBridgeService.findSecretChangePolicyById.mockResolvedValueOnce(null);
+ await expect(service.createSecretChangeRequestSideEffects(SIDE_EFFECTS_DTO)).rejects.toThrow("has been deleted");
+ expect(runSecretChangeRequestSideEffects).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts
index aa719f8b51..dded63a92f 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-service.ts
@@ -87,6 +87,7 @@ import {
import {
TApprovalRequestUser,
TSecretChangeRequestBridgeMethods,
+ TSecretChangeRequestCommitInsert,
TSecretChangeRequestPolicySummary
} from "./secret-change-request-bridge-types";
import { TSecretChangeRequestDALFactory } from "./secret-change-request-dal";
@@ -162,9 +163,6 @@ type TSecretChangeRequestBridgeServiceFactoryDep = {
export type TSecretChangeRequestBridgeServiceFactory = ReturnType<typeof secretChangeRequestBridgeServiceFactory>;
-const notAvailable = () =>
- new BadRequestError({ message: "Secret change requests on the approval system are not available yet." });
-
export const secretChangeRequestBridgeServiceFactory = ({
approvalRequestDAL,
approvalRequestStepsDAL,
@@ -251,20 +249,22 @@ export const secretChangeRequestBridgeServiceFactory = ({
const findSecretChangeRequest = (requestId: string, tx?: Knex) => approvalRequestDAL.findById(requestId, tx);
- const $findSecretChangeRequestOrThrow = async (requestId: string) => {
- const approvalRequest = await approvalRequestDAL.findById(requestId);
+ const $findSecretChangeRequestOrThrow = async (requestId: string, tx?: Knex) => {
+ const approvalRequest = await approvalRequestDAL.findById(requestId, tx);
if (!approvalRequest || approvalRequest.type !== ApprovalPolicyType.SecretChange) {
throw new NotFoundError({ message: `Secret approval request with ID '${requestId}' not found` });
}
- const secretChangeRequest = await secretChangeRequestDAL.findOne({ approvalRequestId: approvalRequest.id });
+ const secretChangeRequest = await secretChangeRequestDAL.findOne({ approvalRequestId: approvalRequest.id }, tx);
if (!secretChangeRequest) {
throw new NotFoundError({ message: `Secret approval request with ID '${requestId}' not found` });
}
return { approvalRequest, secretChangeRequest };
};
- const $findSecretChangePolicyOrThrow = async (policyId: string | null | undefined) => {
- const policy = policyId ? await secretChangePolicyBridgeService.findSecretChangePolicyById(policyId) : undefined;
+ const $findSecretChangePolicyOrThrow = async (policyId: string | null | undefined, tx?: Knex) => {
+ const policy = policyId
+ ? await secretChangePolicyBridgeService.findSecretChangePolicyById(policyId, tx)
+ : undefined;
if (!policy) {
throw new BadRequestError({
message: "The policy associated with this secret approval request has been deleted."
@@ -316,72 +316,112 @@ export const secretChangeRequestBridgeServiceFactory = ({
return { hasRole, permission, steps, currentStep, userGroupIds };
};
- const generateSecretChangeRequest: TSecretChangeRequestBridgeMethods["generateSecretChangeRequest"] = async (dto) => {
- const { actor, actorId, actorOrgId, projectId, environment, secretPath, commitMessage, trx, skipPostProcessing } =
- dto;
- const { folderId, project, commits, commitTagIds, tagIds, secretKeys } = await buildSecretApprovalCommits(dto);
+ const $writeSecretChangeRequest = async (
+ {
+ policyId,
+ folderId,
+ projectId,
+ orgId,
+ actor,
+ actorId,
+ commitMessage,
+ isReplicated,
+ commits,
+ commitTags
+ }: {
+ policyId: string;
+ folderId: string;
+ projectId: string;
+ orgId: string;
+ actor: ActorType;
+ actorId: string;
+ commitMessage?: string | null;
+ isReplicated?: boolean | null;
+ commits: TSecretChangeRequestCommitInsert[];
+ commitTags: Record<string, string[]>;
+ },
+ tx: Knex
+ ) => {
+ const policy = await secretChangePolicyBridgeService.findSecretChangePolicyById(policyId, tx);
+ if (!policy) {
+ throw new NotFoundError({ message: `Secret approval policy with ID '${policyId}' not found` });
+ }
- const write = async (tx: Knex) => {
- const policy = await secretChangePolicyBridgeService.findSecretChangePolicyById(dto.policy.id, tx);
- if (!policy) {
- throw new NotFoundError({ message: `Secret approval policy with ID '${dto.policy.id}' not found` });
- }
+ const policySteps = await approvalPolicyDAL.findStepsByPolicyId(policy.id, tx);
+ if (!policySteps.length) {
+ throw new BadRequestError({
+ message: `Secret approval policy '${policy.name}' has no approval step configured. Edit the policy and set its approvers before requesting changes.`
+ });
+ }
- const policySteps = await approvalPolicyDAL.findStepsByPolicyId(policy.id, tx);
- if (!policySteps.length) {
- throw new BadRequestError({
- message: `Secret approval policy '${policy.name}' has no approval step configured. Edit the policy and set its approvers before requesting changes.`
- });
- }
+ const requester = await resolveRequester(actor, actorId, tx);
+
+ const approvalRequest = await createApprovalRequestWithSteps(
+ {
+ projectId,
+ organizationId: orgId,
+ policyId: policy.id,
+ policyType: ApprovalPolicyType.SecretChange,
+ policySteps,
+ requestData: {},
+ status: ApprovalRequestStatus.Open,
+ ...requester,
+ scopeType: null,
+ scopeId: null
+ },
+ { approvalRequestDAL, approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },
+ tx
+ );
- const requester = await resolveRequester(actor, actorId, tx);
+ const secretChangeRequest = await secretChangeRequestDAL.create(
+ {
+ approvalRequestId: approvalRequest.id,
+ folderId,
+ slug: alphaNumericNanoId(),
+ hasMerged: false,
+ commitMessage,
+ isReplicated
+ },
+ tx
+ );
- const approvalRequest = await createApprovalRequestWithSteps(
- {
- projectId,
- organizationId: project.orgId,
- policyId: policy.id,
- policyType: ApprovalPolicyType.SecretChange,
- policySteps,
- requestData: {},
- status: ApprovalRequestStatus.Open,
- ...requester,
- scopeType: null,
- scopeId: null
- },
- { approvalRequestDAL, approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },
- tx
- );
+ const approvalCommits = await secretApprovalRequestSecretDAL.insertV2Bridge(
+ commits.map((commit) => ({ ...commit, secretChangeId: secretChangeRequest.id })),
+ tx
+ );
- const secretChangeRequest = await secretChangeRequestDAL.create(
+ const commitsGroupByKey = groupBy(approvalCommits, (commit) => commit.key);
+ const approvalSecretTags = Object.entries(commitTags).flatMap(([key, keyTagIds]) =>
+ keyTagIds.map((tagId) => ({ secretId: commitsGroupByKey[key][0].id, tagId }))
+ );
+ if (approvalSecretTags.length) {
+ await secretApprovalRequestSecretDAL.insertApprovalSecretV2Tags(approvalSecretTags, tx);
+ }
+
+ return { policy, approvalRequest, secretChangeRequest, commits: approvalCommits };
+ };
+
+ const generateSecretChangeRequest: TSecretChangeRequestBridgeMethods["generateSecretChangeRequest"] = async (dto) => {
+ const { actor, actorId, actorOrgId, projectId, environment, secretPath, commitMessage, trx, skipPostProcessing } =
+ dto;
+ const { folderId, project, commits, commitTagIds, secretKeys } = await buildSecretApprovalCommits(dto);
+
+ const write = (tx: Knex) =>
+ $writeSecretChangeRequest(
{
- approvalRequestId: approvalRequest.id,
+ policyId: dto.policy.id,
folderId,
- slug: alphaNumericNanoId(),
- hasMerged: false,
- commitMessage
+ projectId,
+ orgId: project.orgId,
+ actor,
+ actorId,
+ commitMessage,
+ commits: commits.map((commit) => pickApprovalCommitColumns(commit)),
+ commitTags: commitTagIds
},
tx
);
- const approvalCommits = await secretApprovalRequestSecretDAL.insertV2Bridge(
- commits.map((commit) => ({ ...pickApprovalCommitColumns(commit), secretChangeId: secretChangeRequest.id })),
- tx
- );
-
- if (tagIds.length) {
- const commitsGroupByKey = groupBy(approvalCommits, (commit) => commit.key);
- await secretApprovalRequestSecretDAL.insertApprovalSecretV2Tags(
- Object.entries(commitTagIds).flatMap(([key, keyTagIds]) =>
- keyTagIds.map((tagId) => ({ secretId: commitsGroupByKey[key][0].id, tagId }))
- ),
- tx
- );
- }
-
- return { policy, approvalRequest, secretChangeRequest, commits: approvalCommits };
- };
-
const created = trx ? await write(trx) : await approvalRequestDAL.transaction(write);
const result = toSecretChangeRequest(created);
@@ -402,6 +442,77 @@ export const secretChangeRequestBridgeServiceFactory = ({
return result;
};
+ const createSecretChangeRequest: TSecretChangeRequestBridgeMethods["createSecretChangeRequest"] = async (
+ dto,
+ trx
+ ) => {
+ const write = async (tx: Knex) => {
+ const policy = await secretChangePolicyBridgeService.findSecretChangePolicyById(dto.policy.id, tx);
+ if (!policy) {
+ throw new NotFoundError({ message: `Secret approval policy with ID '${dto.policy.id}' not found` });
+ }
+ const project = await projectDAL.findById(policy.projectId, tx);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${policy.projectId}' not found` });
+
+ return $writeSecretChangeRequest(
+ {
+ policyId: policy.id,
+ folderId: dto.folderId,
+ projectId: project.id,
+ orgId: project.orgId,
+ actor: dto.actor,
+ actorId: dto.actorId,
+ commitMessage: dto.commitMessage,
+ isReplicated: dto.isReplicated,
+ commits: dto.commits.map(({ tagIds, ...commit }) => commit),
+ commitTags: Object.fromEntries(
+ dto.commits.flatMap(({ key, tagIds }) => (tagIds?.length ? [[key, tagIds]] : []))
+ )
+ },
+ tx
+ );
+ };
+
+ const created = trx ? await write(trx) : await approvalRequestDAL.transaction(write);
+ return toSecretChangeRequest(created);
+ };
+
+ const createSecretChangeRequestSideEffects: TSecretChangeRequestBridgeMethods["createSecretChangeRequestSideEffects"] =
+ async ({
+ secretApprovalRequest,
+ projectId,
+ environment,
+ secretPath,
+ secretKeys,
+ actor,
+ actorId,
+ actorOrgId,
+ tx
+ }) => {
+ const { approvalRequest, secretChangeRequest } = await $findSecretChangeRequestOrThrow(
+ secretApprovalRequest.id,
+ tx
+ );
+ const policy = await $findSecretChangePolicyOrThrow(approvalRequest.policyId, tx);
+ const project = await projectDAL.findById(projectId, tx);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+
+ await runSecretChangeRequestSideEffects({
+ approvalRequest,
+ secretChangeRequest,
+ policy,
+ project,
+ commits: secretApprovalRequest.commits,
+ environment,
+ secretPath,
+ secretKeys,
+ actor,
+ actorId,
+ actorOrgId,
+ tx
+ });
+ };
+
const mergeSecretChangeRequest: TSecretChangeRequestBridgeMethods["mergeSecretChangeRequest"] = async ({
approvalId,
actor,
@@ -959,6 +1070,8 @@ export const secretChangeRequestBridgeServiceFactory = ({
return {
findSecretChangeRequest,
generateSecretChangeRequest,
+ createSecretChangeRequest,
+ createSecretChangeRequestSideEffects,
mergeSecretChangeRequest,
reviewSecretChangeRequest,
updateSecretChangeRequestStatus,
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-types.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-types.ts
index c64dc59b3d..55177e64b5 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-types.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-bridge-types.ts
@@ -3,7 +3,8 @@ import { Knex } from "knex";
import {
TSecretApprovalRequests,
TSecretApprovalRequestsReviewers,
- TSecretApprovalRequestsSecretsV2
+ TSecretApprovalRequestsSecretsV2,
+ TSecretApprovalRequestsSecretsV2Insert
} from "@app/db/schemas";
import { Actor, Event } from "@app/ee/services/audit-log/audit-log-types";
@@ -12,6 +13,7 @@ import { TFormattedSecretApprovalCommitV2Bridge } from "../secret-approval-reque
import { TMergedSecretsV2Bridge } from "../secret-approval-request/secret-approval-request-merge-fns";
import {
TCreateSecretApprovalRequestV2BridgeDTO,
+ TCreateSecretApprovalSideEffectsDTO,
TGenerateSecretApprovalRequestV2BridgeDTO,
TMergeSecretApprovalRequestDTO,
TReviewRequestDTO,
@@ -25,6 +27,11 @@ export type TSecretChangeRequestData = Record<string, never>;
export type TSecretChangeRequest = TSecretApprovalRequests & { commits: TSecretApprovalRequestsSecretsV2[] };
+export type TSecretChangeRequestCommitInsert = Omit<
+ TSecretApprovalRequestsSecretsV2Insert,
+ "requestId" | "secretChangeId"
+>;
+
export type TSecretChangeRequestReview = TSecretApprovalRequestsReviewers & { projectId: string };
export type TSecretChangeRequestMergeResult = {
@@ -102,7 +109,8 @@ export type TSecretChangeRequestBridgeMethods = {
generateSecretChangeRequest: (
dto: TGenerateSecretApprovalRequestV2BridgeDTO & { trx?: Knex; skipPostProcessing?: boolean }
) => Promise<TSecretChangeRequest>;
- createSecretChangeRequest: (dto: TCreateSecretApprovalRequestV2BridgeDTO, tx?: Knex) => Promise<never>;
+ createSecretChangeRequest: (dto: TCreateSecretApprovalRequestV2BridgeDTO, tx?: Knex) => Promise<TSecretChangeRequest>;
+ createSecretChangeRequestSideEffects: (dto: TCreateSecretApprovalSideEffectsDTO) => Promise<void>;
mergeSecretChangeRequest: (dto: TMergeSecretApprovalRequestDTO) => Promise<TSecretChangeRequestMergeResult>;
reviewSecretChangeRequest: (dto: TReviewRequestDTO) => Promise<TSecretChangeRequestReview>;
updateSecretChangeRequestStatus: (dto: TStatusChangeDTO) => Promise<TSecretChangeRequestStatusResult>;
diff --git a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-dal.ts b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-dal.ts
index 4c22c8dc69..6ad9fee42b 100644
--- a/backend/src/ee/services/secret-change-request-bridge/secret-change-request-dal.ts
+++ b/backend/src/ee/services/secret-change-request-bridge/secret-change-request-dal.ts
@@ -18,7 +18,14 @@ export type TSecretChangeRequestDALFactory = ReturnType<typeof secretChangeReque
export type TSecretChangeRequestListRow = TApprovalRequests &
Pick<
TSecretChangeRequests,
- "folderId" | "slug" | "hasMerged" | "conflicts" | "commitMessage" | "bypassReason" | "statusChangedByUserId"
+ | "folderId"
+ | "slug"
+ | "hasMerged"
+ | "conflicts"
+ | "commitMessage"
+ | "bypassReason"
+ | "isReplicated"
+ | "statusChangedByUserId"
> & {
secretChangeId: string;
environment: string;
@@ -148,6 +155,7 @@ export const secretChangeRequestDALFactory = (db: TDbClient) => {
db.ref("conflicts").withSchema(TableName.SecretChangeRequests),
db.ref("commitMessage").withSchema(TableName.SecretChangeRequests),
db.ref("bypassReason").withSchema(TableName.SecretChangeRequests),
+ db.ref("isReplicated").withSchema(TableName.SecretChangeRequests),
db.ref("statusChangedByUserId").withSchema(TableName.SecretChangeRequests),
db.ref("slug").withSchema(TableName.Environment).as("environment"),
db.ref("name").withSchema(TableName.Environment).as("environmentName"),