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
test(secret-sync): cover move warnings with unit tests instead of e2e
Calvin538f9a84f233
diff --git a/backend/e2e-test/routes/v1/dashboard-move-warnings.spec.ts b/backend/e2e-test/routes/v1/dashboard-move-warnings.spec.tsdeleted file mode 100644index 24838fc70d..0000000000--- a/backend/e2e-test/routes/v1/dashboard-move-warnings.spec.ts+++ /dev/null@@ -1,240 +0,0 @@-import { randomUUID } from "node:crypto";--import { createAwsAppConnection } from "e2e-test/testUtils/app-connections";-import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";-import { createFolder } from "e2e-test/testUtils/folders";-import { createSecretSync } from "e2e-test/testUtils/secret-syncs";-import jwt from "jsonwebtoken";--import { AccessScope, OrgMembershipRole, OrgMembershipStatus, ProjectMembershipRole, TableName } from "@app/db/schemas";-import { getConfig, initEnvConfig } from "@app/lib/config/env";-import { initLogger, logger } from "@app/lib/logger";-import { alphaNumericNanoId } from "@app/lib/nanoid";-import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";--const ENV = "dev";-const REGION = "us-east-1";--type TMoveWarningSecretSync = {- id: string | null;- name: string | null;- destination: string | null;- secretPath: string | null;- includeAllSubFolders: boolean | null;- isAutoSyncEnabled: boolean | null;-};--describe("Move warnings", async () => {- vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });-- let orgId: string;- let projectId: string;- let adminToken: string;- let cleanupOrg: () => Promise<void>;- let noAccessUserId: string;- let noAccessToken: string;-- const getMoveWarnings = async (- query: {- sourceEnvironment?: string;- sourceSecretPath: string;- destinationEnvironment?: string;- destinationSecretPath: string;- },- authToken = adminToken- ) => {- const res = await testServer.inject({- method: "GET",- url: "/api/v1/dashboard/move-warnings",- headers: { authorization: `Bearer ${authToken}` },- query: {- projectId,- sourceEnvironment: query.sourceEnvironment ?? ENV,- destinationEnvironment: query.destinationEnvironment ?? ENV,- sourceSecretPath: query.sourceSecretPath,- destinationSecretPath: query.destinationSecretPath- }- });-- return res;- };-- const syncNames = async (query: Parameters<typeof getMoveWarnings>[0]) => {- const res = await getMoveWarnings(query);- expect(res.statusCode).toBe(200);- return (res.json().secretSyncs as TMoveWarningSecretSync[]).map((sync) => sync.name);- };-- beforeAll(async () => {- initLogger();- await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);-- ({- orgId,- projectId,- authToken: adminToken,- cleanup: cleanupOrg- } = await createIsolatedOrgAndProject("move-warnings"));-- const connectionId = await createAwsAppConnection({- name: `move-warnings-${randomUUID().slice(0, 8)}`,- authToken: adminToken- });-- for (const folder of [- { secretPath: "/", name: "apps" },- { secretPath: "/apps", name: "payments" },- { secretPath: "/", name: "flat" },- { secretPath: "/", name: "unsynced" }- ]) {- // eslint-disable-next-line no-await-in-loop- await createFolder({ authToken: adminToken, workspaceId: projectId, environmentSlug: ENV, ...folder });- }-- for (const sync of [- { name: "apps-recursive", secretPath: "/apps", includeAllSubFolders: true },- { name: "flat-only", secretPath: "/flat", includeAllSubFolders: false }- ]) {- // eslint-disable-next-line no-await-in-loop- await createSecretSync({- ...sync,- projectId,- connectionId,- environmentSlug: ENV,- region: REGION,- destinationPath: `/${sync.name}/`,- authToken: adminToken- });- }-- const username = `move-warnings-${alphaNumericNanoId(8)}@example.com`.toLowerCase();- const [user] = await testDb(TableName.Users)- .insert({ username, email: username, isGhost: false, isAccepted: true, authMethods: [AuthMethod.EMAIL] })- .returning("*");- noAccessUserId = user.id;-- const [orgMembership] = await testDb(TableName.Membership)- .insert({- scope: AccessScope.Organization,- scopeOrgId: orgId,- actorUserId: noAccessUserId,- status: OrgMembershipStatus.Accepted,- isActive: true- })- .returning("*");- await testDb(TableName.MembershipRole).insert({ membershipId: orgMembership.id, role: OrgMembershipRole.Member });-- const [projectMembership] = await testDb(TableName.Membership)- .insert({- scope: AccessScope.Project,- scopeOrgId: orgId,- scopeProjectId: projectId,- actorUserId: noAccessUserId- })- .returning("*");- await testDb(TableName.MembershipRole).insert({- membershipId: projectMembership.id,- role: ProjectMembershipRole.NoAccess- });-- const sessionId = randomUUID();- await testDb(TableName.AuthTokenSession).insert({- id: sessionId,- userId: noAccessUserId,- ip: "127.0.0.1",- userAgent: "e2e-move-warnings",- accessVersion: 1,- refreshVersion: 1,- lastUsed: new Date()- } as never);-- noAccessToken = jwt.sign(- {- authTokenType: AuthTokenType.ACCESS_TOKEN,- userId: noAccessUserId,- tokenVersionId: sessionId,- authMethod: AuthMethod.EMAIL,- organizationId: orgId,- accessVersion: 1- },- getConfig().AUTH_SECRET,- { expiresIn: 3600 }- );- });-- afterAll(async () => {- await cleanupOrg();- await testDb(TableName.AuthTokenSession).where({ userId: noAccessUserId }).del();- await testDb(TableName.Users).where({ id: noAccessUserId }).del();- });-- test("lists a recursive sync above the destination", async () => {- expect(await syncNames({ sourceSecretPath: "/", destinationSecretPath: "/apps/payments" })).toEqual([- "apps-recursive"- ]);- });-- test("returns the sync's details", async () => {- const res = await getMoveWarnings({ sourceSecretPath: "/", destinationSecretPath: "/apps" });-- expect(res.json().secretSyncs).toEqual([- expect.objectContaining({- name: "apps-recursive",- destination: "aws-parameter-store",- secretPath: "/apps",- includeAllSubFolders: true,- isAutoSyncEnabled: false- })- ]);- });-- test("leaves out a sync that already covers the source", async () => {- expect(await syncNames({ sourceSecretPath: "/apps", destinationSecretPath: "/apps/payments" })).toEqual([]);- });-- test("lists a non-recursive sync on the destination itself", async () => {- expect(await syncNames({ sourceSecretPath: "/", destinationSecretPath: "/flat" })).toEqual(["flat-only"]);- });-- test("does not list a non-recursive sync for a folder moved beneath it", async () => {- // A folder lands at the destination plus its own name, which the non-recursive sync never reads.- expect(await syncNames({ sourceSecretPath: "/unsynced", destinationSecretPath: "/flat/unsynced" })).toEqual([]);- });-- test("lists a recursive sync for a folder moved beneath it", async () => {- expect(await syncNames({ sourceSecretPath: "/unsynced", destinationSecretPath: "/apps/unsynced" })).toEqual([- "apps-recursive"- ]);- });-- test("returns nothing for an unsynced destination", async () => {- expect(await syncNames({ sourceSecretPath: "/apps", destinationSecretPath: "/unsynced" })).toEqual([]);- });-- test("withholds the details of a sync the actor cannot read", async () => {- const res = await getMoveWarnings({ sourceSecretPath: "/", destinationSecretPath: "/apps" }, noAccessToken);-- expect(res.statusCode).toBe(200);- expect(res.json().secretSyncs).toEqual([- {- id: null,- name: null,- destination: null,- secretPath: null,- includeAllSubFolders: null,- isAutoSyncEnabled: null- }- ]);- });-- test("names an environment that does not exist", async () => {- const res = await getMoveWarnings({- sourceSecretPath: "/",- destinationEnvironment: "missing-env",- destinationSecretPath: "/"- });-- expect(res.statusCode).toBe(404);- expect(res.json().message).toContain('"missing-env"');- });-});diff --git a/backend/src/services/secret-sync/secret-sync-recursive-fns.test.ts b/backend/src/services/secret-sync/secret-sync-recursive-fns.test.tsindex 08feb3c158..9436dd1aa3 100644--- a/backend/src/services/secret-sync/secret-sync-recursive-fns.test.ts+++ b/backend/src/services/secret-sync/secret-sync-recursive-fns.test.ts@@ -3,7 +3,8 @@ import {findSecretSyncsCoveringPath,getAncestorPaths,getSyncedFolders,- mergeImportedSecrets+ mergeImportedSecrets,+ toSyncsNewlyCoveringPath} from "./secret-sync-recursive-fns";const deps = {@@ -174,6 +175,81 @@ describe("findSecretSyncsCoveringPath", () => {});});+describe("toSyncsNewlyCoveringPath", () => {+ const sync = (id: string, overrides: Record<string, unknown> = {}) => ({+ id,+ name: id,+ destination: "aws-parameter-store",+ folder: { path: "/apps" },+ syncOptions: { includeAllSubFolders: true },+ isAutoSyncEnabled: true,+ ...overrides+ });++ const canReadAll = () => true;++ test("leaves out a sync that already covers the source", () => {+ const result = toSyncsNewlyCoveringPath({+ sourceSyncs: [sync("shared")],+ destinationSyncs: [sync("shared"), sync("new")],+ canRead: canReadAll+ });++ expect(result.map((entry) => entry.id)).toEqual(["new"]);+ });++ test("returns nothing when the destination is covered only by the source's syncs", () => {+ expect(+ toSyncsNewlyCoveringPath({ sourceSyncs: [sync("a")], destinationSyncs: [sync("a")], canRead: canReadAll })+ ).toEqual([]);+ });++ test("orders syncs by name", () => {+ const result = toSyncsNewlyCoveringPath({+ sourceSyncs: [],+ destinationSyncs: [sync("b", { name: "zeta" }), sync("a", { name: "alpha" })],+ canRead: canReadAll+ });++ expect(result.map((entry) => entry.name)).toEqual(["alpha", "zeta"]);+ });++ test("returns the details of a sync the actor can read", () => {+ const [entry] = toSyncsNewlyCoveringPath({+ sourceSyncs: [],+ destinationSyncs: [sync("a", { folder: { path: "/flat" }, syncOptions: {}, isAutoSyncEnabled: false })],+ canRead: canReadAll+ });++ expect(entry).toEqual({+ id: "a",+ name: "a",+ destination: "aws-parameter-store",+ secretPath: "/flat",+ includeAllSubFolders: false,+ isAutoSyncEnabled: false+ });+ });++ test("withholds every detail of a sync the actor cannot read, but still reports it", () => {+ const result = toSyncsNewlyCoveringPath({+ sourceSyncs: [],+ destinationSyncs: [sync("visible"), sync("hidden")],+ canRead: (entry) => entry.id !== "hidden"+ });++ expect(result).toHaveLength(2);+ expect(result.find((entry) => entry.id === null)).toEqual({+ id: null,+ name: null,+ destination: null,+ secretPath: null,+ includeAllSubFolders: null,+ isAutoSyncEnabled: null+ });+ });+});+describe("mergeImportedSecrets", () => {const imported = (key: string, secretValue: string) => ({ key, secretValue }) as never;diff --git a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts b/backend/src/services/secret-sync/secret-sync-recursive-fns.tsindex 66cd6adc68..ad07a396af 100644--- a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts+++ b/backend/src/services/secret-sync/secret-sync-recursive-fns.ts@@ -7,6 +7,7 @@ import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-foldimport { TSecretImportDALFactory } from "@app/services/secret-import/secret-import-dal";import { fnSecretsV2FromImports } from "@app/services/secret-import/secret-import-fns";import { TSecretSyncDALFactory } from "@app/services/secret-sync/secret-sync-dal";+import { SecretSync } from "@app/services/secret-sync/secret-sync-enums";import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";import {createSecretSyncPayload,@@ -72,6 +73,54 @@ export const findSecretSyncsCoveringPath = async ();};+type TCoveringSync = {+ id: string;+ name: string;+ destination: string;+ folder?: { path: string } | null;+ syncOptions: unknown;+ isAutoSyncEnabled: boolean;+};++// A sync that already covers the source is left out, since the item already reaches it. A sync the+// actor cannot read is still reported, so the warning reaches them, but with every detail withheld.+export const toSyncsNewlyCoveringPath = <T extends TCoveringSync>({+ sourceSyncs,+ destinationSyncs,+ canRead+}: {+ sourceSyncs: T[];+ destinationSyncs: T[];+ canRead: (sync: T) => boolean;+}) => {+ const sourceSyncIds = new Set(sourceSyncs.map((sync) => sync.id));++ return destinationSyncs+ .filter((sync) => !sourceSyncIds.has(sync.id))+ .sort((a, b) => a.name.localeCompare(b.name))+ .map((sync) => {+ if (!canRead(sync)) {+ return {+ id: null,+ name: null,+ destination: null,+ secretPath: null,+ includeAllSubFolders: null,+ isAutoSyncEnabled: null+ };+ }++ return {+ id: sync.id,+ name: sync.name,+ destination: sync.destination as SecretSync,+ secretPath: sync.folder?.path ?? null,+ includeAllSubFolders: Boolean((sync.syncOptions as TSecretSync["syncOptions"])?.includeAllSubFolders),+ isAutoSyncEnabled: sync.isAutoSyncEnabled+ };+ });+};+export const getSyncedFolders = async ({folderDAL,projectEnvDAL,diff --git a/backend/src/services/secret-sync/secret-sync-service.ts b/backend/src/services/secret-sync/secret-sync-service.tsindex f5a0cbd1c3..e0a01e2cda 100644--- a/backend/src/services/secret-sync/secret-sync-service.ts+++ b/backend/src/services/secret-sync/secret-sync-service.ts@@ -37,7 +37,8 @@ import {import {buildSyncPayload,findSecretSyncsCoveringPath,- getSyncedFolders+ getSyncedFolders,+ toSyncsNewlyCoveringPath} from "@app/services/secret-sync/secret-sync-recursive-fns";import {SecretSyncStatus,@@ -437,9 +438,8 @@ export const secretSyncServiceFactory = ({};// The syncs that would start sending an item to their destination if it were moved or copied from the- // source path to the destination path. A sync that already covers the source is left out, since the- // item already reaches it. Any project member gets the list, so the warning still reaches an actor- // who cannot read the syncs themselves; only the details of those syncs are withheld.+ // source path to the destination path. Any project member gets the list, so the warning still reaches+ // an actor who cannot read the syncs themselves.const listSecretSyncsNewlyCoveringPath = async ({projectId,@@ -479,32 +479,11 @@ export const secretSyncServiceFactory = ({)]);- const sourceSyncIds = new Set(sourceSyncs.map((sync) => sync.id));-- return destinationSyncs- .filter((sync) => !sourceSyncIds.has(sync.id))- .sort((a, b) => a.name.localeCompare(b.name))- .map((sync) => {- if (permission.cannot(ProjectPermissionSecretSyncActions.Read, getSecretSyncSubject(sync))) {- return {- id: null,- name: null,- destination: null,- secretPath: null,- includeAllSubFolders: null,- isAutoSyncEnabled: null- };- }-- return {- id: sync.id,- name: sync.name,- destination: sync.destination as SecretSync,- secretPath: sync.folder?.path ?? null,- includeAllSubFolders: Boolean((sync.syncOptions as TSecretSync["syncOptions"])?.includeAllSubFolders),- isAutoSyncEnabled: sync.isAutoSyncEnabled- };- });+ return toSyncsNewlyCoveringPath({+ sourceSyncs,+ destinationSyncs,+ canRead: (sync) => permission.can(ProjectPermissionSecretSyncActions.Read, getSecretSyncSubject(sync))+ });};const findSecretSyncById = async ({ destination, syncId }: TFindSecretSyncByIdDTO, actor: OrgServiceActor) => {