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
Merge branch 'main' into feat/adilsitos/secrets-723
adilsonf1ba676ded57
diff --cc backend/src/@types/fastify.d.tsindex 786f9e3c84,a4a231ce2c..b280b2a4b7--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@@ -349,9 -350,10 +351,11 @@@ declare module "fastify"identitySpiffeAuth: TIdentitySpiffeAuthServiceFactory;identityLdapAuth: TIdentityLdapAuthServiceFactory;accessApprovalPolicy: TAccessApprovalPolicyServiceFactory;+ secretAccessApprovalGlobalPolicyBridge: TSecretAccessApprovalGlobalPolicyBridgeServiceFactory;+ secretAccessApprovalGlobalRequestBridge: TSecretAccessApprovalGlobalRequestBridgeServiceFactory;accessApprovalRequest: TAccessApprovalRequestServiceFactory;secretApprovalPolicy: TSecretApprovalPolicyServiceFactory;+ secretChangePolicyBridge: TSecretChangePolicyBridgeServiceFactory;secretApprovalRequest: TSecretApprovalRequestServiceFactory;saml: TSamlConfigServiceFactory;scim: TScimServiceFactory;diff --cc backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-fns.tsindex 392d386b90,0000000000..3a063ea240mode 100644,000000..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@@@ -1,392 -1,0 +1,392 @@@+import { Knex } from "knex";+import { z } from "zod";++import { TApprovalPolicies, TProjectEnvironments } from "@app/db/schemas";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import {+ TApprovalPolicyBypassersDALFactory,+ TApprovalPolicyDALFactory,++ TApprovalPolicySecretEnvironmentDALFactory,+ TApprovalPolicyStepApproversDALFactory,+ TApprovalPolicyStepsDALFactory+} from "@app/services/approval-policy/approval-policy-dal";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import { TProjectDALFactory } from "@app/services/project/project-dal";+import { TUserDALFactory } from "@app/services/user/user-dal";++import { approvalPolicyMembershipVerifierFactory } from "../access-approval-policy/access-approval-policy-fns";+import { 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 { 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, "create" | "updateById">;+ approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "insertMany" | "delete">;+ approvalPolicyBypassersDAL: Pick<TApprovalPolicyBypassersDALFactory, "insertMany" | "delete">;+ approvalPolicySecretEnvironmentDAL: Pick<+ TApprovalPolicySecretEnvironmentDALFactory,- "findPolicyByEnvIdAndSecretPath" | "insertMany" | "delete"++ "findSecretChangePolicyByEnvIdsAndSecretPath" | "insertMany" | "delete"+ >;+ secretChangePolicyBridgeDAL: Pick<TSecretChangePolicyBridgeDALFactory, "findSecretChangePolicies">;+ secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "findPolicyByEnvIdAndSecretPath">;+ projectDAL: Pick<TProjectDALFactory, "findEffectiveProjectSubjectsMembership">;+ userDAL: Pick<TUserDALFactory, "find">;+};++type TUpdatePolicyInput = Pick<+ TUpdateSapDTO,+ "name" | "approvals" | "secretPath" | "enforcementLevel" | "allowedSelfApprovals" | "bypassForMachineIdentities"+> & {+ policy: Pick<TApprovalPolicies, "id">;+ requestedEnvs?: TSecretChangePolicyEnvironment[];+ approverCount: number;+ userApproverIds: string[];+ groupApprovers: string[];+ bypasserUserIds: string[];+ groupBypassers: string[];+};++const SecretChangePolicyConstraintsSchema = z+ .object({+ constraints: z.object({ allowedSelfApprovals: z.boolean().optional() }).passthrough().optional()+ })+ .passthrough();++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)+ .map((approver) => approver.id)+ .filter(Boolean) as string[],+ userApprovers: approvers+ .filter((approver) => approver.type === ApproverType.User)+ .map((approver) => approver.id)+ .filter(Boolean) as string[],+ userApproverNames: approvers+ .map((approver) => (approver.type === ApproverType.User ? approver.username : undefined))+ .filter(Boolean) as string[]+});++export const secretChangePolicyFnsFactory = ({+ approvalPolicyDAL,+ approvalPolicyStepsDAL,+ approvalPolicyStepApproversDAL,+ approvalPolicyBypassersDAL,+ approvalPolicySecretEnvironmentDAL,+ secretChangePolicyBridgeDAL,+ secretApprovalPolicyDAL,+ projectDAL,+ userDAL+}: TSecretChangePolicyFnsFactoryDep) => {+ const { verifyProjectSubjectsMembership } = approvalPolicyMembershipVerifierFactory({ projectDAL });++ const findSecretChangePolicy = (policyId: string, tx?: Knex) =>+ approvalPolicyDAL.findOne({ id: policyId, type: ApprovalPolicyType.SecretChange }, tx);++ const findSecretChangePolicyById = async (policyId: string, tx?: Knex) => {+ const [row] = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ policyId }, tx);+ return row ? toSecretChangePolicy(row) : undefined;+ };++ const findSecretChangePolicyBySecretPath = (+ { envIds, secretPath }: { envIds: string[]; secretPath: string },+ tx?: Knex- ) => approvalPolicySecretEnvironmentDAL.findPolicyByEnvIdAndSecretPath({ envIds, secretPath }, tx);++ ) => approvalPolicySecretEnvironmentDAL.findSecretChangePolicyByEnvIdsAndSecretPath({ envIds, secretPath }, tx);++ 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 (+ {+ envs,+ secretPath,+ excludePolicyId+ }: {+ envs: Pick<TProjectEnvironments, "id" | "slug">[];+ secretPath: string;+ excludePolicyId?: string;+ },+ tx?: Knex+ ) => {+ const envIds = envs.map((env) => env.id);- const secretChangePolicy = await approvalPolicySecretEnvironmentDAL.findPolicyByEnvIdAndSecretPath(++ const secretChangePolicy = await approvalPolicySecretEnvironmentDAL.findSecretChangePolicyByEnvIdsAndSecretPath(+ { envIds, secretPath, excludePolicyId },+ tx+ );+ const legacyPolicy = await secretApprovalPolicyDAL.findPolicyByEnvIdAndSecretPath({ envIds, secretPath }, tx);+ const existingPolicy = secretChangePolicy || legacyPolicy;+ if (!existingPolicy) return;++ const governedEnvIds = new Set(existingPolicy.environments.map((env) => env.id));+ const env = envs.find((el) => governedEnvIds.has(el.id)) ?? envs[0];+ throw new BadRequestError({+ message: `A policy for secret path '${secretPath}' already exists in environment '${env.slug}'`+ });+ };++ const resolveBypassers = async (bypassers: TCreateSapDTO["bypassers"]) => {+ let groupBypassers: string[] = [];+ let bypasserUserIds: string[] = [];++ if (bypassers && bypassers.length) {+ groupBypassers = bypassers+ .filter((bypasser) => bypasser.type === BypasserType.Group)+ .map((bypasser) => bypasser.id) as string[];++ const userBypassers = bypassers+ .filter((bypasser) => bypasser.type === BypasserType.User)+ .map((bypasser) => bypasser.id)+ .filter(Boolean) as string[];++ const userBypasserNames = bypassers+ .map((bypasser) => (bypasser.type === BypasserType.User ? bypasser.username : undefined))+ .filter(Boolean) as string[];++ bypasserUserIds = userBypassers;+ if (userBypasserNames.length) {+ const bypasserUsers = await userDAL.find({+ $in: {+ username: userBypasserNames+ }+ });++ const bypasserNamesFromDb = bypasserUsers.map((user) => user.username);+ const invalidUsernames = userBypasserNames.filter((username) => !bypasserNamesFromDb.includes(username));++ if (invalidUsernames.length) {+ throw new BadRequestError({+ message: `Invalid bypasser user: ${invalidUsernames.join(", ")}`+ });+ }++ bypasserUserIds = bypasserUserIds.concat(bypasserUsers.map((user) => user.id));+ }+ }++ return { bypasserUserIds, groupBypassers };+ };++ const resolveApproverUserIds = async ({+ userApprovers,+ userApproverNames+ }: {+ userApprovers: string[];+ userApproverNames: string[];+ }) => {+ if (!userApproverNames.length) return userApprovers;++ const approverUsers = await userDAL.find({+ $in: {+ username: userApproverNames+ }+ });++ const approverNamesFromDb = approverUsers.map((user) => user.username);+ const invalidUsernames = userApproverNames.filter((username) => !approverNamesFromDb.includes(username));++ if (invalidUsernames.length) {+ throw new BadRequestError({+ message: `Invalid approver user: ${invalidUsernames.join(", ")}`+ });+ }++ return userApprovers.concat(approverUsers.map((user) => user.id));+ };++ const verifyPolicyActorsMembership = async ({+ userApproverIds,+ groupApprovers,+ bypasserUserIds,+ groupBypassers,+ orgId,+ projectId+ }: {+ userApproverIds: string[];+ groupApprovers: string[];+ bypasserUserIds: string[];+ groupBypassers: string[];+ orgId: string;+ projectId: string;+ }) => {+ await verifyProjectSubjectsMembership({+ userIds: userApproverIds,+ groupIds: groupApprovers,+ orgId,+ projectId+ });++ if (bypasserUserIds.length) {+ await verifyProjectSubjectsMembership({+ userIds: bypasserUserIds,+ groupIds: [],+ orgId,+ projectId+ });+ }++ if (groupBypassers.length) {+ await verifyProjectSubjectsMembership({+ userIds: [],+ groupIds: groupBypassers,+ orgId,+ projectId+ });+ }+ };++ 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 '${policyId}' no longer governs any environment`+ });+ }++ const policy = toSecretChangePolicy(row);+ return {+ step: row.steps[0],+ envs: row.environments,+ secretPath: policy.secretPath,+ approvals: policy.approvals+ };+ };++ const updatePolicy = ({+ policy,+ name,+ approvals,+ secretPath,+ enforcementLevel,+ allowedSelfApprovals,+ bypassForMachineIdentities,+ requestedEnvs,+ approverCount,+ userApproverIds,+ groupApprovers,+ bypasserUserIds,+ groupBypassers+ }: TUpdatePolicyInput) =>+ approvalPolicyDAL.transaction(async (tx) => {+ // Lock the policy row so concurrent updates serialize; the collision check and the+ // delete-then-insert rewrites below are only safe against the state read under that lock.+ const lockedPolicy = await approvalPolicyDAL.findByIdForUpdate(policy.id, tx);+ if (!lockedPolicy) {+ throw new NotFoundError({ message: `Secret approval policy with ID '${policy.id}' not found` });+ }+ const current = await getSecretChangePolicyState(policy.id, tx);++ const nextApprovals = approvals ?? current.approvals;+ if (!groupApprovers.length && nextApprovals > approverCount)+ throw new BadRequestError({ message: "Approvals cannot be greater than approvers" });++ const envs = requestedEnvs ?? current.envs;+ const nextSecretPath = secretPath ?? current.secretPath;+ await assertNoPolicyForSecretPath({ envs, secretPath: nextSecretPath, excludePolicyId: policy.id }, tx);++ const updateDoc: Parameters<typeof approvalPolicyDAL.updateById>[1] = {};+ if (name !== undefined) updateDoc.name = name;+ if (enforcementLevel !== undefined) updateDoc.enforcementLevel = enforcementLevel;+ if (bypassForMachineIdentities !== undefined) updateDoc.bypassForMachineIdentities = bypassForMachineIdentities;+ if (allowedSelfApprovals !== undefined) {+ updateDoc.constraints = {+ version: 1,+ constraints: { ...readSecretChangePolicyConstraints(lockedPolicy.constraints), allowedSelfApprovals }+ };+ }+ if (Object.keys(updateDoc).length) await approvalPolicyDAL.updateById(policy.id, updateDoc, tx);++ let { step } = current;+ if (!step) {+ step = await approvalPolicyStepsDAL.create(+ { policyId: policy.id, stepNumber: 1, requiredApprovals: nextApprovals },+ tx+ );+ } else if (approvals !== undefined) {+ step = await approvalPolicyStepsDAL.updateById(step.id, { requiredApprovals: approvals }, tx);+ }++ await approvalPolicyStepApproversDAL.delete({ policyStepId: step.id }, tx);+ await approvalPolicyStepApproversDAL.insertMany(+ [+ ...userApproverIds.map((userId) => ({ policyStepId: step.id, userId, groupId: null })),+ ...groupApprovers.map((groupId) => ({ policyStepId: step.id, userId: null, groupId }))+ ],+ tx+ );++ if (requestedEnvs || secretPath !== undefined) {+ await approvalPolicySecretEnvironmentDAL.delete({ policyId: policy.id }, tx);+ await approvalPolicySecretEnvironmentDAL.insertMany(+ envs.map((env) => ({ policyId: policy.id, envId: env.id, secretPath: nextSecretPath })),+ tx+ );+ }++ await approvalPolicyBypassersDAL.delete({ policyId: policy.id }, tx);+ await approvalPolicyBypassersDAL.insertMany(+ [+ ...bypasserUserIds.map((userId) => ({ policyId: policy.id, userId, groupId: null })),+ ...groupBypassers.map((groupId) => ({ policyId: policy.id, userId: null, groupId }))+ ],+ tx+ );++ const [row] = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ policyId: policy.id }, tx);+ return toSecretChangePolicy(row);+ });++ return {+ findSecretChangePolicy,+ findSecretChangePolicyById,+ findSecretChangePolicyBySecretPath,+ findSecretChangePoliciesByEnvId,+ findSecretChangePoliciesByProjectId,+ assertNoPolicyForSecretPath,+ resolveBypassers,+ resolveApproverUserIds,+ verifyPolicyActorsMembership,+ updatePolicy+ };+};diff --cc backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.test.tsindex df60b27cb2,0000000000..b39f669dcbmode 100644,000000..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@@@ -1,821 -1,0 +1,821 @@@+import { createMongoAbility, ForbiddenError } from "@casl/ability";+import { Knex } from "knex";+import { describe, expect, test, vi } from "vitest";++import { ProjectVersion } from "@app/db/schemas";+import { conditionsMatcher } from "@app/lib/casl";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { EnforcementLevel } from "@app/lib/types";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+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 { RequestState } from "../secret-approval-request/secret-approval-request-types";+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";+const PROJECT_ID = "project-1";+const ENV_DEV = { id: "env-dev", name: "Development", slug: "dev", projectId: PROJECT_ID };+const ENV_PROD = { id: "env-prod", name: "Production", slug: "prod", projectId: PROJECT_ID };+const TX = { isTx: true } as unknown as Knex;++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 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",+ 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,+ 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 ctx = {+ actor: ActorType.USER,+ actorId: "actor-1",+ actorOrgId: ORG_ID,+ actorAuthMethod: null+} as unknown as Pick<+ Parameters<ReturnType<typeof secretChangePolicyBridgeServiceFactory>["createSecretChangePolicy"]>[0],+ "actor" | "actorId" | "actorOrgId" | "actorAuthMethod"+>;++type TMembership = { effectiveUserIds: string[]; effectiveGroupIds: string[] };+type TExistingPolicy = { id: string; environments: { id: string }[] };+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.+const buildService = ({+ permission = allowCreate,+ plan = { secretApproval: true },+ project = { id: PROJECT_ID, version: ProjectVersion.V3 } as { id: string; version: ProjectVersion } | null,+ envs = [ENV_DEV, ENV_PROD],+ users = [] as { id: string; username: string }[],+ existingPolicy = undefined as TExistingPolicy | undefined,+ existingLegacyPolicy = undefined as TExistingPolicy | undefined,+ memberships = [{ effectiveUserIds: ["user-1"], effectiveGroupIds: [] }] as TMembership[],+ rows = [buildRow()] as TSecretChangePolicyRow[]+} = {}) => {+ const findEffectiveProjectSubjectsMembership = vi.fn();+ memberships.forEach((membership) => findEffectiveProjectSubjectsMembership.mockResolvedValueOnce(membership));++ const deps = {+ approvalPolicyDAL: {+ 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",+ createdAt: new Date("2026-01-01"),+ updatedAt: new Date("2026-01-01"),+ ...row+ })+ ),+ 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 })),+ updateById: vi.fn((id: string, row: Record<string, unknown>) => Promise.resolve({ id, ...row }))+ },+ approvalPolicyStepApproversDAL: {+ insertMany: vi.fn((rows_: unknown[]) => Promise.resolve(rows_)),+ delete: vi.fn().mockResolvedValue([])+ },+ approvalPolicyBypassersDAL: {+ insertMany: vi.fn((rows_: unknown[]) => Promise.resolve(rows_)),+ delete: vi.fn().mockResolvedValue([])+ },+ approvalPolicySecretEnvironmentDAL: {+ insertMany: vi.fn((rows_: unknown[]) => Promise.resolve(rows_)),+ delete: vi.fn().mockResolvedValue([]),- findPolicyByEnvIdAndSecretPath: vi.fn().mockResolvedValue(existingPolicy)++ findSecretChangePolicyByEnvIdsAndSecretPath: vi.fn().mockResolvedValue(existingPolicy)+ },+ approvalRequestDAL: { update: vi.fn().mockResolvedValue([]) },+ 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)))+ )+ },+ projectDAL: { findById: vi.fn().mockResolvedValue(project), findEffectiveProjectSubjectsMembership },+ userDAL: {+ find: vi.fn(({ $in }: { $in: { username: string[] } }) =>+ Promise.resolve(users.filter((user) => $in.username.includes(user.username)))+ )+ },+ permissionService: { getProjectPermission: vi.fn().mockResolvedValue({ permission }) },+ licenseService: { getPlan: vi.fn().mockResolvedValue(plan) }+ };++ const service = secretChangePolicyBridgeServiceFactory(+ deps as unknown as Parameters<typeof secretChangePolicyBridgeServiceFactory>[0]+ );+ return { service, deps };+};++type TService = ReturnType<typeof buildService>["service"];+type TCreateInput = Parameters<TService["createSecretChangePolicy"]>[0];+type TUpdateInput = Parameters<TService["updateSecretChangePolicy"]>[0];++const update = (service: TService, overrides: Partial<TUpdateInput> = {}) =>+ service.updateSecretChangePolicy({+ ...ctx,+ secretPolicyId: "policy-1",+ approvers: [{ type: ApproverType.User, id: "user-1" }],+ ...overrides+ });++const remove = (service: TService) => service.deleteSecretChangePolicy({ ...ctx, secretPolicyId: "policy-1" });++const expectNoWrites = (deps: ReturnType<typeof buildService>["deps"]) => {+ expect(deps.approvalPolicyDAL.updateById).not.toHaveBeenCalled();+ expect(deps.approvalPolicyStepsDAL.updateById).not.toHaveBeenCalled();+ expect(deps.approvalPolicyStepApproversDAL.delete).not.toHaveBeenCalled();+ expect(deps.approvalPolicySecretEnvironmentDAL.delete).not.toHaveBeenCalled();+ expect(deps.approvalPolicyBypassersDAL.delete).not.toHaveBeenCalled();+};++const create = (service: TService, overrides: Partial<TCreateInput> = {}) =>+ service.createSecretChangePolicy({+ ...ctx,+ projectId: PROJECT_ID,+ name: "dev-policy",+ approvals: 1,+ approvers: [{ type: ApproverType.User, id: "user-1" }],+ secretPath: "/",+ environment: "dev",+ enforcementLevel: EnforcementLevel.Hard,+ allowedSelfApprovals: true,+ bypassForMachineIdentities: false,+ ...overrides+ });++describe("secretChangePolicyBridge findSecretChangePolicy", () => {+ test("only matches policies of the secret-change type", async () => {+ const { service, deps } = buildService();++ await service.findSecretChangePolicy("policy-1", TX);++ expect(deps.approvalPolicyDAL.findOne).toHaveBeenCalledWith(+ { id: "policy-1", type: ApprovalPolicyType.SecretChange },+ TX+ );+ });+});++describe("secretChangePolicyBridge createSecretChangePolicy", () => {+ test("rejects approvals greater than the number of user approvers", async () => {+ const { service, deps } = buildService();++ await expect(create(service, { approvals: 2 })).rejects.toThrow("Approvals cannot be greater than approvers");+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("skips the approvals count check when a group approver is present", async () => {+ 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" }] })+ ).resolves.toMatchObject({ approvals: 5 });+ });++ test("rejects an actor without create permission on secret approvals", async () => {+ const { service, deps } = buildService({ permission: denyAll });++ await expect(create(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({ plan: { secretApproval: false } });++ await expect(create(service)).rejects.toThrow("plan restriction");+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("rejects a project that has not been upgraded to the latest secrets version", async () => {+ const { service, deps } = buildService({ project: { id: PROJECT_ID, version: ProjectVersion.V2 } });++ const result = create(service);+ await expect(result).rejects.toBeInstanceOf(BadRequestError);+ await expect(result).rejects.toThrow("upgraded to the latest secrets version");+ expect(deps.projectDAL.findById).toHaveBeenCalledWith(PROJECT_ID);+ expect(deps.licenseService.getPlan).not.toHaveBeenCalled();+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("reports a missing project as not found", async () => {+ const { service, deps } = buildService({ project: null });++ const result = create(service);+ await expect(result).rejects.toBeInstanceOf(NotFoundError);+ await expect(result).rejects.toThrow(`Project with ID '${PROJECT_ID}' not found`);+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("rejects when no environment is provided", async () => {+ const { service } = buildService();++ await expect(create(service, { environment: undefined, environments: [] })).rejects.toThrow(+ "Must provide either environment or environments"+ );+ });++ test("rejects an environment slug that does not exist in the project", async () => {+ const { service } = buildService({ envs: [ENV_DEV] });++ const result = create(service, { environment: undefined, environments: ["dev", "prod"] });+ await expect(result).rejects.toBeInstanceOf(NotFoundError);+ await expect(result).rejects.toThrow("One or more environments not found: prod");+ });++ test("rejects a second policy on the same secret path and environment", async () => {+ const { service, deps } = buildService({+ existingPolicy: { id: "other-policy", environments: [{ id: ENV_DEV.id }] }+ });++ await expect(create(service)).rejects.toThrow("A policy for secret path '/' already exists in environment 'dev'");- expect(deps.approvalPolicySecretEnvironmentDAL.findPolicyByEnvIdAndSecretPath).toHaveBeenCalledWith(++ expect(deps.approvalPolicySecretEnvironmentDAL.findSecretChangePolicyByEnvIdsAndSecretPath).toHaveBeenCalledWith(+ { envIds: [ENV_DEV.id], secretPath: "/" },+ undefined+ );+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("rejects a second policy when the legacy secret approval tables already govern the path", async () => {+ const { service, deps } = buildService({+ existingLegacyPolicy: { id: "legacy-policy", environments: [{ id: ENV_DEV.id }] }+ });++ await expect(create(service)).rejects.toThrow("A policy for secret path '/' already exists in environment 'dev'");+ expect(deps.secretApprovalPolicyDAL.findPolicyByEnvIdAndSecretPath).toHaveBeenCalledWith(+ { envIds: [ENV_DEV.id], secretPath: "/" },+ undefined+ );+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("rejects a bypasser username that matches no user", async () => {+ const { service } = buildService();++ await expect(+ create(service, { bypassers: [{ type: BypasserType.User, username: "[email protected]" }] })+ ).rejects.toThrow("Invalid bypasser user: [email protected]");+ });++ test("rejects an approver username that matches no user", async () => {+ const { service } = buildService();++ await expect(+ create(service, { approvers: [{ type: ApproverType.User, username: "[email protected]" }] })+ ).rejects.toThrow("Invalid approver user: [email protected]");+ });++ test("rejects an approver who is not a project member", async () => {+ const { service, deps } = buildService({ memberships: [{ effectiveUserIds: [], effectiveGroupIds: [] }] });++ await expect(create(service)).rejects.toThrow("Some users are not members of the project: user-1");+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("rejects an approver group that is not a project member", async () => {+ const { service } = buildService({ memberships: [{ effectiveUserIds: [], effectiveGroupIds: [] }] });++ await expect(create(service, { approvers: [{ type: ApproverType.Group, id: "g-1" }] })).rejects.toThrow(+ "Some groups are not members of the project: g-1"+ );+ });++ test("rejects a bypasser who is not a project member", async () => {+ const { service, deps } = buildService({+ memberships: [+ { effectiveUserIds: ["user-1"], effectiveGroupIds: [] },+ { effectiveUserIds: [], effectiveGroupIds: [] }+ ]+ });++ await expect(create(service, { bypassers: [{ type: BypasserType.User, id: "u-3" }] })).rejects.toThrow(+ "Some users are not members of the project: u-3"+ );+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("writes the policy, one step, approvers, bypassers and environment rows in one transaction", async () => {+ const { service, deps } = buildService({+ users: [{ id: "user-2", username: "[email protected]" }],+ memberships: [+ { effectiveUserIds: ["user-1", "user-2"], effectiveGroupIds: ["g-1"] },+ { effectiveUserIds: ["u-3"], effectiveGroupIds: [] },+ { effectiveUserIds: [], effectiveGroupIds: ["g-2"] }+ ]+ });++ await create(service, {+ environment: undefined,+ environments: ["dev", "prod"],+ approvers: [+ { type: ApproverType.User, id: "user-1" },+ { type: ApproverType.User, username: "[email protected]" },+ { type: ApproverType.Group, id: "g-1" }+ ],+ bypassers: [+ { type: BypasserType.User, id: "u-3" },+ { type: BypasserType.Group, id: "g-2" }+ ]+ });++ expect(deps.approvalPolicyDAL.create).toHaveBeenCalledWith(+ {+ projectId: PROJECT_ID,+ organizationId: ORG_ID,+ type: ApprovalPolicyType.SecretChange,+ name: "dev-policy",+ enforcementLevel: EnforcementLevel.Hard,+ bypassForMachineIdentities: false,+ conditions: { version: 1, conditions: [] },+ constraints: { version: 1, constraints: { allowedSelfApprovals: true } },+ scopeType: null,+ scopeId: null+ },+ TX+ );+ expect(deps.approvalPolicyStepsDAL.create).toHaveBeenCalledWith(+ { policyId: "policy-1", stepNumber: 1, requiredApprovals: 1 },+ TX+ );+ expect(deps.approvalPolicyStepApproversDAL.insertMany).toHaveBeenCalledWith(+ [+ { policyStepId: "step-1", userId: "user-1", groupId: null },+ { policyStepId: "step-1", userId: "user-2", groupId: null },+ { policyStepId: "step-1", userId: null, groupId: "g-1" }+ ],+ TX+ );+ expect(deps.approvalPolicyBypassersDAL.insertMany).toHaveBeenCalledWith(+ [+ { policyId: "policy-1", userId: "u-3", groupId: null },+ { policyId: "policy-1", userId: null, groupId: "g-2" }+ ],+ TX+ );+ expect(deps.approvalPolicySecretEnvironmentDAL.insertMany).toHaveBeenCalledWith(+ [+ { policyId: "policy-1", envId: ENV_DEV.id, secretPath: "/" },+ { policyId: "policy-1", envId: ENV_PROD.id, secretPath: "/" }+ ],+ TX+ );+ expect(deps.projectDAL.findEffectiveProjectSubjectsMembership).toHaveBeenNthCalledWith(1, {+ orgId: ORG_ID,+ projectId: PROJECT_ID,+ userIds: ["user-1", "user-2"],+ groupIds: ["g-1"]+ });+ });++ 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",+ secretPath: "/",+ approvals: 1,+ envId: ENV_DEV.id,+ createdAt: new Date("2026-01-01"),+ updatedAt: new Date("2026-01-01"),+ enforcementLevel: EnforcementLevel.Hard,+ deletedAt: null,+ allowedSelfApprovals: true,+ bypassForMachineIdentities: false,+ projectId: PROJECT_ID,+ 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 global approval system", async () => {+ const { service, deps } = buildService({ permission: allowEdit, rows: [] });++ const result = update(service);+ await expect(result).rejects.toBeInstanceOf(NotFoundError);+ await expect(result).rejects.toThrow("Secret approval policy with ID 'policy-1' not found");+ 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 });++ 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, 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."+ );+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("rejects approvals greater than the number of user approvers", async () => {+ 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, envs: [ENV_DEV] });++ const result = update(service, { environments: ["dev", "staging"] });+ await expect(result).rejects.toBeInstanceOf(NotFoundError);+ await expect(result).rejects.toThrow("One or more environments not found: staging");+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("rejects an empty environment list", async () => {+ 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 global approval system policy already governs, excluding itself", async () => {+ const { service, deps } = buildService({+ permission: allowEdit,+ existingPolicy: { id: "other-policy", environments: [{ id: ENV_DEV.id }] }+ });++ await expect(update(service, { secretPath: "/shared" })).rejects.toThrow(+ "A policy for secret path '/shared' already exists in environment 'dev'"+ );- expect(deps.approvalPolicySecretEnvironmentDAL.findPolicyByEnvIdAndSecretPath).toHaveBeenCalledWith(++ expect(deps.approvalPolicySecretEnvironmentDAL.findSecretChangePolicyByEnvIdsAndSecretPath).toHaveBeenCalledWith(+ { envIds: [ENV_DEV.id], secretPath: "/shared", excludePolicyId: "policy-1" },+ TX+ );+ expectNoWrites(deps);+ });++ test("rejects moving onto a path the legacy secret approval tables already govern", async () => {+ const { service, deps } = buildService({+ permission: allowEdit,+ existingLegacyPolicy: { id: "legacy-policy", environments: [{ id: ENV_PROD.id }] }+ });++ await expect(update(service, { environments: ["dev", "prod"] })).rejects.toThrow(+ "A policy for secret path '/' already exists in environment 'prod'"+ );+ expect(deps.secretApprovalPolicyDAL.findPolicyByEnvIdAndSecretPath).toHaveBeenCalledWith(+ { envIds: [ENV_DEV.id, ENV_PROD.id], secretPath: "/" },+ TX+ );+ expectNoWrites(deps);+ });++ test("rejects an approver who is not a project member", async () => {+ const { service, deps } = buildService({+ permission: allowEdit,+ memberships: [{ effectiveUserIds: [], effectiveGroupIds: [] }]+ });++ await expect(update(service)).rejects.toThrow("Some users are not members of the project: user-1");+ expect(deps.approvalPolicyDAL.transaction).not.toHaveBeenCalled();+ });++ test("locks the policy row before reading its state and rewriting it", async () => {+ 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.secretChangePolicyBridgeDAL.findSecretChangePolicies.mock.invocationCallOrder[stateRead]+ );+ expect(lockOrder).toBeLessThan(- deps.approvalPolicySecretEnvironmentDAL.findPolicyByEnvIdAndSecretPath.mock.invocationCallOrder[0]++ deps.approvalPolicySecretEnvironmentDAL.findSecretChangePolicyByEnvIdsAndSecretPath.mock.invocationCallOrder[0]+ );+ expect(lockOrder).toBeLessThan(deps.approvalPolicyStepApproversDAL.delete.mock.invocationCallOrder[0]);+ });++ test("rejects when the policy is deleted between the lookup and the lock", async () => {+ const { service, deps } = buildService({ permission: allowEdit });+ deps.approvalPolicyDAL.findByIdForUpdate.mockResolvedValue(undefined);++ await expect(update(service)).rejects.toBeInstanceOf(NotFoundError);+ expectNoWrites(deps);+ });++ test("rewrites only approvers and bypassers when no policy field changes", async () => {+ const { service, deps } = buildService({ permission: allowEdit });++ const policy = await update(service);++ expect(deps.approvalPolicyDAL.updateById).not.toHaveBeenCalled();+ expect(deps.approvalPolicyStepsDAL.updateById).not.toHaveBeenCalled();+ expect(deps.approvalPolicySecretEnvironmentDAL.delete).not.toHaveBeenCalled();+ expect(deps.approvalPolicySecretEnvironmentDAL.insertMany).not.toHaveBeenCalled();+ expect(deps.approvalPolicyStepApproversDAL.delete).toHaveBeenCalledWith({ policyStepId: "step-1" }, TX);+ expect(deps.approvalPolicyStepApproversDAL.insertMany).toHaveBeenCalledWith(+ [{ policyStepId: "step-1", userId: "user-1", groupId: null }],+ TX+ );+ expect(deps.approvalPolicyBypassersDAL.delete).toHaveBeenCalledWith({ policyId: "policy-1" }, TX);+ expect(deps.approvalPolicyBypassersDAL.insertMany).toHaveBeenCalledWith([], TX);+ expect(policy).toMatchObject({+ id: "policy-1",+ secretPath: "/",+ approvals: 1,+ environments: [toPolicyEnv(ENV_DEV)]+ });+ });++ 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,+ 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, {+ name: "renamed",+ approvals: 2,+ enforcementLevel: EnforcementLevel.Soft,+ allowedSelfApprovals: false,+ bypassForMachineIdentities: true,+ secretPath: "/new",+ environments: ["dev", "prod"],+ approvers: [+ { type: ApproverType.User, id: "user-1" },+ { type: ApproverType.User, username: "[email protected]" },+ { type: ApproverType.Group, id: "g-1" }+ ],+ bypassers: [{ type: BypasserType.User, id: "u-3" }]+ });++ expect(deps.approvalPolicyDAL.updateById).toHaveBeenCalledWith(+ "policy-1",+ {+ name: "renamed",+ enforcementLevel: EnforcementLevel.Soft,+ bypassForMachineIdentities: true,+ constraints: { version: 1, constraints: { allowedSelfApprovals: false } }+ },+ TX+ );+ expect(deps.approvalPolicyStepsDAL.updateById).toHaveBeenCalledWith("step-1", { requiredApprovals: 2 }, TX);+ expect(deps.approvalPolicyStepApproversDAL.delete).toHaveBeenCalledWith({ policyStepId: "step-1" }, TX);+ expect(deps.approvalPolicyStepApproversDAL.insertMany).toHaveBeenCalledWith(+ [+ { policyStepId: "step-1", userId: "user-1", groupId: null },+ { policyStepId: "step-1", userId: "user-2", groupId: null },+ { policyStepId: "step-1", userId: null, groupId: "g-1" }+ ],+ TX+ );+ expect(deps.approvalPolicySecretEnvironmentDAL.delete).toHaveBeenCalledWith({ policyId: "policy-1" }, TX);+ expect(deps.approvalPolicySecretEnvironmentDAL.insertMany).toHaveBeenCalledWith(+ [+ { policyId: "policy-1", envId: ENV_DEV.id, secretPath: "/new" },+ { policyId: "policy-1", envId: ENV_PROD.id, secretPath: "/new" }+ ],+ TX+ );+ expect(deps.approvalPolicyBypassersDAL.delete).toHaveBeenCalledWith({ policyId: "policy-1" }, TX);+ expect(deps.approvalPolicyBypassersDAL.insertMany).toHaveBeenCalledWith(+ [{ policyId: "policy-1", userId: "u-3", groupId: null }],+ TX+ );+ 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,+ rows: [buildRow({ environments: [toPolicyEnv(ENV_DEV), toPolicyEnv(ENV_PROD)] })]+ });++ await update(service, { secretPath: "/moved" });++ expect(deps.projectEnvDAL.find).not.toHaveBeenCalled();+ expect(deps.approvalPolicySecretEnvironmentDAL.insertMany).toHaveBeenCalledWith(+ [+ { policyId: "policy-1", envId: ENV_DEV.id, secretPath: "/moved" },+ { policyId: "policy-1", envId: ENV_PROD.id, secretPath: "/moved" }+ ],+ TX+ );+ });++ test("recreates the approval step when the policy has none", async () => {+ const { service, deps } = buildService({ permission: allowEdit, rows: [buildRow({ steps: [] })] });++ await update(service, { approvals: 1 });++ expect(deps.approvalPolicyStepsDAL.create).toHaveBeenCalledWith(+ { policyId: "policy-1", stepNumber: 1, requiredApprovals: 1 },+ TX+ );+ expect(deps.approvalPolicyStepsDAL.updateById).not.toHaveBeenCalled();+ });+});++describe("secretChangePolicyBridge deleteSecretChangePolicy", () => {+ 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.approvalRequestDAL.update).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 });++ await expect(remove(service)).rejects.toBeInstanceOf(ForbiddenError);+ expect(deps.approvalRequestDAL.update).not.toHaveBeenCalled();+ expect(deps.approvalPolicyDAL.deleteById).not.toHaveBeenCalled();+ });++ test("reports a policy deleted before the lock was taken as not found and writes nothing", async () => {+ const { service, deps } = buildService({ permission: allowDelete });+ deps.approvalPolicyDAL.findByIdForUpdate.mockResolvedValueOnce(undefined);++ await expect(remove(service)).rejects.toBeInstanceOf(NotFoundError);+ expect(deps.approvalRequestDAL.update).not.toHaveBeenCalled();+ expect(deps.approvalPolicyDAL.deleteById).not.toHaveBeenCalled();+ });++ test("locks the policy, closes its open requests and hard-deletes it in one transaction, skipping the plan check", async () => {+ const { service, deps } = buildService({ permission: allowDelete });++ const policy = await remove(service);++ expect(deps.licenseService.getPlan).not.toHaveBeenCalled();+ expect(deps.approvalPolicyDAL.findByIdForUpdate).toHaveBeenCalledWith("policy-1", TX);+ expect(deps.approvalRequestDAL.update).toHaveBeenCalledWith(+ { policyId: "policy-1", status: RequestState.Open },+ { status: RequestState.Closed },+ TX+ );+ expect(deps.approvalPolicyDAL.deleteById).toHaveBeenCalledWith("policy-1", TX);+ const [lockOrder] = deps.approvalPolicyDAL.findByIdForUpdate.mock.invocationCallOrder;+ const [closeOrder] = deps.approvalRequestDAL.update.mock.invocationCallOrder;+ const [deleteOrder] = deps.approvalPolicyDAL.deleteById.mock.invocationCallOrder;+ expect(lockOrder).toBeLessThan(closeOrder);+ expect(closeOrder).toBeLessThan(deleteOrder);+ expect(policy).toMatchObject({+ id: "policy-1",+ secretPath: "/",+ approvals: 1,+ allowedSelfApprovals: true,+ projectId: PROJECT_ID,+ environments: [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 })+ );+ });+});diff --cc backend/src/ee/services/secret-change-policy-bridge/secret-change-policy-bridge-service.tsindex 28050ded87,0000000000..ef27ab3666mode 100644,000000..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,383 -1,0 +1,383 @@@+import { ForbiddenError } from "@casl/ability";++import { ActionProjectType, ProjectVersion } 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 {+ TApprovalPolicyBypassersDALFactory,+ TApprovalPolicyDALFactory,++ TApprovalPolicySecretEnvironmentDALFactory,+ TApprovalPolicyStepApproversDALFactory,+ TApprovalPolicyStepsDALFactory+} from "@app/services/approval-policy/approval-policy-dal";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";+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";++import { TLicenseServiceFactory } from "../license/license-service";+import { TSecretApprovalPolicyDALFactory } from "../secret-approval-policy/secret-approval-policy-dal";+import { RequestState } from "../secret-approval-request/secret-approval-request-types";+import { TSecretChangePolicyBridgeDALFactory } from "./secret-change-policy-bridge-dal";+import { secretChangePolicyFnsFactory, splitApprovers, toSecretChangePolicy } from "./secret-change-policy-bridge-fns";+import { TSecretChangePolicyBridgeMethods, TSecretChangePolicyEnvironment } from "./secret-change-policy-bridge-types";- import { TApprovalPolicySecretEnvironmentDALFactory } from "./secret-change-policy-environment-dal";++type TSecretChangePolicyBridgeServiceFactoryDep = {+ approvalPolicyDAL: Pick<+ TApprovalPolicyDALFactory,+ "findOne" | "findByIdForUpdate" | "create" | "updateById" | "deleteById" | "transaction"+ >;+ approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create" | "updateById">;+ approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "insertMany" | "delete">;+ approvalPolicyBypassersDAL: Pick<TApprovalPolicyBypassersDALFactory, "insertMany" | "delete">;+ approvalPolicySecretEnvironmentDAL: Pick<+ TApprovalPolicySecretEnvironmentDALFactory,- "insertMany" | "delete" | "findPolicyByEnvIdAndSecretPath"++ "insertMany" | "delete" | "findSecretChangePolicyByEnvIdsAndSecretPath"+ >;+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "update">;+ secretChangePolicyBridgeDAL: Pick<TSecretChangePolicyBridgeDALFactory, "findSecretChangePolicies">;+ secretApprovalPolicyDAL: Pick<TSecretApprovalPolicyDALFactory, "findPolicyByEnvIdAndSecretPath">;+ projectEnvDAL: Pick<TProjectEnvDALFactory, "find">;+ projectDAL: Pick<TProjectDALFactory, "findById" | "findEffectiveProjectSubjectsMembership">;+ userDAL: Pick<TUserDALFactory, "find">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+};++export type TSecretChangePolicyBridgeServiceFactory = ReturnType<typeof secretChangePolicyBridgeServiceFactory>;++export const secretChangePolicyBridgeServiceFactory = ({+ approvalPolicyDAL,+ approvalPolicyStepsDAL,+ approvalPolicyStepApproversDAL,+ approvalPolicyBypassersDAL,+ approvalPolicySecretEnvironmentDAL,+ approvalRequestDAL,+ secretChangePolicyBridgeDAL,+ secretApprovalPolicyDAL,+ projectEnvDAL,+ projectDAL,+ userDAL,+ permissionService,+ licenseService+}: TSecretChangePolicyBridgeServiceFactoryDep) => {+ const {+ findSecretChangePolicy,+ findSecretChangePolicyById,+ findSecretChangePolicyBySecretPath,+ findSecretChangePoliciesByEnvId,+ findSecretChangePoliciesByProjectId,+ assertNoPolicyForSecretPath,+ resolveBypassers,+ resolveApproverUserIds,+ verifyPolicyActorsMembership,+ updatePolicy+ } = secretChangePolicyFnsFactory({+ approvalPolicyDAL,+ approvalPolicyStepsDAL,+ approvalPolicyStepApproversDAL,+ approvalPolicyBypassersDAL,+ approvalPolicySecretEnvironmentDAL,+ secretChangePolicyBridgeDAL,+ secretApprovalPolicyDAL,+ projectDAL,+ userDAL+ });++ // 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` });+ }+ return toSecretChangePolicy(row);+ };++ const createSecretChangePolicy: TSecretChangePolicyBridgeMethods["createSecretChangePolicy"] = async ({+ name,+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod,+ approvals,+ approvers,+ bypassers,+ projectId,+ secretPath,+ environment,+ environments,+ enforcementLevel,+ allowedSelfApprovals,+ bypassForMachineIdentities+ }) => {+ const { groupApprovers, userApprovers, userApproverNames } = splitApprovers(approvers);++ if (!groupApprovers.length && approvals > approvers.length)+ throw new BadRequestError({ message: "Approvals cannot be greater than approvers" });++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionActions.Create,+ ProjectPermissionSub.SecretApproval+ );++ const project = await projectDAL.findById(projectId);+ if (!project) {+ throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });+ }+ if (project.version !== ProjectVersion.V3) {+ throw new BadRequestError({+ message:+ "Secret approval policies on the global approval system are only supported on projects that have been upgraded to the latest secrets version. Upgrade the project before creating one."+ });+ }++ const plan = await licenseService.getPlan(actorOrgId);+ if (!plan.secretApproval) {+ throw new BadRequestError({+ message:+ "Failed to create secret approval policy due to plan restriction. Upgrade plan to create secret approval policy."+ });+ }++ const mergedEnvs = (environment ? [environment] : environments) || [];+ if (mergedEnvs.length === 0) {+ throw new BadRequestError({ message: "Must provide either environment or environments" });+ }+ const envs = await projectEnvDAL.find({ $in: { slug: mergedEnvs }, projectId });+ if (!envs.length || envs.length !== mergedEnvs.length) {+ const notFoundEnvs = mergedEnvs.filter((env) => !envs.find((el) => el.slug === env));+ throw new NotFoundError({ message: `One or more environments not found: ${notFoundEnvs.join(", ")}` });+ }++ await assertNoPolicyForSecretPath({ envs, secretPath });++ const { bypasserUserIds, groupBypassers } = await resolveBypassers(bypassers);+ const userApproverIds = await resolveApproverUserIds({ userApprovers, userApproverNames });++ await verifyPolicyActorsMembership({+ userApproverIds,+ groupApprovers,+ bypasserUserIds,+ groupBypassers,+ orgId: actorOrgId,+ projectId+ });++ return approvalPolicyDAL.transaction(async (tx) => {+ const doc = await approvalPolicyDAL.create(+ {+ projectId,+ organizationId: actorOrgId,+ type: ApprovalPolicyType.SecretChange,+ name,+ enforcementLevel,+ bypassForMachineIdentities,+ conditions: { version: 1, conditions: [] },+ constraints: { version: 1, constraints: { allowedSelfApprovals } },+ scopeType: null,+ scopeId: null+ },+ tx+ );++ const step = await approvalPolicyStepsDAL.create(+ {+ policyId: doc.id,+ stepNumber: 1,+ requiredApprovals: approvals+ },+ tx+ );++ await approvalPolicyStepApproversDAL.insertMany(+ [+ ...userApproverIds.map((userId) => ({ policyStepId: step.id, userId, groupId: null })),+ ...groupApprovers.map((groupId) => ({ policyStepId: step.id, userId: null, groupId }))+ ],+ tx+ );++ await approvalPolicyBypassersDAL.insertMany(+ [+ ...bypasserUserIds.map((userId) => ({ policyId: doc.id, userId, groupId: null })),+ ...groupBypassers.map((groupId) => ({ policyId: doc.id, userId: null, groupId }))+ ],+ tx+ );++ await approvalPolicySecretEnvironmentDAL.insertMany(+ envs.map((env) => ({ policyId: doc.id, envId: env.id, secretPath })),+ tx+ );++ const [row] = await secretChangePolicyBridgeDAL.findSecretChangePolicies({ policyId: doc.id }, tx);+ return toSecretChangePolicy(row);+ });+ };++ const updateSecretChangePolicy: TSecretChangePolicyBridgeMethods["updateSecretChangePolicy"] = async ({+ secretPolicyId,+ name,+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod,+ approvals,+ approvers,+ bypassers,+ secretPath,+ environments,+ enforcementLevel,+ allowedSelfApprovals,+ bypassForMachineIdentities+ }) => {+ const { groupApprovers, userApprovers, userApproverNames } = splitApprovers(approvers);++ const policy = await $findSecretChangePolicyOrThrow(secretPolicyId, actorOrgId);++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: policy.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.SecretApproval);++ const plan = await licenseService.getPlan(actorOrgId);+ if (!plan.secretApproval) {+ throw new BadRequestError({+ message:+ "Failed to update secret approval policy due to plan restriction. Upgrade plan to update secret approval policy."+ });+ }++ let requestedEnvs: TSecretChangePolicyEnvironment[] | undefined;+ if (environments) {+ const envSlugs = [...new Set(environments)];+ if (!envSlugs.length) {+ throw new BadRequestError({ message: "At least one environment must be provided" });+ }+ const foundEnvs = await projectEnvDAL.find({ $in: { slug: envSlugs }, projectId: policy.projectId });+ if (foundEnvs.length !== envSlugs.length) {+ const notFoundEnvs = envSlugs.filter((slug) => !foundEnvs.find((el) => el.slug === slug));+ throw new NotFoundError({ message: `One or more environments not found: ${notFoundEnvs.join(", ")}` });+ }+ requestedEnvs = foundEnvs.map(({ id, slug, name: envName }) => ({ id, slug, name: envName }));+ }++ const { bypasserUserIds, groupBypassers } = await resolveBypassers(bypassers);+ const userApproverIds = await resolveApproverUserIds({ userApprovers, userApproverNames });++ await verifyPolicyActorsMembership({+ userApproverIds,+ groupApprovers,+ bypasserUserIds,+ groupBypassers,+ orgId: actorOrgId,+ projectId: policy.projectId+ });++ return updatePolicy({+ policy,+ name,+ approvals,+ secretPath,+ enforcementLevel,+ allowedSelfApprovals,+ bypassForMachineIdentities,+ requestedEnvs,+ approverCount: approvers.length,+ userApproverIds,+ groupApprovers,+ bypasserUserIds,+ groupBypassers+ });+ };++ const deleteSecretChangePolicy: TSecretChangePolicyBridgeMethods["deleteSecretChangePolicy"] = async ({+ secretPolicyId,+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod+ }) => {+ const policy = await $findSecretChangePolicyOrThrow(secretPolicyId, actorOrgId);++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: policy.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionActions.Delete,+ ProjectPermissionSub.SecretApproval+ );++ await approvalPolicyDAL.transaction(async (tx) => {+ const lockedPolicy = await approvalPolicyDAL.findByIdForUpdate(policy.id, tx);+ if (!lockedPolicy) {+ throw new NotFoundError({ message: `Secret approval policy with ID '${policy.id}' not found` });+ }+ await approvalRequestDAL.update(+ { policyId: policy.id, status: RequestState.Open },+ { status: RequestState.Closed },+ tx+ );+ await approvalPolicyDAL.deleteById(policy.id, tx);+ });++ return { ...policy, deletedAt: new Date() };+ };++ 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,+ findSecretChangePolicyById,+ findSecretChangePolicyBySecretPath,+ findSecretChangePoliciesByEnvId,+ findSecretChangePoliciesByProjectId,+ createSecretChangePolicy,+ updateSecretChangePolicy,+ deleteSecretChangePolicy,+ getSecretChangePolicyById+ };+};diff --cc backend/src/server/routes/index.tsindex 115e3a33ab,3a9cd70be4..abbaa8b9a6--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@@ -204,11 -203,6 +204,10 @@@ import { secretApprovalRequestDALFactorimport { 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";+import { secretChangeRequestDALFactory } from "@app/ee/services/secret-change-request-bridge/secret-change-request-dal";import { secretReplicationServiceFactory } from "@app/ee/services/secret-replication/secret-replication-service";import { secretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";import { secretRotationV2QueueServiceFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-queue";@@@ -1863,7 -1864,13 +1892,9 @@@ export const registerRoutes = asyncconst approvalRequestGrantsDAL = approvalRequestGrantsDALFactory(db);const approvalRequestStepsDAL = approvalRequestStepsDALFactory(db);const approvalRequestStepEligibleApproversDAL = approvalRequestStepEligibleApproversDALFactory(db);- const approvalPolicyStepsDAL = approvalPolicyStepsDALFactory(db);- const approvalPolicyStepApproversDAL = approvalPolicyStepApproversDALFactory(db);- const approvalPolicyBypassersDAL = approvalPolicyBypassersDALFactory(db);- const approvalPolicySecretEnvironmentDAL = approvalPolicySecretEnvironmentDALFactory(db);+ const secretAccessApprovalGlobalPolicyBridgeDAL = secretAccessApprovalGlobalPolicyBridgeDALFactory(db);+ const secretAccessApprovalGlobalRequestBridgeDAL = secretAccessApprovalGlobalRequestBridgeDALFactory(db);+ const secretChangeRequestDAL = secretChangeRequestDALFactory(db);const approvalRequestApprovalsDAL = approvalRequestApprovalsDALFactory(db);const orgGatewayConfigV2DAL = orgGatewayConfigV2DalFactory(db);@@@ -4511,9 -4527,10 +4593,11 @@@identitySpiffeAuth: identitySpiffeAuthService,identityLdapAuth: identityLdapAuthService,accessApprovalPolicy: accessApprovalPolicyService,+ secretAccessApprovalGlobalPolicyBridge: secretAccessApprovalGlobalPolicyBridgeService,+ secretAccessApprovalGlobalRequestBridge: secretAccessApprovalGlobalRequestBridgeService,accessApprovalRequest: accessApprovalRequestService,secretApprovalPolicy: secretApprovalPolicyService,+ secretChangePolicyBridge: secretChangePolicyBridgeService,secretApprovalRequest: secretApprovalRequestService,dynamicSecret: dynamicSecretService,dynamicSecretLease: dynamicSecretLeaseService,diff --cc backend/src/services/approval-policy/approval-policy-dal.tsindex 969ca2df09,c521767622..9c31630ea5--- a/backend/src/services/approval-policy/approval-policy-dal.ts+++ b/backend/src/services/approval-policy/approval-policy-dal.ts@@@ -1,9 -1,9 +1,9 @@@import { Knex } from "knex";import { TDbClient } from "@app/db";--import { TableName } from "@app/db/schemas";++import { ApprovalPoliciesSchema, TableName } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";- import { ormify } from "@app/lib/knex";-import { ormify, selectAllTableCols } from "@app/lib/knex";++import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";import { ApprovalPolicyType, ApproverType } from "./approval-policy-enums";import { ApprovalPolicyStep, PolicyBypasser } from "./approval-policy-types";@@@ -224,19 -208,58 +224,57 @@@ export const approvalPolicyDALFactory}};- /**- * Return the list of policies (with name + id) that include any of the given subjects as an approver- * on any step. The subjects are identified by `userIds` OR `groupId` (not both). Used to block- * removing members while they're still wired up as reviewers.- */- const findPoliciesWhereSubjectIsApprover = async (args: {+ const findSecretAccessPolicyByEnvIdAndSecretPath = async ({+ projectId,+ envId,+ secretPath+ }: {projectId: string;- type?: string;- scopeType?: string;- scopeId?: string;- userIds?: string[];- groupId?: string;+ envId: string;+ secretPath: string;}) => {+ try {+ const policy = await db+ .replicaNode()(TableName.ApprovalPolicies)+ .join(+ TableName.ApprovalPolicySecretEnvironment,+ `${TableName.ApprovalPolicySecretEnvironment}.policyId`,+ `${TableName.ApprovalPolicies}.id`+ )+ .where(`${TableName.ApprovalPolicies}.type`, ApprovalPolicyType.SecretAccess)+ .where(`${TableName.ApprovalPolicies}.projectId`, projectId)+ .where(`${TableName.ApprovalPolicySecretEnvironment}.envId`, envId)+ .where(`${TableName.ApprovalPolicySecretEnvironment}.secretPath`, secretPath)+ .select(selectAllTableCols(TableName.ApprovalPolicies))+ .first();++ if (!policy) return null;++ const [steps, bypassers] = await Promise.all([+ findStepsByPolicyId(policy.id),+ findBypassersByPolicyId(policy.id)+ ]);++ return { ...policy, steps, bypassers };+ } catch (error) {+ throw new DatabaseError({ error, name: "Find secret access approval policy by environment and secret path" });+ }+ };++ /**- * Return the list of policies (with name + id) that include the given subject as an approver- * on any step. The subject is identified by `userId` OR `groupId` (not both). Used to block- * removing a member from an application while they're still wired up as a reviewer.++ * Return the list of policies (with name + id) in a project or an organization that include any of the++ * given subjects as an approver on any step. The subjects are identified by `userIds` OR `groupId` (not++ * both). Used to block removing members while they're still wired up as reviewers.+ */+ const findPoliciesWhereSubjectIsApprover = async (+ args: {+ type?: ApprovalPolicyType;+ scopeType?: string;+ scopeId?: string;- userId?: string;+ userIds?: string[];+ groupId?: string;+ } & ({ projectId: string; organizationId?: undefined } | { projectId?: undefined; organizationId: string })+ ) => {try {const dbInstance = db.replicaNode();@@@ -542,3 -573,49 +588,125 @@@ export const approvalPolicyBypassersDALconst orm = ormify(db, TableName.ApprovalPolicyBypassers);return orm;};++ // Approval Policy Secret Environments+ export type TApprovalPolicySecretEnvironmentDALFactory = ReturnType<typeof approvalPolicySecretEnvironmentDALFactory>;+ export const approvalPolicySecretEnvironmentDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.ApprovalPolicySecretEnvironment);++ const findPolicyByEnvIdsAndSecretPath = async (+ { envIds, secretPath, excludePolicyId }: { envIds: string[]; secretPath: string; excludePolicyId?: string },+ tx?: Knex+ ) => {+ try {+ const doc = (await (tx || db.replicaNode())(TableName.ApprovalPolicySecretEnvironment)+ .join(+ TableName.ApprovalPolicies,+ `${TableName.ApprovalPolicies}.id`,+ `${TableName.ApprovalPolicySecretEnvironment}.policyId`+ )+ .where(`${TableName.ApprovalPolicies}.type`, ApprovalPolicyType.SecretAccess)+ .where((qb) => {+ if (excludePolicyId) void qb.whereNot(`${TableName.ApprovalPolicies}.id`, excludePolicyId);+ })+ .whereIn(`${TableName.ApprovalPolicySecretEnvironment}.envId`, envIds)+ .where(`${TableName.ApprovalPolicySecretEnvironment}.secretPath`, secretPath)+ .select(+ db.ref("id").withSchema(TableName.ApprovalPolicies).as("policyId"),+ db.ref("name").withSchema(TableName.ApprovalPolicies).as("policyName"),+ db.ref("envId").withSchema(TableName.ApprovalPolicySecretEnvironment)+ )+ .first()) as { policyId: string; policyName: string; envId: string } | undefined;++ return doc;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find approval policy by env ids and secret path" });+ }+ };+++ const findSecretChangePolicyByEnvIdsAndSecretPath = async (++ { envIds, secretPath, excludePolicyId }: { envIds: string[]; secretPath: string; excludePolicyId?: string },++ tx?: Knex++ ) => {++ try {++ const docs = await (tx || db.replicaNode())(TableName.ApprovalPolicies)++ .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(`${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"))++ .select(db.ref("id").withSchema(TableName.Environment).as("environmentId"));++++ const formattedDocs = sqlNestRelationships({++ data: docs,++ key: "id",++ parentMapper: (data) => ApprovalPoliciesSchema.parse(data),++ childrenMapper: [++ {++ key: "environmentId",++ label: "environments" as const,++ mapper: ({ environmentId: id, envName, envSlug }) => ({++ id,++ name: envName,++ slug: envSlug++ })++ }++ ]++ });++ return formattedDocs?.[0];++ } catch (error) {++ throw new DatabaseError({ error, name: "Find secret change approval policy by env ids and secret path" });++ }++ };++++ const findPolicyByEnvId = async (envId: string, tx?: Knex) => {++ try {++ const doc = (await (tx || db.replicaNode())(TableName.ApprovalPolicySecretEnvironment)++ .join(++ TableName.ApprovalPolicies,++ `${TableName.ApprovalPolicies}.id`,++ `${TableName.ApprovalPolicySecretEnvironment}.policyId`++ )++ .where(`${TableName.ApprovalPolicySecretEnvironment}.envId`, envId)++ .select(++ db.ref("name").withSchema(TableName.ApprovalPolicies).as("policyName"),++ db.ref("type").withSchema(TableName.ApprovalPolicies).as("policyType")++ )++ .first()) as { policyName: string; policyType: ApprovalPolicyType } | undefined;++++ return doc;++ } catch (error) {++ throw new DatabaseError({ error, name: "Find approval policy by env id" });++ }++ };+++ const findByPolicyIdForUpdate = async (policyId: string, tx: Knex) => {+ try {+ return await tx(TableName.ApprovalPolicySecretEnvironment).forUpdate().where({ policyId }).orderBy("id", "asc");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find approval policy secret environments by policy id for update" });+ }+ };+- return { ...orm, findPolicyByEnvIdsAndSecretPath, findByPolicyIdForUpdate };++ return {++ ...orm,++ findPolicyByEnvIdsAndSecretPath,++ findSecretChangePolicyByEnvIdsAndSecretPath,++ findPolicyByEnvId,++ findByPolicyIdForUpdate++ };+ };diff --cc backend/src/services/approval-policy/approval-policy-enums.tsindex 801c4ec0ca,107efeace6..797ca96b46--- a/backend/src/services/approval-policy/approval-policy-enums.ts+++ b/backend/src/services/approval-policy/approval-policy-enums.ts@@@ -16,7 -16,7 +16,8 @@@ export enum ApprovalPolicyTypePamAccess = "pam-access",CertRequest = "cert-request",CertCodeSigning = "cert-code-signing",- SecretChange = "secret-change"++ SecretChange = "secret-change",+ SecretAccess = "secret-access"}export enum ApprovalPolicyScope {diff --cc backend/src/services/approval-policy/approval-policy-types.tsindex 98df8d91d3,cbac26012b..0ae1f998e7--- a/backend/src/services/approval-policy/approval-policy-types.ts+++ b/backend/src/services/approval-policy/approval-policy-types.ts@@@ -64,7 -77,7 +78,8 @@@ export type TApprovalRequestData| TPamAccessRequestData| TCertRequestRequestData| TCodeSigningRequestData- | TSecretChangeRequestData;++ | TSecretChangeRequestData+ | TSecretAccessRequestData;// Bypass-affordance fields the service stamps onto every request response.export type TBypassAffordances = {@@@ -130,7 -143,8 +145,8 @@@ export interface TUpdatePolicyDTOexport interface TCreateRequestDTO {scope: ApprovalPolicyScope;scopeId: string;- requestData: TApprovalRequest["requestData"]["requestData"];- // Secret access requests are created in the access-approval bridge, not through this DTO.- requestData: Exclude<TApprovalRequestData, TSecretAccessRequestData>;++ // Secret access and secret change requests are created in their bridges, not through this DTO.++ requestData: Exclude<TApprovalRequestData, TSecretAccessRequestData | TSecretChangeRequestData>;justification?: TApprovalRequest["justification"];requestDuration?: string | null;// Set by a caller that decides the request in the same breath (break-glass), so approvers are notdiff --cc backend/src/services/approval-policy/approval-request-dal.tsindex 60d4a38cfa,69b39c82f1..3afb31bdab--- a/backend/src/services/approval-policy/approval-request-dal.ts+++ b/backend/src/services/approval-policy/approval-request-dal.ts@@@ -154,9 -197,9 +165,10 @@@ export const approvalRequestDALFactoryreturn {...orm,findStepsByRequestId,+ findStepsByRequestIds,findByProjectId,findByIdForUpdate,+ findPendingByPolicyIdForUpdate,markExpiredRequests};};diff --cc backend/src/services/project-env/project-env-service.tsindex 19a900a001,a10b7f28d7..bea60c6353--- a/backend/src/services/project-env/project-env-service.ts+++ b/backend/src/services/project-env/project-env-service.ts@@@ -9,7 -9,7 +9,8 @@@ import { TSecretApprovalPolicyEnvironmeimport { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";+ import { TApprovalPolicySecretEnvironmentDALFactory } from "@app/services/approval-policy/approval-policy-dal";++import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";import { ActorType } from "../auth/auth-type";import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";@@@ -32,7 -32,7 +33,7 @@@ type TProjectEnvServiceFactoryDep =keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem" | "waitTillReady" | "deleteItem">;accessApprovalPolicyEnvironmentDAL: Pick<TAccessApprovalPolicyEnvironmentDALFactory, "findAvailablePoliciesByEnvId">;secretApprovalPolicyEnvironmentDAL: Pick<TSecretApprovalPolicyEnvironmentDALFactory, "findAvailablePoliciesByEnvId">;-- approvalPolicySecretEnvironmentDAL: Pick<TApprovalPolicySecretEnvironmentDALFactory, "findOne">;++ approvalPolicySecretEnvironmentDAL: Pick<TApprovalPolicySecretEnvironmentDALFactory, "findPolicyByEnvId">;};export type TProjectEnvServiceFactory = ReturnType<typeof projectEnvServiceFactory>;@@@ -287,10 -287,10 +288,10 @@@ export const projectEnvServiceFactoryname: "DeleteEnvironment"});}- const accessApprovalPolicies = await accessApprovalPolicyEnvironmentDAL.findAvailablePoliciesByEnvId(id, tx);- if (accessApprovalPolicies.length > 0) {- const globalAccessApprovalPolicy = await approvalPolicySecretEnvironmentDAL.findOne({ envId: id }, tx);- if (globalAccessApprovalPolicy) {++ const approvalPolicy = await approvalPolicySecretEnvironmentDAL.findPolicyByEnvId(id, tx);++ if (approvalPolicy) {throw new BadRequestError({-- message: "Environment is in use by an access approval policy",++ message: `Environment is in use by ${approvalPolicy.policyType === ApprovalPolicyType.SecretAccess ? "an access approval policy" : "a secret approval policy"}`,name: "DeleteEnvironment"});}