Skip to content

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

add a migration to move secret change to global approval system

adilsona1325afbcaf9
diff --git a/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts b/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts
index d7ec96cb9f..d5d88fbfb7 100644
--- a/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-approval-global-guards.spec.ts
@@ -380,6 +380,83 @@ describe("Global approval system guards outside the approval routes", () => {
expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeUndefined();
});
+ test("a user who approves a migrated policy's legacy twin is removable once the global policy drops them", async () => {
+ const { userId, username } = await createProjectUser("migrated-approver");
+ userIds.push(userId);
+ const policyId = await createGlobalPolicy("migrated-user-guard", "/migrated-user-guard", {
+ type: ApproverType.User,
+ id: userId
+ });
+ policyIds.push(policyId);
+ await seedLegacySecretApprovalPolicy(getDb(), {
+ id: policyId,
+ projectId,
+ environment: envSlug,
+ secretPath: "/migrated-user-guard",
+ name: "migrated-user-guard",
+ approverUserId: userId
+ });
+ legacyPolicyIds.push(policyId);
+
+ const blocked = await removeProjectUser(username);
+ expect(blocked.statusCode).toBe(400);
+
+ await replaceGlobalPolicyApprover(policyId, { type: ApproverType.User, id: seedData1.id });
+
+ const removed = await removeProjectUser(username);
+ expect(removed.statusCode).toBe(200);
+ });
+
+ test("a folder whose open legacy request was migrated is deletable once the global copy closes", async () => {
+ const { parentName, parent, child } = await createFolderTree();
+ const legacyPolicy = await seedLegacySecretApprovalPolicy(getDb(), {
+ projectId,
+ environment: envSlug,
+ secretPath: `/${parentName}/child`,
+ name: "migrated-folder-guard",
+ approverUserId: seedData1.id
+ });
+ legacyPolicyIds.push(legacyPolicy.id);
+ const requestId = await seedOpenLegacyRequest(child.id, legacyPolicy.id);
+ legacyRequestIds.push(requestId);
+ const globalTwin = {
+ id: requestId,
+ projectId,
+ organizationId: orgId,
+ policyId: null,
+ requesterId: seedData1.id,
+ requesterName: "test",
+ requesterEmail: seedData1.email,
+ type: ApprovalPolicyType.SecretChange,
+ status: "open",
+ currentStep: 1,
+ requestData: JSON.stringify({})
+ };
+ await getDb()(TableName.ApprovalRequests).insert(globalTwin);
+ await getDb()(TableName.SecretChangeRequests).insert({
+ approvalRequestId: requestId,
+ folderId: child.id,
+ slug: `guard-${crypto.randomUUID().slice(0, 8)}`
+ });
+ requestIds.push(requestId);
+
+ const blocked = await deleteFolderRequest(parent.id, "/");
+ expect(blocked.statusCode).toBe(400);
+ expect(blocked.json().message).toBe(openRequestMessage(`/${parentName}/child`));
+
+ await getDb()(TableName.ApprovalRequests).where({ id: requestId }).update({ status: "close" });
+
+ await deleteFolder({
+ workspaceId: projectId,
+ environmentSlug: envSlug,
+ secretPath: "/",
+ id: parent.id,
+ authToken: jwtAuthToken,
+ forceDelete: true
+ });
+ expect(await getDb()(TableName.SecretFolder).where({ id: child.id }).first()).toBeUndefined();
+ });
+
test("a folder with an open legacy change request cannot be deleted until the request is closed", async () => {
const { parentName, parent, child } = await createFolderTree();
const legacyPolicy = await seedLegacySecretApprovalPolicy(getDb(), {
diff --git a/backend/e2e-test/routes/v1/secret-approval-policy-bridge.spec.ts b/backend/e2e-test/routes/v1/secret-approval-policy-bridge.spec.ts
index fc9572b4d8..d27a8f5e7e 100644
--- a/backend/e2e-test/routes/v1/secret-approval-policy-bridge.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-approval-policy-bridge.spec.ts
@@ -15,6 +15,8 @@ const NEW_PATH = "/sap-policy-bridge-new";
const MOVED_PATH = "/sap-policy-bridge-moved";
const GLOB_BASE = "/sap-policy-bridge-glob";
const V1_PATH = "/sap-policy-bridge-v1";
+const MIGRATED_PATH = "/sap-policy-bridge-migrated";
+const MIGRATED_MOVED_PATH = "/sap-policy-bridge-migrated-moved";
const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });
const approvers = [{ type: ApproverType.User, id: seedData1.id }];
@@ -330,6 +332,49 @@ describe("Secret approval policy bridge routing", () => {
expect(deleteEnvRes.json().environment.id).toBe(guardedEnvId);
});
+ test("a migrated policy's legacy twin is hidden until the global policy is deleted", async () => {
+ const createRes = await createBridgePolicy(MIGRATED_PATH);
+ expect(createRes.statusCode).toBe(200);
+ const policyId = createRes.json().approval.id as string;
+ bridgeIds.push(policyId);
+ await seedLegacySecretApprovalPolicy(getDb(), {
+ id: policyId,
+ projectId,
+ environment: envSlug,
+ secretPath: MIGRATED_PATH,
+ name: "migrated-twin",
+ approverUserId: seedData1.id
+ });
+ legacyIds.push(policyId);
+
+ const renamed = await updatePolicy(policyId, { name: "migrated-renamed" });
+ expect(renamed.statusCode).toBe(200);
+ expect(await legacyRow(policyId)).toMatchObject({ name: "migrated-twin" });
+ expect(await bridgeRow(policyId)).toMatchObject({ name: "migrated-renamed" });
+
+ const listRes = await listPolicies();
+ expect(listRes.statusCode).toBe(200);
+ expect(listRes.json().approvals.filter((policy: { id: string }) => policy.id === policyId)).toHaveLength(1);
+
+ const boardRes = await getBoardPolicy(MIGRATED_PATH);
+ expect(boardRes.statusCode).toBe(200);
+ expect(boardRes.json().policy).toMatchObject({ id: policyId, name: "migrated-renamed" });
+
+ const moved = await updatePolicy(policyId, { secretPath: MIGRATED_MOVED_PATH });
+ expect(moved.statusCode).toBe(200);
+ const replacementRes = await createBridgePolicy(MIGRATED_PATH);
+ expect(replacementRes.statusCode).toBe(200);
+ bridgeIds.push(replacementRes.json().approval.id as string);
+
+ const deleteRes = await deletePolicy(policyId);
+ expect(deleteRes.statusCode).toBe(200);
+ expect(await bridgeRow(policyId)).toBeUndefined();
+ expect((await legacyRow(policyId))?.deletedAt).toBeInstanceOf(Date);
+
+ const afterDelete = await listPolicies();
+ expect(afterDelete.json().approvals.map((policy: { id: string }) => policy.id)).not.toContain(policyId);
+ });
+
test("the deprecated v1 create puts a policy on a V3 project on the global approval system", async () => {
const createRes = await testServer.inject({
method: "POST",
diff --git a/backend/e2e-test/routes/v1/secret-approval-request-bridge.spec.ts b/backend/e2e-test/routes/v1/secret-approval-request-bridge.spec.ts
index 89630987a1..10d22da936 100644
--- a/backend/e2e-test/routes/v1/secret-approval-request-bridge.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-approval-request-bridge.spec.ts
@@ -105,6 +105,7 @@ describe("Secret approval request bridge routing", () => {
let globalSystemPolicyId: string;
let globalSystemFolderId: string;
const globalSystemRequestIds: string[] = [];
+ const legacyTwinRequestIds: string[] = [];
const secretKeys = ["SAR_BRIDGE_MERGE", "SAR_BRIDGE_STATUS", "SAR_BRIDGE_LIST_LEGACY", "SAR_BRIDGE_STATUS_LEGACY"];
beforeAll(async () => {
@@ -141,6 +142,7 @@ describe("Secret approval request bridge routing", () => {
throw new Error(`cleanup: unexpected ${res.statusCode} deleting policy ${legacyPolicyId} - ${res.payload}`);
}
await Promise.all(secretKeys.map((key) => deleteSecret(key)));
+ await db(TableName.SecretApprovalRequest).whereIn("id", legacyTwinRequestIds).del();
await db(TableName.ApprovalRequests).whereIn("id", globalSystemRequestIds).del();
await db(TableName.ApprovalPolicies).where({ id: globalSystemPolicyId }).del();
await deleteFolder({
@@ -308,6 +310,42 @@ describe("Secret approval request bridge routing", () => {
expect(countRes.json().approvals.open).toBeGreaterThanOrEqual(2);
});
+ test("a migrated request's legacy twin is not listed, counted or read", async () => {
+ const globalRes = await createSecret("SAR_BRIDGE_MIGRATED", "value", GLOBAL_SYSTEM_PATH);
+ expect(globalRes.statusCode).toBe(200);
+ const requestId = (globalRes.json().approval as TListedRequest).id;
+ globalSystemRequestIds.push(requestId);
+
+ const before = await countRequests();
+ expect(before.statusCode).toBe(200);
+
+ const legacyTwin = {
+ id: requestId,
+ policyId: legacyPolicyId,
+ folderId: globalSystemFolderId,
+ slug: "sar-bridge-migrated-twin",
+ status: RequestState.Open,
+ committerUserId: seedData1.id
+ };
+ await getDb()(TableName.SecretApprovalRequest).insert(legacyTwin);
+ legacyTwinRequestIds.push(requestId);
+
+ const listRes = await listRequests();
+ expect(listRes.statusCode).toBe(200);
+ const listed: { approvals: (TListedRequest & { policy: { id: string } })[] } = listRes.json();
+ const matches = listed.approvals.filter((row) => row.id === requestId);
+ expect(matches).toHaveLength(1);
+ expect(matches[0].policy.id).toBe(globalSystemPolicyId);
+
+ const after = await countRequests();
+ expect(after.statusCode).toBe(200);
+ expect(after.json().approvals).toEqual(before.json().approvals);
+
+ const getRes = await getRequest(requestId);
+ expect(getRes.statusCode).toBe(200);
+ expect(getRes.json().approval).toMatchObject({ id: requestId, policy: { id: globalSystemPolicyId } });
+ });
+
test("a status change keeps a request on the system it was opened on", async () => {
const db = getDb();
diff --git a/backend/e2e-test/secret-approval-migration.spec.ts b/backend/e2e-test/secret-approval-migration.spec.ts
new file mode 100644
index 0000000000..07be0ea290
--- /dev/null
+++ b/backend/e2e-test/secret-approval-migration.spec.ts
@@ -0,0 +1,353 @@
+import crypto from "node:crypto";
+
+import { Knex } from "knex";
+
+import { down, up } from "@app/db/migrations/20261014120100_migrate-secret-approval-policies-to-global";
+import { TableName } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+
+const getDb = () => (globalThis as unknown as { testDb: Knex }).testDb;
+
+const orgId = seedData1.organization.id;
+const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });
+const MIGRATED_PATH = "/sap-migration";
+
+type TSeededRequest = { id: string; commitIds: string[] };
+
+const seedLegacyPolicy = async (
+ db: Knex,
+ dto: { projectId: string; name: string; approvals: number; approverUserId: string; approverGroupId?: string }
+) => {
+ const env = await db(TableName.Environment)
+ .where({ projectId: dto.projectId, slug: seedData1.environment.slug })
+ .first();
+ if (!env) throw new Error("seeded environment not found");
+
+ const [policy] = await db(TableName.SecretApprovalPolicy)
+ .insert({
+ name: dto.name,
+ secretPath: MIGRATED_PATH,
+ approvals: dto.approvals,
+ envId: env.id,
+ enforcementLevel: "soft",
+ allowedSelfApprovals: false,
+ bypassForMachineIdentities: true
+ })
+ .returning("*");
+ await db(TableName.SecretApprovalPolicyEnvironment).insert({ policyId: policy.id, envId: env.id });
+ await db(TableName.SecretApprovalPolicyApprover).insert({ policyId: policy.id, approverUserId: dto.approverUserId });
+ if (dto.approverGroupId) {
+ await db(TableName.SecretApprovalPolicyApprover).insert({
+ policyId: policy.id,
+ approverGroupId: dto.approverGroupId
+ });
+ }
+ await db(TableName.SecretApprovalPolicyBypasser).insert({ policyId: policy.id, bypasserUserId: dto.approverUserId });
+ return { policyId: policy.id as string, envId: env.id as string };
+};
+
+const seedLegacyRequest = async (
+ db: Knex,
+ dto: {
+ policyId: string;
+ folderId: string;
+ status: "open" | "close";
+ committerUserId?: string | null;
+ committerIdentityId?: string | null;
+ hasMerged?: boolean;
+ bypassReason?: string | null;
+ conflicts?: unknown;
+ statusChangedByUserId?: string | null;
+ commits: number;
+ }
+): Promise<TSeededRequest> => {
+ const [request] = await db(TableName.SecretApprovalRequest)
+ .insert({
+ policyId: dto.policyId,
+ folderId: dto.folderId,
+ slug: `sap-migration-${crypto.randomUUID().slice(0, 8)}`,
+ status: dto.status,
+ committerUserId: dto.committerUserId ?? null,
+ committerIdentityId: dto.committerIdentityId ?? null,
+ hasMerged: dto.hasMerged ?? false,
+ bypassReason: dto.bypassReason ?? null,
+ conflicts: dto.conflicts === undefined ? null : JSON.stringify(dto.conflicts),
+ statusChangedByUserId: dto.statusChangedByUserId ?? null,
+ commitMessage: "seeded by the migration spec"
+ })
+ .returning("id");
+ const requestId = (request as { id: string }).id;
+
+ const commitIds: string[] = [];
+ for (let index = 0; index < dto.commits; index += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const [commit] = await db(TableName.SecretApprovalRequestSecretV2)
+ .insert({ requestId, key: `SAP_MIGRATION_${index}`, op: "create", skipMultilineEncoding: false })
+ .returning("id");
+ commitIds.push((commit as { id: string }).id);
+ }
+ return { id: requestId, commitIds };
+};
+
+const commitsOf = (db: Knex, commitIds: string[]) =>
+ db(TableName.SecretApprovalRequestSecretV2).whereIn("id", commitIds).select("id", "requestId", "secretChangeId");
+
+describe("Legacy secret approval policies migrate to the global approval system", () => {
+ const db = getDb();
+ let groupId: string;
+ let v3PolicyId: string;
+ let v1PolicyId: string;
+ let openRequest: TSeededRequest;
+ let mergedRequest: TSeededRequest;
+ let identityRequest: TSeededRequest;
+ let orphanRequest: TSeededRequest;
+ let v1Request: TSeededRequest;
+
+ beforeAll(async () => {
+ const slug = `sap-migration-${crypto.randomUUID().slice(0, 8)}`;
+ const [group] = await db(TableName.Groups).insert({ orgId, name: slug, slug }).returning("id");
+ groupId = (group as { id: string }).id;
+ await db(TableName.UserGroupMembership).insert({ groupId, userId: seedData1.id });
+
+ const v3 = await seedLegacyPolicy(db, {
+ projectId: seedData1.projectV3.id,
+ name: "sap-migration-v3",
+ approvals: 1,
+ approverUserId: seedData1.id,
+ approverGroupId: groupId
+ });
+ v3PolicyId = v3.policyId;
+ const v3Folder = await db(TableName.SecretFolder).where({ envId: v3.envId, parentId: null }).first();
+ if (!v3Folder) throw new Error("root folder of the V3 project not found");
+
+ openRequest = await seedLegacyRequest(db, {
+ policyId: v3PolicyId,
+ folderId: v3Folder.id,
+ status: "open",
+ committerUserId: seedData1.id,
+ commits: 2
+ });
+ await db(TableName.SecretApprovalRequestReviewer).insert({
+ requestId: openRequest.id,
+ reviewerUserId: seedData1.id,
+ status: "approved",
+ comment: "ship it"
+ });
+ mergedRequest = await seedLegacyRequest(db, {
+ policyId: v3PolicyId,
+ folderId: v3Folder.id,
+ status: "close",
+ committerUserId: seedData1.id,
+ hasMerged: true,
+ bypassReason: "incident 42 needed the key right away",
+ conflicts: [{ op: "update", secretId: crypto.randomUUID() }],
+ statusChangedByUserId: seedData1.id,
+ commits: 1
+ });
+ identityRequest = await seedLegacyRequest(db, {
+ policyId: v3PolicyId,
+ folderId: v3Folder.id,
+ status: "open",
+ committerIdentityId: seedData1.machineIdentity.id,
+ commits: 1
+ });
+ orphanRequest = await seedLegacyRequest(db, {
+ policyId: v3PolicyId,
+ folderId: v3Folder.id,
+ status: "close",
+ committerUserId: null,
+ commits: 0
+ });
+
+ const v1 = await seedLegacyPolicy(db, {
+ projectId: seedData1.project.id,
+ name: "sap-migration-v1",
+ approvals: 1,
+ approverUserId: seedData1.id
+ });
+ v1PolicyId = v1.policyId;
+ const v1Folder = await db(TableName.SecretFolder).where({ envId: v1.envId, parentId: null }).first();
+ if (!v1Folder) throw new Error("root folder of the V1 project not found");
+ v1Request = await seedLegacyRequest(db, {
+ policyId: v1PolicyId,
+ folderId: v1Folder.id,
+ status: "open",
+ committerUserId: seedData1.id,
+ commits: 1
+ });
+ });
+
+ afterAll(async () => {
+ await db(TableName.ApprovalPolicies).whereIn("id", [v3PolicyId, v1PolicyId]).del();
+ await db(TableName.ApprovalRequests)
+ .whereIn("id", [openRequest.id, mergedRequest.id, identityRequest.id, orphanRequest.id, v1Request.id])
+ .del();
+ await db(TableName.SecretApprovalPolicy).whereIn("id", [v3PolicyId, v1PolicyId]).del();
+ await db(TableName.UserGroupMembership).where({ groupId }).del();
+ await db(TableName.Groups).where({ id: groupId }).del();
+ });
+
+ test("up moves a V3 policy with its requests, reviews and commits and leaves a V1 policy on legacy", async () => {
+ await up(db);
+
+ expect(await db(TableName.ApprovalPolicies).where({ id: v3PolicyId }).first()).toMatchObject({
+ type: "secret-change",
+ projectId: seedData1.projectV3.id,
+ organizationId: orgId,
+ name: "sap-migration-v3",
+ enforcementLevel: "soft",
+ bypassForMachineIdentities: true,
+ constraints: { version: 1, constraints: { allowedSelfApprovals: false } }
+ });
+ const steps = await db(TableName.ApprovalPolicySteps).where({ policyId: v3PolicyId });
+ expect(steps).toMatchObject([{ stepNumber: 1, requiredApprovals: 1 }]);
+ const stepApprovers = await db(TableName.ApprovalPolicyStepApprovers).where({ policyStepId: steps[0].id });
+ expect(stepApprovers).toHaveLength(2);
+ expect(stepApprovers).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ userId: seedData1.id, groupId: null }),
+ expect.objectContaining({ userId: null, groupId })
+ ])
+ );
+ expect(await db(TableName.ApprovalPolicyBypassers).where({ policyId: v3PolicyId })).toMatchObject([
+ { userId: seedData1.id, groupId: null }
+ ]);
+ expect(await db(TableName.ApprovalPolicySecretEnvironment).where({ policyId: v3PolicyId })).toMatchObject([
+ { secretPath: MIGRATED_PATH }
+ ]);
+
+ expect(await db(TableName.ApprovalRequests).where({ id: openRequest.id }).first()).toMatchObject({
+ type: "secret-change",
+ status: "open",
+ policyId: v3PolicyId,
+ requesterId: seedData1.id,
+ requesterEmail: seedData1.email,
+ currentStep: 1
+ });
+ const [openStep] = await db(TableName.ApprovalRequestSteps).where({ requestId: openRequest.id });
+ expect(openStep).toMatchObject({ stepNumber: 1, status: "in-progress", requiredApprovals: 1, completedAt: null });
+ expect(await db(TableName.ApprovalRequestApprovals).where({ stepId: openStep.id })).toMatchObject([
+ { approverUserId: seedData1.id, decision: "approved", comment: "ship it" }
+ ]);
+ const openChange = await db(TableName.SecretChangeRequests).where({ approvalRequestId: openRequest.id }).first();
+ expect(openChange).toMatchObject({ hasMerged: false, commitMessage: "seeded by the migration spec" });
+ expect(await commitsOf(db, openRequest.commitIds)).toEqual(
+ openRequest.commitIds.map((id) => ({ id, requestId: null, secretChangeId: openChange?.id }))
+ );
+
+ expect(await db(TableName.ApprovalRequests).where({ id: mergedRequest.id }).first()).toMatchObject({
+ status: "close"
+ });
+ const mergedChange = await db(TableName.SecretChangeRequests)
+ .where({ approvalRequestId: mergedRequest.id })
+ .first();
+ expect(mergedChange).toMatchObject({
+ hasMerged: true,
+ bypassReason: "incident 42 needed the key right away",
+ statusChangedByUserId: seedData1.id,
+ conflicts: [{ op: "update", secretId: expect.any(String) as string }]
+ });
+ expect(await commitsOf(db, mergedRequest.commitIds)).toEqual(
+ mergedRequest.commitIds.map((id) => ({ id, requestId: null, secretChangeId: mergedChange?.id }))
+ );
+
+ expect(await db(TableName.ApprovalRequests).where({ id: identityRequest.id }).first()).toMatchObject({
+ requesterId: null,
+ machineIdentityId: seedData1.machineIdentity.id,
+ requesterName: seedData1.machineIdentity.name,
+ requesterEmail: ""
+ });
+ expect(await db(TableName.ApprovalRequests).where({ id: orphanRequest.id }).first()).toMatchObject({
+ requesterId: null,
+ machineIdentityId: null,
+ requesterName: "",
+ requesterEmail: ""
+ });
+
+ expect(await db(TableName.ApprovalPolicies).where({ id: v1PolicyId }).first()).toBeUndefined();
+ expect(await db(TableName.ApprovalRequests).where({ id: v1Request.id }).first()).toBeUndefined();
+ expect(await commitsOf(db, v1Request.commitIds)).toMatchObject([{ requestId: v1Request.id, secretChangeId: null }]);
+ });
+
+ test("the migrated policy and its requests are served once, from the global approval system", async () => {
+ const listRes = await testServer.inject({
+ method: "GET",
+ url: `/api/v2/secret-approvals?projectId=${seedData1.projectV3.id}`,
+ headers: authHeaders()
+ });
+ expect(listRes.statusCode).toBe(200);
+ const policies = listRes.json().approvals.filter((policy: { id: string }) => policy.id === v3PolicyId);
+ expect(policies).toHaveLength(1);
+ expect(policies[0]).toMatchObject({ name: "sap-migration-v3", approvals: 1, allowedSelfApprovals: false });
+
+ const requestRes = await testServer.inject({
+ method: "GET",
+ url: `/api/v1/secret-approval-requests/${openRequest.id}`,
+ headers: authHeaders()
+ });
+ expect(requestRes.statusCode).toBe(200);
+ const { approval } = requestRes.json();
+ expect(approval).toMatchObject({
+ id: openRequest.id,
+ status: "open",
+ policy: { id: v3PolicyId },
+ reviewers: [{ userId: seedData1.id, status: "approved", comment: "ship it" }]
+ });
+ expect(approval.commits.map((commit: { secretKey: string }) => commit.secretKey).sort()).toEqual([
+ "SAP_MIGRATION_0",
+ "SAP_MIGRATION_1"
+ ]);
+
+ const listRequests = await testServer.inject({
+ method: "GET",
+ url: `/api/v1/secret-approval-requests?projectId=${seedData1.projectV3.id}&limit=50`,
+ headers: authHeaders()
+ });
+ expect(listRequests.statusCode).toBe(200);
+ const listed = listRequests.json().approvals.filter((row: { id: string }) => row.id === openRequest.id);
+ expect(listed).toHaveLength(1);
+ });
+
+ test("a second run leaves everything as it is", async () => {
+ const before = await db(TableName.ApprovalRequests).where({ policyId: v3PolicyId }).count().first();
+
+ await up(db);
+
+ const after = await db(TableName.ApprovalRequests).where({ policyId: v3PolicyId }).count().first();
+ expect(after).toEqual(before);
+ expect(await db(TableName.ApprovalPolicies).where({ id: v1PolicyId }).first()).toBeUndefined();
+ });
+
+ test("down relinks the commits and writes the global outcome back onto the legacy rows", async () => {
+ await db(TableName.ApprovalRequests).where({ id: openRequest.id }).update({ status: "close" });
+ await db(TableName.SecretChangeRequests)
+ .where({ approvalRequestId: openRequest.id })
+ .update({ hasMerged: true, statusChangedByUserId: seedData1.id });
+
+ await down(db);
+
+ expect(await db(TableName.ApprovalPolicies).where({ id: v3PolicyId }).first()).toBeUndefined();
+ expect(await db(TableName.ApprovalRequests).whereIn("id", [openRequest.id, mergedRequest.id])).toEqual([]);
+ expect(await db(TableName.SecretChangeRequests).whereIn("approvalRequestId", [openRequest.id])).toEqual([]);
+
+ expect(await commitsOf(db, openRequest.commitIds)).toEqual(
+ openRequest.commitIds.map((id) => ({ id, requestId: openRequest.id, secretChangeId: null }))
+ );
+ expect(await commitsOf(db, mergedRequest.commitIds)).toEqual(
+ mergedRequest.commitIds.map((id) => ({ id, requestId: mergedRequest.id, secretChangeId: null }))
+ );
+ expect(await db(TableName.SecretApprovalRequest).where({ id: openRequest.id }).first()).toMatchObject({
+ status: "close",
+ hasMerged: true,
+ statusChangedByUserId: seedData1.id
+ });
+ expect(await db(TableName.SecretApprovalRequest).where({ id: mergedRequest.id }).first()).toMatchObject({
+ status: "close",
+ hasMerged: true,
+ bypassReason: "incident 42 needed the key right away"
+ });
+ expect(await db(TableName.SecretApprovalPolicy).where({ id: v3PolicyId }).first()).toMatchObject({
+ deletedAt: null
+ });
+ });
+});
diff --git a/backend/e2e-test/testUtils/secret-approval-policies.ts b/backend/e2e-test/testUtils/secret-approval-policies.ts
index 6925dca84b..c6048e13cf 100644
--- a/backend/e2e-test/testUtils/secret-approval-policies.ts
+++ b/backend/e2e-test/testUtils/secret-approval-policies.ts
@@ -10,13 +10,14 @@ import { request } from "./request";
// approval system can only be seeded directly.
export const seedLegacySecretApprovalPolicy = async (
db: Knex,
- dto: { projectId: string; environment: string; secretPath: string; name: string; approverUserId: string }
+ dto: { projectId: string; environment: string; secretPath: string; name: string; approverUserId: string; id?: string }
) => {
const env = await db(TableName.Environment).where({ projectId: dto.projectId, slug: dto.environment }).first();
if (!env) throw new Error(`environment '${dto.environment}' not found in project ${dto.projectId}`);
const [policy] = await db(TableName.SecretApprovalPolicy)
.insert({
+ ...(dto.id ? { id: dto.id } : {}),
name: dto.name,
secretPath: dto.secretPath,
approvals: 1,
diff --git a/backend/src/db/migrations/20261014120000_add-secret-approval-secrets-v2-request-id-index.ts b/backend/src/db/migrations/20261014120000_add-secret-approval-secrets-v2-request-id-index.ts
new file mode 100644
index 0000000000..3fae19439a
--- /dev/null
+++ b/backend/src/db/migrations/20261014120000_add-secret-approval-secrets-v2-request-id-index.ts
@@ -0,0 +1,49 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const INDEX_NAME = "idx_secret_approval_requests_secrets_v2_request_id";
+const COLUMN = "requestId";
+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds
+
+export async function up(knex: Knex): Promise<void> {
+ const connection = await knex.client.acquireConnection();
+ const raw = (sql: string, bindings: readonly Knex.RawBinding[] = []) =>
+ knex.raw(sql, bindings).connection(connection);
+
+ try {
+ const stmtResult = await raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout as string;
+ const lockResult = await raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout as string;
+
+ try {
+ await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+
+ if (
+ (await knex.schema.hasTable(TableName.SecretApprovalRequestSecretV2)) &&
+ (await knex.schema.hasColumn(TableName.SecretApprovalRequestSecretV2, COLUMN))
+ ) {
+ await raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}"
+ ON ${TableName.SecretApprovalRequestSecretV2} ("${COLUMN}")
+ WHERE "${COLUMN}" IS NOT NULL
+ `);
+ }
+ } finally {
+ await raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+ } finally {
+ await knex.client.releaseConnection(connection);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${INDEX_NAME}"`);
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/db/migrations/20261014120100_migrate-secret-approval-policies-to-global.ts b/backend/src/db/migrations/20261014120100_migrate-secret-approval-policies-to-global.ts
new file mode 100644
index 0000000000..e633ec6600
--- /dev/null
+++ b/backend/src/db/migrations/20261014120100_migrate-secret-approval-policies-to-global.ts
@@ -0,0 +1,470 @@
+/* eslint-disable no-await-in-loop -- policies migrate one after another on purpose */
+import crypto from "node:crypto";
+
+import { Knex } from "knex";
+
+import { chunkArray, groupBy } from "@app/lib/fn";
+
+import { TableName } from "../schemas";
+import {
+ buildApprovalSteps,
+ buildBypasserRows,
+ buildGlobalPolicyRow,
+ buildPolicyEnvironmentRows,
+ buildPolicyStepRows,
+ buildRequestStepRows,
+ checkPolicyEnvironments,
+ checkRequestsAlreadyMigrated,
+ checkReviewStatuses,
+ INSERT_CHUNK_SIZE,
+ insertChunked,
+ insertGlobalPolicyRows,
+ insertGlobalRequestRows,
+ lockLegacyPolicy,
+ logFailedChecks,
+ POLICY_STATEMENT_TIMEOUT_MS,
+ readApproverGroupMembers,
+ readLegacyApprovers,
+ readLegacyBypassers,
+ readLegacyReviews,
+ readPolicyEnvironments,
+ readRequestIdsAlreadyOnGlobal,
+ replayReviews,
+ runLegacyPolicyMigration,
+ TGlobalPolicyRows,
+ TGlobalRequestRows,
+ TGroupMember,
+ TLegacyApprovalTables,
+ TLegacyApprover,
+ TLegacyBypasser,
+ TLegacyReview,
+ TMigrationFailure,
+ TPolicyEnvironment,
+ TPolicyOutcome
+} from "./utils/approval-migration";
+
+const LOG_PREFIX = "migrate-secret-approval-policies-to-global";
+const SECRET_CHANGE = "secret-change";
+const PROJECT_VERSION_V3 = 3;
+
+const LEGACY_TABLES: TLegacyApprovalTables = {
+ legacyPolicies: TableName.SecretApprovalPolicy,
+ legacyApprovers: TableName.SecretApprovalPolicyApprover,
+ legacyBypassers: TableName.SecretApprovalPolicyBypasser,
+ legacyEnvironments: TableName.SecretApprovalPolicyEnvironment,
+ legacyReviewers: TableName.SecretApprovalRequestReviewer
+};
+
+enum LegacyRequestStatus {
+ Open = "open",
+ Closed = "close"
+}
+
+type TLegacyPolicy = {
+ id: string;
+ name: string;
+ approvals: number;
+ secretPath: string;
+ enforcementLevel: string;
+ allowedSelfApprovals: boolean;
+ bypassForMachineIdentities: boolean;
+ deletedAt?: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+type TLegacyRequest = {
+ id: string;
+ policyId: string;
+ status: string;
+ hasMerged: boolean;
+ conflicts?: unknown;
+ slug: string;
+ folderId: string;
+ isReplicated?: boolean | null;
+ committerUserId?: string | null;
+ committerIdentityId?: string | null;
+ statusChangedByUserId?: string | null;
+ bypassReason?: string | null;
+ commitMessage?: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+type TProject = { id: string; version: number };
+
+type TCommitter = {
+ id: string;
+ username: string;
+ email?: string | null;
+ firstName?: string | null;
+ lastName?: string | null;
+};
+
+type TCommitterIdentity = { id: string; name: string };
+
+export type TPolicyData = {
+ policy: TLegacyPolicy;
+ project: TProject | null;
+ environments: TPolicyEnvironment[];
+ approvers: TLegacyApprover[];
+ bypassers: TLegacyBypasser[];
+ requests: TLegacyRequest[];
+ reviews: TLegacyReview[];
+ committers: TCommitter[];
+ committerIdentities: TCommitterIdentity[];
+ groupMembers: TGroupMember[];
+ requestIdsAlreadyOnGlobal: string[];
+};
+
+type TSecretChangeRequestRow = {
+ id: string;
+ approvalRequestId: string;
+ folderId: string;
+ slug: string;
+ hasMerged: boolean;
+ conflicts: string | null;
+ commitMessage: string | null;
+ bypassReason: string | null;
+ isReplicated: boolean | null;
+ statusChangedByUserId: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+type TGlobalRows = TGlobalPolicyRows & TGlobalRequestRows & { secretChangeRequests: TSecretChangeRequestRow[] };
+
+type TRequester = {
+ requesterId: string | null;
+ machineIdentityId: string | null;
+ requesterName: string;
+ requesterEmail: string;
+};
+
+const isId = (id: string | null | undefined): id is string => Boolean(id);
+
+const resolveRequester = (
+ request: TLegacyRequest,
+ committerById: Map<string, TCommitter>,
+ committerIdentityById: Map<string, TCommitterIdentity>
+): TRequester => {
+ const user = request.committerUserId ? committerById.get(request.committerUserId) : undefined;
+ if (user) {
+ return {
+ requesterId: user.id,
+ machineIdentityId: null,
+ requesterName: [user.firstName, user.lastName].filter(Boolean).join(" ").trim() || user.username,
+ requesterEmail: user.email ?? ""
+ };
+ }
+
+ const identity = request.committerIdentityId ? committerIdentityById.get(request.committerIdentityId) : undefined;
+ if (identity) {
+ return { requesterId: null, machineIdentityId: identity.id, requesterName: identity.name, requesterEmail: "" };
+ }
+
+ return { requesterId: null, machineIdentityId: null, requesterName: "", requesterEmail: "" };
+};
+
+const latestReviewPerReviewer = (reviews: TLegacyReview[]) => {
+ const byReviewer = new Map<string, TLegacyReview>();
+ [...reviews]
+ .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime() || a.id.localeCompare(b.id))
+ .forEach((review) => byReviewer.set(review.reviewerUserId, review));
+ return [...byReviewer.values()];
+};
+
+export const translatePolicy = (data: TPolicyData) => {
+ const { policy, project, environments, approvers, bypassers, requests, reviews, committers, committerIdentities } =
+ data;
+ const failures: TMigrationFailure[] = [];
+
+ const { projectId, orgId } = checkPolicyEnvironments(environments, failures);
+
+ if (!project || project.version !== PROJECT_VERSION_V3) {
+ failures.push({
+ code: "project-not-v3",
+ message: `The global approval system only supports secret change policies on V3 projects, and project ${projectId ?? "unknown"} is on version ${project?.version ?? "unknown"}. Upgrade the project first`
+ });
+ }
+ if (policy.approvals < 1) {
+ failures.push({
+ code: "invalid-approvals",
+ message: `The policy requires ${policy.approvals} approvals, and the global approval system needs at least 1`
+ });
+ }
+
+ // I need to check it more carefully
+ const steps = buildApprovalSteps(
+ {
+ policy,
+ approvers: approvers.map((approver) => ({ ...approver, sequence: 1, approvalsRequired: policy.approvals })),
+ groupMembers: data.groupMembers
+ },
+ failures
+ );
+
+ const rows: TGlobalRows = {
+ policy: buildGlobalPolicyRow({
+ policy,
+ projectId,
+ orgId,
+ type: SECRET_CHANGE,
+ conditions: { version: 1, conditions: [] },
+ constraints: { version: 1, constraints: { allowedSelfApprovals: policy.allowedSelfApprovals } },
+ bypassForMachineIdentities: policy.bypassForMachineIdentities
+ }),
+ secretEnvironments: buildPolicyEnvironmentRows(policy.id, environments, policy.secretPath),
+ ...buildPolicyStepRows(policy.id, steps), // I need to check it more carefully
+ bypassers: buildBypasserRows(policy.id, bypassers),
+ requests: [],
+ requestSteps: [],
+ eligibleApprovers: [],
+ approvals: [],
+ secretChangeRequests: []
+ };
+
+ checkRequestsAlreadyMigrated(data.requestIdsAlreadyOnGlobal, failures);
+
+ const committerById = new Map(committers.map((committer) => [committer.id, committer]));
+ const committerIdentityById = new Map(committerIdentities.map((identity) => [identity.id, identity]));
+ const reviewsByRequestId = groupBy(reviews, (review) => review.requestId);
+ const knownStatuses = Object.values(LegacyRequestStatus) as string[];
+
+ requests.forEach((request) => {
+ const requestReviews = latestReviewPerReviewer(reviewsByRequestId[request.id] ?? []);
+
+ if (!knownStatuses.includes(request.status)) {
+ failures.push({
+ code: "unknown-request-status",
+ requestId: request.id,
+ message: `Status '${request.status}' has no equivalent on the global approval system`
+ });
+ }
+ if (request.committerUserId && request.committerIdentityId) {
+ failures.push({
+ code: "ambiguous-committer",
+ requestId: request.id,
+ message: `The request names both user ${request.committerUserId} and machine identity ${request.committerIdentityId} as its committer, and the global approval system records one requester`
+ });
+ }
+ checkReviewStatuses(request.id, requestReviews, failures);
+
+ rows.requests.push({
+ id: request.id,
+ projectId,
+ organizationId: orgId,
+ policyId: policy.id,
+ ...resolveRequester(request, committerById, committerIdentityById),
+ type: SECRET_CHANGE,
+ status: request.status,
+ justification: null,
+ currentStep: 1,
+ requestData: { version: 1, requestData: {} },
+ expiresAt: null,
+ scopeType: null,
+ scopeId: null,
+ createdAt: request.createdAt,
+ updatedAt: request.updatedAt
+ });
+
+ const replay = replayReviews(steps, requestReviews);
+ const { requestSteps, eligibleApprovers, approvals } = buildRequestStepRows({
+ requestId: request.id,
+ steps,
+ replay,
+ isApprovedLike: false,
+ requestCreatedAt: request.createdAt,
+ fallbackCompletedAt: request.updatedAt
+ });
+ rows.requestSteps.push(...requestSteps);
+ rows.eligibleApprovers.push(...eligibleApprovers);
+ rows.approvals.push(...approvals);
+
+ rows.secretChangeRequests.push({
+ id: crypto.randomUUID(),
+ approvalRequestId: request.id,
+ folderId: request.folderId,
+ slug: request.slug,
+ hasMerged: request.hasMerged,
+ conflicts:
+ request.conflicts === null || request.conflicts === undefined ? null : JSON.stringify(request.conflicts),
+ commitMessage: request.commitMessage ?? null,
+ bypassReason: request.bypassReason ?? null,
+ isReplicated: request.isReplicated ?? null,
+ statusChangedByUserId: request.statusChangedByUserId ?? null,
+ createdAt: request.createdAt,
+ updatedAt: request.updatedAt
+ });
+ });
+
+ return { failures, rows, projectId };
+};
+
+const relinkCommitsToSecretChangeRequests = async (tx: Knex, secretChangeRequests: TSecretChangeRequestRow[]) => {
+ for (const chunk of chunkArray(secretChangeRequests, INSERT_CHUNK_SIZE)) {
+ const values = chunk.map(() => "(?::uuid, ?::uuid)").join(", ");
+ await tx.raw(
+ `UPDATE ${TableName.SecretApprovalRequestSecretV2} AS c
+ SET "secretChangeId" = m.secret_change_id, "requestId" = NULL
+ FROM (VALUES ${values}) AS m(request_id, secret_change_id)
+ WHERE c."requestId" = m.request_id`,
+ chunk.flatMap(({ approvalRequestId, id }) => [approvalRequestId, id])
+ );
+ }
+};
+
+const readPolicyData = async (tx: Knex, policy: TLegacyPolicy, requests: TLegacyRequest[]): Promise<TPolicyData> => {
+ const { id: policyId } = policy;
+ const requestIds = requests.map(({ id }) => id);
+ const committerIds = [...new Set(requests.map(({ committerUserId }) => committerUserId).filter(isId))];
+ const committerIdentityIds = [
+ ...new Set(requests.map(({ committerIdentityId }) => committerIdentityId).filter(isId))
+ ];
+
+ const environments = await readPolicyEnvironments(tx, LEGACY_TABLES, policyId);
+ const projectId = environments[0]?.projectId;
+ const project = projectId
+ ? (((await tx(TableName.Project).where({ id: projectId }).first("id", "version")) as TProject | undefined) ?? null)
+ : null;
+
+ const approvers = await readLegacyApprovers(tx, LEGACY_TABLES, policyId);
+ const bypassers = await readLegacyBypassers(tx, LEGACY_TABLES, policyId);
+ const reviews = await readLegacyReviews(tx, LEGACY_TABLES, requestIds, { withComment: true });
+
+ const committers = committerIds.length
+ ? ((await tx(TableName.Users)
+ .whereRaw(`"id" = ANY(?::uuid[])`, [committerIds])
+ .select("id", "username", "email", "firstName", "lastName")) as TCommitter[])
+ : [];
+ const committerIdentities = committerIdentityIds.length
+ ? ((await tx(TableName.Identity)
+ .whereRaw(`"id" = ANY(?::uuid[])`, [committerIdentityIds])
+ .select("id", "name")) as TCommitterIdentity[])
+ : [];
+
+ const groupMembers = await readApproverGroupMembers(tx, approvers);
+ const requestIdsAlreadyOnGlobal = await readRequestIdsAlreadyOnGlobal(tx, requestIds);
+
+ return {
+ policy,
+ project,
+ environments,
+ approvers,
+ bypassers,
+ requests,
+ reviews,
+ committers,
+ committerIdentities,
+ groupMembers,
+ requestIdsAlreadyOnGlobal
+ };
+};
+
+const migratePolicy = async (tx: Knex, policyId: string): Promise<TPolicyOutcome> => {
+ const policy = await lockLegacyPolicy<TLegacyPolicy>(tx, LEGACY_TABLES, policyId);
+ if (!policy) return "skipped";
+
+ const requests = (await tx(TableName.SecretApprovalRequest)
+ .where({ policyId })
+ .orderBy("id", "asc")
+ .forUpdate()
+ .select("*")) as TLegacyRequest[];
+
+ const data = await readPolicyData(tx, policy, requests);
+ const { failures, rows, projectId } = translatePolicy(data);
+
+ if (failures.length) {
+ logFailedChecks({ logPrefix: LOG_PREFIX, policyId, projectId, failures });
+ return "failedChecks";
+ }
+
+ await insertGlobalPolicyRows(tx, rows);
+ await insertGlobalRequestRows(tx, rows);
+ await insertChunked(tx, TableName.SecretChangeRequests, rows.secretChangeRequests);
+ await relinkCommitsToSecretChangeRequests(tx, rows.secretChangeRequests);
+
+ return "migrated";
+};
+
+export async function up(knex: Knex): Promise<void> {
+ if (
+ !(await knex.schema.hasTable(TableName.SecretApprovalPolicy)) ||
+ !(await knex.schema.hasTable(TableName.SecretChangeRequests))
+ ) {
+ return;
+ }
+
+ await runLegacyPolicyMigration(knex, { tables: LEGACY_TABLES, logPrefix: LOG_PREFIX, migratePolicy });
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (
+ !(await knex.schema.hasTable(TableName.SecretApprovalPolicy)) ||
+ !(await knex.schema.hasTable(TableName.ApprovalPolicies)) ||
+ !(await knex.schema.hasTable(TableName.SecretChangeRequests))
+ ) {
+ return;
+ }
+
+ const migratedTwinOf = (legacyTable: TableName, globalTable: TableName) => (qb: Knex.QueryBuilder) => {
+ void qb
+ .select(knex.raw("1"))
+ .from(globalTable)
+ .whereRaw(`"${globalTable}"."id" = "${legacyTable}"."id"`)
+ .where(`${globalTable}.type`, SECRET_CHANGE);
+ };
+
+ const policyIds = (await knex(TableName.SecretApprovalPolicy)
+ .where((qb) => {
+ void qb
+ .whereExists(migratedTwinOf(TableName.SecretApprovalPolicy, TableName.ApprovalPolicies))
+ .orWhereExists((sub) => {
+ void sub
+ .select(knex.raw("1"))
+ .from(TableName.SecretApprovalRequest)
+ .whereRaw(`"${TableName.SecretApprovalRequest}"."policyId" = "${TableName.SecretApprovalPolicy}"."id"`)
+ .whereExists(migratedTwinOf(TableName.SecretApprovalRequest, TableName.ApprovalRequests));
+ });
+ })
+ .orderBy("id", "asc")
+ .pluck("id")) as string[];
+
+ for (const policyId of policyIds) {
+ await knex.transaction(async (tx) => {
+ await tx.raw(`SET LOCAL statement_timeout = ${POLICY_STATEMENT_TIMEOUT_MS}`);
+
+ await tx.raw(
+ `UPDATE ${TableName.SecretApprovalRequest} AS lr
+ SET "status" = ar."status",
+ "hasMerged" = scr."hasMerged",
+ "conflicts" = scr."conflicts",
+ "statusChangedByUserId" = scr."statusChangedByUserId",
+ "bypassReason" = scr."bypassReason"
+ FROM ${TableName.ApprovalRequests} AS ar
+ JOIN ${TableName.SecretChangeRequests} AS scr ON scr."approvalRequestId" = ar."id"
+ WHERE lr."id" = ar."id" AND ar."type" = ? AND lr."policyId" = ?`,
+ [SECRET_CHANGE, policyId]
+ );
+
+ await tx.raw(
+ `UPDATE ${TableName.SecretApprovalRequestSecretV2} AS c
+ SET "requestId" = scr."approvalRequestId", "secretChangeId" = NULL
+ FROM ${TableName.SecretChangeRequests} AS scr
+ JOIN ${TableName.SecretApprovalRequest} AS lr ON lr."id" = scr."approvalRequestId"
+ WHERE c."secretChangeId" = scr."id" AND lr."policyId" = ?`,
+ [policyId]
+ );
+
+ await tx(TableName.ApprovalRequests)
+ .where({ type: SECRET_CHANGE })
+ .whereIn("id", tx(TableName.SecretApprovalRequest).where({ policyId }).select("id"))
+ .delete();
+
+ await tx(TableName.ApprovalPolicies).where({ id: policyId, type: SECRET_CHANGE }).delete();
+ });
+ }
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/db/migrations/utils/approval-migration.test.ts b/backend/src/db/migrations/utils/approval-migration.test.ts
index 8ff11eed08..b9cc9e6b74 100644
--- a/backend/src/db/migrations/utils/approval-migration.test.ts
+++ b/backend/src/db/migrations/utils/approval-migration.test.ts
@@ -674,7 +674,15 @@ describe("runLegacyPolicyMigration", () => {
}
);
- expect(migratePolicy.mock.calls.map(([, policyId]) => policyId)).toEqual(["p1", "p2", "p3", "p4", "p5"]);
+ expect(migratePolicy.mock.calls.map(([, policyId]) => policyId)).toEqual([
+ "p1",
+ "p2",
+ "p3",
+ "p4",
+ "p5",
+ "p2",
+ "p2"
+ ]);
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("[policyId=p2] reasons=[locked:"));
expect(logger.error).toHaveBeenCalledWith(
expect.objectContaining({ message: "boom" }),
@@ -685,6 +693,25 @@ describe("runLegacyPolicyMigration", () => {
);
});
+ test("retries a locked policy after the remaining ones and counts it once it goes through", async () => {
+ let p1Attempts = 0;
+ const migratePolicy = vi.fn((_tx: Knex, policyId: string) => {
+ if (policyId === "p1") {
+ p1Attempts += 1;
+ if (p1Attempts === 1) return Promise.reject(Object.assign(new Error("lock"), { code: "55P03" }));
+ }
+ return Promise.resolve("migrated" as TPolicyOutcome);
+ });
+
+ await runLegacyPolicyMigration(fakeKnex([["p1", "p2"]]), { tables: legacyTables, logPrefix: "pfx", migratePolicy });
+
+ expect(migratePolicy.mock.calls.map(([, policyId]) => policyId)).toEqual(["p1", "p2", "p1"]);
+ expect(logger.warn).not.toHaveBeenCalledWith(expect.stringContaining("stays on the legacy approval system"));
+ expect(logger.info).toHaveBeenCalledWith(
+ "pfx: migrated 2 policies, 0 failed checks, 0 were locked, 0 failed with an error, 0 were already migrated or deleted"
+ );
+ });
+
test("does nothing when no legacy policy is left to migrate", async () => {
const migratePolicy = vi.fn(() => Promise.resolve("migrated" as TPolicyOutcome));
diff --git a/backend/src/db/migrations/utils/secret-approval-migration-scenarios.test.ts b/backend/src/db/migrations/utils/secret-approval-migration-scenarios.test.ts
new file mode 100644
index 0000000000..89479780f8
--- /dev/null
+++ b/backend/src/db/migrations/utils/secret-approval-migration-scenarios.test.ts
@@ -0,0 +1,379 @@
+// Lives under utils/ because tsdown compiles every src/db/migrations/*.ts into dist/db/migrations/,
+// where knex would load a test file as a migration.
+import { describe, expect, test } from "vitest";
+
+import { TPolicyData, translatePolicy } from "../20261014120100_migrate-secret-approval-policies-to-global";
+import { TLegacyApprover, TLegacyReview, TMigrationFailure } from "./approval-migration";
+
+type TRequest = TPolicyData["requests"][number];
+
+const T0 = new Date("2026-01-01T00:00:00Z");
+const at = (minutes: number) => new Date(T0.getTime() + minutes * 60_000);
+
+const approver = (approverUserId: string): TLegacyApprover => ({ approverUserId, approverGroupId: null });
+const groupApprover = (approverGroupId: string): TLegacyApprover => ({ approverUserId: null, approverGroupId });
+
+const env = (envSlug: string, projectId = "P") => ({ envId: `env-${envSlug}`, envSlug, projectId, orgId: "O" });
+
+const scenario = (overrides: Partial<TPolicyData> = {}): TPolicyData => ({
+ policy: {
+ id: "pol-1",
+ name: "Prod changes",
+ approvals: 1,
+ secretPath: "/apps/**",
+ enforcementLevel: "hard",
+ allowedSelfApprovals: true,
+ bypassForMachineIdentities: true,
+ deletedAt: null,
+ createdAt: at(0),
+ updatedAt: at(1)
+ },
+ project: { id: "P", version: 3 },
+ environments: [env("dev")],
+ approvers: [approver("u1"), approver("u2")],
+ bypassers: [],
+ requests: [],
+ reviews: [],
+ committers: [{ id: "c1", username: "[email protected]", email: "[email protected]", firstName: "Cam", lastName: "Doe" }],
+ committerIdentities: [],
+ groupMembers: [],
+ requestIdsAlreadyOnGlobal: [],
+ ...overrides
+});
+
+const request = (overrides: Partial<TRequest> = {}): TRequest => ({
+ id: "req-1",
+ policyId: "pol-1",
+ status: "open",
+ hasMerged: false,
+ conflicts: null,
+ slug: "slug-1",
+ folderId: "f1",
+ isReplicated: false,
+ committerUserId: "c1",
+ committerIdentityId: null,
+ statusChangedByUserId: null,
+ bypassReason: null,
+ commitMessage: "rotate api key",
+ createdAt: at(10),
+ updatedAt: at(10),
+ ...overrides
+});
+
+const review = (
+ id: string,
+ reviewerUserId: string,
+ status: string,
+ createdAt: Date,
+ { requestId = "req-1", comment = null as string | null } = {}
+): TLegacyReview => ({ id, requestId, reviewerUserId, status, createdAt, comment });
+
+const run = (data: TPolicyData) => translatePolicy(data);
+const codes = (failures: TMigrationFailure[]) => failures.map((failure) => failure.code);
+
+describe("secret approval migration scenarios that migrate", () => {
+ test("translates a policy into one step with the policy's approvals, keeping its bypass flags", () => {
+ const { failures, rows, projectId } = run(
+ scenario({
+ policy: { ...scenario().policy, approvals: 2, enforcementLevel: "soft", allowedSelfApprovals: false },
+ environments: [env("dev"), env("prod")],
+ approvers: [approver("u1"), groupApprover("g1"), approver("u2")],
+ groupMembers: [{ groupId: "g1", userId: "u3" }],
+ bypassers: [{ bypasserUserId: "b1" }, { bypasserUserId: "b1" }, { bypasserGroupId: "g2" }]
+ })
+ );
+
+ expect(failures).toEqual([]);
+ expect(projectId).toBe("P");
+ expect(rows.policy).toEqual({
+ id: "pol-1",
+ projectId: "P",
+ organizationId: "O",
+ type: "secret-change",
+ name: "Prod changes",
+ isActive: true,
+ maxRequestTtl: null,
+ conditions: { version: 1, conditions: [] },
+ constraints: { version: 1, constraints: { allowedSelfApprovals: false } },
+ enforcementLevel: "soft",
+ bypassForMachineIdentities: true,
+ scopeType: null,
+ scopeId: null,
+ createdAt: at(0),
+ updatedAt: at(1)
+ });
+ expect(rows.secretEnvironments).toEqual([
+ { policyId: "pol-1", envId: "env-dev", secretPath: "/apps/**" },
+ { policyId: "pol-1", envId: "env-prod", secretPath: "/apps/**" }
+ ]);
+ expect(rows.policySteps).toMatchObject([{ policyId: "pol-1", stepNumber: 1, requiredApprovals: 2 }]);
+ expect(rows.policyStepApprovers).toEqual([
+ { policyStepId: rows.policySteps[0].id, userId: "u1", groupId: null },
+ { policyStepId: rows.policySteps[0].id, userId: "u2", groupId: null },
+ { policyStepId: rows.policySteps[0].id, userId: null, groupId: "g1" }
+ ]);
+ expect(rows.bypassers).toEqual([
+ { policyId: "pol-1", userId: "b1", groupId: null },
+ { policyId: "pol-1", userId: null, groupId: "g2" }
+ ]);
+ expect(rows.requests).toEqual([]);
+ expect(rows.secretChangeRequests).toEqual([]);
+ });
+
+ test("a machine identity bypass flag of false is copied rather than defaulted", () => {
+ const { rows } = run(scenario({ policy: { ...scenario().policy, bypassForMachineIdentities: false } }));
+
+ expect(rows.policy.bypassForMachineIdentities).toBe(false);
+ });
+
+ test("carries an open request over with its single step in progress and every review as an approval", () => {
+ const { failures, rows } = run(
+ scenario({
+ approvers: [approver("u1"), groupApprover("g1")],
+ groupMembers: [{ groupId: "g1", userId: "u3" }],
+ requests: [request()],
+ reviews: [
+ review("rv1", "u1", "approved", at(15), { comment: "looks good" }),
+ review("rv2", "u3", "rejected", at(16))
+ ]
+ })
+ );
+
+ expect(failures).toEqual([]);
+ expect(rows.requests).toEqual([
+ {
+ id: "req-1",
+ projectId: "P",
+ organizationId: "O",
+ policyId: "pol-1",
+ requesterId: "c1",
+ machineIdentityId: null,
+ requesterName: "Cam Doe",
+ requesterEmail: "[email protected]",
+ type: "secret-change",
+ status: "open",
+ justification: null,
+ currentStep: 1,
+ requestData: { version: 1, requestData: {} },
+ expiresAt: null,
+ scopeType: null,
+ scopeId: null,
+ createdAt: at(10),
+ updatedAt: at(10)
+ }
+ ]);
+ expect(rows.requestSteps).toEqual([
+ {
+ id: expect.any(String),
+ requestId: "req-1",
+ stepNumber: 1,
+ name: null,
+ status: "in-progress",
+ requiredApprovals: 1,
+ notifyApprovers: false,
+ startedAt: at(10),
+ completedAt: null
+ }
+ ]);
+ const stepId = rows.requestSteps[0].id;
+ expect(rows.eligibleApprovers).toEqual([
+ { stepId, userId: "u1", groupId: null },
+ { stepId, userId: null, groupId: "g1" }
+ ]);
+ expect(rows.approvals).toEqual([
+ { stepId, approverUserId: "u1", decision: "approved", comment: "looks good", createdAt: at(15) },
+ { stepId, approverUserId: "u3", decision: "rejected", comment: null, createdAt: at(16) }
+ ]);
+ expect(rows.secretChangeRequests).toEqual([
+ {
+ id: expect.any(String),
+ approvalRequestId: "req-1",
+ folderId: "f1",
+ slug: "slug-1",
+ hasMerged: false,
+ conflicts: null,
+ commitMessage: "rotate api key",
+ bypassReason: null,
+ isReplicated: false,
+ statusChangedByUserId: null,
+ createdAt: at(10),
+ updatedAt: at(10)
+ }
+ ]);
+ });
+
+ test("keeps only the newest review row per reviewer", () => {
+ const { failures, rows } = run(
+ scenario({
+ requests: [request()],
+ reviews: [review("rv1", "u1", "rejected", at(15)), review("rv2", "u1", "approved", at(20))]
+ })
+ );
+
+ expect(failures).toEqual([]);
+ expect(rows.approvals).toEqual([expect.objectContaining({ approverUserId: "u1", decision: "approved" })]);
+ });
+
+ test("a review left by someone who is not an approver is carried over without failing", () => {
+ const { failures, rows } = run(
+ scenario({ requests: [request()], reviews: [review("rv1", "admin-1", "approved", at(15))] })
+ );
+
+ expect(failures).toEqual([]);
+ expect(rows.approvals).toEqual([expect.objectContaining({ approverUserId: "admin-1", decision: "approved" })]);
+ });
+
+ test("a merged request keeps its merge outcome on the secret change row and closes on global", () => {
+ const { failures, rows } = run(
+ scenario({
+ requests: [
+ request({
+ status: "close",
+ hasMerged: true,
+ conflicts: [{ op: "update", secretId: "s1" }],
+ statusChangedByUserId: "u1",
+ bypassReason: "incident 42 needs the key now",
+ updatedAt: at(30)
+ })
+ ],
+ reviews: [review("rv1", "u1", "approved", at(15))]
+ })
+ );
+
+ expect(failures).toEqual([]);
+ expect(rows.requests[0]).toMatchObject({ status: "close", currentStep: 1, updatedAt: at(30) });
+ expect(rows.requestSteps[0]).toMatchObject({ status: "in-progress", completedAt: null });
+ expect(rows.secretChangeRequests[0]).toMatchObject({
+ hasMerged: true,
+ conflicts: JSON.stringify([{ op: "update", secretId: "s1" }]),
+ statusChangedByUserId: "u1",
+ bypassReason: "incident 42 needs the key now",
+ updatedAt: at(30)
+ });
+ });
+
+ test("a closed unmerged request closes on global without a merge outcome", () => {
+ const { failures, rows } = run(
+ scenario({ requests: [request({ status: "close", statusChangedByUserId: "c1", updatedAt: at(12) })] })
+ );
+
+ expect(failures).toEqual([]);
+ expect(rows.requests[0]).toMatchObject({ status: "close" });
+ expect(rows.secretChangeRequests[0]).toMatchObject({ hasMerged: false, statusChangedByUserId: "c1" });
+ });
+
+ test("a request opened by a machine identity names the identity", () => {
+ const { failures, rows } = run(
+ scenario({
+ committerIdentities: [{ id: "i1", name: "deploy-bot" }],
+ requests: [request({ committerUserId: null, committerIdentityId: "i1" })]
+ })
+ );
+
+ expect(failures).toEqual([]);
+ expect(rows.requests[0]).toMatchObject({
+ requesterId: null,
+ machineIdentityId: "i1",
+ requesterName: "deploy-bot",
+ requesterEmail: ""
+ });
+ });
+
+ test("a request whose committer was deleted migrates with no requester", () => {
+ const { failures, rows } = run(scenario({ requests: [request({ committerUserId: null })] }));
+
+ expect(failures).toEqual([]);
+ expect(rows.requests[0]).toMatchObject({
+ requesterId: null,
+ machineIdentityId: null,
+ requesterName: "",
+ requesterEmail: ""
+ });
+ });
+
+ test("a committer without a name is named by their username", () => {
+ const { rows } = run(
+ scenario({
+ committers: [{ id: "c1", username: "[email protected]", email: null, firstName: null, lastName: null }],
+ requests: [request()]
+ })
+ );
+
+ expect(rows.requests[0]).toMatchObject({ requesterName: "[email protected]", requesterEmail: "" });
+ });
+});
+
+describe("secret approval migration scenarios that fail the checks", () => {
+ test("a policy on a project that is not V3", () => {
+ const { failures } = run(scenario({ project: { id: "P", version: 2 } }));
+
+ expect(codes(failures)).toEqual(["project-not-v3"]);
+ expect(failures[0].message).toContain("version 2");
+ });
+
+ test("a policy whose project could not be read", () => {
+ const { failures } = run(scenario({ project: null }));
+
+ expect(codes(failures)).toEqual(["project-not-v3"]);
+ });
+
+ test("a policy without environments", () => {
+ const { failures } = run(scenario({ environments: [] }));
+
+ expect(codes(failures)).toEqual(["no-environments"]);
+ });
+
+ test("a policy without approvers", () => {
+ const { failures } = run(scenario({ approvers: [] }));
+
+ expect(codes(failures)).toEqual(["no-approvers"]);
+ });
+
+ test("a policy that requires more approvals than it has user approvers", () => {
+ const { failures } = run(scenario({ policy: { ...scenario().policy, approvals: 3 } }));
+
+ expect(codes(failures)).toEqual(["required-approvals-exceed-approvers"]);
+ });
+
+ test("a policy that requires zero approvals", () => {
+ const { failures } = run(scenario({ policy: { ...scenario().policy, approvals: 0 } }));
+
+ expect(codes(failures)).toEqual(["invalid-approvals"]);
+ });
+
+ test("a request with a status the global approval system does not have", () => {
+ const { failures } = run(scenario({ requests: [request({ status: "merged" })] }));
+
+ expect(failures).toEqual([
+ {
+ code: "unknown-request-status",
+ requestId: "req-1",
+ message: "Status 'merged' has no equivalent on the global approval system"
+ }
+ ]);
+ });
+
+ test("a review with a status other than approved or rejected", () => {
+ const { failures } = run(scenario({ requests: [request()], reviews: [review("rv1", "u1", "pending", at(15))] }));
+
+ expect(codes(failures)).toEqual(["unknown-review-status"]);
+ });
+
+ test("a request that names both a committer user and a committer identity", () => {
+ const { failures } = run(
+ scenario({
+ committerIdentities: [{ id: "i1", name: "deploy-bot" }],
+ requests: [request({ committerUserId: "c1", committerIdentityId: "i1" })]
+ })
+ );
+
+ expect(codes(failures)).toEqual(["ambiguous-committer"]);
+ expect(failures[0]).toMatchObject({ requestId: "req-1" });
+ });
+
+ test("a request that already exists on the global approval system", () => {
+ const { failures } = run(scenario({ requests: [request()], requestIdsAlreadyOnGlobal: ["req-1"] }));
+
+ expect(codes(failures)).toEqual(["request-already-migrated"]);
+ });
+});
diff --git a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-dal.ts b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-dal.ts
index d0bb3f1bac..c8f66c7776 100644
--- a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-dal.ts
+++ b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-dal.ts
@@ -9,7 +9,14 @@ import {
TUsers
} from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
-import { buildFindFilter, ormify, selectAllTableCols, sqlNestRelationships, TFindFilter } from "@app/lib/knex";
+import {
+ buildFindFilter,
+ ormify,
+ rowWithSameIdIn,
+ selectAllTableCols,
+ sqlNestRelationships,
+ TFindFilter
+} from "@app/lib/knex";
import { ApproverType, BypasserType } from "../access-approval-policy/access-approval-policy-types";
@@ -29,6 +36,7 @@ export const secretApprovalPolicyDALFactory = (db: TDbClient) => {
tx(TableName.SecretApprovalPolicy)
// eslint-disable-next-line
.where(buildFindFilter(filter))
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalPolicies, TableName.SecretApprovalPolicy))
.where((qb) => {
if (customFilter?.sapId) {
void qb.where(`${TableName.SecretApprovalPolicy}.id`, "=", customFilter.sapId);
@@ -303,6 +311,7 @@ export const secretApprovalPolicyDALFactory = (db: TDbClient) => {
)
)
.whereNull(`${TableName.SecretApprovalPolicy}.deletedAt`)
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalPolicies, TableName.SecretApprovalPolicy))
.orderBy("deletedAt", "desc")
.orderByRaw(`"deletedAt" IS NULL`)
.select(selectAllTableCols(TableName.SecretApprovalPolicy))
diff --git a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-environment-dal.ts b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-environment-dal.ts
index d12ace04c8..409b3aa07a 100644
--- a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-environment-dal.ts
+++ b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-environment-dal.ts
@@ -3,7 +3,7 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
-import { buildFindFilter, ormify, selectAllTableCols } from "@app/lib/knex";
+import { buildFindFilter, ormify, rowWithSameIdIn, selectAllTableCols } from "@app/lib/knex";
export type TSecretApprovalPolicyEnvironmentDALFactory = ReturnType<typeof secretApprovalPolicyEnvironmentDALFactory>;
@@ -21,6 +21,7 @@ export const secretApprovalPolicyEnvironmentDALFactory = (db: TDbClient) => {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
.where(buildFindFilter({ envId }, TableName.SecretApprovalPolicyEnvironment))
.whereNull(`${TableName.SecretApprovalPolicy}.deletedAt`)
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalPolicies, TableName.SecretApprovalPolicy))
.select(selectAllTableCols(TableName.SecretApprovalPolicyEnvironment));
return docs;
} catch (error) {
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-dal.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-dal.ts
index fc2db70f3d..e168bdeb1d 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-dal.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-dal.ts
@@ -14,7 +14,14 @@ import {
} from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { sanitizeSqlLikeString } from "@app/lib/fn";
-import { ormify, selectAllTableCols, sqlNestRelationships, stripUndefinedInWhere, TFindFilter } from "@app/lib/knex";
+import {
+ ormify,
+ rowWithSameIdIn,
+ selectAllTableCols,
+ sqlNestRelationships,
+ stripUndefinedInWhere,
+ TFindFilter
+} from "@app/lib/knex";
import { OrderByDirection } from "@app/lib/types";
import { RequestState, SecretApprovalRequestOrderBy } from "./secret-approval-request-types";
@@ -111,6 +118,7 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
const findQuery = (filter: TFindFilter<TSecretApprovalRequests>, tx: Knex) =>
tx(TableName.SecretApprovalRequest)
.where(filter)
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalRequests, TableName.SecretApprovalRequest))
.join(TableName.SecretFolder, `${TableName.SecretApprovalRequest}.folderId`, `${TableName.SecretFolder}.id`)
.join(TableName.Environment, function joinActiveEnvForSecretFolder() {
this.on(`${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`).andOnNull(
@@ -465,6 +473,7 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
`${TableName.UserGroupMembership}.groupId`
)
.where({ projectId })
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalRequests, TableName.SecretApprovalRequest))
.where((qb) => {
if (policyId) void qb.where(`${TableName.SecretApprovalPolicy}.id`, policyId);
})
@@ -572,6 +581,7 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
committerUserId: committer
})
)
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalRequests, TableName.SecretApprovalRequest))
.modify((qb) => buildUserAccessFilter(qb, userId))
.select(selectAllTableCols(TableName.SecretApprovalRequest))
.select(
@@ -799,6 +809,7 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
committerUserId: committer
})
)
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalRequests, TableName.SecretApprovalRequest))
.modify((qb) => buildUserAccessFilter(qb, userId))
.select(selectAllTableCols(TableName.SecretApprovalRequest))
.select(
@@ -990,6 +1001,19 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
}
};
+ const findOpenByFolderIds = async (folderIds: string[], tx?: Knex) => {
+ try {
+ const docs = await (tx || db.replicaNode())(TableName.SecretApprovalRequest)
+ .whereIn("folderId", folderIds)
+ .where({ status: RequestState.Open })
+ .whereNotExists(rowWithSameIdIn(TableName.ApprovalRequests, TableName.SecretApprovalRequest))
+ .select("id", "folderId");
+ return docs;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindOpenByFolderIds" });
+ }
+ };
+
const deleteByProjectId = async (projectId: string, tx?: Knex) => {
try {
const query = await (tx || db)(TableName.SecretApprovalRequest)
@@ -1011,6 +1035,7 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
findProjectRequestCount,
findByProjectId,
findByProjectIdBridgeSecretV2,
+ findOpenByFolderIds,
deleteByProjectId
};
};
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 62e37d6103..a7a59c39af 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
@@ -1799,10 +1799,7 @@ export const secretApprovalRequestServiceFactory = ({
const findFolderIdsWithOpenRequests = async (folderIds: string[], tx?: Knex) => {
if (!folderIds.length) return [];
- const legacyRequests = await secretApprovalRequestDAL.find(
- { $in: { folderId: folderIds }, status: RequestState.Open },
- { tx }
- );
+ const legacyRequests = await secretApprovalRequestDAL.findOpenByFolderIds(folderIds, tx);
const secretChangeFolderIds =
await secretChangeGlobalRequestBridgeService.findFolderIdsWithOpenSecretChangeRequests(folderIds, tx);
diff --git a/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.test.ts b/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.test.ts
index a72cc4e16c..cdcbfec6f3 100644
--- a/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.test.ts
+++ b/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.test.ts
@@ -139,7 +139,10 @@ const buildService = ({
)
)
},
- secretApprovalPolicyDAL: { findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(existingLegacyPolicy) },
+ secretApprovalPolicyDAL: {
+ findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(existingLegacyPolicy),
+ update: vi.fn().mockResolvedValue([])
+ },
projectEnvDAL: {
find: vi.fn(({ $in }: { $in: { slug: string[] } }) =>
Promise.resolve(envs.filter((env) => $in.slug.includes(env.slug)))
@@ -768,6 +771,11 @@ describe("secretChangeGlobalPolicyBridge deleteSecretChangePolicy", () => {
TX
);
expect(deps.approvalPolicyDAL.deleteById).toHaveBeenCalledWith("policy-1", TX);
+ expect(deps.secretApprovalPolicyDAL.update).toHaveBeenCalledWith(
+ { id: "policy-1", deletedAt: null },
+ { deletedAt: expect.any(Date) as Date },
+ TX
+ );
const [lockOrder] = deps.approvalPolicyDAL.findByIdForUpdate.mock.invocationCallOrder;
const [closeOrder] = deps.approvalRequestDAL.update.mock.invocationCallOrder;
const [deleteOrder] = deps.approvalPolicyDAL.deleteById.mock.invocationCallOrder;
diff --git a/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.ts b/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.ts
index 3ad0c5372f..958409bbb9 100644
--- a/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.ts
+++ b/backend/src/ee/services/secret-change-global-policy-bridge/secret-change-global-policy-bridge-service.ts
@@ -45,7 +45,7 @@ type TSecretChangeGlobalPolicyBridgeServiceFactoryDep = {
>;
approvalRequestDAL: Pick<TApprovalRequestDALFactory, "update">;
secretChangeGlobalPolicyBridgeDAL: Pick<TSecretChangeGlobalPolicyBridgeDALFactory, "findSecretChangePolicies">;
- secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "findPolicyByEnvIdAndSecretPath">;
+ secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "findPolicyByEnvIdAndSecretPath" | "update">;
projectEnvDAL: Pick<TProjectEnvDALFactory, "find">;
projectDAL: Pick<TProjectDALFactory, "findById" | "findEffectiveProjectSubjectsMembership">;
userDAL: Pick<TUserDALFactory, "find">;
@@ -351,6 +351,7 @@ export const secretChangeGlobalPolicyBridgeServiceFactory = ({
tx
);
await approvalPolicyDAL.deleteById(policy.id, tx);
+ await secretApprovalPolicyDAL.update({ id: policy.id, deletedAt: null }, { deletedAt: new Date() }, tx);
});
return { ...policy, deletedAt: new Date() };
diff --git a/legacy-secret-change-approvals-seed.sql b/legacy-secret-change-approvals-seed.sql
new file mode 100644
index 0000000000..5299e5943e
--- /dev/null
+++ b/legacy-secret-change-approvals-seed.sql
@@ -0,0 +1,798 @@
+-- Seeds legacy secret change approval policies and requests (secret_approval_* tables) covering approval
+-- counts, group approvers, self-approval, soft enforcement and bypassers, machine identity and deleted
+-- committers, replication, tags, merge conflicts and deleted policies. Every request, commit and review
+-- row is written the way the legacy service writes it, including states only reachable through deleted
+-- users or groups or through duplicates the API accepts (see the notes on p03, p08, p10, p13, p17, p18
+-- and p19).
+--
+-- Usage: edit the three ids in seed_params, then run the whole file (psql -f, or pgAdmin's query tool).
+-- docker exec -i infisical-db-1 psql -U infisical -d infisical -v ON_ERROR_STOP=1 < legacy-secret-change-approvals-seed.sql
+--
+-- The project must be on V3, the only version the migration moves. A V3 project can no longer create
+-- legacy policies, so these stand in for policies created before the global approval system took over.
+--
+-- Secret values and comments are empty: SQL cannot encrypt with the project's KMS key, and every read path
+-- treats a NULL ciphertext as an empty or unchanged value. Merges write the secrets and their versions, but
+-- not folder commits.
+--
+-- Re-running is safe: it first deletes every legacy secret approval policy in the project whose name
+-- matches ^p[0-9]{2}- together with its requests, plus any global copies the migration made of them (same
+-- ids) and global requests filed against those copies, and every folder this seed created (marked by its
+-- description) with the secrets in it.
+--
+-- The migration is already recorded as applied on a dev DB that ran it, so roll it back and re-run it to
+-- migrate a fresh seed.
+
+BEGIN;
+
+CREATE TEMP TABLE seed_params ON COMMIT DROP AS
+SELECT
+ 'b74165da-868a-4912-8887-58488b5a6cf5'::text AS project_id,
+ 'ee1008ae-1082-4be2-90e6-b979e82f2476'::uuid AS admin_id, -- project admin: approver and reviewer
+ '1e10c1da-e8c1-4100-ab70-0eaae8b6b639'::uuid AS requester_id; -- project member: files the requests
+
+-- Every write takes the next instant on one timeline, so the rows read in the order the script runs.
+CREATE TEMP TABLE seed_clock ON COMMIT DROP AS SELECT now() - interval '3 hours' AS at;
+CREATE TEMP TABLE seed_policies (name text PRIMARY KEY, id uuid NOT NULL, path text NOT NULL, created_at timestamptz NOT NULL) ON COMMIT DROP;
+CREATE TEMP TABLE seed_requests (key text PRIMARY KEY, id uuid NOT NULL, folder_id uuid NOT NULL, updated_at timestamptz NOT NULL) ON COMMIT DROP;
+CREATE TEMP TABLE seed_review_revisions (id uuid PRIMARY KEY, updated_at timestamptz NOT NULL) ON COMMIT DROP;
+
+-- ---------------------------------------------------------------------------------------------------
+-- Helpers (session-scoped, gone when the connection closes)
+-- ---------------------------------------------------------------------------------------------------
+
+CREATE OR REPLACE FUNCTION pg_temp.project() RETURNS text LANGUAGE sql STABLE AS
+$$ SELECT project_id FROM seed_params $$;
+CREATE OR REPLACE FUNCTION pg_temp.admin() RETURNS uuid LANGUAGE sql STABLE AS
+$$ SELECT admin_id FROM seed_params $$;
+CREATE OR REPLACE FUNCTION pg_temp.requester() RETURNS uuid LANGUAGE sql STABLE AS
+$$ SELECT requester_id FROM seed_params $$;
+CREATE OR REPLACE FUNCTION pg_temp.folder_marker() RETURNS text LANGUAGE sql IMMUTABLE AS
+$$ SELECT 'Created by legacy-secret-change-approvals-seed.sql' $$;
+
+CREATE OR REPLACE FUNCTION pg_temp.tick(p_step interval) RETURNS timestamptz LANGUAGE sql AS
+$$ UPDATE seed_clock SET at = at + p_step RETURNING at $$;
+
+CREATE OR REPLACE FUNCTION pg_temp.env_id(p_slug text) RETURNS uuid LANGUAGE plpgsql STABLE AS $$
+DECLARE v_id uuid;
+BEGIN
+ SELECT id INTO v_id FROM project_environments
+ WHERE "projectId" = pg_temp.project() AND slug = p_slug AND "deleteAfter" IS NULL;
+ IF v_id IS NULL THEN
+ RAISE EXCEPTION 'Environment "%" not found in project %', p_slug, pg_temp.project();
+ END IF;
+ RETURN v_id;
+END $$;
+
+-- Find or create a group in the project's org, make it a project member, and set its members to
+-- exactly p_member (or nobody).
+CREATE OR REPLACE FUNCTION pg_temp.seed_group(p_slug text, p_member uuid) RETURNS uuid LANGUAGE plpgsql AS $$
+DECLARE
+ v_org uuid;
+ v_group uuid;
+ v_membership uuid;
+BEGIN
+ SELECT "orgId" INTO v_org FROM projects WHERE id = pg_temp.project();
+ IF v_org IS NULL THEN
+ RAISE EXCEPTION 'Project % not found', pg_temp.project();
+ END IF;
+
+ SELECT id INTO v_group FROM groups WHERE "orgId" = v_org AND (slug = p_slug OR name = p_slug);
+ IF v_group IS NULL THEN
+ INSERT INTO groups ("orgId", name, slug) VALUES (v_org, p_slug, p_slug) RETURNING id INTO v_group;
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM memberships WHERE scope = 'organization' AND "scopeOrgId" = v_org AND "actorGroupId" = v_group) THEN
+ INSERT INTO memberships (scope, "actorGroupId", "scopeOrgId") VALUES ('organization', v_group, v_org)
+ RETURNING id INTO v_membership;
+ INSERT INTO membership_roles ("membershipId", role) VALUES (v_membership, 'no-access');
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM memberships WHERE scope = 'project' AND "scopeProjectId" = pg_temp.project() AND "actorGroupId" = v_group) THEN
+ INSERT INTO memberships (scope, "actorGroupId", "scopeOrgId", "scopeProjectId")
+ VALUES ('project', v_group, v_org, pg_temp.project())
+ RETURNING id INTO v_membership;
+ INSERT INTO membership_roles ("membershipId", role) VALUES (v_membership, 'member');
+ END IF;
+
+ DELETE FROM user_group_membership WHERE "groupId" = v_group AND "userId" IS DISTINCT FROM p_member;
+ IF p_member IS NOT NULL AND NOT EXISTS (SELECT 1 FROM user_group_membership WHERE "groupId" = v_group AND "userId" = p_member) THEN
+ INSERT INTO user_group_membership ("userId", "groupId") VALUES (p_member, v_group);
+ END IF;
+
+ RETURN v_group;
+END $$;
+
+-- Find or create an org-level machine identity and make it a project member. It has no auth method, so it
+-- only ever appears as the committer of the requests below.
+CREATE OR REPLACE FUNCTION pg_temp.seed_identity(p_name text) RETURNS uuid LANGUAGE plpgsql AS $$
+DECLARE
+ v_org uuid;
+ v_identity uuid;
+ v_membership uuid;
+BEGIN
+ SELECT "orgId" INTO v_org FROM projects WHERE id = pg_temp.project();
+
+ SELECT id INTO v_identity FROM identities WHERE "orgId" = v_org AND name = p_name AND "projectId" IS NULL;
+ IF v_identity IS NULL THEN
+ INSERT INTO identities (name, "orgId") VALUES (p_name, v_org) RETURNING id INTO v_identity;
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM memberships WHERE scope = 'organization' AND "scopeOrgId" = v_org AND "actorIdentityId" = v_identity) THEN
+ INSERT INTO memberships (scope, "actorIdentityId", "scopeOrgId") VALUES ('organization', v_identity, v_org)
+ RETURNING id INTO v_membership;
+ INSERT INTO membership_roles ("membershipId", role) VALUES (v_membership, 'no-access');
+ END IF;
+
+ IF NOT EXISTS (SELECT 1 FROM memberships WHERE scope = 'project' AND "scopeProjectId" = pg_temp.project() AND "actorIdentityId" = v_identity) THEN
+ INSERT INTO memberships (scope, "actorIdentityId", "scopeOrgId", "scopeProjectId")
+ VALUES ('project', v_identity, v_org, pg_temp.project())
+ RETURNING id INTO v_membership;
+ INSERT INTO membership_roles ("membershipId", role) VALUES (v_membership, 'member');
+ END IF;
+
+ RETURN v_identity;
+END $$;
+
+CREATE OR REPLACE FUNCTION pg_temp.seed_tag(p_slug text) RETURNS uuid LANGUAGE plpgsql AS $$
+DECLARE v_id uuid;
+BEGIN
+ SELECT id INTO v_id FROM secret_tags WHERE "projectId" = pg_temp.project() AND slug = p_slug;
+ IF v_id IS NULL THEN
+ INSERT INTO secret_tags (slug, color, "projectId", "createdBy", "createdByActorType")
+ VALUES (p_slug, '#e11d48', pg_temp.project(), pg_temp.admin(), 'user')
+ RETURNING id INTO v_id;
+ END IF;
+ RETURN v_id;
+END $$;
+
+-- Find or create the folder at p_path, one segment at a time. Folders created here carry folder_marker()
+-- as their description, which is how the next run finds and deletes them.
+CREATE OR REPLACE FUNCTION pg_temp.seed_folder(p_env text, p_path text) RETURNS uuid LANGUAGE plpgsql AS $$
+DECLARE
+ v_env uuid := pg_temp.env_id(p_env);
+ v_folder uuid;
+ v_child uuid;
+ v_name text;
+BEGIN
+ SELECT id INTO v_folder FROM secret_folders WHERE "envId" = v_env AND "parentId" IS NULL;
+ FOR v_name IN SELECT unnest(string_to_array(trim(BOTH '/' FROM p_path), '/')) LOOP
+ CONTINUE WHEN v_name = '';
+ SELECT id INTO v_child FROM secret_folders WHERE "parentId" = v_folder AND name = v_name;
+ IF v_child IS NULL THEN
+ INSERT INTO secret_folders (name, "envId", "parentId", description, "createdAt", "updatedAt")
+ SELECT v_name, v_env, v_folder, pg_temp.folder_marker(), at, at FROM seed_clock
+ RETURNING id INTO v_child;
+ END IF;
+ v_folder := v_child;
+ END LOOP;
+ RETURN v_folder;
+END $$;
+
+-- The reserved folder secret replication writes into, named after the import it replicates. No import row
+-- is created, so nothing replicates into it for real.
+CREATE OR REPLACE FUNCTION pg_temp.seed_replication_folder(p_env text, p_path text) RETURNS uuid LANGUAGE plpgsql AS $$
+DECLARE
+ v_parent uuid := pg_temp.seed_folder(p_env, p_path);
+ v_folder uuid;
+BEGIN
+ SELECT id INTO v_folder FROM secret_folders WHERE "parentId" = v_parent AND starts_with(name, '__reserve_replication_');
+ IF v_folder IS NULL THEN
+ INSERT INTO secret_folders (name, "envId", "parentId", "isReserved", description, "createdAt", "updatedAt")
+ SELECT '__reserve_replication_' || gen_random_uuid(), pg_temp.env_id(p_env), v_parent, true, pg_temp.folder_marker(), at, at
+ FROM seed_clock
+ RETURNING id INTO v_folder;
+ END IF;
+ RETURN v_folder;
+END $$;
+
+-- Secrets as a direct write leaves them: version 1 plus its version row.
+CREATE OR REPLACE FUNCTION pg_temp.seed_secrets(p_env text, p_path text, p_keys text[]) RETURNS void LANGUAGE plpgsql AS $$
+DECLARE
+ v_folder uuid := pg_temp.seed_folder(p_env, p_path);
+ v_key text;
+ v_at timestamptz;
+ v_secret uuid;
+BEGIN
+ FOREACH v_key IN ARRAY p_keys LOOP
+ v_at := pg_temp.tick('5 seconds');
+ INSERT INTO secrets_v2 ("folderId", key, version, type, "skipMultilineEncoding", "createdAt", "updatedAt")
+ VALUES (v_folder, v_key, 1, 'shared', false, v_at, v_at)
+ RETURNING id INTO v_secret;
+ INSERT INTO secret_versions_v2
+ ("secretId", "folderId", key, version, type, "skipMultilineEncoding", "actorType", "userActorId", "createdAt", "updatedAt")
+ VALUES (v_secret, v_folder, v_key, 1, 'shared', false, 'user', pg_temp.admin(), v_at, v_at);
+ END LOOP;
+END $$;
+
+-- The API defaults bypassForMachineIdentities to false, unlike the column.
+CREATE OR REPLACE FUNCTION pg_temp.seed_policy(
+ p_name text,
+ p_envs text[],
+ p_path text,
+ p_approvals int DEFAULT 1,
+ p_enforcement text DEFAULT 'hard',
+ p_allow_self boolean DEFAULT true,
+ p_bypass_machines boolean DEFAULT false
+) RETURNS uuid LANGUAGE plpgsql AS $$
+DECLARE
+ v_id uuid;
+ v_at timestamptz := pg_temp.tick('1 minute');
+BEGIN
+ INSERT INTO secret_approval_policies
+ (name, approvals, "secretPath", "envId", "enforcementLevel", "allowedSelfApprovals", "bypassForMachineIdentities", "createdAt", "updatedAt")
+ VALUES
+ (p_name, p_approvals, p_path, pg_temp.env_id(p_envs[1]), p_enforcement, p_allow_self, p_bypass_machines, v_at, v_at)
+ RETURNING id INTO v_id;
+
+ INSERT INTO secret_approval_policies_environments ("policyId", "envId", "createdAt", "updatedAt")
+ SELECT v_id, pg_temp.env_id(e), v_at, v_at FROM unnest(p_envs) AS e;
+
+ IF position('*' IN p_path) = 0 THEN
+ PERFORM pg_temp.seed_folder(e, p_path) FROM unnest(p_envs) AS e;
+ END IF;
+
+ INSERT INTO seed_policies (name, id, path, created_at) VALUES (p_name, v_id, p_path, v_at);
+ RETURN v_id;
+END $$;
+
+CREATE OR REPLACE FUNCTION pg_temp.seed_approver(p_policy text, p_user uuid, p_group uuid) RETURNS void LANGUAGE sql AS $$
+ INSERT INTO secret_approval_policies_approvers ("policyId", "approverUserId", "approverGroupId", "createdAt", "updatedAt")
+ SELECT id, p_user, p_group, created_at, created_at FROM seed_policies WHERE name = p_policy
+$$;
+
+CREATE OR REPLACE FUNCTION pg_temp.seed_bypasser(p_policy text, p_user uuid, p_group uuid) RETURNS void LANGUAGE sql AS $$
+ INSERT INTO secret_approval_policies_bypassers ("policyId", "bypasserUserId", "bypasserGroupId", "createdAt", "updatedAt")
+ SELECT id, p_user, p_group, created_at, created_at FROM seed_policies WHERE name = p_policy
+$$;
+
+-- p_commits is a list of {"op", "key"} objects, plus "newKey" and "reminderNote" on an update and "tags"
+-- (slugs) on a create or update. An update or delete looks its secret up by key in the request's folder
+-- and copies what the legacy service copies from the secret and its latest version.
+CREATE OR REPLACE FUNCTION pg_temp.seed_request(
+ p_key text,
+ p_policy text,
+ p_committer uuid,
+ p_env text,
+ p_commits jsonb,
+ p_path text DEFAULT NULL,
+ p_message text DEFAULT NULL,
+ p_identity uuid DEFAULT NULL,
+ p_replicated boolean DEFAULT NULL
+) RETURNS uuid LANGUAGE plpgsql AS $$
+DECLARE
+ v_policy_id uuid;
+ v_path text;
+ v_folder uuid;
+ v_at timestamptz := pg_temp.tick('1 minute');
+ v_id uuid;
+ v_commit jsonb;
+ v_commit_id uuid;
+ v_secret secrets_v2;
+ v_version secret_versions_v2;
+ v_tag text;
+BEGIN
+ SELECT id, coalesce(p_path, path) INTO v_policy_id, v_path FROM seed_policies WHERE name = p_policy;
+ IF v_policy_id IS NULL THEN
+ RAISE EXCEPTION 'Policy "%" was not seeded', p_policy;
+ END IF;
+ v_folder := CASE WHEN p_replicated THEN pg_temp.seed_replication_folder(p_env, v_path) ELSE pg_temp.seed_folder(p_env, v_path) END;
+
+ INSERT INTO secret_approval_requests
+ ("policyId", "folderId", slug, status, "hasMerged", "committerUserId", "committerIdentityId", "isReplicated", "commitMessage", "createdAt", "updatedAt")
+ VALUES
+ (v_policy_id, v_folder, substr(md5(random()::text), 1, 10), 'open', false, p_committer, p_identity, p_replicated, p_message, v_at, v_at)
+ RETURNING id INTO v_id;
+
+ FOR v_commit IN SELECT value FROM jsonb_array_elements(p_commits) LOOP
+ IF v_commit ->> 'op' = 'create' THEN
+ INSERT INTO secret_approval_requests_secrets_v2
+ ("requestId", op, key, version, "skipMultilineEncoding", "secretMetadata", "createdAt", "updatedAt")
+ VALUES (v_id, 'create', v_commit ->> 'key', 1, false, '[]', v_at, v_at)
+ RETURNING id INTO v_commit_id;
+ ELSIF v_commit ->> 'op' IN ('update', 'delete') THEN
+ SELECT * INTO v_secret FROM secrets_v2 WHERE "folderId" = v_folder AND key = v_commit ->> 'key' AND type = 'shared';
+ IF v_secret.id IS NULL THEN
+ RAISE EXCEPTION 'Secret "%" not found for request %', v_commit ->> 'key', p_key;
+ END IF;
+ SELECT * INTO v_version FROM secret_versions_v2 WHERE "secretId" = v_secret.id ORDER BY version DESC LIMIT 1;
+
+ IF v_commit ->> 'op' = 'update' THEN
+ -- A NULL value and comment is what the legacy service writes when neither changes.
+ INSERT INTO secret_approval_requests_secrets_v2
+ ("requestId", op, key, version, "secretId", "secretVersion", "reminderNote", "secretMetadata", "createdAt", "updatedAt")
+ VALUES (v_id, 'update', coalesce(v_commit ->> 'newKey', v_secret.key), v_secret.version, v_secret.id, v_version.id,
+ v_commit ->> 'reminderNote', '[]', v_at, v_at)
+ RETURNING id INTO v_commit_id;
+ ELSE
+ INSERT INTO secret_approval_requests_secrets_v2
+ ("requestId", op, key, version, "secretId", "secretVersion", "encryptedValue", "encryptedComment", "reminderNote",
+ "reminderRepeatDays", "skipMultilineEncoding", "secretMetadata", "createdAt", "updatedAt")
+ VALUES (v_id, 'delete', v_secret.key, v_version.version, v_secret.id, v_version.id, v_version."encryptedValue",
+ v_version."encryptedComment", v_version."reminderNote", v_version."reminderRepeatDays",
+ v_version."skipMultilineEncoding", '[]', v_at, v_at)
+ RETURNING id INTO v_commit_id;
+ END IF;
+ ELSE
+ RAISE EXCEPTION 'Unknown commit op "%" in request %', v_commit ->> 'op', p_key;
+ END IF;
+
+ FOR v_tag IN SELECT value FROM jsonb_array_elements_text(coalesce(v_commit -> 'tags', '[]')) LOOP
+ INSERT INTO secret_approval_request_secret_tags_v2 ("secretId", "tagId", "createdAt", "updatedAt")
+ VALUES (v_commit_id, pg_temp.seed_tag(v_tag), v_at, v_at);
+ END LOOP;
+ END LOOP;
+
+ INSERT INTO seed_requests (key, id, folder_id, updated_at) VALUES (p_key, v_id, v_folder, v_at);
+ RETURN v_id;
+END $$;
+
+-- The legacy service keeps one review row per reviewer and updates it in place when they review again, so
+-- a second review revises the first. Reviewing never touches the request row.
+CREATE OR REPLACE FUNCTION pg_temp.seed_review(p_key text, p_reviewer uuid, p_status text, p_comment text DEFAULT NULL)
+RETURNS void LANGUAGE plpgsql AS $$
+DECLARE
+ v_request uuid;
+ v_review uuid;
+ v_at timestamptz := pg_temp.tick('15 seconds');
+BEGIN
+ SELECT id INTO v_request FROM seed_requests WHERE key = p_key;
+ IF v_request IS NULL THEN
+ RAISE EXCEPTION 'Request "%" was not seeded', p_key;
+ END IF;
+
+ SELECT id INTO v_review FROM secret_approval_requests_reviewers WHERE "requestId" = v_request AND "reviewerUserId" = p_reviewer;
+ IF v_review IS NULL THEN
+ INSERT INTO secret_approval_requests_reviewers ("requestId", "reviewerUserId", status, comment, "createdAt", "updatedAt")
+ VALUES (v_request, p_reviewer, p_status, p_comment, v_at, v_at);
+ ELSE
+ UPDATE secret_approval_requests_reviewers SET status = p_status, comment = p_comment WHERE id = v_review;
+ INSERT INTO seed_review_revisions (id, updated_at) VALUES (v_review, v_at)
+ ON CONFLICT (id) DO UPDATE SET updated_at = excluded.updated_at;
+ END IF;
+END $$;
+
+-- Mirrors the legacy merge: conflicts are found against the folder as it is now (a create whose key is
+-- taken, an update whose secret is gone or whose key another secret holds), everything else is applied,
+-- and the request closes as merged. Whether the request may merge is the caller's call. Pass
+-- p_bypass_reason only for a soft-enforcement merge without the required approvals; the legacy service
+-- drops the reason on any other merge.
+CREATE OR REPLACE FUNCTION pg_temp.seed_merge(p_key text, p_merger uuid, p_bypass_reason text DEFAULT NULL)
+RETURNS void LANGUAGE plpgsql AS $$
+DECLARE
+ v_request_id uuid;
+ v_folder uuid;
+ v_at timestamptz := pg_temp.tick('15 seconds');
+ v_commit record;
+ v_conflicts jsonb := '[]';
+ v_conflicting uuid[] := '{}';
+ v_holder uuid;
+ v_live_id uuid;
+ v_live_key text;
+ v_secret uuid;
+BEGIN
+ SELECT id, folder_id INTO v_request_id, v_folder FROM seed_requests WHERE key = p_key;
+ IF v_request_id IS NULL THEN
+ RAISE EXCEPTION 'Request "%" was not seeded', p_key;
+ END IF;
+
+ FOR v_commit IN
+ SELECT c.id, c.op, c.key, c."secretId", v.key AS reviewed_key
+ FROM secret_approval_requests_secrets_v2 c
+ LEFT JOIN secret_versions_v2 v ON v.id = c."secretVersion"
+ WHERE c."requestId" = v_request_id AND c.op IN ('create', 'update')
+ LOOP
+ SELECT id INTO v_holder FROM secrets_v2 WHERE "folderId" = v_folder AND key = v_commit.key AND type = 'shared';
+ SELECT id, key INTO v_live_id, v_live_key FROM secrets_v2 WHERE id = v_commit."secretId";
+ IF (v_commit.op = 'create' AND v_holder IS NOT NULL)
+ OR (v_commit.op = 'update' AND (
+ v_live_id IS NULL
+ OR (v_holder IS NOT NULL AND v_holder <> v_live_id)
+ OR (v_holder IS NULL AND v_commit.key = coalesce(v_commit.reviewed_key, v_live_key)))) THEN
+ v_conflicts := v_conflicts || jsonb_build_array(jsonb_build_object('op', v_commit.op, 'secretId', v_commit.id));
+ v_conflicting := v_conflicting || v_commit.id;
+ END IF;
+ END LOOP;
+
+ FOR v_commit IN
+ SELECT * FROM secret_approval_requests_secrets_v2
+ WHERE "requestId" = v_request_id AND NOT (id = ANY (v_conflicting))
+ ORDER BY CASE op WHEN 'create' THEN 1 WHEN 'update' THEN 2 ELSE 3 END, id
+ LOOP
+ IF v_commit.op = 'create' THEN
+ INSERT INTO secrets_v2 ("folderId", key, version, type, "encryptedValue", "skipMultilineEncoding", "createdAt", "updatedAt")
+ VALUES (v_folder, v_commit.key, 1, 'shared', v_commit."encryptedValue", coalesce(v_commit."skipMultilineEncoding", false), v_at, v_at)
+ RETURNING id INTO v_secret;
+ INSERT INTO secret_versions_v2
+ ("secretId", "folderId", key, version, type, "encryptedValue", "skipMultilineEncoding", "actorType", "userActorId", "createdAt", "updatedAt")
+ VALUES (v_secret, v_folder, v_commit.key, 1, 'shared', v_commit."encryptedValue", coalesce(v_commit."skipMultilineEncoding", false),
+ 'user', p_merger, v_at, v_at);
+ ELSIF v_commit.op = 'update' THEN
+ UPDATE secrets_v2
+ SET key = v_commit.key, version = version + 1, "reminderNote" = coalesce(v_commit."reminderNote", "reminderNote")
+ WHERE id = v_commit."secretId";
+ INSERT INTO secret_versions_v2
+ ("secretId", "folderId", key, version, type, "encryptedValue", "encryptedComment", "reminderNote", "skipMultilineEncoding",
+ "actorType", "userActorId", "createdAt", "updatedAt")
+ SELECT id, "folderId", key, version, type, "encryptedValue", "encryptedComment", "reminderNote", "skipMultilineEncoding",
+ 'user', p_merger, v_at, v_at
+ FROM secrets_v2 WHERE id = v_commit."secretId";
+ ELSE
+ -- The commits' secretId FK is ON DELETE SET NULL, so this also clears it on every request still
+ -- pointing at the secret.
+ DELETE FROM secrets_v2 WHERE id = v_commit."secretId";
+ END IF;
+ END LOOP;
+
+ UPDATE secret_approval_requests
+ SET status = 'close', "hasMerged" = true, conflicts = v_conflicts, "statusChangedByUserId" = p_merger,
+ "bypassReason" = p_bypass_reason
+ WHERE id = v_request_id;
+ UPDATE seed_requests SET updated_at = v_at WHERE key = p_key;
+END $$;
+
+-- Closing or reopening without merging, as the status endpoint does.
+CREATE OR REPLACE FUNCTION pg_temp.seed_set_status(p_key text, p_by uuid, p_status text) RETURNS void LANGUAGE plpgsql AS $$
+DECLARE v_at timestamptz := pg_temp.tick('15 seconds');
+BEGIN
+ UPDATE secret_approval_requests SET status = p_status, "statusChangedByUserId" = p_by
+ WHERE id = (SELECT id FROM seed_requests WHERE key = p_key);
+ UPDATE seed_requests SET updated_at = v_at WHERE key = p_key;
+END $$;
+
+-- Mirrors the legacy delete: close the policy's open requests, leaving statusChangedByUserId as it was,
+-- and soft-delete the policy.
+CREATE OR REPLACE FUNCTION pg_temp.seed_delete_policy(p_policy text) RETURNS void LANGUAGE plpgsql AS $$
+DECLARE
+ v_id uuid;
+ v_at timestamptz := pg_temp.tick('1 minute');
+BEGIN
+ SELECT id INTO v_id FROM seed_policies WHERE name = p_policy;
+ UPDATE seed_requests SET updated_at = v_at
+ WHERE id IN (SELECT id FROM secret_approval_requests WHERE "policyId" = v_id AND status = 'open');
+ UPDATE secret_approval_requests SET status = 'close' WHERE "policyId" = v_id AND status = 'open';
+ UPDATE secret_approval_policies SET "deletedAt" = v_at WHERE id = v_id;
+END $$;
+
+-- ---------------------------------------------------------------------------------------------------
+-- Remove the previous seed (legacy rows, global copies sharing their ids, seeded folders and secrets)
+-- ---------------------------------------------------------------------------------------------------
+
+CREATE TEMP TABLE seed_old_policies ON COMMIT DROP AS
+SELECT p.id
+FROM secret_approval_policies p
+JOIN project_environments e ON e.id = p."envId"
+WHERE e."projectId" = pg_temp.project() AND p.name ~ '^p[0-9]{2}-';
+
+CREATE TEMP TABLE seed_old_global_requests ON COMMIT DROP AS
+SELECT id FROM approval_requests WHERE "policyId" IN (SELECT id FROM seed_old_policies)
+UNION
+SELECT g.id FROM approval_requests g
+JOIN secret_approval_requests r ON r.id = g.id
+WHERE r."policyId" IN (SELECT id FROM seed_old_policies);
+
+CREATE TEMP TABLE seed_old_folders ON COMMIT DROP AS
+SELECT f.id
+FROM secret_folders f
+JOIN project_environments e ON e.id = f."envId"
+WHERE e."projectId" = pg_temp.project() AND f.description = pg_temp.folder_marker();
+
+-- Cascades to secret_change_requests and the commits the migration relinked onto them.
+DELETE FROM approval_requests WHERE id IN (SELECT id FROM seed_old_global_requests);
+DELETE FROM approval_policies WHERE id IN (SELECT id FROM seed_old_policies);
+DELETE FROM secret_approval_policies WHERE id IN (SELECT id FROM seed_old_policies);
+-- secret_versions_v2 has no foreign key to its folder or its secret, so nothing cascades to it.
+DELETE FROM secret_versions_v2 WHERE "folderId" IN (SELECT id FROM seed_old_folders);
+DELETE FROM secret_folders WHERE id IN (SELECT id FROM seed_old_folders);
+
+-- ---------------------------------------------------------------------------------------------------
+-- Seed
+-- ---------------------------------------------------------------------------------------------------
+
+DO $$
+DECLARE
+ a uuid := pg_temp.admin();
+ b uuid := pg_temp.requester();
+ -- The admin is the approver group's only member, which is what lets group approvers and group
+ -- bypassers be exercised by a user who can log in.
+ g uuid := pg_temp.seed_group('seed-change-approvers', pg_temp.admin());
+ empty_group uuid := pg_temp.seed_group('seed-change-empty-approvers', NULL);
+ -- The requester is this group's only member, so in p04 they count as an approver through it.
+ requester_group uuid := pg_temp.seed_group('seed-change-requester-approvers', pg_temp.requester());
+ bot uuid := pg_temp.seed_identity('seed-change-bot');
+BEGIN
+ -- p01: plain hard policy, every request state the legacy service leaves behind
+ PERFORM pg_temp.seed_policy('p01-hard-single-approver', ARRAY['dev'], '/backend');
+ PERFORM pg_temp.seed_approver('p01-hard-single-approver', a, NULL);
+ PERFORM pg_temp.seed_secrets('dev', '/backend', ARRAY['DB_HOST', 'DB_PASSWORD', 'CACHE_URL', 'FEATURE_FLAGS', 'SMTP_HOST', 'LEGACY_TOKEN', 'LOG_LEVEL']);
+
+ PERFORM pg_temp.seed_request('r01a-open-untouched', 'p01-hard-single-approver', b, 'dev',
+ '[{"op":"create","key":"NEW_RELIC_KEY"},{"op":"update","key":"DB_HOST","reminderNote":"rotate quarterly"},{"op":"delete","key":"LEGACY_TOKEN"}]',
+ p_message => 'rotate database credentials');
+ PERFORM pg_temp.seed_request('r01b-open-approved', 'p01-hard-single-approver', b, 'dev', '[{"op":"create","key":"SENTRY_DSN"}]');
+ PERFORM pg_temp.seed_review('r01b-open-approved', a, 'approved', 'lgtm');
+ PERFORM pg_temp.seed_request('r01c-open-rejected', 'p01-hard-single-approver', b, 'dev', '[{"op":"update","key":"CACHE_URL","newKey":"REDIS_URL"}]');
+ PERFORM pg_temp.seed_review('r01c-open-rejected', a, 'rejected', 'use the managed redis instead');
+ PERFORM pg_temp.seed_request('r01d-merged', 'p01-hard-single-approver', b, 'dev',
+ '[{"op":"create","key":"STRIPE_KEY"},{"op":"update","key":"FEATURE_FLAGS","reminderNote":"review after launch"}]',
+ p_message => 'launch checkout');
+ PERFORM pg_temp.seed_review('r01d-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r01d-merged', a);
+ PERFORM pg_temp.seed_request('r01e-closed-by-committer', 'p01-hard-single-approver', b, 'dev', '[{"op":"create","key":"TEMP_DEBUG"}]');
+ PERFORM pg_temp.seed_set_status('r01e-closed-by-committer', b, 'close');
+ PERFORM pg_temp.seed_request('r01f-closed-then-reopened', 'p01-hard-single-approver', b, 'dev', '[{"op":"update","key":"SMTP_HOST","newKey":"SMTP_HOSTNAME"}]');
+ PERFORM pg_temp.seed_set_status('r01f-closed-then-reopened', a, 'close');
+ PERFORM pg_temp.seed_set_status('r01f-closed-then-reopened', b, 'open');
+ PERFORM pg_temp.seed_request('r01g-rejected-then-approved', 'p01-hard-single-approver', b, 'dev', '[{"op":"create","key":"ANALYTICS_KEY"}]');
+ PERFORM pg_temp.seed_review('r01g-rejected-then-approved', a, 'rejected', 'missing the ticket');
+ PERFORM pg_temp.seed_review('r01g-rejected-then-approved', a, 'approved', 'ticket linked');
+ -- the committer may review their own request, but is not an approver, so the approval does not count
+ PERFORM pg_temp.seed_request('r01h-committer-reviewed-own', 'p01-hard-single-approver', b, 'dev', '[{"op":"update","key":"LOG_LEVEL"}]');
+ PERFORM pg_temp.seed_review('r01h-committer-reviewed-own', b, 'approved');
+ -- deleting LOG_LEVEL also clears secretId on r01h's still open update
+ PERFORM pg_temp.seed_request('r01i-merged-delete', 'p01-hard-single-approver', b, 'dev', '[{"op":"delete","key":"LOG_LEVEL"}]');
+ PERFORM pg_temp.seed_review('r01i-merged-delete', a, 'approved');
+ PERFORM pg_temp.seed_merge('r01i-merged-delete', a);
+ -- r01k creates KAFKA_BROKERS and deletes DB_PASSWORD before r01j merges, so r01j records a create and an
+ -- update conflict and applies only KAFKA_TOPIC
+ PERFORM pg_temp.seed_request('r01j-merged-with-conflicts', 'p01-hard-single-approver', b, 'dev',
+ '[{"op":"create","key":"KAFKA_BROKERS"},{"op":"update","key":"DB_PASSWORD"},{"op":"create","key":"KAFKA_TOPIC"}]');
+ PERFORM pg_temp.seed_review('r01j-merged-with-conflicts', a, 'approved');
+ PERFORM pg_temp.seed_request('r01k-merged-first', 'p01-hard-single-approver', b, 'dev',
+ '[{"op":"create","key":"KAFKA_BROKERS"},{"op":"delete","key":"DB_PASSWORD"}]');
+ PERFORM pg_temp.seed_review('r01k-merged-first', a, 'approved');
+ PERFORM pg_temp.seed_merge('r01k-merged-first', a);
+ PERFORM pg_temp.seed_merge('r01j-merged-with-conflicts', a);
+
+ -- p02: two approvals from two user approvers, the requester being one of them. Machine identities
+ -- bypass this policy, so it has no identity requests.
+ PERFORM pg_temp.seed_policy('p02-two-approvals', ARRAY['staging'], '/payments', p_approvals => 2, p_bypass_machines => true);
+ PERFORM pg_temp.seed_approver('p02-two-approvals', a, NULL);
+ PERFORM pg_temp.seed_approver('p02-two-approvals', b, NULL);
+ PERFORM pg_temp.seed_secrets('staging', '/payments', ARRAY['PAYMENT_API_KEY', 'PAYMENT_WEBHOOK_SECRET']);
+ PERFORM pg_temp.seed_request('r02a-open-1-of-2', 'p02-two-approvals', b, 'staging', '[{"op":"update","key":"PAYMENT_API_KEY"}]');
+ PERFORM pg_temp.seed_review('r02a-open-1-of-2', a, 'approved');
+ PERFORM pg_temp.seed_request('r02b-open-2-of-2', 'p02-two-approvals', b, 'staging', '[{"op":"create","key":"PAYMENT_REGION"}]');
+ PERFORM pg_temp.seed_review('r02b-open-2-of-2', a, 'approved');
+ PERFORM pg_temp.seed_review('r02b-open-2-of-2', b, 'approved');
+ PERFORM pg_temp.seed_request('r02c-merged-2-of-2', 'p02-two-approvals', b, 'staging',
+ '[{"op":"update","key":"PAYMENT_WEBHOOK_SECRET","newKey":"PAYMENT_WEBHOOK_SIGNING_SECRET"}]');
+ PERFORM pg_temp.seed_review('r02c-merged-2-of-2', b, 'approved');
+ PERFORM pg_temp.seed_review('r02c-merged-2-of-2', a, 'approved');
+ PERFORM pg_temp.seed_merge('r02c-merged-2-of-2', b);
+ PERFORM pg_temp.seed_request('r02d-open-approved-and-rejected', 'p02-two-approvals', b, 'staging', '[{"op":"create","key":"PAYMENT_TIMEOUT"}]');
+ PERFORM pg_temp.seed_review('r02d-open-approved-and-rejected', a, 'rejected', 'needs a load test first');
+ PERFORM pg_temp.seed_review('r02d-open-approved-and-rejected', b, 'approved');
+ PERFORM pg_temp.seed_request('r02e-open-untouched', 'p02-two-approvals', b, 'staging', '[{"op":"create","key":"PAYMENT_RETRIES"}]');
+
+ -- p03: two approvals, the admin named directly and through the group. The legacy findById lists him once
+ -- (both approver lists share the "approvers" label and are keyed by user id), so his approval is 1 of 2
+ -- and, with nobody else eligible, nothing here can be merged.
+ PERFORM pg_temp.seed_policy('p03-approver-direct-and-via-group', ARRAY['prod'], '/database', p_approvals => 2);
+ PERFORM pg_temp.seed_approver('p03-approver-direct-and-via-group', a, NULL);
+ PERFORM pg_temp.seed_approver('p03-approver-direct-and-via-group', NULL, g);
+ PERFORM pg_temp.seed_secrets('prod', '/database', ARRAY['PG_PRIMARY_URL']);
+ PERFORM pg_temp.seed_request('r03a-open-approved-once', 'p03-approver-direct-and-via-group', b, 'prod', '[{"op":"update","key":"PG_PRIMARY_URL"}]');
+ PERFORM pg_temp.seed_review('r03a-open-approved-once', a, 'approved');
+ PERFORM pg_temp.seed_request('r03b-closed-after-approval', 'p03-approver-direct-and-via-group', b, 'prod', '[{"op":"create","key":"PG_REPLICA_URL"}]');
+ PERFORM pg_temp.seed_review('r03b-closed-after-approval', a, 'approved');
+ PERFORM pg_temp.seed_set_status('r03b-closed-after-approval', b, 'close');
+
+ -- p04: two approvals from the admin and the requester's group
+ PERFORM pg_temp.seed_policy('p04-two-approvals-user-and-group', ARRAY['prod'], '/platform', p_approvals => 2);
+ PERFORM pg_temp.seed_approver('p04-two-approvals-user-and-group', a, NULL);
+ PERFORM pg_temp.seed_approver('p04-two-approvals-user-and-group', NULL, requester_group);
+ PERFORM pg_temp.seed_secrets('prod', '/platform', ARRAY['K8S_TOKEN']);
+ PERFORM pg_temp.seed_request('r04a-open-1-of-2', 'p04-two-approvals-user-and-group', b, 'prod', '[{"op":"update","key":"K8S_TOKEN"}]');
+ PERFORM pg_temp.seed_review('r04a-open-1-of-2', a, 'approved');
+ PERFORM pg_temp.seed_request('r04b-open-2-of-2', 'p04-two-approvals-user-and-group', b, 'prod', '[{"op":"create","key":"HELM_REPO_TOKEN"}]');
+ PERFORM pg_temp.seed_review('r04b-open-2-of-2', a, 'approved');
+ PERFORM pg_temp.seed_review('r04b-open-2-of-2', b, 'approved');
+ PERFORM pg_temp.seed_request('r04c-merged-2-of-2', 'p04-two-approvals-user-and-group', b, 'prod', '[{"op":"create","key":"ARGOCD_TOKEN"}]');
+ PERFORM pg_temp.seed_review('r04c-merged-2-of-2', b, 'approved');
+ PERFORM pg_temp.seed_review('r04c-merged-2-of-2', a, 'approved');
+ PERFORM pg_temp.seed_merge('r04c-merged-2-of-2', a);
+
+ -- p05: the only approver is a group
+ PERFORM pg_temp.seed_policy('p05-group-only-approver', ARRAY['dev'], '/grouped');
+ PERFORM pg_temp.seed_approver('p05-group-only-approver', NULL, g);
+ PERFORM pg_temp.seed_request('r05a-open-approved-via-group', 'p05-group-only-approver', b, 'dev', '[{"op":"create","key":"GROUPED_KEY"}]');
+ PERFORM pg_temp.seed_review('r05a-open-approved-via-group', a, 'approved');
+ PERFORM pg_temp.seed_request('r05b-merged', 'p05-group-only-approver', b, 'dev', '[{"op":"create","key":"GROUPED_OTHER"}]');
+ PERFORM pg_temp.seed_review('r05b-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r05b-merged', a);
+ PERFORM pg_temp.seed_request('r05c-open-untouched', 'p05-group-only-approver', b, 'dev', '[{"op":"create","key":"GROUPED_PENDING"}]');
+
+ -- p06: self-approval disallowed (the requester's own review is refused, so only the admin's lands)
+ PERFORM pg_temp.seed_policy('p06-self-approval-blocked', ARRAY['dev'], '/no-self', p_allow_self => false);
+ PERFORM pg_temp.seed_approver('p06-self-approval-blocked', a, NULL);
+ PERFORM pg_temp.seed_approver('p06-self-approval-blocked', b, NULL);
+ PERFORM pg_temp.seed_request('r06a-open-approved-by-other', 'p06-self-approval-blocked', b, 'dev', '[{"op":"create","key":"NO_SELF_A"}]');
+ PERFORM pg_temp.seed_review('r06a-open-approved-by-other', a, 'approved');
+ PERFORM pg_temp.seed_request('r06b-open-untouched', 'p06-self-approval-blocked', b, 'dev', '[{"op":"create","key":"NO_SELF_B"}]');
+ PERFORM pg_temp.seed_request('r06c-merged', 'p06-self-approval-blocked', b, 'dev', '[{"op":"create","key":"NO_SELF_C"}]');
+ PERFORM pg_temp.seed_review('r06c-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r06c-merged', a);
+
+ -- p07: soft with no bypassers listed, so anyone who may merge can bypass
+ PERFORM pg_temp.seed_policy('p07-soft-no-bypassers', ARRAY['prod'], '/hotfix', p_enforcement => 'soft');
+ PERFORM pg_temp.seed_approver('p07-soft-no-bypassers', a, NULL);
+ PERFORM pg_temp.seed_secrets('prod', '/hotfix', ARRAY['HOTFIX_FLAG']);
+ PERFORM pg_temp.seed_request('r07a-bypass-with-reason', 'p07-soft-no-bypassers', b, 'prod', '[{"op":"update","key":"HOTFIX_FLAG"}]');
+ PERFORM pg_temp.seed_merge('r07a-bypass-with-reason', b, 'Production incident INC-4821, paging on-call');
+ -- a bypass without a reason is stored like a normal merge, minus the approvals
+ PERFORM pg_temp.seed_request('r07b-bypass-without-reason', 'p07-soft-no-bypassers', b, 'prod', '[{"op":"create","key":"HOTFIX_NOTE"}]');
+ PERFORM pg_temp.seed_merge('r07b-bypass-without-reason', b);
+ PERFORM pg_temp.seed_request('r07c-normal-merge', 'p07-soft-no-bypassers', b, 'prod', '[{"op":"create","key":"HOTFIX_OWNER"}]');
+ PERFORM pg_temp.seed_review('r07c-normal-merge', a, 'approved');
+ PERFORM pg_temp.seed_merge('r07c-normal-merge', a);
+ -- a rejection does not stop a bypass
+ PERFORM pg_temp.seed_request('r07d-bypass-after-rejection', 'p07-soft-no-bypassers', b, 'prod', '[{"op":"create","key":"HOTFIX_RISKY"}]');
+ PERFORM pg_temp.seed_review('r07d-bypass-after-rejection', a, 'rejected', 'too risky for a friday');
+ PERFORM pg_temp.seed_merge('r07d-bypass-after-rejection', b, 'Customer escalation, agreed on the call');
+ PERFORM pg_temp.seed_request('r07e-open-untouched', 'p07-soft-no-bypassers', b, 'prod', '[{"op":"create","key":"HOTFIX_PENDING"}]');
+
+ -- p08: soft with a user and a group bypasser. The requester is listed twice, which the API stores when
+ -- the same bypasser is sent once by id and once by username.
+ PERFORM pg_temp.seed_policy('p08-soft-user-and-group-bypassers', ARRAY['prod'], '/billing', p_enforcement => 'soft');
+ PERFORM pg_temp.seed_approver('p08-soft-user-and-group-bypassers', a, NULL);
+ PERFORM pg_temp.seed_bypasser('p08-soft-user-and-group-bypassers', b, NULL);
+ PERFORM pg_temp.seed_bypasser('p08-soft-user-and-group-bypassers', b, NULL);
+ PERFORM pg_temp.seed_bypasser('p08-soft-user-and-group-bypassers', NULL, g);
+ PERFORM pg_temp.seed_request('r08a-user-bypasser-merged', 'p08-soft-user-and-group-bypassers', b, 'prod', '[{"op":"create","key":"BILLING_KEY"}]');
+ PERFORM pg_temp.seed_merge('r08a-user-bypasser-merged', b, 'Invoice run blocked on the old key');
+ -- the admin bypasses as a member of the bypasser group
+ PERFORM pg_temp.seed_request('r08b-group-bypasser-merged', 'p08-soft-user-and-group-bypassers', b, 'prod', '[{"op":"create","key":"BILLING_REGION"}]');
+ PERFORM pg_temp.seed_merge('r08b-group-bypasser-merged', a, 'Month-end close');
+ PERFORM pg_temp.seed_request('r08c-open-untouched', 'p08-soft-user-and-group-bypassers', b, 'prod', '[{"op":"create","key":"BILLING_PENDING"}]');
+
+ -- p09: soft, but only the admin may bypass, so the requester's merge is refused
+ PERFORM pg_temp.seed_policy('p09-soft-bypasser-is-someone-else', ARRAY['staging'], '/ops', p_enforcement => 'soft');
+ PERFORM pg_temp.seed_approver('p09-soft-bypasser-is-someone-else', a, NULL);
+ PERFORM pg_temp.seed_bypasser('p09-soft-bypasser-is-someone-else', a, NULL);
+ PERFORM pg_temp.seed_request('r09a-bypass-refused', 'p09-soft-bypasser-is-someone-else', b, 'staging', '[{"op":"create","key":"OPS_KEY"}]');
+
+ -- p10: one policy over two environments. The admin is listed twice as an approver (sent once by id and
+ -- once by username), which the legacy findById collapses into one.
+ PERFORM pg_temp.seed_policy('p10-multi-environment', ARRAY['dev', 'staging'], '/shared');
+ PERFORM pg_temp.seed_approver('p10-multi-environment', a, NULL);
+ PERFORM pg_temp.seed_approver('p10-multi-environment', a, NULL);
+ PERFORM pg_temp.seed_request('r10a-dev-approved', 'p10-multi-environment', b, 'dev', '[{"op":"create","key":"SHARED_DEV_KEY"}]');
+ PERFORM pg_temp.seed_review('r10a-dev-approved', a, 'approved');
+ PERFORM pg_temp.seed_request('r10b-staging-merged', 'p10-multi-environment', b, 'staging', '[{"op":"create","key":"SHARED_STAGING_KEY"}]');
+ PERFORM pg_temp.seed_review('r10b-staging-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r10b-staging-merged', a);
+ PERFORM pg_temp.seed_request('r10c-staging-open', 'p10-multi-environment', b, 'staging', '[{"op":"create","key":"SHARED_STAGING_PENDING"}]');
+
+ -- p11: a glob path, with requests in two folders under it
+ PERFORM pg_temp.seed_policy('p11-glob-path', ARRAY['dev'], '/apps/**');
+ PERFORM pg_temp.seed_approver('p11-glob-path', a, NULL);
+ PERFORM pg_temp.seed_secrets('dev', '/apps/api', ARRAY['API_PORT']);
+ PERFORM pg_temp.seed_request('r11a-api-open', 'p11-glob-path', b, 'dev', '[{"op":"update","key":"API_PORT"}]', p_path => '/apps/api');
+ PERFORM pg_temp.seed_request('r11b-web-merged', 'p11-glob-path', b, 'dev', '[{"op":"create","key":"WEB_ORIGIN"}]', p_path => '/apps/web');
+ PERFORM pg_temp.seed_review('r11b-web-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r11b-web-merged', a);
+
+ -- p12: machine identities do not bypass this policy, so the bot's writes become requests
+ PERFORM pg_temp.seed_policy('p12-machine-identity-committer', ARRAY['staging'], '/automation');
+ PERFORM pg_temp.seed_approver('p12-machine-identity-committer', a, NULL);
+ PERFORM pg_temp.seed_request('r12a-identity-open', 'p12-machine-identity-committer', NULL, 'staging', '[{"op":"create","key":"CI_DEPLOY_KEY"}]',
+ p_message => 'automated rotation', p_identity => bot);
+ PERFORM pg_temp.seed_request('r12b-identity-merged', 'p12-machine-identity-committer', NULL, 'staging', '[{"op":"create","key":"CI_CACHE_KEY"}]',
+ p_identity => bot);
+ PERFORM pg_temp.seed_review('r12b-identity-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r12b-identity-merged', a);
+ PERFORM pg_temp.seed_request('r12c-user-open', 'p12-machine-identity-committer', b, 'staging', '[{"op":"create","key":"AUTOMATION_NOTE"}]');
+
+ -- p13: committers deleted after filing. Deleting a user or an identity sets committerUserId or
+ -- committerIdentityId to NULL, leaving a request with no committer at all.
+ PERFORM pg_temp.seed_policy('p13-committer-deleted', ARRAY['dev'], '/orphans');
+ PERFORM pg_temp.seed_approver('p13-committer-deleted', a, NULL);
+ PERFORM pg_temp.seed_request('r13a-open-no-committer', 'p13-committer-deleted', NULL, 'dev', '[{"op":"create","key":"ORPHAN_A"}]');
+ PERFORM pg_temp.seed_request('r13b-merged-no-committer', 'p13-committer-deleted', NULL, 'dev', '[{"op":"create","key":"ORPHAN_B"}]');
+ PERFORM pg_temp.seed_review('r13b-merged-no-committer', a, 'approved');
+ PERFORM pg_temp.seed_merge('r13b-merged-no-committer', a);
+
+ -- p14: requests in several states, then the policy is deleted. The delete closes r14b and r14d without
+ -- recording who, so r14d keeps the requester who last reopened it.
+ PERFORM pg_temp.seed_policy('p14-deleted-policy', ARRAY['dev'], '/retired');
+ PERFORM pg_temp.seed_approver('p14-deleted-policy', a, NULL);
+ PERFORM pg_temp.seed_secrets('dev', '/retired', ARRAY['RETIRED_KEY']);
+ PERFORM pg_temp.seed_request('r14a-merged', 'p14-deleted-policy', b, 'dev', '[{"op":"update","key":"RETIRED_KEY"}]');
+ PERFORM pg_temp.seed_review('r14a-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r14a-merged', a);
+ PERFORM pg_temp.seed_request('r14b-open-closed-by-delete', 'p14-deleted-policy', b, 'dev', '[{"op":"create","key":"RETIRED_PENDING"}]');
+ PERFORM pg_temp.seed_request('r14c-closed-by-committer', 'p14-deleted-policy', b, 'dev', '[{"op":"create","key":"RETIRED_CLOSED"}]');
+ PERFORM pg_temp.seed_set_status('r14c-closed-by-committer', b, 'close');
+ PERFORM pg_temp.seed_request('r14d-reopened-then-closed-by-delete', 'p14-deleted-policy', b, 'dev', '[{"op":"create","key":"RETIRED_REOPENED"}]');
+ PERFORM pg_temp.seed_set_status('r14d-reopened-then-closed-by-delete', a, 'close');
+ PERFORM pg_temp.seed_set_status('r14d-reopened-then-closed-by-delete', b, 'open');
+ PERFORM pg_temp.seed_delete_policy('p14-deleted-policy');
+
+ -- p15: requests written by secret replication into the reserved folder under /replicated. They carry
+ -- isReplicated and no commit message.
+ PERFORM pg_temp.seed_policy('p15-replicated', ARRAY['staging'], '/replicated');
+ PERFORM pg_temp.seed_approver('p15-replicated', a, NULL);
+ PERFORM pg_temp.seed_request('r15a-replicated-open', 'p15-replicated', b, 'staging',
+ '[{"op":"create","key":"REPLICATED_A"},{"op":"create","key":"REPLICATED_B"}]', p_replicated => true);
+ PERFORM pg_temp.seed_request('r15b-replicated-merged', 'p15-replicated', b, 'staging', '[{"op":"create","key":"REPLICATED_C"}]', p_replicated => true);
+ PERFORM pg_temp.seed_review('r15b-replicated-merged', a, 'approved');
+ PERFORM pg_temp.seed_merge('r15b-replicated-merged', a);
+
+ -- p16: commits carrying tags
+ PERFORM pg_temp.seed_policy('p16-tagged-commits', ARRAY['prod'], '/tagged');
+ PERFORM pg_temp.seed_approver('p16-tagged-commits', a, NULL);
+ PERFORM pg_temp.seed_secrets('prod', '/tagged', ARRAY['TAGGED_EXISTING']);
+ PERFORM pg_temp.seed_request('r16a-open-with-tags', 'p16-tagged-commits', b, 'prod',
+ '[{"op":"create","key":"TAGGED_NEW","tags":["seed-critical"]},{"op":"update","key":"TAGGED_EXISTING","tags":["seed-critical"]}]');
+ PERFORM pg_temp.seed_request('r16b-merged-with-tags', 'p16-tagged-commits', b, 'prod', '[{"op":"create","key":"TAGGED_MERGED","tags":["seed-critical"]}]');
+ PERFORM pg_temp.seed_review('r16b-merged-with-tags', a, 'approved');
+ PERFORM pg_temp.seed_merge('r16b-merged-with-tags', a);
+
+ -- p17: the only approver is a group that was emptied after the request was filed, so no one can approve
+ PERFORM pg_temp.seed_policy('p17-empty-group-only-approver', ARRAY['staging'], '/empty-group');
+ PERFORM pg_temp.seed_approver('p17-empty-group-only-approver', NULL, empty_group);
+ PERFORM pg_temp.seed_request('r17a-unapprovable', 'p17-empty-group-only-approver', b, 'staging', '[{"op":"create","key":"EMPTY_GROUP_KEY"}]');
+
+ -- p18: two approvals, one approver left. The second approver was a user who has since been deleted, and
+ -- their approver row went with them (ON DELETE CASCADE).
+ PERFORM pg_temp.seed_policy('p18-approvals-exceed-approvers', ARRAY['dev'], '/approver-removed', p_approvals => 2);
+ PERFORM pg_temp.seed_approver('p18-approvals-exceed-approvers', a, NULL);
+ PERFORM pg_temp.seed_request('r18a-stuck-1-of-2', 'p18-approvals-exceed-approvers', b, 'dev', '[{"op":"create","key":"APPROVER_REMOVED_KEY"}]');
+ PERFORM pg_temp.seed_review('r18a-stuck-1-of-2', a, 'approved');
+
+ -- p19: no approvers left. The only approver was a group that has since been deleted.
+ PERFORM pg_temp.seed_policy('p19-no-approvers-left', ARRAY['dev'], '/no-approvers');
+ PERFORM pg_temp.seed_request('r19a-unapprovable', 'p19-no-approvers-left', b, 'dev', '[{"op":"create","key":"NO_APPROVERS_KEY"}]');
+
+ -- p20-p21: the requester is the only approver.
+
+ -- p20: self-approval allowed. The admin reviews r20c without being an approver, which an admin may do.
+ PERFORM pg_temp.seed_policy('p20-requester-only-approver', ARRAY['dev'], '/requester-approver');
+ PERFORM pg_temp.seed_approver('p20-requester-only-approver', b, NULL);
+ PERFORM pg_temp.seed_request('r20a-pending-untouched', 'p20-requester-only-approver', b, 'dev', '[{"op":"create","key":"REQ_APPROVER_A"}]');
+ PERFORM pg_temp.seed_request('r20b-self-approved-merged', 'p20-requester-only-approver', b, 'dev', '[{"op":"create","key":"REQ_APPROVER_B"}]');
+ PERFORM pg_temp.seed_review('r20b-self-approved-merged', b, 'approved');
+ PERFORM pg_temp.seed_merge('r20b-self-approved-merged', b);
+ PERFORM pg_temp.seed_request('r20c-admin-reviewed-not-approver', 'p20-requester-only-approver', b, 'dev', '[{"op":"create","key":"REQ_APPROVER_C"}]');
+ PERFORM pg_temp.seed_review('r20c-admin-reviewed-not-approver', a, 'approved', 'looks fine to me');
+
+ -- p21: self-approval disallowed, so nobody can ever approve
+ PERFORM pg_temp.seed_policy('p21-requester-only-approver-self-blocked', ARRAY['dev'], '/requester-approver-blocked', p_allow_self => false);
+ PERFORM pg_temp.seed_approver('p21-requester-only-approver-self-blocked', b, NULL);
+ PERFORM pg_temp.seed_request('r21a-unapprovable', 'p21-requester-only-approver-self-blocked', b, 'dev', '[{"op":"create","key":"REQ_BLOCKED_A"}]');
+END $$;
+
+-- The updatedAt triggers stamp every UPDATE with the transaction's start time, so every merged, closed or
+-- reopened request would share one updatedAt. Put back the times from the seed's timeline with triggers
+-- off; only timestamp columns change, so no foreign key needs checking. Turning triggers off needs a
+-- superuser (the docker dev DB's user is one); without one the stamped times stay.
+DO $$
+BEGIN
+ SET LOCAL session_replication_role = replica;
+ UPDATE secret_approval_requests r SET "updatedAt" = sr.updated_at FROM seed_requests sr WHERE r.id = sr.id;
+ UPDATE secret_approval_requests_reviewers rv SET "updatedAt" = rr.updated_at FROM seed_review_revisions rr WHERE rv.id = rr.id;
+ UPDATE secret_approval_policies p SET "updatedAt" = p."deletedAt"
+ FROM seed_policies sp WHERE p.id = sp.id AND p."deletedAt" IS NOT NULL;
+ SET LOCAL session_replication_role = origin;
+EXCEPTION WHEN insufficient_privilege THEN
+ RAISE NOTICE 'Not a superuser, so merged, closed and reopened requests keep the time this script ran as their updatedAt';
+END $$;
+
+SELECT p.name AS policy,
+ p."deletedAt" IS NOT NULL AS deleted,
+ count(DISTINCT r.id) AS requests,
+ count(DISTINCT r.id) FILTER (WHERE r.status = 'open') AS open,
+ count(DISTINCT r.id) FILTER (WHERE r."hasMerged") AS merged,
+ count(DISTINCT r.id) FILTER (WHERE r.status = 'close' AND NOT r."hasMerged") AS closed,
+ count(DISTINCT c.id) AS commits,
+ count(DISTINCT rv.id) AS reviews
+FROM seed_policies sp
+JOIN secret_approval_policies p ON p.id = sp.id
+LEFT JOIN secret_approval_requests r ON r."policyId" = p.id
+LEFT JOIN secret_approval_requests_secrets_v2 c ON c."requestId" = r.id
+LEFT JOIN secret_approval_requests_reviewers rv ON rv."requestId" = r.id
+GROUP BY p.name, p."deletedAt"
+ORDER BY p.name;
+
+COMMIT;