Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: implement get policy on brdige
adilson535b38c9c034
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.tsindex b6d556f117..6468d74a10 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@@ -12,6 +12,7 @@ const envSlug = seedData1.environment.slug;const LEGACY_PATH = "/sap-policy-bridge-legacy";const NEW_PATH = "/sap-policy-bridge-new";const MOVED_PATH = "/sap-policy-bridge-moved";+const GLOB_BASE = "/sap-policy-bridge-glob";const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });const approvers = [{ type: ApproverType.User, id: seedData1.id }];@@ -45,6 +46,16 @@ const deletePolicy = (id: string) =>const listPolicies = () =>testServer.inject({ method: "GET", url: `/api/v2/secret-approvals?projectId=${projectId}`, headers: authHeaders() });+const getPolicy = (id: string) =>+ testServer.inject({ method: "GET", url: `/api/v2/secret-approvals/${id}`, headers: authHeaders() });++const getBoardPolicy = (secretPath: string) =>+ testServer.inject({+ method: "GET",+ url: `/api/v2/secret-approvals/board?projectId=${projectId}&environment=${envSlug}&secretPath=${encodeURIComponent(secretPath)}`,+ headers: authHeaders()+ });+const legacyRow = (id: string) => getDb()(TableName.SecretApprovalPolicy).where({ id }).first();const bridgeRow = (id: string) => getDb()(TableName.ApprovalPolicies).where({ id }).first();const bridgeEnvRows = (policyId: string) => getDb()(TableName.ApprovalPolicySecretEnvironment).where({ policyId });@@ -112,7 +123,7 @@ describe("Secret approval policy bridge routing", () => {expect(listRes.json().approvals.map((policy: { id: string }) => policy.id)).not.toContain(legacyId);});- test("a policy created after the legacy one is deleted lands on the approval system tables", async () => {+ test("a policy created after the legacy one is deleted lands on the global approval system tables", async () => {const createRes = await createBridgePolicy(LEGACY_PATH);expect(createRes.statusCode).toBe(200);const bridgeId = createRes.json().approval.id as string;@@ -121,6 +132,53 @@ describe("Secret approval policy bridge routing", () => {expect(await bridgeRow(bridgeId)).toMatchObject({ type: ApprovalPolicyType.SecretChange, projectId });expect(await bridgeEnvRows(bridgeId)).toMatchObject([{ policyId: bridgeId, envId, secretPath: LEGACY_PATH }]);expect(await legacyRow(bridgeId)).toBeUndefined();+ expect(createRes.json().approval).toMatchObject({+ id: bridgeId,+ secretPath: LEGACY_PATH,+ approvals: 1,+ envId,+ environment: { id: envId, slug: envSlug },+ environments: [{ id: envId, slug: envSlug }]+ });+ });++ test("a policy on the global approval system is read back through the legacy routes", async () => {+ const [bridgeId] = bridgeIds;++ const listRes = await listPolicies();+ expect(listRes.statusCode).toBe(200);+ expect(listRes.json().approvals).toContainEqual(+ expect.objectContaining({+ id: bridgeId,+ secretPath: LEGACY_PATH,+ approvers: [{ id: seedData1.id, type: ApproverType.User }],+ bypassers: []+ })+ );++ const getRes = await getPolicy(bridgeId);+ expect(getRes.statusCode).toBe(200);+ expect(getRes.json().approval).toMatchObject({+ id: bridgeId,+ secretPath: LEGACY_PATH,+ approvals: 1,+ deletedAt: null,+ environment: { id: envId, slug: envSlug },+ environments: [{ id: envId, slug: envSlug }],+ approvers: [{ id: seedData1.id, type: ApproverType.User, username: seedData1.email }],+ bypassers: []+ });++ const boardRes = await getBoardPolicy(LEGACY_PATH);+ expect(boardRes.statusCode).toBe(200);+ expect(boardRes.json().policy).toMatchObject({+ id: bridgeId,+ secretPath: LEGACY_PATH,+ userApprovers: [{ userId: seedData1.id }]+ });++ const missRes = await getPolicy("00000000-0000-0000-0000-000000000000");+ expect(missRes.statusCode).toBe(404);});test("an update is refused when the path is governed by a policy on the other store", async () => {@@ -147,7 +205,7 @@ describe("Secret approval policy bridge routing", () => {expect(await bridgeRow(bridgeId)).toMatchObject({ name: "bridge-renamed" });});- test("a policy on the approval system is updated in place and hard-deleted", async () => {+ test("a policy on the global approval system is updated in place and hard-deleted", async () => {const [bridgeId] = bridgeIds;const updateRes = await updatePolicy(bridgeId, {@@ -185,7 +243,7 @@ describe("Secret approval policy bridge routing", () => {expect(await bridgeStep(bridgeId)).toBeUndefined();// Pins the current gap: the bridge does not cancel pending requests the way legacy closes open ones.- // Flip this to expect "cancelled" when secret change requests move onto the approval system.+ // Flip this to expect "cancelled" when secret change requests move onto the global approval system.expect(await getDb()(TableName.ApprovalRequests).where({ id: requestId }).first()).toMatchObject({status: "pending",policyId: null@@ -195,4 +253,30 @@ describe("Secret approval policy bridge routing", () => {expect(recreateRes.statusCode).toBe(200);bridgeIds.push(recreateRes.json().approval.id);});++ test("a secret path is resolved across both stores with the exact path winning over a glob", async () => {+ const legacyRes = await createLegacyPolicy(`${GLOB_BASE}/**`);+ expect(legacyRes.statusCode).toBe(200);+ const legacyId = legacyRes.json().approval.id as string;+ legacyIds.push(legacyId);++ const bridgeRes = await createBridgePolicy(`${GLOB_BASE}/svc`);+ expect(bridgeRes.statusCode).toBe(200);+ const bridgeId = bridgeRes.json().approval.id as string;+ bridgeIds.push(bridgeId);++ const exactRes = await getBoardPolicy(`${GLOB_BASE}/svc`);+ expect(exactRes.statusCode).toBe(200);+ expect(exactRes.json().policy).toMatchObject({ id: bridgeId, secretPath: `${GLOB_BASE}/svc` });++ const globRes = await getBoardPolicy(`${GLOB_BASE}/other`);+ expect(globRes.statusCode).toBe(200);+ expect(globRes.json().policy).toMatchObject({ id: legacyId, secretPath: `${GLOB_BASE}/**` });++ const listRes = await listPolicies();+ expect(listRes.statusCode).toBe(200);+ expect(listRes.json().approvals.map((policy: { id: string }) => policy.id)).toEqual(+ expect.arrayContaining([legacyId, bridgeId])+ );+ });});diff --git a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.test.ts b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.test.tsindex 9a2c84dcdc..aa0c675151 100644--- a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.test.ts+++ b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.test.ts@@ -2,10 +2,57 @@ import { describe, expect, test } from "vitest";import { ActorType } from "@app/services/auth/auth-type";-import { shouldApplyPolicy } from "./secret-approval-policy-fns";+import { getPolicyScore, resolvePolicyForPath, shouldApplyPolicy } from "./secret-approval-policy-fns";const makePolicy = (bypassForMachineIdentities = false) => ({ bypassForMachineIdentities });+const makePathPolicy = (id: string, secretPath: string | null, createdAt = "2026-01-01") => ({+ id,+ secretPath,+ createdAt: new Date(createdAt)+});++describe("getPolicyScore", () => {+ test("ranks an exact path above a glob above an environment-wide policy", () => {+ expect(getPolicyScore({ secretPath: "/app/svc" })).toBe(2);+ expect(getPolicyScore({ secretPath: "/app/**" })).toBe(1);+ expect(getPolicyScore({ secretPath: null })).toBe(0);+ expect(getPolicyScore({})).toBe(0);+ });+});++describe("resolvePolicyForPath", () => {+ test("picks the exact path over a glob over an environment-wide policy", () => {+ const envWide = makePathPolicy("env", null);+ const glob = makePathPolicy("glob", "/app/**");+ const exact = makePathPolicy("exact", "/app/svc");++ expect(resolvePolicyForPath([envWide, glob, exact], "/app/svc")).toBe(exact);+ expect(resolvePolicyForPath([envWide, glob, exact], "/app/other")).toBe(glob);+ expect(resolvePolicyForPath([envWide, glob, exact], "/elsewhere")).toBe(envWide);+ });++ test("ignores policies whose path does not match", () => {+ expect(resolvePolicyForPath([makePathPolicy("a", "/app/**")], "/db")).toBeUndefined();+ expect(resolvePolicyForPath([], "/db")).toBeUndefined();+ });++ test("breaks a tie on the earliest creation regardless of input order", () => {+ const newer = makePathPolicy("newer", "/app/**", "2026-02-01");+ const older = makePathPolicy("older", "/app/*", "2026-01-01");++ expect(resolvePolicyForPath([newer, older], "/app/svc")).toBe(older);+ expect(resolvePolicyForPath([older, newer], "/app/svc")).toBe(older);+ });++ test("falls back to the id when creation times are equal", () => {+ const b = makePathPolicy("b", "/app/**");+ const a = makePathPolicy("a", "/app/*");++ expect(resolvePolicyForPath([b, a], "/app/svc")).toBe(a);+ });+});+describe("shouldApplyPolicy", () => {test("returns false when policy is undefined", () => {expect(shouldApplyPolicy(undefined, ActorType.USER)).toBe(false);diff --git a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.ts b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.tsindex f1cdef4607..e95c2a4303 100644--- a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.ts+++ b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-fns.ts@@ -1,5 +1,32 @@+import picomatch from "picomatch";++import { containsGlobPatterns } from "@app/lib/picomatch";import { ActorType } from "@app/services/auth/auth-type";+export const getPolicyScore = (policy: { secretPath?: string | null }) =>+ // if glob pattern score is 1, if not exist score is 0 and if its not both then its exact path meaning score 2+ // eslint-disable-next-line+ policy.secretPath ? (containsGlobPatterns(policy.secretPath) ? 1 : 2) : 0;++// picks the highest-priority policy governing a secret path: exact path match first, then glob, then env-scoped.+// Legacy and approval-system policies are resolved together, so the tie-break is explicit rather than+// relying on the order one DAL happened to return.+export const resolvePolicyForPath = <T extends { secretPath?: string | null; createdAt: Date; id: string }>(+ policies: T[],+ secretPath: string+) =>+ policies+ .filter(+ ({ secretPath: policyPath }) => !policyPath || picomatch.isMatch(secretPath, policyPath, { strictSlashes: false })+ )+ .sort(+ (a, b) =>+ getPolicyScore(b) - getPolicyScore(a) ||+ a.createdAt.getTime() - b.createdAt.getTime() ||+ a.id.localeCompare(b.id)+ )+ .shift();+/*** Returns the committer ID fields for a secret approval request,* setting the appropriate field based on the actor type.diff --git a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.test.ts b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.test.tsindex 8976d9975d..712edff4c4 100644--- a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.test.ts+++ b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.test.ts@@ -1,4 +1,5 @@import { createMongoAbility } from "@casl/ability";+import { Knex } from "knex";import { describe, expect, test, vi } from "vitest";import { conditionsMatcher } from "@app/lib/casl";@@ -12,21 +13,62 @@ import { secretApprovalPolicyServiceFactory } from "./secret-approval-policy-serconst ORG_ID = "org-1";const PROJECT_ID = "project-1";const ENV_DEV = { id: "env-dev", name: "Development", slug: "dev", projectId: PROJECT_ID };+const TX = { isTx: true } as unknown as Knex;-const allowCreate = createMongoAbility<ProjectPermissionSet>(- [{ action: ProjectPermissionActions.Create, subject: ProjectPermissionSub.SecretApproval }],+const allowAll = createMongoAbility<ProjectPermissionSet>(+ [+ { action: ProjectPermissionActions.Create, subject: ProjectPermissionSub.SecretApproval },+ { action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.SecretApproval }+ ],{ conditionsMatcher });-// Only the collaborators the duplicate-policy check reaches; anything else crashes the test if touched.-const buildService = ({ bridgePolicy }: { bridgePolicy?: { id: string; environments: { id: string }[] } }) => {+const ctx = {+ actor: ActorType.USER,+ actorId: "actor-1",+ actorOrgId: ORG_ID,+ actorAuthMethod: null+} as unknown as Pick<+ Parameters<ReturnType<typeof secretApprovalPolicyServiceFactory>["getSecretApprovalPolicyById"]>[0],+ "actor" | "actorId" | "actorOrgId" | "actorAuthMethod"+>;++const makePolicy = (id: string, secretPath: string, createdAt: string) => ({+ id,+ secretPath,+ name: id,+ createdAt: new Date(createdAt),+ projectId: PROJECT_ID,+ bypassForMachineIdentities: false+});++type TPolicy = ReturnType<typeof makePolicy>;+type TExistingPolicy = { id: string; environments: { id: string }[] };++// Only the collaborators the read and duplicate-policy paths reach; anything else crashes the test if touched.+const buildService = ({+ bridgePolicy = undefined as TExistingPolicy | undefined,+ legacyPolicies = [] as TPolicy[],+ bridgePolicies = [] as TPolicy[],+ bridgeOwnsPolicy = false+} = {}) => {const deps = {- permissionService: { getProjectPermission: vi.fn().mockResolvedValue({ permission: allowCreate }) },+ permissionService: { getProjectPermission: vi.fn().mockResolvedValue({ permission: allowAll }) },licenseService: { getPlan: vi.fn().mockResolvedValue({ secretApproval: true }) },- projectEnvDAL: { find: vi.fn().mockResolvedValue([ENV_DEV]) },- secretApprovalPolicyDAL: { findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(undefined) },+ projectEnvDAL: {+ find: vi.fn().mockResolvedValue([ENV_DEV]),+ findOne: vi.fn(({ slug }: { slug: string }) => Promise.resolve(slug === ENV_DEV.slug ? ENV_DEV : undefined))+ },+ secretApprovalPolicyDAL: {+ findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(undefined),+ find: vi.fn().mockResolvedValue(legacyPolicies)+ },secretChangePolicyBridgeService: {- findSecretChangePolicyBySecretPath: vi.fn().mockResolvedValue(bridgePolicy)+ findSecretChangePolicy: vi.fn().mockResolvedValue(bridgeOwnsPolicy ? { id: "bridge-policy" } : undefined),+ findSecretChangePolicyBySecretPath: vi.fn().mockResolvedValue(bridgePolicy),+ findSecretChangePoliciesByEnvId: vi.fn().mockResolvedValue(bridgePolicies),+ findSecretChangePoliciesByProjectId: vi.fn().mockResolvedValue(bridgePolicies),+ getSecretChangePolicyById: vi.fn().mockResolvedValue({ id: "bridge-policy" })}};@@ -44,10 +86,7 @@ describe("secretApprovalPolicyService createSecretApprovalPolicy", () => {await expect(service.createSecretApprovalPolicy({- actor: ActorType.USER,- actorId: "actor-1",- actorOrgId: ORG_ID,- actorAuthMethod: null,+ ...ctx,projectId: PROJECT_ID,name: "dev-policy",approvals: 1,@@ -70,3 +109,89 @@ describe("secretApprovalPolicyService createSecretApprovalPolicy", () => {});});});++describe("secretApprovalPolicyService getSecretApprovalPolicyByProjectId", () => {+ test("lists legacy and global approval system policies together, oldest first", async () => {+ const legacy = makePolicy("legacy", "/a", "2026-01-02");+ const bridge = makePolicy("bridge", "/b", "2026-01-01");+ const { service, deps } = buildService({ legacyPolicies: [legacy], bridgePolicies: [bridge] });++ await expect(service.getSecretApprovalPolicyByProjectId({ ...ctx, projectId: PROJECT_ID })).resolves.toEqual([+ bridge,+ legacy+ ]);+ expect(deps.secretApprovalPolicyDAL.find).toHaveBeenCalledWith({ projectId: PROJECT_ID, deletedAt: null });+ expect(deps.secretChangePolicyBridgeService.findSecretChangePoliciesByProjectId).toHaveBeenCalledWith(PROJECT_ID);+ });+});++describe("secretApprovalPolicyService getSecretApprovalPolicy", () => {+ test("resolves the path over both stores and threads the transaction to each", async () => {+ const legacyGlob = makePolicy("legacy-glob", "/app/**", "2026-01-01");+ const bridgeExact = makePolicy("bridge-exact", "/app/svc", "2026-01-02");+ const { service, deps } = buildService({ legacyPolicies: [legacyGlob], bridgePolicies: [bridgeExact] });++ await expect(service.getSecretApprovalPolicy(PROJECT_ID, ENV_DEV.slug, "/app/svc", TX)).resolves.toBe(bridgeExact);+ await expect(service.getSecretApprovalPolicy(PROJECT_ID, ENV_DEV.slug, "/app/other", TX)).resolves.toBe(legacyGlob);+ expect(deps.secretApprovalPolicyDAL.find).toHaveBeenCalledWith({ deletedAt: null }, { envId: ENV_DEV.id }, TX);+ expect(deps.secretChangePolicyBridgeService.findSecretChangePoliciesByEnvId).toHaveBeenCalledWith(ENV_DEV.id, TX);+ });++ test("lets a legacy exact path win over a global approval system glob", async () => {+ const legacyExact = makePolicy("legacy-exact", "/app/svc", "2026-01-02");+ const bridgeGlob = makePolicy("bridge-glob", "/app/**", "2026-01-01");+ const { service } = buildService({ legacyPolicies: [legacyExact], bridgePolicies: [bridgeGlob] });++ await expect(service.getSecretApprovalPolicy(PROJECT_ID, ENV_DEV.slug, "/app/svc")).resolves.toBe(legacyExact);+ });++ test("breaks a tie across stores on the earliest creation", async () => {+ const legacyGlob = makePolicy("legacy-glob", "/app/**", "2026-01-02");+ const bridgeGlob = makePolicy("bridge-glob", "/app/*", "2026-01-01");+ const { service } = buildService({ legacyPolicies: [legacyGlob], bridgePolicies: [bridgeGlob] });++ await expect(service.getSecretApprovalPolicy(PROJECT_ID, ENV_DEV.slug, "/app/svc")).resolves.toBe(bridgeGlob);+ });++ test("resolves several paths against both stores with one read each", async () => {+ const legacyGlob = makePolicy("legacy-glob", "/app/**", "2026-01-01");+ const bridgeExact = makePolicy("bridge-exact", "/app/svc", "2026-01-02");+ const { service, deps } = buildService({ legacyPolicies: [legacyGlob], bridgePolicies: [bridgeExact] });++ const byPath = await service.getSecretApprovalPolicyByPaths(PROJECT_ID, ENV_DEV.slug, [+ "/app/svc",+ "/app/other",+ "/db"+ ]);++ expect(byPath.get("/app/svc")).toBe(bridgeExact);+ expect(byPath.get("/app/other")).toBe(legacyGlob);+ expect(byPath.has("/db")).toBe(false);+ expect(deps.secretApprovalPolicyDAL.find).toHaveBeenCalledTimes(1);+ expect(deps.secretChangePolicyBridgeService.findSecretChangePoliciesByEnvId).toHaveBeenCalledTimes(1);+ });+});++describe("secretApprovalPolicyService getSecretApprovalPolicyById", () => {+ test("routes a policy that lives on the global approval system to the bridge", async () => {+ const { service, deps } = buildService({ bridgeOwnsPolicy: true });++ await expect(service.getSecretApprovalPolicyById({ ...ctx, sapId: "bridge-policy" })).resolves.toEqual({+ id: "bridge-policy"+ });+ expect(deps.secretChangePolicyBridgeService.getSecretChangePolicyById).toHaveBeenCalledWith({+ ...ctx,+ sapId: "bridge-policy"+ });+ expect(deps.secretApprovalPolicyDAL.find).not.toHaveBeenCalled();+ });++ test("reads a legacy policy from the legacy tables", async () => {+ const legacy = makePolicy("legacy", "/a", "2026-01-01");+ const { service, deps } = buildService({ legacyPolicies: [legacy] });++ await expect(service.getSecretApprovalPolicyById({ ...ctx, sapId: "legacy" })).resolves.toBe(legacy);+ expect(deps.secretApprovalPolicyDAL.find).toHaveBeenCalledWith({}, { sapId: "legacy" });+ expect(deps.secretChangePolicyBridgeService.getSecretChangePolicyById).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.ts b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.tsindex eb1628bf80..975a857b3d 100644--- a/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.ts+++ b/backend/src/ee/services/secret-approval-policy/secret-approval-policy-service.ts@@ -1,13 +1,11 @@import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";-import picomatch from "picomatch";import { ActionProjectType } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { removeTrailingSlash } from "@app/lib/fn";-import { containsGlobPatterns } from "@app/lib/picomatch";import { TProjectDALFactory } from "@app/services/project/project-dal";import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";import { TUserDALFactory } from "@app/services/user/user-dal";@@ -24,6 +22,7 @@ import {} from "./secret-approval-policy-approver-dal";import { TSecretApprovalPolicyDALFactory } from "./secret-approval-policy-dal";import { TSecretApprovalPolicyEnvironmentDALFactory } from "./secret-approval-policy-environment-dal";+import { resolvePolicyForPath } from "./secret-approval-policy-fns";import {TCreateSapDTO,TDeleteSapDTO,@@ -33,22 +32,6 @@ import {TUpdateSapDTO} from "./secret-approval-policy-types";-const getPolicyScore = (policy: { secretPath?: string | null }) =>- // if glob pattern score is 1, if not exist score is 0 and if its not both then its exact path meaning score 2- // eslint-disable-next-line- policy.secretPath ? (containsGlobPatterns(policy.secretPath) ? 1 : 2) : 0;--// picks the highest-priority policy governing a secret path: exact path match first, then glob, then env-scoped.-const resolvePolicyForPath = <T extends { secretPath?: string | null }>(policies: T[], secretPath: string) => {- // this will filter policies either without scoped to secret path or the one that matches with secret path- const policiesFilteredByPath = policies.filter(- ({ secretPath: policyPath }) => !policyPath || picomatch.isMatch(secretPath, policyPath, { strictSlashes: false })- );- // now sort by priority. exact secret path gets first match followed by glob followed by just env scoped- // if that is tie get by first createdAt- return policiesFilteredByPath.sort((a, b) => getPolicyScore(b) - getPolicyScore(a)).shift();-};-type TSecretApprovalPolicyServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;secretApprovalPolicyDAL: TSecretApprovalPolicyDALFactory;@@ -64,8 +47,11 @@ type TSecretApprovalPolicyServiceFactoryDep = {TSecretChangePolicyBridgeServiceFactory,| "findSecretChangePolicy"| "findSecretChangePolicyBySecretPath"+ | "findSecretChangePoliciesByEnvId"+ | "findSecretChangePoliciesByProjectId"| "updateSecretChangePolicy"| "deleteSecretChangePolicy"+ | "getSecretChangePolicyById">;};@@ -632,8 +618,11 @@ export const secretApprovalPolicyServiceFactory = ({});ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SecretApproval);- const sapPolicies = await secretApprovalPolicyDAL.find({ projectId, deletedAt: null });- return sapPolicies;+ const [legacyPolicies, secretChangePolicies] = await Promise.all([+ secretApprovalPolicyDAL.find({ projectId, deletedAt: null }),+ secretChangePolicyBridgeService.findSecretChangePoliciesByProjectId(projectId)+ ]);+ return [...legacyPolicies, ...secretChangePolicies].sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());};const findEnvPolicies = async (projectId: string, environment: string, tx?: Knex) => {@@ -643,7 +632,11 @@ export const secretApprovalPolicyServiceFactory = ({message: `Environment with slug '${environment}' not found in project with ID ${projectId}`});}- return secretApprovalPolicyDAL.find({ deletedAt: null }, { envId: env.id }, tx);+ const [legacyPolicies, secretChangePolicies] = await Promise.all([+ secretApprovalPolicyDAL.find({ deletedAt: null }, { envId: env.id }, tx),+ secretChangePolicyBridgeService.findSecretChangePoliciesByEnvId(env.id, tx)+ ]);+ return [...legacyPolicies, ...secretChangePolicies];};const getSecretApprovalPolicy = async (projectId: string, environment: string, path: string, tx?: Knex) => {@@ -658,7 +651,7 @@ export const secretApprovalPolicyServiceFactory = ({secretPaths: string[],tx?: Knex) => {- const policyByPath = new Map<string, Awaited<ReturnType<typeof secretApprovalPolicyDAL.find>>[number]>();+ const policyByPath = new Map<string, Awaited<ReturnType<typeof findEnvPolicies>>[number]>();const policies = await findEnvPolicies(projectId, environment, tx);if (!policies.length) return policyByPath;@@ -690,13 +683,12 @@ export const secretApprovalPolicyServiceFactory = ({return getSecretApprovalPolicy(projectId, environment, secretPath);};- const getSecretApprovalPolicyById = async ({- actorId,- actor,- actorOrgId,- actorAuthMethod,- sapId- }: TGetSapByIdDTO) => {+ const getSecretApprovalPolicyById = async (dto: TGetSapByIdDTO) => {+ if (await $useSecretChangePolicyBridge(dto.sapId)) {+ return secretChangePolicyBridgeService.getSecretChangePolicyById(dto);+ }++ const { actorId, actor, actorOrgId, actorAuthMethod, sapId } = dto;const [sapPolicy] = await secretApprovalPolicyDAL.find({}, { sapId });if (!sapPolicy) {diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-dal.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-dal.tsnew file mode 100644index 0000000000..45e1b16113--- /dev/null+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-dal.ts@@ -0,0 +1,170 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { ApprovalPoliciesSchema, TableName, TUsers } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";++import { ApproverType, BypasserType } from "../access-approval-policy/access-approval-policy-types";++export type TSecretChangePolicyBridgeDALFactory = ReturnType<typeof secretChangePolicyBridgeDALFactory>;++export type TSecretChangePolicyRow = Awaited<+ ReturnType<TSecretChangePolicyBridgeDALFactory["findSecretChangePolicies"]>+>[number];++export const secretChangePolicyBridgeDALFactory = (db: TDbClient) => {+ const findSecretChangePolicies = async (+ {+ policyId,+ projectId,+ envId,+ organizationId+ }: { policyId?: string; projectId?: string; envId?: string; organizationId?: string },+ tx?: Knex+ ) => {+ try {+ const docs = await (tx || db.replicaNode())(TableName.ApprovalPolicies)+ .where(`${TableName.ApprovalPolicies}.type`, ApprovalPolicyType.SecretChange)+ .where((qb) => {+ if (policyId) void qb.where(`${TableName.ApprovalPolicies}.id`, policyId);+ if (projectId) void qb.where(`${TableName.ApprovalPolicies}.projectId`, projectId);+ if (organizationId) void qb.where(`${TableName.ApprovalPolicies}.organizationId`, organizationId);+ })+ .join(+ TableName.ApprovalPolicySecretEnvironment,+ `${TableName.ApprovalPolicySecretEnvironment}.policyId`,+ `${TableName.ApprovalPolicies}.id`+ )+ .join(TableName.Environment, function joinActiveEnvForSecretChangePolicy() {+ this.on(`${TableName.ApprovalPolicySecretEnvironment}.envId`, `${TableName.Environment}.id`).andOnNull(+ `${TableName.Environment}.deleteAfter`+ );+ })+ .where((qb) => {+ if (envId) void qb.where(`${TableName.ApprovalPolicySecretEnvironment}.envId`, envId);+ })+ .leftJoin(+ TableName.ApprovalPolicySteps,+ `${TableName.ApprovalPolicySteps}.policyId`,+ `${TableName.ApprovalPolicies}.id`+ )+ .leftJoin(+ TableName.ApprovalPolicyStepApprovers,+ `${TableName.ApprovalPolicyStepApprovers}.policyStepId`,+ `${TableName.ApprovalPolicySteps}.id`+ )+ .leftJoin<TUsers>(+ db(TableName.Users).as("approverUser"),+ `${TableName.ApprovalPolicyStepApprovers}.userId`,+ "approverUser.id"+ )+ .leftJoin(+ TableName.UserGroupMembership,+ `${TableName.ApprovalPolicyStepApprovers}.groupId`,+ `${TableName.UserGroupMembership}.groupId`+ )+ .leftJoin(+ TableName.ApprovalPolicyBypassers,+ `${TableName.ApprovalPolicyBypassers}.policyId`,+ `${TableName.ApprovalPolicies}.id`+ )+ .leftJoin<TUsers>(+ db(TableName.Users).as("bypasserUser"),+ `${TableName.ApprovalPolicyBypassers}.userId`,+ "bypasserUser.id"+ )+ .select(selectAllTableCols(TableName.ApprovalPolicies))+ .select(+ db.ref("id").withSchema(TableName.Environment).as("environmentId"),+ db.ref("name").withSchema(TableName.Environment).as("envName"),+ db.ref("slug").withSchema(TableName.Environment).as("envSlug"),+ db.ref("secretPath").withSchema(TableName.ApprovalPolicySecretEnvironment).as("envSecretPath"),+ db.ref("id").withSchema(TableName.ApprovalPolicySteps).as("stepId"),+ db.ref("stepNumber").withSchema(TableName.ApprovalPolicySteps),+ db.ref("requiredApprovals").withSchema(TableName.ApprovalPolicySteps),+ db.ref("userId").withSchema(TableName.ApprovalPolicyStepApprovers).as("approverUserId"),+ db.ref("groupId").withSchema(TableName.ApprovalPolicyStepApprovers).as("approverGroupId"),+ db.ref("username").withSchema("approverUser").as("approverUsername"),+ db.ref("userId").withSchema(TableName.UserGroupMembership).as("approverGroupUserId"),+ db.ref("userId").withSchema(TableName.ApprovalPolicyBypassers).as("bypasserUserId"),+ db.ref("groupId").withSchema(TableName.ApprovalPolicyBypassers).as("bypasserGroupId"),+ db.ref("username").withSchema("bypasserUser").as("bypasserUsername")+ )+ .orderBy([+ { column: `${TableName.ApprovalPolicies}.createdAt`, order: "asc" },+ { column: `${TableName.ApprovalPolicies}.id`, order: "asc" },+ { column: `${TableName.Environment}.position`, order: "asc" },+ { column: `${TableName.ApprovalPolicySteps}.stepNumber`, order: "asc" }+ ]);++ return sqlNestRelationships({+ data: docs,+ key: "id",+ parentMapper: (data) => ({+ ...ApprovalPoliciesSchema.parse(data),+ secretPath: data.envSecretPath+ }),+ childrenMapper: [+ {+ key: "environmentId",+ label: "environments" as const,+ mapper: ({ environmentId: id, envName, envSlug }) => ({ id, name: envName, slug: envSlug })+ },+ {+ key: "stepId",+ label: "steps" as const,+ mapper: ({ stepId: id, stepNumber, requiredApprovals }) => ({+ id,+ stepNumber: stepNumber as number,+ requiredApprovals: requiredApprovals as number+ })+ },+ {+ key: "approverUserId",+ label: "approvers" as const,+ mapper: ({ approverUserId: id, approverUsername }) => ({+ type: ApproverType.User as const,+ id,+ username: approverUsername+ })+ },+ {+ key: "approverGroupId",+ label: "approvers" as const,+ mapper: ({ approverGroupId: id }) => ({ type: ApproverType.Group as const, id })+ },+ {+ key: "bypasserUserId",+ label: "bypassers" as const,+ mapper: ({ bypasserUserId: id, bypasserUsername }) => ({+ type: BypasserType.User as const,+ id,+ username: bypasserUsername+ })+ },+ {+ key: "bypasserGroupId",+ label: "bypassers" as const,+ mapper: ({ bypasserGroupId: id }) => ({ type: BypasserType.Group as const, id })+ },+ {+ key: "approverUserId",+ label: "userApprovers" as const,+ mapper: ({ approverUserId: userId }) => ({ userId })+ },+ {+ key: "approverGroupUserId",+ label: "userApprovers" as const,+ mapper: ({ approverGroupUserId: userId }) => ({ userId })+ }+ ]+ });+ } catch (error) {+ throw new DatabaseError({ error, name: "findSecretChangePolicies" });+ }+ };++ return { findSecretChangePolicies };+};diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.test.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.test.tsnew file mode 100644index 0000000000..26f75f07d6--- /dev/null+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.test.ts@@ -0,0 +1,103 @@+import { describe, expect, test } from "vitest";++import { EnforcementLevel } from "@app/lib/types";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";++import { ApproverType, BypasserType } from "../access-approval-policy/access-approval-policy-types";+import { TSecretChangePolicyRow } from "./secret-change-policy-bridge-dal";+import { readSecretChangePolicyConstraints, toSecretChangePolicy } from "./secret-change-policy-bridge-fns";++const ENV_DEV = { id: "env-dev", name: "Development", slug: "dev" };+const ENV_PROD = { id: "env-prod", name: "Production", slug: "prod" };++const buildRow = (overrides: Partial<TSecretChangePolicyRow> = {}): TSecretChangePolicyRow => ({+ id: "policy-1",+ projectId: "project-1",+ organizationId: "org-1",+ type: ApprovalPolicyType.SecretChange,+ name: "dev-policy",+ isActive: true,+ maxRequestTtl: null,+ conditions: { version: 1, conditions: [] },+ constraints: { version: 1, constraints: { allowedSelfApprovals: false } },+ createdAt: new Date("2026-01-01"),+ updatedAt: new Date("2026-01-02"),+ bypassForMachineIdentities: true,+ enforcementLevel: EnforcementLevel.Soft,+ scopeType: null,+ scopeId: null,+ secretPath: "/app",+ environments: [ENV_DEV, ENV_PROD],+ steps: [{ id: "step-1", stepNumber: 1, requiredApprovals: 2 }],+ approvers: [+ { type: ApproverType.User, id: "user-1", username: "[email protected]" },+ { type: ApproverType.Group, id: "group-1" }+ ],+ bypassers: [{ type: BypasserType.User, id: "user-2", username: "[email protected]" }],+ userApprovers: [{ userId: "user-1" }, { userId: "user-3" }],+ ...overrides+});++describe("readSecretChangePolicyConstraints", () => {+ test("reads allowedSelfApprovals from the stored constraints blob", () => {+ expect(readSecretChangePolicyConstraints({ version: 1, constraints: { allowedSelfApprovals: false } })).toEqual({+ allowedSelfApprovals: false+ });+ });++ test("returns nothing for a blob it cannot read", () => {+ expect(readSecretChangePolicyConstraints(null)).toEqual({});+ expect(readSecretChangePolicyConstraints({ version: 1, constraints: { allowedSelfApprovals: "yes" } })).toEqual({});+ });+});++describe("toSecretChangePolicy", () => {+ test("flattens a global approval system row into the legacy secret approval policy shape", () => {+ const row = buildRow();++ expect(toSecretChangePolicy(row)).toEqual({+ id: "policy-1",+ name: "dev-policy",+ projectId: "project-1",+ enforcementLevel: EnforcementLevel.Soft,+ bypassForMachineIdentities: true,+ createdAt: new Date("2026-01-01"),+ updatedAt: new Date("2026-01-02"),+ deletedAt: null,+ secretPath: "/app",+ approvals: 2,+ allowedSelfApprovals: false,+ envId: ENV_DEV.id,+ environment: ENV_DEV,+ environments: [ENV_DEV, ENV_PROD],+ approvers: row.approvers,+ bypassers: row.bypassers,+ userApprovers: row.userApprovers+ });+ });++ test("takes the approval count from the first step and defaults to one without a step", () => {+ expect(+ toSecretChangePolicy(+ buildRow({+ steps: [+ { id: "step-1", stepNumber: 1, requiredApprovals: 3 },+ { id: "step-2", stepNumber: 2, requiredApprovals: 1 }+ ]+ })+ ).approvals+ ).toBe(3);+ expect(toSecretChangePolicy(buildRow({ steps: [] })).approvals).toBe(1);+ });++ test("defaults allowedSelfApprovals to true when the constraints blob is unreadable", () => {+ expect(toSecretChangePolicy(buildRow({ constraints: "corrupt" })).allowedSelfApprovals).toBe(true);+ expect(toSecretChangePolicy(buildRow({ constraints: { version: 1, constraints: {} } })).allowedSelfApprovals).toBe(+ true+ );+ });++ test("treats a missing machine identity bypass flag as disabled", () => {+ expect(toSecretChangePolicy(buildRow({ bypassForMachineIdentities: null })).bypassForMachineIdentities).toBe(false);+ });+});diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.tsindex 393e82c2ec..9a7f47052a 100644--- a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.ts+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.ts@@ -17,18 +17,20 @@ import { approvalPolicyMembershipVerifierFactory } from "../access-approval-poliimport { ApproverType, BypasserType } from "../access-approval-policy/access-approval-policy-types";import { TSecretApprovalPolicyDALFactory } from "../secret-approval-policy/secret-approval-policy-dal";import { TCreateSapDTO, TUpdateSapDTO } from "../secret-approval-policy/secret-approval-policy-types";-import { TSecretChangePolicyEnvironment } from "./secret-change-policy-bridge-types";+import { TSecretChangePolicyBridgeDALFactory, TSecretChangePolicyRow } from "./secret-change-policy-bridge-dal";+import { TSecretChangePolicy, TSecretChangePolicyEnvironment } from "./secret-change-policy-bridge-types";import { TApprovalPolicySecretEnvironmentDALFactory } from "./secret-change-policy-environment-dal";type TSecretChangePolicyFnsFactoryDep = {approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findOne" | "findByIdForUpdate" | "updateById" | "transaction">;- approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "findOne" | "create" | "updateById">;+ approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create" | "updateById">;approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "insertMany" | "delete">;approvalPolicyBypassersDAL: Pick<TApprovalPolicyBypassersDALFactory, "insertMany" | "delete">;approvalPolicySecretEnvironmentDAL: Pick<TApprovalPolicySecretEnvironmentDALFactory,- "findPolicyByEnvIdAndSecretPath" | "findEnvironmentsByPolicyId" | "insertMany" | "delete"+ "findPolicyByEnvIdAndSecretPath" | "insertMany" | "delete">;+ secretChangePolicyBridgeDAL: Pick<TSecretChangePolicyBridgeDALFactory, "findSecretChangePolicies">;secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "findPolicyByEnvIdAndSecretPath">;projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;userDAL: Pick<TUserDALFactory, "find">;@@ -38,7 +40,7 @@ type TUpdatePolicyInput = Pick<TUpdateSapDTO,"name" | "approvals" | "secretPath" | "enforcementLevel" | "allowedSelfApprovals" | "bypassForMachineIdentities"> & {- policy: TApprovalPolicies;+ policy: Pick<TApprovalPolicies, "id">;requestedEnvs?: TSecretChangePolicyEnvironment[];approverCount: number;userApproverIds: string[];@@ -53,11 +55,37 @@ const SecretChangePolicyConstraintsSchema = z}).passthrough();-const readConstraints = (policy: TApprovalPolicies) => {- const parsed = SecretChangePolicyConstraintsSchema.safeParse(policy.constraints);+export const readSecretChangePolicyConstraints = (constraints: unknown): { allowedSelfApprovals?: boolean } => {+ const parsed = SecretChangePolicyConstraintsSchema.safeParse(constraints);return parsed.success ? (parsed.data.constraints ?? {}) : {};};+// The global approval system stores what the legacy policy row carried inline: the path per environment row,+// the approval count on the first step and self-approval in the constraints blob.+export const toSecretChangePolicy = (row: TSecretChangePolicyRow): TSecretChangePolicy => {+ const [firstStep] = row.steps;+ const [environment] = row.environments;+ return {+ id: row.id,+ name: row.name,+ projectId: row.projectId,+ enforcementLevel: row.enforcementLevel,+ bypassForMachineIdentities: row.bypassForMachineIdentities ?? false,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ deletedAt: null,+ secretPath: row.secretPath,+ approvals: firstStep?.requiredApprovals ?? 1,+ allowedSelfApprovals: readSecretChangePolicyConstraints(row.constraints).allowedSelfApprovals ?? true,+ envId: environment.id,+ environment,+ environments: row.environments,+ approvers: row.approvers,+ bypassers: row.bypassers,+ userApprovers: row.userApprovers+ };+};+export const splitApprovers = (approvers: TCreateSapDTO["approvers"]) => ({groupApprovers: approvers.filter((approver) => approver.type === ApproverType.Group)@@ -78,6 +106,7 @@ export const secretChangePolicyFnsFactory = ({approvalPolicyStepApproversDAL,approvalPolicyBypassersDAL,approvalPolicySecretEnvironmentDAL,+ secretChangePolicyBridgeDAL,secretApprovalPolicyDAL,projectDAL,userDAL@@ -92,7 +121,17 @@ export const secretChangePolicyFnsFactory = ({tx?: Knex) => approvalPolicySecretEnvironmentDAL.findPolicyByEnvIdAndSecretPath({ envIds, secretPath }, tx);- // Policies are being migrated onto the approval system, so a path is taken whether the policy that+ const findSecretChangePoliciesByEnvId = async (envId: string, tx?: Knex) => {+ const rows = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ envId }, tx);+ return rows.map(toSecretChangePolicy);+ };++ const findSecretChangePoliciesByProjectId = async (projectId: string) => {+ const rows = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ projectId });+ return rows.map(toSecretChangePolicy);+ };++ // Policies are being migrated onto the global approval system, so a path is taken whether the policy that// governs it still lives on the legacy secret approval tables or already lives on the new ones.const assertNoPolicyForSecretPath = async ({@@ -232,22 +271,20 @@ export const secretChangePolicyFnsFactory = ({}};- const getSecretChangePolicyState = async (policy: TApprovalPolicies, tx?: Knex) => {- const envRows = await approvalPolicySecretEnvironmentDAL.findEnvironmentsByPolicyId(policy.id, tx);- const step = await approvalPolicyStepsDAL.findOne({ policyId: policy.id }, tx);- if (!envRows.length) {+ const getSecretChangePolicyState = async (policyId: string, tx: Knex) => {+ const [row] = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ policyId }, tx);+ if (!row) {throw new NotFoundError({- message: `Secret approval policy with ID '${policy.id}' no longer governs any environment`+ message: `Secret approval policy with ID '${policyId}' no longer governs any environment`});}- const constraints = readConstraints(policy);+ const policy = toSecretChangePolicy(row);return {- step,- envs: envRows.map(({ id, name, slug }) => ({ id, name, slug })),- secretPath: envRows[0].secretPath,- approvals: step?.requiredApprovals ?? 1,- allowedSelfApprovals: constraints.allowedSelfApprovals ?? true+ step: row.steps[0],+ envs: row.environments,+ secretPath: policy.secretPath,+ approvals: policy.approvals};};@@ -273,7 +310,7 @@ export const secretChangePolicyFnsFactory = ({if (!lockedPolicy) {throw new NotFoundError({ message: `Secret approval policy with ID '${policy.id}' not found` });}- const current = await getSecretChangePolicyState(lockedPolicy, tx);+ const current = await getSecretChangePolicyState(policy.id, tx);const nextApprovals = approvals ?? current.approvals;if (!groupApprovers.length && nextApprovals > approverCount)@@ -290,12 +327,10 @@ export const secretChangePolicyFnsFactory = ({if (allowedSelfApprovals !== undefined) {updateDoc.constraints = {version: 1,- constraints: { ...readConstraints(lockedPolicy), allowedSelfApprovals }+ constraints: { ...readSecretChangePolicyConstraints(lockedPolicy.constraints), allowedSelfApprovals }};}- const doc = Object.keys(updateDoc).length- ? await approvalPolicyDAL.updateById(policy.id, updateDoc, tx)- : lockedPolicy;+ if (Object.keys(updateDoc).length) await approvalPolicyDAL.updateById(policy.id, updateDoc, tx);let { step } = current;if (!step) {@@ -333,23 +368,19 @@ export const secretChangePolicyFnsFactory = ({tx);- return {- policy: doc,- envs,- approvals: nextApprovals,- secretPath: nextSecretPath,- allowedSelfApprovals: allowedSelfApprovals ?? current.allowedSelfApprovals- };+ const [row] = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ policyId: policy.id }, tx);+ return toSecretChangePolicy(row);});return {findSecretChangePolicy,findSecretChangePolicyBySecretPath,+ findSecretChangePoliciesByEnvId,+ findSecretChangePoliciesByProjectId,assertNoPolicyForSecretPath,resolveBypassers,resolveApproverUserIds,verifyPolicyActorsMembership,- getSecretChangePolicyState,updatePolicy};};diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.test.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.test.tsindex ba6125b6f2..4084c4c138 100644--- a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.test.ts+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.test.ts@@ -10,6 +10,8 @@ import { ActorType } from "@app/services/auth/auth-type";import { ApproverType, BypasserType } from "../access-approval-policy/access-approval-policy-types";import { ProjectPermissionActions, ProjectPermissionSet, ProjectPermissionSub } from "../permission/project-permission";+import { TSecretChangePolicyRow } from "./secret-change-policy-bridge-dal";+import { toSecretChangePolicy } from "./secret-change-policy-bridge-fns";import { secretChangePolicyBridgeServiceFactory } from "./secret-change-policy-bridge-service";const ORG_ID = "org-1";@@ -18,43 +20,42 @@ const ENV_DEV = { id: "env-dev", name: "Development", slug: "dev", projectId: PRconst ENV_PROD = { id: "env-prod", name: "Production", slug: "prod", projectId: PROJECT_ID };const TX = { isTx: true } as unknown as Knex;-const allowCreate = createMongoAbility<ProjectPermissionSet>(- [{ action: ProjectPermissionActions.Create, subject: ProjectPermissionSub.SecretApproval }],- { conditionsMatcher }-);-const allowEdit = createMongoAbility<ProjectPermissionSet>(- [{ action: ProjectPermissionActions.Edit, subject: ProjectPermissionSub.SecretApproval }],- { conditionsMatcher }-);-const allowDelete = createMongoAbility<ProjectPermissionSet>(- [{ action: ProjectPermissionActions.Delete, subject: ProjectPermissionSub.SecretApproval }],- { conditionsMatcher }-);+const allow = (action: ProjectPermissionActions) =>+ createMongoAbility<ProjectPermissionSet>([{ action, subject: ProjectPermissionSub.SecretApproval }], {+ conditionsMatcher+ });+const allowCreate = allow(ProjectPermissionActions.Create);+const allowEdit = allow(ProjectPermissionActions.Edit);+const allowDelete = allow(ProjectPermissionActions.Delete);+const allowRead = allow(ProjectPermissionActions.Read);const denyAll = createMongoAbility<ProjectPermissionSet>([], { conditionsMatcher });-const POLICY_ROW = {+const toPolicyEnv = (env: typeof ENV_DEV) => ({ id: env.id, name: env.name, slug: env.slug });++const buildRow = (overrides: Partial<TSecretChangePolicyRow> = {}): TSecretChangePolicyRow => ({id: "policy-1",projectId: PROJECT_ID,organizationId: ORG_ID,type: ApprovalPolicyType.SecretChange,name: "dev-policy",- enforcementLevel: EnforcementLevel.Hard,- bypassForMachineIdentities: false,+ isActive: true,+ maxRequestTtl: null,conditions: { version: 1, conditions: [] },constraints: { version: 1, constraints: { allowedSelfApprovals: true } },createdAt: new Date("2026-01-01"),updatedAt: new Date("2026-01-01"),+ bypassForMachineIdentities: false,+ enforcementLevel: EnforcementLevel.Hard,scopeType: null,- scopeId: null-};-const STEP_ROW = { id: "step-1", policyId: "policy-1", stepNumber: 1, requiredApprovals: 1 };-const toEnvRow = (env: typeof ENV_DEV, secretPath = "/") => ({- id: env.id,- name: env.name,- slug: env.slug,- secretPath+ scopeId: null,+ secretPath: "/",+ environments: [toPolicyEnv(ENV_DEV)],+ steps: [{ id: "step-1", stepNumber: 1, requiredApprovals: 1 }],+ approvers: [{ type: ApproverType.User, id: "user-1", username: "[email protected]" }],+ bypassers: [],+ userApprovers: [{ userId: "user-1" }],+ ...overrides});-const toPolicyEnv = (env: typeof ENV_DEV) => ({ id: env.id, name: env.name, slug: env.slug });const ctx = {actor: ActorType.USER,@@ -68,7 +69,7 @@ const ctx = {type TMembership = { effectiveUserIds: string[]; effectiveGroupIds: string[] };type TExistingPolicy = { id: string; environments: { id: string }[] };-type TEnvRow = ReturnType<typeof toEnvRow>;+type TFindFilter = { policyId?: string; projectId?: string; envId?: string; organizationId?: string };// Only the collaborators the service touches; everything else is left undefined so an// unexpected reach shows up as a crash rather than a silent pass.@@ -80,17 +81,15 @@ const buildService = ({existingPolicy = undefined as TExistingPolicy | undefined,existingLegacyPolicy = undefined as TExistingPolicy | undefined,memberships = [{ effectiveUserIds: ["user-1"], effectiveGroupIds: [] }] as TMembership[],- policyRow = undefined as typeof POLICY_ROW | undefined,- envRows = [toEnvRow(ENV_DEV)] as TEnvRow[],- step = STEP_ROW as typeof STEP_ROW | null+ rows = [buildRow()] as TSecretChangePolicyRow[]} = {}) => {const findEffectiveProjectSubjectsMembership = vi.fn();memberships.forEach((membership) => findEffectiveProjectSubjectsMembership.mockResolvedValueOnce(membership));const deps = {approvalPolicyDAL: {- findOne: vi.fn().mockResolvedValue(policyRow),- findByIdForUpdate: vi.fn().mockResolvedValue(policyRow),+ findOne: vi.fn().mockResolvedValue(undefined),+ findByIdForUpdate: vi.fn((id: string) => Promise.resolve(rows.find((row) => row.id === id))),create: vi.fn((row: Record<string, unknown>) =>Promise.resolve({id: "policy-1",@@ -99,33 +98,50 @@ const buildService = ({...row})),- updateById: vi.fn((_id: string, row: Record<string, unknown>) => Promise.resolve({ ...policyRow, ...row })),- deleteById: vi.fn().mockResolvedValue(policyRow),+ updateById: vi.fn((id: string, row: Record<string, unknown>) =>+ Promise.resolve({ ...rows.find((el) => el.id === id), ...row })+ ),+ deleteById: vi.fn((id: string) => Promise.resolve(rows.find((row) => row.id === id))),transaction: vi.fn((cb: (tx: unknown) => unknown) => Promise.resolve(cb(TX)))},approvalPolicyStepsDAL: {create: vi.fn((row: Record<string, unknown>) => Promise.resolve({ id: "step-1", ...row })),- findOne: vi.fn().mockResolvedValue(step ?? undefined),- updateById: vi.fn((_id: string, row: Record<string, unknown>) => Promise.resolve({ ...step, ...row }))+ updateById: vi.fn((id: string, row: Record<string, unknown>) => Promise.resolve({ id, ...row }))},approvalPolicyStepApproversDAL: {- insertMany: vi.fn((rows: unknown[]) => Promise.resolve(rows)),+ insertMany: vi.fn((rows_: unknown[]) => Promise.resolve(rows_)),delete: vi.fn().mockResolvedValue([])},approvalPolicyBypassersDAL: {- insertMany: vi.fn((rows: unknown[]) => Promise.resolve(rows)),+ insertMany: vi.fn((rows_: unknown[]) => Promise.resolve(rows_)),delete: vi.fn().mockResolvedValue([])},approvalPolicySecretEnvironmentDAL: {- insertMany: vi.fn((rows: unknown[]) => Promise.resolve(rows)),+ insertMany: vi.fn((rows_: unknown[]) => Promise.resolve(rows_)),delete: vi.fn().mockResolvedValue([]),- findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(existingPolicy),- findEnvironmentsByPolicyId: vi.fn().mockResolvedValue(envRows)+ findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(existingPolicy)+ },+ secretChangePolicyBridgeDAL: {+ findSecretChangePolicies: vi.fn<(filter: TFindFilter, tx?: Knex) => Promise<TSecretChangePolicyRow[]>>(+ ({ policyId, projectId, envId, organizationId }) =>+ Promise.resolve(+ rows.filter(+ (row) =>+ (!policyId || row.id === policyId) &&+ (!projectId || row.projectId === projectId) &&+ (!organizationId || row.organizationId === organizationId) &&+ (!envId || row.environments.some((env) => env.id === envId))+ )+ )+ )},secretApprovalPolicyDAL: { findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(existingLegacyPolicy) },projectEnvDAL: {find: vi.fn(({ $in }: { $in: { slug: string[] } }) =>Promise.resolve(envs.filter((env) => $in.slug.includes(env.slug)))+ ),+ findOne: vi.fn(({ slug, projectId }: { slug: string; projectId: string }) =>+ Promise.resolve(envs.find((env) => env.slug === slug && env.projectId === projectId)))},projectDAL: { findEffectiveProjectSubjectsMembership },@@ -203,7 +219,10 @@ describe("secretChangePolicyBridge createSecretChangePolicy", () => {});test("skips the approvals count check when a group approver is present", async () => {- const { service } = buildService({ memberships: [{ effectiveUserIds: [], effectiveGroupIds: ["g-1"] }] });+ const { service } = buildService({+ memberships: [{ effectiveUserIds: [], effectiveGroupIds: ["g-1"] }],+ rows: [buildRow({ steps: [{ id: "step-1", stepNumber: 1, requiredApprovals: 5 }] })]+ });await expect(create(service, { approvals: 5, approvers: [{ type: ApproverType.Group, id: "g-1" }] })@@ -384,11 +403,19 @@ describe("secretChangePolicyBridge createSecretChangePolicy", () => {});});- test("returns the legacy secret approval policy shape", async () => {- const { service } = buildService();+ test("returns the policy re-read inside the transaction in the legacy shape", async () => {+ const row = buildRow({+ environments: [toPolicyEnv(ENV_DEV), toPolicyEnv(ENV_PROD)],+ bypassers: [{ type: BypasserType.Group, id: "g-2" }]+ });+ const { service, deps } = buildService({ rows: [row] });const policy = await create(service, { environment: undefined, environments: ["dev", "prod"] });+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).toHaveBeenLastCalledWith(+ { policyId: "policy-1" },+ TX+ );expect(policy).toEqual({id: "policy-1",name: "dev-policy",@@ -402,15 +429,18 @@ describe("secretChangePolicyBridge createSecretChangePolicy", () => {allowedSelfApprovals: true,bypassForMachineIdentities: false,projectId: PROJECT_ID,- environments: [ENV_DEV, ENV_PROD],- environment: ENV_DEV+ environments: [toPolicyEnv(ENV_DEV), toPolicyEnv(ENV_PROD)],+ environment: toPolicyEnv(ENV_DEV),+ approvers: [{ type: ApproverType.User, id: "user-1", username: "[email protected]" }],+ bypassers: [{ type: BypasserType.Group, id: "g-2" }],+ userApprovers: [{ userId: "user-1" }]});});});describe("secretChangePolicyBridge updateSecretChangePolicy", () => {- test("rejects a policy id that does not live on the approval system", async () => {- const { service, deps } = buildService({ permission: allowEdit });+ test("rejects a policy id that does not live on the global approval system", async () => {+ const { service, deps } = buildService({ permission: allowEdit, rows: [] });const result = update(service);await expect(result).rejects.toBeInstanceOf(NotFoundError);@@ -418,19 +448,25 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();});+ test("looks the policy up within the actor's organization", async () => {+ const { service, deps } = buildService({ permission: allowEdit, rows: [buildRow({ organizationId: "org-2" })] });++ await expect(update(service)).rejects.toBeInstanceOf(NotFoundError);+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).toHaveBeenCalledWith({+ policyId: "policy-1",+ organizationId: ORG_ID+ });+ });+test("rejects an actor without edit permission on secret approvals", async () => {- const { service, deps } = buildService({ permission: denyAll, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: denyAll });await expect(update(service)).rejects.toBeInstanceOf(ForbiddenError);expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();});test("rejects when the plan does not include secret approvals", async () => {- const { service, deps } = buildService({- permission: allowEdit,- policyRow: POLICY_ROW,- plan: { secretApproval: false }- });+ const { service, deps } = buildService({ permission: allowEdit, plan: { secretApproval: false } });await expect(update(service)).rejects.toThrow("Failed to update secret approval policy due to plan restriction. Upgrade plan to update secret approval policy."@@ -439,14 +475,14 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {});test("rejects approvals greater than the number of user approvers", async () => {- const { service, deps } = buildService({ permission: allowEdit, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: allowEdit });await expect(update(service, { approvals: 2 })).rejects.toThrow("Approvals cannot be greater than approvers");expectNoWrites(deps);});test("rejects an environment slug that does not exist in the project", async () => {- const { service, deps } = buildService({ permission: allowEdit, policyRow: POLICY_ROW, envs: [ENV_DEV] });+ const { service, deps } = buildService({ permission: allowEdit, envs: [ENV_DEV] });const result = update(service, { environments: ["dev", "staging"] });await expect(result).rejects.toBeInstanceOf(NotFoundError);@@ -455,16 +491,15 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {});test("rejects an empty environment list", async () => {- const { service, deps } = buildService({ permission: allowEdit, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: allowEdit });await expect(update(service, { environments: [] })).rejects.toThrow("At least one environment must be provided");expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();});- test("rejects moving onto a path another approval system policy already governs, excluding itself", async () => {+ test("rejects moving onto a path another global approval system policy already governs, excluding itself", async () => {const { service, deps } = buildService({permission: allowEdit,- policyRow: POLICY_ROW,existingPolicy: { id: "other-policy", environments: [{ id: ENV_DEV.id }] }});@@ -481,7 +516,6 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {test("rejects moving onto a path the legacy secret approval tables already govern", async () => {const { service, deps } = buildService({permission: allowEdit,- policyRow: POLICY_ROW,existingLegacyPolicy: { id: "legacy-policy", environments: [{ id: ENV_PROD.id }] }});@@ -498,7 +532,6 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {test("rejects an approver who is not a project member", async () => {const { service, deps } = buildService({permission: allowEdit,- policyRow: POLICY_ROW,memberships: [{ effectiveUserIds: [], effectiveGroupIds: [] }]});@@ -507,24 +540,30 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {});test("locks the policy row before reading its state and rewriting it", async () => {- const { service, deps } = buildService({ permission: allowEdit, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: allowEdit });await update(service, { secretPath: "/moved" });expect(deps.approvalPolicyDAL.findByIdForUpdate).toHaveBeenCalledWith("policy-1", TX);const lockOrder = deps.approvalPolicyDAL.findByIdForUpdate.mock.invocationCallOrder[0];+ const stateRead = deps.secretChangePolicyBridgeDAL.findSecretChangePolicies.mock.calls.findIndex(+ ([, tx]) => tx === TX+ );+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies.mock.calls[stateRead]).toEqual([+ { policyId: "policy-1" },+ TX+ ]);expect(lockOrder).toBeLessThan(- deps.approvalPolicySecretEnvironmentDAL.findEnvironmentsByPolicyId.mock.invocationCallOrder[0]+ deps.secretChangePolicyBridgeDAL.findSecretChangePolicies.mock.invocationCallOrder[stateRead]);expect(lockOrder).toBeLessThan(deps.approvalPolicySecretEnvironmentDAL.findPolicyByEnvIdAndSecretPath.mock.invocationCallOrder[0]);expect(lockOrder).toBeLessThan(deps.approvalPolicyStepApproversDAL.delete.mock.invocationCallOrder[0]);- expect(deps.approvalPolicySecretEnvironmentDAL.findEnvironmentsByPolicyId).toHaveBeenCalledWith("policy-1", TX);});test("rejects when the policy is deleted between the lookup and the lock", async () => {- const { service, deps } = buildService({ permission: allowEdit, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: allowEdit });deps.approvalPolicyDAL.findByIdForUpdate.mockResolvedValue(undefined);await expect(update(service)).rejects.toBeInstanceOf(NotFoundError);@@ -532,7 +571,7 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {});test("rewrites only approvers and bypassers when no policy field changes", async () => {- const { service, deps } = buildService({ permission: allowEdit, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: allowEdit });const policy = await update(service);@@ -556,14 +595,30 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {});test("rewrites the policy, step, approvers, environments and bypassers in one transaction", async () => {+ const updatedRow = buildRow({+ name: "renamed",+ enforcementLevel: EnforcementLevel.Soft,+ bypassForMachineIdentities: true,+ constraints: { version: 1, constraints: { allowedSelfApprovals: false } },+ secretPath: "/new",+ environments: [toPolicyEnv(ENV_DEV), toPolicyEnv(ENV_PROD)],+ steps: [{ id: "step-1", stepNumber: 1, requiredApprovals: 2 }],+ approvers: [+ { type: ApproverType.User, id: "user-1", username: "[email protected]" },+ { type: ApproverType.User, id: "user-2", username: "[email protected]" },+ { type: ApproverType.Group, id: "g-1" }+ ],+ bypassers: [{ type: BypasserType.User, id: "u-3", username: "[email protected]" }],+ userApprovers: [{ userId: "user-1" }, { userId: "user-2" }, { userId: "user-9" }]+ });const { service, deps } = buildService({permission: allowEdit,- policyRow: POLICY_ROW,users: [{ id: "user-2", username: "[email protected]" }],memberships: [{ effectiveUserIds: ["user-1", "user-2"], effectiveGroupIds: ["g-1"] },{ effectiveUserIds: ["u-3"], effectiveGroupIds: [] }- ]+ ],+ rows: [updatedRow]});const policy = await update(service, {@@ -615,29 +670,17 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {[{ policyId: "policy-1", userId: "u-3", groupId: null }],TX);- expect(policy).toEqual({- id: "policy-1",- name: "renamed",- secretPath: "/new",- approvals: 2,- envId: ENV_DEV.id,- createdAt: new Date("2026-01-01"),- updatedAt: new Date("2026-01-01"),- enforcementLevel: EnforcementLevel.Soft,- deletedAt: null,- allowedSelfApprovals: false,- bypassForMachineIdentities: true,- projectId: PROJECT_ID,- environments: [toPolicyEnv(ENV_DEV), toPolicyEnv(ENV_PROD)],- environment: toPolicyEnv(ENV_DEV)- });+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).toHaveBeenLastCalledWith(+ { policyId: "policy-1" },+ TX+ );+ expect(policy).toEqual(toSecretChangePolicy(updatedRow));});test("rewrites the environment rows with the current environments when only the path changes", async () => {const { service, deps } = buildService({permission: allowEdit,- policyRow: POLICY_ROW,- envRows: [toEnvRow(ENV_DEV), toEnvRow(ENV_PROD)]+ rows: [buildRow({ environments: [toPolicyEnv(ENV_DEV), toPolicyEnv(ENV_PROD)] })]});await update(service, { secretPath: "/moved" });@@ -653,7 +696,7 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {});test("recreates the approval step when the policy has none", async () => {- const { service, deps } = buildService({ permission: allowEdit, policyRow: POLICY_ROW, step: null });+ const { service, deps } = buildService({ permission: allowEdit, rows: [buildRow({ steps: [] })] });await update(service, { approvals: 1 });@@ -666,22 +709,22 @@ describe("secretChangePolicyBridge updateSecretChangePolicy", () => {});describe("secretChangePolicyBridge deleteSecretChangePolicy", () => {- test("rejects a policy id that does not live on the approval system", async () => {- const { service, deps } = buildService({ permission: allowDelete });+ test("rejects a policy id that does not live on the global approval system", async () => {+ const { service, deps } = buildService({ permission: allowDelete, rows: [] });await expect(remove(service)).rejects.toBeInstanceOf(NotFoundError);- expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ expect(deps.approvalPolicyDAL.deleteById).not.toHaveBeenCalled();});test("rejects an actor without delete permission on secret approvals", async () => {- const { service, deps } = buildService({ permission: denyAll, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: denyAll });await expect(remove(service)).rejects.toBeInstanceOf(ForbiddenError);- expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ expect(deps.approvalPolicyDAL.deleteById).not.toHaveBeenCalled();});test("hard-deletes the policy and skips the plan check", async () => {- const { service, deps } = buildService({ permission: allowDelete, policyRow: POLICY_ROW });+ const { service, deps } = buildService({ permission: allowDelete });const policy = await remove(service);@@ -694,8 +737,128 @@ describe("secretChangePolicyBridge deleteSecretChangePolicy", () => {allowedSelfApprovals: true,projectId: PROJECT_ID,environments: [toPolicyEnv(ENV_DEV)],- environment: toPolicyEnv(ENV_DEV)+ environment: toPolicyEnv(ENV_DEV),+ approvers: [{ type: ApproverType.User, id: "user-1", username: "[email protected]" }]});expect(policy.deletedAt).toBeInstanceOf(Date);});});++describe("secretChangePolicyBridge getSecretChangePolicyById", () => {+ const getById = (service: TService) => service.getSecretChangePolicyById({ ...ctx, sapId: "policy-1" });++ test("looks the policy up within the actor's organization and reports a miss as not found", async () => {+ const { service, deps } = buildService({ permission: allowRead, rows: [] });++ const result = getById(service);+ await expect(result).rejects.toBeInstanceOf(NotFoundError);+ await expect(result).rejects.toThrow("Secret approval policy with ID 'policy-1' not found");+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).toHaveBeenCalledWith({+ policyId: "policy-1",+ organizationId: ORG_ID+ });+ expect(deps.permissionService.getProjectPermission).not.toHaveBeenCalled();+ });++ test("rejects an actor without read permission on secret approvals", async () => {+ const { service } = buildService({ permission: denyAll });++ await expect(getById(service)).rejects.toBeInstanceOf(ForbiddenError);+ });++ test("returns the policy in the legacy shape", async () => {+ const row = buildRow();+ const { service, deps } = buildService({ permission: allowRead, rows: [row] });++ await expect(getById(service)).resolves.toEqual(toSecretChangePolicy(row));+ expect(deps.permissionService.getProjectPermission).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: PROJECT_ID })+ );+ });+});++describe("secretChangePolicyBridge getSecretChangePolicyByProjectId", () => {+ const list = (service: TService) => service.getSecretChangePolicyByProjectId({ ...ctx, projectId: PROJECT_ID });++ test("rejects an actor without read permission on secret approvals", async () => {+ const { service, deps } = buildService({ permission: denyAll });++ await expect(list(service)).rejects.toBeInstanceOf(ForbiddenError);+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).not.toHaveBeenCalled();+ });++ test("returns every policy of the project in the legacy shape", async () => {+ const rows = [buildRow(), buildRow({ id: "policy-2", secretPath: "/other" })];+ const { service, deps } = buildService({ permission: allowRead, rows });++ await expect(list(service)).resolves.toEqual(rows.map(toSecretChangePolicy));+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).toHaveBeenCalledWith({ projectId: PROJECT_ID });+ });+});++describe("secretChangePolicyBridge getSecretChangePolicy", () => {+ const globRow = buildRow({ id: "glob", secretPath: "/app/**", createdAt: new Date("2026-01-01") });+ const exactRow = buildRow({ id: "exact", secretPath: "/app/svc", createdAt: new Date("2026-01-02") });++ test("rejects an environment slug that does not exist in the project", async () => {+ const { service, deps } = buildService();++ const result = service.getSecretChangePolicy(PROJECT_ID, "staging", "/app", TX);+ await expect(result).rejects.toBeInstanceOf(NotFoundError);+ await expect(result).rejects.toThrow("Environment with slug 'staging' not found in project with ID project-1");+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).not.toHaveBeenCalled();+ });++ test("threads the transaction through the environment lookup and the policy read", async () => {+ const { service, deps } = buildService({ rows: [globRow] });++ await service.getSecretChangePolicy(PROJECT_ID, "dev", "/app/svc", TX);++ expect(deps.projectEnvDAL.findOne).toHaveBeenCalledWith({ slug: "dev", projectId: PROJECT_ID }, TX);+ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).toHaveBeenCalledWith({ envId: ENV_DEV.id }, TX);+ });++ test("prefers an exact path over a glob and ignores a trailing slash", async () => {+ const { service } = buildService({ rows: [globRow, exactRow] });++ await expect(service.getSecretChangePolicy(PROJECT_ID, "dev", "/app/svc/")).resolves.toMatchObject({+ id: "exact"+ });+ await expect(service.getSecretChangePolicy(PROJECT_ID, "dev", "/app/other")).resolves.toMatchObject({+ id: "glob"+ });+ await expect(service.getSecretChangePolicy(PROJECT_ID, "dev", "/elsewhere")).resolves.toBeUndefined();+ });++ test("returns a policy per governed path when resolving several paths at once", async () => {+ const { service, deps } = buildService({ rows: [globRow, exactRow] });++ const byPath = await service.getSecretChangePolicyByPaths(+ PROJECT_ID,+ "dev",+ ["/app/svc/", "/app/other", "/elsewhere"],+ TX+ );++ expect(deps.secretChangePolicyBridgeDAL.findSecretChangePolicies).toHaveBeenCalledTimes(1);+ expect([...byPath.keys()]).toEqual(["/app/svc/", "/app/other"]);+ expect(byPath.get("/app/svc/")).toMatchObject({ id: "exact" });+ expect(byPath.get("/app/other")).toMatchObject({ id: "glob" });+ });++ test("only requires project membership to read the policy of a folder", async () => {+ const { service, deps } = buildService({ permission: denyAll, rows: [exactRow] });++ await expect(+ service.getSecretChangePolicyOfFolder({+ ...ctx,+ projectId: PROJECT_ID,+ environment: "dev",+ secretPath: "/app/svc"+ })+ ).resolves.toMatchObject({ id: "exact", userApprovers: [{ userId: "user-1" }] });+ expect(deps.permissionService.getProjectPermission).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: PROJECT_ID })+ );+ });+});diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.tsindex edb178a7f6..dca5fb8e66 100644--- a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.ts+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.ts@@ -1,9 +1,11 @@import { ForbiddenError } from "@casl/ability";+import { Knex } from "knex";-import { ActionProjectType, TApprovalPolicies } from "@app/db/schemas";+import { ActionProjectType } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { removeTrailingSlash } from "@app/lib/fn";import {TApprovalPolicyBypassersDALFactory,TApprovalPolicyDALFactory,@@ -17,7 +19,9 @@ import { TUserDALFactory } from "@app/services/user/user-dal";import { TLicenseServiceFactory } from "../license/license-service";import { TSecretApprovalPolicyDALFactory } from "../secret-approval-policy/secret-approval-policy-dal";-import { secretChangePolicyFnsFactory, splitApprovers } from "./secret-change-policy-bridge-fns";+import { resolvePolicyForPath } from "../secret-approval-policy/secret-approval-policy-fns";+import { TSecretChangePolicyBridgeDALFactory } from "./secret-change-policy-bridge-dal";+import { secretChangePolicyFnsFactory, splitApprovers, toSecretChangePolicy } from "./secret-change-policy-bridge-fns";import {TSecretChangePolicy,TSecretChangePolicyBridgeMethods,@@ -30,15 +34,16 @@ type TSecretChangePolicyBridgeServiceFactoryDep = {TApprovalPolicyDALFactory,"findOne" | "findByIdForUpdate" | "create" | "updateById" | "deleteById" | "transaction">;- approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create" | "findOne" | "updateById">;+ approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create" | "updateById">;approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "insertMany" | "delete">;approvalPolicyBypassersDAL: Pick<TApprovalPolicyBypassersDALFactory, "insertMany" | "delete">;approvalPolicySecretEnvironmentDAL: Pick<TApprovalPolicySecretEnvironmentDALFactory,- "insertMany" | "delete" | "findPolicyByEnvIdAndSecretPath" | "findEnvironmentsByPolicyId"+ "insertMany" | "delete" | "findPolicyByEnvIdAndSecretPath">;+ secretChangePolicyBridgeDAL: Pick<TSecretChangePolicyBridgeDALFactory, "findSecretChangePolicies">;secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "findPolicyByEnvIdAndSecretPath">;- projectEnvDAL: Pick<TProjectEnvDALFactory, "find">;+ projectEnvDAL: Pick<TProjectEnvDALFactory, "find" | "findOne">;projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;userDAL: Pick<TUserDALFactory, "find">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;@@ -47,15 +52,13 @@ type TSecretChangePolicyBridgeServiceFactoryDep = {export type TSecretChangePolicyBridgeServiceFactory = ReturnType<typeof secretChangePolicyBridgeServiceFactory>;-const notAvailable = () =>- new BadRequestError({ message: "Secret change policies on the approval system are not available yet." });-export const secretChangePolicyBridgeServiceFactory = ({approvalPolicyDAL,approvalPolicyStepsDAL,approvalPolicyStepApproversDAL,approvalPolicyBypassersDAL,approvalPolicySecretEnvironmentDAL,+ secretChangePolicyBridgeDAL,secretApprovalPolicyDAL,projectEnvDAL,projectDAL,@@ -66,11 +69,12 @@ export const secretChangePolicyBridgeServiceFactory = ({const {findSecretChangePolicy,findSecretChangePolicyBySecretPath,+ findSecretChangePoliciesByEnvId,+ findSecretChangePoliciesByProjectId,assertNoPolicyForSecretPath,resolveBypassers,resolveApproverUserIds,verifyPolicyActorsMembership,- getSecretChangePolicyState,updatePolicy} = secretChangePolicyFnsFactory({approvalPolicyDAL,@@ -78,49 +82,32 @@ export const secretChangePolicyBridgeServiceFactory = ({approvalPolicyStepApproversDAL,approvalPolicyBypassersDAL,approvalPolicySecretEnvironmentDAL,+ secretChangePolicyBridgeDAL,secretApprovalPolicyDAL,projectDAL,userDAL});- const $toSecretChangePolicy = (- policy: TApprovalPolicies,- {- envs,- approvals,- secretPath,- allowedSelfApprovals,- deletedAt = null- }: {- envs: TSecretChangePolicyEnvironment[];- approvals: number;- secretPath: string;- allowedSelfApprovals: boolean;- deletedAt?: Date | null;+ // Scoped to the actor's org so an id from another tenant reads as not found rather than forbidden.+ const $findSecretChangePolicyOrThrow = async (secretPolicyId: string, organizationId: string) => {+ const [row] = await secretChangePolicyBridgeDAL.findSecretChangePolicies({+ policyId: secretPolicyId,+ organizationId+ });+ if (!row) {+ throw new NotFoundError({ message: `Secret approval policy with ID '${secretPolicyId}' not found` });}- ): TSecretChangePolicy => ({- id: policy.id,- name: policy.name,- secretPath,- approvals,- envId: envs[0].id,- createdAt: policy.createdAt,- updatedAt: policy.updatedAt,- enforcementLevel: policy.enforcementLevel,- deletedAt,- allowedSelfApprovals,- bypassForMachineIdentities: policy.bypassForMachineIdentities ?? false,- projectId: policy.projectId,- environments: envs,- environment: envs[0]- });+ return toSecretChangePolicy(row);+ };- const $findSecretChangePolicyOrThrow = async (secretPolicyId: string) => {- const policy = await findSecretChangePolicy(secretPolicyId);- if (!policy) {- throw new NotFoundError({ message: `Secret approval policy with ID '${secretPolicyId}' not found` });+ const $findEnvPolicies = async (projectId: string, environment: string, tx?: Knex) => {+ const env = await projectEnvDAL.findOne({ slug: environment, projectId }, tx);+ if (!env) {+ throw new NotFoundError({+ message: `Environment with slug '${environment}' not found in project with ID ${projectId}`+ });}- return policy;+ return findSecretChangePoliciesByEnvId(env.id, tx);};const createSecretChangePolicy: TSecretChangePolicyBridgeMethods["createSecretChangePolicy"] = async ({@@ -190,7 +177,7 @@ export const secretChangePolicyBridgeServiceFactory = ({projectId});- const policy = await approvalPolicyDAL.transaction(async (tx) => {+ return approvalPolicyDAL.transaction(async (tx) => {const doc = await approvalPolicyDAL.create({projectId,@@ -237,10 +224,9 @@ export const secretChangePolicyBridgeServiceFactory = ({tx);- return doc;+ const [row] = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ policyId: doc.id }, tx);+ return toSecretChangePolicy(row);});-- return $toSecretChangePolicy(policy, { envs, approvals, secretPath, allowedSelfApprovals });};const updateSecretChangePolicy: TSecretChangePolicyBridgeMethods["updateSecretChangePolicy"] = async ({@@ -261,7 +247,7 @@ export const secretChangePolicyBridgeServiceFactory = ({}) => {const { groupApprovers, userApprovers, userApproverNames } = splitApprovers(approvers);- const policy = await $findSecretChangePolicyOrThrow(secretPolicyId);+ const policy = await $findSecretChangePolicyOrThrow(secretPolicyId, actorOrgId);const { permission } = await permissionService.getProjectPermission({actor,@@ -307,7 +293,7 @@ export const secretChangePolicyBridgeServiceFactory = ({projectId: policy.projectId});- const updated = await updatePolicy({+ return updatePolicy({policy,name,approvals,@@ -322,8 +308,6 @@ export const secretChangePolicyBridgeServiceFactory = ({bypasserUserIds,groupBypassers});-- return $toSecretChangePolicy(updated.policy, updated);};const deleteSecretChangePolicy: TSecretChangePolicyBridgeMethods["deleteSecretChangePolicy"] = async ({@@ -333,7 +317,7 @@ export const secretChangePolicyBridgeServiceFactory = ({actorOrgId,actorAuthMethod}) => {- const policy = await $findSecretChangePolicyOrThrow(secretPolicyId);+ const policy = await $findSecretChangePolicyOrThrow(secretPolicyId, actorOrgId);const { permission } = await permissionService.getProjectPermission({actor,@@ -348,45 +332,106 @@ export const secretChangePolicyBridgeServiceFactory = ({ProjectPermissionSub.SecretApproval);- const current = await getSecretChangePolicyState(policy);-// Legacy delete closes the policy's open requests. Secret change requests are not created on the- // approval system yet, so cancelling them moves with the request migration.+ // global approval system yet, so cancelling them moves with the request migration.await approvalPolicyDAL.deleteById(policy.id);- return $toSecretChangePolicy(policy, {- envs: current.envs,- approvals: current.approvals,- secretPath: current.secretPath,- allowedSelfApprovals: current.allowedSelfApprovals,- deletedAt: new Date()- });+ return { ...policy, deletedAt: new Date() };};- const getSecretChangePolicy: TSecretChangePolicyBridgeMethods["getSecretChangePolicy"] = async () => {- throw notAvailable();+ const getSecretChangePolicy: TSecretChangePolicyBridgeMethods["getSecretChangePolicy"] = async (+ projectId,+ environment,+ path,+ tx+ ) => {+ const policies = await $findEnvPolicies(projectId, environment, tx);+ return resolvePolicyForPath(policies, removeTrailingSlash(path));};- const getSecretChangePolicyByPaths: TSecretChangePolicyBridgeMethods["getSecretChangePolicyByPaths"] = async () => {- throw notAvailable();+ const getSecretChangePolicyByPaths: TSecretChangePolicyBridgeMethods["getSecretChangePolicyByPaths"] = async (+ projectId,+ environment,+ secretPaths,+ tx+ ) => {+ const policyByPath = new Map<string, TSecretChangePolicy>();+ const policies = await $findEnvPolicies(projectId, environment, tx);+ if (!policies.length) return policyByPath;++ for (const path of secretPaths) {+ const policy = resolvePolicyForPath(policies, removeTrailingSlash(path));+ if (policy) policyByPath.set(path, policy);+ }+ return policyByPath;};const getSecretChangePolicyByProjectId: TSecretChangePolicyBridgeMethods["getSecretChangePolicyByProjectId"] =- async () => {- throw notAvailable();+ async ({ actor, actorId, actorOrgId, actorAuthMethod, projectId }) => {+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionActions.Read,+ ProjectPermissionSub.SecretApproval+ );++ return findSecretChangePoliciesByProjectId(projectId);};- const getSecretChangePolicyOfFolder: TSecretChangePolicyBridgeMethods["getSecretChangePolicyOfFolder"] = async () => {- throw notAvailable();+ const getSecretChangePolicyOfFolder: TSecretChangePolicyBridgeMethods["getSecretChangePolicyOfFolder"] = async ({+ projectId,+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod,+ environment,+ secretPath+ }) => {+ await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });++ return getSecretChangePolicy(projectId, environment, secretPath);};- const getSecretChangePolicyById: TSecretChangePolicyBridgeMethods["getSecretChangePolicyById"] = async () => {- throw notAvailable();+ const getSecretChangePolicyById: TSecretChangePolicyBridgeMethods["getSecretChangePolicyById"] = async ({+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod,+ sapId+ }) => {+ const policy = await $findSecretChangePolicyOrThrow(sapId, actorOrgId);++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: policy.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.SecretApproval);++ return policy;};return {findSecretChangePolicy,findSecretChangePolicyBySecretPath,+ findSecretChangePoliciesByEnvId,+ findSecretChangePoliciesByProjectId,createSecretChangePolicy,updateSecretChangePolicy,deleteSecretChangePolicy,diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-types.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-types.tsindex 9d9e6ad08b..ccd36c4e4f 100644--- a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-types.ts+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-types.ts@@ -2,6 +2,7 @@ import { Knex } from "knex";import { TProjectEnvironments, TSecretApprovalPolicies } from "@app/db/schemas";+import { ApproverType, BypasserType } from "../access-approval-policy/access-approval-policy-types";import {TCreateSapDTO,TDeleteSapDTO,@@ -13,16 +14,24 @@ import {export type TSecretChangePolicyEnvironment = Pick<TProjectEnvironments, "id" | "name" | "slug">;+export type TSecretChangePolicyApprover = { type: ApproverType; id: string; username?: string | null };+export type TSecretChangePolicyBypasser = { type: BypasserType; id: string; username?: string | null };+export type TSecretChangePolicy = TSecretApprovalPolicies & {projectId: string;environments: TSecretChangePolicyEnvironment[];environment: TSecretChangePolicyEnvironment;+ approvers: TSecretChangePolicyApprover[];+ bypassers: TSecretChangePolicyBypasser[];+ userApprovers: { userId: string }[];};export type TSecretChangePolicyBridgeMethods = {createSecretChangePolicy: (dto: TCreateSapDTO) => Promise<TSecretChangePolicy>;updateSecretChangePolicy: (dto: TUpdateSapDTO) => Promise<TSecretChangePolicy>;deleteSecretChangePolicy: (dto: TDeleteSapDTO) => Promise<TSecretChangePolicy>;+ findSecretChangePoliciesByEnvId: (envId: string, tx?: Knex) => Promise<TSecretChangePolicy[]>;+ findSecretChangePoliciesByProjectId: (projectId: string) => Promise<TSecretChangePolicy[]>;getSecretChangePolicy: (projectId: string,environment: string,diff --git a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-environment-dal.ts b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-environment-dal.tsindex 6aa2479717..94bca1eb6e 100644--- a/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-environment-dal.ts+++ b/backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-environment-dal.ts@@ -12,7 +12,7 @@ export const approvalPolicySecretEnvironmentDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.ApprovalPolicySecretEnvironment);const findPolicyByEnvIdAndSecretPath = async (- { envIds, secretPath }: { envIds: string[]; secretPath: string },+ { envIds, secretPath, excludePolicyId }: { envIds: string[]; secretPath: string; excludePolicyId?: string },tx?: Knex) => {try {@@ -30,6 +30,9 @@ export const approvalPolicySecretEnvironmentDALFactory = (db: TDbClient) => {.where(`${TableName.ApprovalPolicies}.type`, ApprovalPolicyType.SecretChange).whereIn(`${TableName.ApprovalPolicySecretEnvironment}.envId`, envIds).where(`${TableName.ApprovalPolicySecretEnvironment}.secretPath`, secretPath)+ .where((qb) => {+ if (excludePolicyId) void qb.whereNot(`${TableName.ApprovalPolicies}.id`, excludePolicyId);+ }).select(selectAllTableCols(TableName.ApprovalPolicies)).select(db.ref("name").withSchema(TableName.Environment).as("envName")).select(db.ref("slug").withSchema(TableName.Environment).as("envSlug"))@@ -57,26 +60,5 @@ export const approvalPolicySecretEnvironmentDALFactory = (db: TDbClient) => {}};- const findEnvironmentsByPolicyId = async (policyId: string, tx?: Knex) => {- try {- const docs = await (tx || db.replicaNode())(TableName.ApprovalPolicySecretEnvironment)- .join(TableName.Environment, function joinActiveEnvForSecretChangePolicy() {- this.on(`${TableName.ApprovalPolicySecretEnvironment}.envId`, `${TableName.Environment}.id`).andOnNull(- `${TableName.Environment}.deleteAfter`- );- })- .where(`${TableName.ApprovalPolicySecretEnvironment}.policyId`, policyId)- .select(db.ref("id").withSchema(TableName.Environment))- .select(db.ref("name").withSchema(TableName.Environment))- .select(db.ref("slug").withSchema(TableName.Environment))- .select(db.ref("secretPath").withSchema(TableName.ApprovalPolicySecretEnvironment))- .orderBy(`${TableName.Environment}.position`, "asc");-- return docs as { id: string; name: string; slug: string; secretPath: string }[];- } catch (error) {- throw new DatabaseError({ error, name: "findEnvironmentsByPolicyId" });- }- };-- return { ...orm, findPolicyByEnvIdAndSecretPath, findEnvironmentsByPolicyId };+ return { ...orm, findPolicyByEnvIdAndSecretPath };};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 043bf33b82..96458be832 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -201,6 +201,7 @@ import { secretApprovalRequestDALFactory } from "@app/ee/services/secret-approvaimport { secretApprovalRequestReviewerDALFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-reviewer-dal";import { secretApprovalRequestSecretDALFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-secret-dal";import { secretApprovalRequestServiceFactory } from "@app/ee/services/secret-approval-request/secret-approval-request-service";+import { secretChangePolicyBridgeDALFactory } from "@app/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-dal";import { secretChangePolicyBridgeServiceFactory } from "@app/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service";import { approvalPolicySecretEnvironmentDALFactory } from "@app/ee/services/secret-change-policy-bridge/secret-change-policy-environment-dal";import { secretChangeRequestBridgeServiceFactory } from "@app/ee/services/secret-change-request-bridge/secret-change-request-bridge-service";@@ -837,6 +838,7 @@ export const registerRoutes = async (const approvalPolicyStepApproversDAL = approvalPolicyStepApproversDALFactory(db);const approvalPolicyBypassersDAL = approvalPolicyBypassersDALFactory(db);const approvalPolicySecretEnvironmentDAL = approvalPolicySecretEnvironmentDALFactory(db);+ const secretChangePolicyBridgeDAL = secretChangePolicyBridgeDALFactory(db);const roleDAL = roleDALFactory(db);const pkiAlertHistoryDAL = pkiAlertHistoryDALFactory(db);const pkiAlertChannelDAL = pkiAlertChannelDALFactory(db);@@ -1267,6 +1269,7 @@ export const registerRoutes = async (approvalPolicyStepApproversDAL,approvalPolicyBypassersDAL,approvalPolicySecretEnvironmentDAL,+ secretChangePolicyBridgeDAL,secretApprovalPolicyDAL,projectEnvDAL,projectDAL,