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(e2e): cover secret sync create, update, delete, triggers, status, recursion, access and license on GitHub
varonixa2fce9fdc949
diff --git a/backend/e2e-test/routes/v1/secret-sync-recursive.spec.ts b/backend/e2e-test/routes/v1/secret-sync-recursive.spec.tsdeleted file mode 100644index 084c99e128..0000000000--- a/backend/e2e-test/routes/v1/secret-sync-recursive.spec.ts+++ /dev/null@@ -1,557 +0,0 @@-import { randomUUID } from "node:crypto";--import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";-import { createAwsAppConnection } from "e2e-test/testUtils/app-connections";-import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";-import { createFolder, deleteFolder } from "e2e-test/testUtils/folders";-import { addIdentityToProject, createIdentityActor, grantIdentityFolderAccess } from "e2e-test/testUtils/identities";-import {- createSecretSync,- expectDestinationUnchanged,- getSecretSync,- listSecretSyncs,- setAutoSync,- updateSecretSync,- waitForDestinationSecrets,- waitForSyncRun-} from "e2e-test/testUtils/secret-syncs";-import { createSecretV2 } from "e2e-test/testUtils/secrets";--import { ProjectMembershipRole, SecretFolderRole } from "@app/db/schemas";-import { initEnvConfig } from "@app/lib/config/env";-import { initLogger, logger } from "@app/lib/logger";-import { SecretSyncInitialSyncBehavior } from "@app/services/secret-sync/secret-sync-enums";--const ENV = "dev";-const REGION = "us-east-1";--// Each group owns an org of its own (createIsolatedOrgAndProject), so its folders, secrets,-// memberships and syncs cannot reach another group's, and tearing it down is one org delete.--describe("A secret sync is refused when it would read a folder the actor cannot", async () => {- vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });-- // The sync worker reads every folder a sync covers with authorization disabled (canExpandValue- // and hasSecretAccess both return true), so create and update are the only gate. A folder grant- // is what makes the escalation reachable: it can give an actor read on a parent folder while- // the base project role denies every child.-- let orgId: string;- let projectId: string;- let adminToken: string;- let cleanupOrg: () => Promise<void>;- let connectionId: string;- let actorToken: string;-- const newSync = (dto: { name: string; includeAllSubFolders: boolean; expectStatusCode?: number }) =>- createSecretSync({- name: dto.name,- projectId,- connectionId,- environmentSlug: ENV,- secretPath: "/backend",- region: REGION,- destinationPath: `/${dto.name}/`,- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: dto.includeAllSubFolders,- isAutoSyncEnabled: false,- authToken: actorToken,- expectStatusCode: dto.expectStatusCode- });-- beforeAll(async () => {- initLogger();- await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);-- ({- orgId,- projectId,- authToken: adminToken,- cleanup: cleanupOrg- } = await createIsolatedOrgAndProject("secret-sync-recursive-perms"));-- connectionId = await createAwsAppConnection({- name: `secret-sync-recursive-perms-${randomUUID().slice(0, 8)}`,- authToken: adminToken- });-- for (const folder of [- { secretPath: "/", name: "backend" },- { secretPath: "/backend", name: "api" }- ]) {- // eslint-disable-next-line no-await-in-loop- await createFolder({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- ...folder- });- }-- for (const secret of [- { secretPath: "/backend", key: "BACKEND_KEY", value: "backend-value" },- { secretPath: "/backend/api", key: "API_KEY", value: "api-value" }- ]) {- // eslint-disable-next-line no-await-in-loop- await createSecretV2({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- ...secret- });- }-- const actor = await createIdentityActor({ orgId, authToken: adminToken });- actorToken = actor.authToken;-- // The base role grants nothing, so every folder the grant below does not name is denied.- await addIdentityToProject({- projectId,- identityId: actor.identityId,- role: ProjectMembershipRole.NoAccess,- authToken: adminToken- });-- // Manage is the lowest tier carrying secret sync create, and a folder grant applies to the- // named folder only, so "/backend/api" falls back to the no-access base role.- await grantIdentityFolderAccess({- projectId,- identityId: actor.identityId,- environmentSlug: ENV,- secretPath: "/backend",- permission: SecretFolderRole.Manage,- authToken: adminToken- });- });-- afterAll(async () => {- await cleanupOrg();- });-- test("creating a sync that includes subfolders is refused, naming the folder that is denied", async () => {- const { error } = await newSync({ name: "recursive-denied", includeAllSubFolders: true, expectStatusCode: 403 });-- expect(error.message).toContain("/backend/api");- });-- test("repointing an existing recursive sync at another destination is refused", async () => {- // The admin can read the whole subtree, so this sync is legitimate at the moment it is made.- // The Manage grant then gives the actor Edit on it, scoped to "/backend", while leaving- // "/backend/api" denied. Without a check on this path the actor sends the denied folder to a- // destination of their choosing without ever touching the sync's source.- const { secretSync } = await createSecretSync({- name: "recursive-created-by-admin",- projectId,- connectionId,- environmentSlug: ENV,- secretPath: "/backend",- region: REGION,- destinationPath: "/recursive-created-by-admin/",- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: true,- isAutoSyncEnabled: false,- authToken: adminToken- });-- const { error } = await updateSecretSync({- syncId: secretSync!.id,- body: { destinationConfig: { region: REGION, path: "/actor-controlled/" } },- authToken: actorToken,- expectStatusCode: 403- });-- expect(error.message).toContain("/backend/api");- });-- test("turning subfolders on for an existing sync is refused", async () => {- const { secretSync } = await newSync({ name: "recursive-turned-on-later", includeAllSubFolders: false });-- const { error } = await updateSecretSync({- syncId: secretSync!.id,- body: {- syncOptions: {- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: true- }- },- authToken: actorToken,- expectStatusCode: 403- });-- expect(error.message).toContain("/backend/api");- });-});--describe("A recursive secret sync is refused when two folders use the same secret name", async () => {- vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });-- // A destination that stores secrets in one flat list cannot hold the same name twice, so a- // recursive sync whose subtree reuses a name is broken from the moment it is saved. The- // job-time check still exists for the sync that only clashes later.-- let projectId: string;- let adminToken: string;- let cleanupOrg: () => Promise<void>;- let connectionId: string;-- const newSync = (dto: { name: string; includeAllSubFolders: boolean; expectStatusCode?: number }) =>- createSecretSync({- name: dto.name,- projectId,- connectionId,- environmentSlug: ENV,- secretPath: "/backend",- region: REGION,- destinationPath: `/${dto.name}/`,- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: dto.includeAllSubFolders,- isAutoSyncEnabled: false,- authToken: adminToken,- expectStatusCode: dto.expectStatusCode- });-- // Creating a recursive sync over an existing collision is refused, so the only way one can be- // holding a collision is for the second name to have appeared after it was saved. The update- // tests all need a sync in that state, so they build it the same way: a recursive sync over a- // subtree that is still clean, then the colliding name written into both of its folders.- const recursiveSyncWithLateCollision = async (dto: { name: string; folder: string }) => {- for (const folder of [- { secretPath: "/", name: dto.folder },- { secretPath: `/${dto.folder}`, name: "child" }- ]) {- // eslint-disable-next-line no-await-in-loop- await createFolder({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- ...folder- });- }-- const { secretSync } = await createSecretSync({- name: dto.name,- projectId,- connectionId,- environmentSlug: ENV,- secretPath: `/${dto.folder}`,- region: REGION,- destinationPath: `/${dto.name}/`,- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: true,- isAutoSyncEnabled: false,- authToken: adminToken- });-- for (const secretPath of [`/${dto.folder}`, `/${dto.folder}/child`]) {- // eslint-disable-next-line no-await-in-loop- await createSecretV2({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath,- key: "LATE_KEY",- value: `value-for-${secretPath}`- });- }-- return secretSync!;- };-- beforeAll(async () => {- initLogger();- await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);-- ({- projectId,- authToken: adminToken,- cleanup: cleanupOrg- } = await createIsolatedOrgAndProject("secret-sync-recursive-dupes"));-- connectionId = await createAwsAppConnection({- name: `secret-sync-recursive-dupes-${randomUUID().slice(0, 8)}`,- authToken: adminToken- });-- for (const folder of [- { secretPath: "/", name: "backend" },- { secretPath: "/backend", name: "api" }- ]) {- // eslint-disable-next-line no-await-in-loop- await createFolder({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- ...folder- });- }-- for (const secretPath of ["/backend", "/backend/api"]) {- // eslint-disable-next-line no-await-in-loop- await createSecretV2({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath,- key: "DB_URL",- value: `postgres:/${secretPath}`- });- }- });-- afterAll(async () => {- await cleanupOrg();- });-- test("creating it is refused, naming the secret and both folders", async () => {- const { error } = await newSync({ name: "recursive-duplicate", includeAllSubFolders: true, expectStatusCode: 400 });-- expect(error.message).toContain("DB_URL");- expect(error.message).toContain("/backend");- expect(error.message).toContain("/backend/api");- });-- test("the refused request leaves no sync behind", async () => {- const secretSyncs = await listSecretSyncs({ projectId, authToken: adminToken });-- expect(secretSyncs.map((sync) => sync.name)).not.toContain("recursive-duplicate");- });-- // The two tests below pin the same rule from opposite sides: the checks an update runs read the- // sync options that update is about to store. Reading the request alone misses that an absent- // syncOptions leaves the stored ones in place; reading the stored row alone misses that a- // supplied syncOptions replaces them outright.-- test("turning subfolders off is allowed even though the subtree collides", async () => {- const secretSync = await recursiveSyncWithLateCollision({- name: "recursive-turned-off-later",- folder: "reports"- });-- await updateSecretSync({- syncId: secretSync.id,- body: { syncOptions: { initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination } },- authToken: adminToken- });-- const updated = await getSecretSync({ syncId: secretSync.id, authToken: adminToken });-- expect(updated.syncOptions.includeAllSubFolders).toBeFalsy();- });-- test("an update that leaves the sync options alone is still checked as recursive", async () => {- const secretSync = await recursiveSyncWithLateCollision({- name: "recursive-left-alone",- folder: "metrics"- });-- const { error } = await updateSecretSync({- syncId: secretSync.id,- body: { name: "recursive-left-alone-renamed" },- authToken: adminToken,- expectStatusCode: 400- });-- expect(error.message).toContain("LATE_KEY");- expect(error.message).toContain("/metrics");- expect(error.message).toContain("/metrics/child");- });-- test("turning subfolders on for an existing sync is refused", async () => {- const { secretSync } = await newSync({ name: "recursive-turned-on-later", includeAllSubFolders: false });-- const { error } = await updateSecretSync({- syncId: secretSync!.id,- body: {- syncOptions: {- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: true- }- },- authToken: adminToken,- expectStatusCode: 400- });-- expect(error.message).toContain("DB_URL");- expect(error.message).toContain("/backend/api");- });-});--describe("A change in a subfolder reaches the recursive sync above it", async () => {- vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });-- // Each test waits for the auto-sync-enable run to finish (via waitForSyncRun) before writing the- // subfolder secret. Skipping that wait would let the enable-time run, which always resolves the- // full recursive subtree at whatever the DB holds when it executes, pick up the later write by- // coincidence and mask a missing trigger.-- let projectId: string;- let adminToken: string;- let cleanupOrg: () => Promise<void>;- let connectionId: string;-- beforeAll(async () => {- initLogger();- await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);-- ({- projectId,- authToken: adminToken,- cleanup: cleanupOrg- } = await createIsolatedOrgAndProject("secret-sync-recursive-trigger"));-- connectionId = await createAwsAppConnection({- name: `secret-sync-recursive-trigger-${randomUUID().slice(0, 8)}`,- authToken: adminToken- });-- for (const folder of [- { secretPath: "/", name: "backend" },- { secretPath: "/backend", name: "api" }- ]) {- // eslint-disable-next-line no-await-in-loop- await createFolder({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- ...folder- });- }- });-- afterAll(async () => {- await cleanupOrg();- });-- test("a write at a subfolder reaches the recursive sync rooted above it", async () => {- const destinationPath = "/recursive-trigger-target/";-- const { secretSync } = await createSecretSync({- name: "recursive-trigger",- projectId,- connectionId,- environmentSlug: ENV,- secretPath: "/backend",- region: REGION,- destinationPath,- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: true,- isAutoSyncEnabled: false,- authToken: adminToken- });-- const runCountBeforeEnable = fakeParameterStore.at(REGION, destinationPath).runCount();- await setAutoSync({ syncId: secretSync!.id, isAutoSyncEnabled: true, authToken: adminToken });- await waitForSyncRun({- syncId: secretSync!.id,- region: REGION,- destinationPath,- runCountBefore: runCountBeforeEnable,- authToken: adminToken- });-- expect(fakeParameterStore.at(REGION, destinationPath).read()).toEqual({});-- await createSecretV2({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath: "/backend/api",- key: "SUBFOLDER_KEY",- value: "subfolder-value"- });-- await waitForDestinationSecrets({- region: REGION,- destinationPath,- expected: { SUBFOLDER_KEY: "subfolder-value" }- });- });-- // Deleting a folder takes secrets away from a recursive sync with no secret-level write to carry- // it, so the trigger has to come from the folder delete itself. Built on its own subtree so the- // destination holds nothing but this test's secret.- test("deleting a subfolder removes its secrets from the recursive sync above it", async () => {- const destinationPath = "/recursive-folder-delete-target/";-- await createFolder({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath: "/",- name: "audit"- });- const reports = await createFolder({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath: "/audit",- name: "reports"- });-- await createSecretV2({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath: "/audit/reports",- key: "AUDIT_KEY",- value: "audit-value"- });-- const { secretSync } = await createSecretSync({- name: "recursive-folder-delete",- projectId,- connectionId,- environmentSlug: ENV,- secretPath: "/audit",- region: REGION,- destinationPath,- initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,- includeAllSubFolders: true,- isAutoSyncEnabled: false,- authToken: adminToken- });-- await setAutoSync({ syncId: secretSync!.id, isAutoSyncEnabled: true, authToken: adminToken });-- // Wait for the secret to land, then for the destination to go quiet. Enabling auto sync can- // leave more than one run in flight, and a straggler arriving after the delete would empty the- // destination for a reason this test would then misread as the delete having triggered a sync.- await waitForDestinationSecrets({- region: REGION,- destinationPath,- expected: { AUDIT_KEY: "audit-value" }- });- await expectDestinationUnchanged({- region: REGION,- destinationPath,- expected: { AUDIT_KEY: "audit-value" }- });-- const runCountBeforeDelete = fakeParameterStore.at(REGION, destinationPath).runCount();-- // Removes "/audit/reports", leaving the sync on "/audit" in place: the route takes the folder- // by id and its parent's path, so secretPath here is the parent rather than the target.- await deleteFolder({- authToken: adminToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath: "/audit",- id: reports.id,- forceDelete: true- });-- // A run that starts after the delete, not merely an empty destination: only the delete can have- // queued it. waitForSyncRun returns once the run has started and the record reports a terminal- // status, which the previous run already satisfies, so the destination is read by polling rather- // than immediately.- await waitForSyncRun({- syncId: secretSync!.id,- region: REGION,- destinationPath,- runCountBefore: runCountBeforeDelete,- authToken: adminToken- });-- await waitForDestinationSecrets({ region: REGION, destinationPath, expected: {} });- });-});diff --git a/tests/suites/secretmanager/syncs/create_test.go b/tests/suites/secretmanager/syncs/create_test.gonew file mode 100644index 0000000000..e874c36d99--- /dev/null+++ b/tests/suites/secretmanager/syncs/create_test.go@@ -0,0 +1,245 @@+package syncs_test++import (+ "bytes"+ "encoding/json"+ "fmt"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++func TestSecretSync_Create(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse and keep the first when the same name is created twice in a project", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ newSync(t, proj, conn, repoScope("acme", "app"), withName("billing"))++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "other"), withName("billing"))++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t,+ fmt.Sprintf(`A Secret Sync with the name "billing" already exists for the project with ID "%s"`, proj.ID),+ message(res.Body))+ require.Equal(t, []string{"billing"}, listSyncNames(t, proj.Tenant().Admin.API, proj))+ })++ t.Run("should refuse and create nothing when the source folder does not exist", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "app"), fromPath("/does/not/exist"))++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, message(res.Body), `Could not find folder with path "/does/not/exist" in environment "dev"`)+ require.Empty(t, listSyncNames(t, proj.Tenant().Admin.API, proj))+ })++ t.Run("should refuse and create nothing when the connection is for another app", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ body := api.CreateAwsParameterStoreSecretSyncJSONRequestBody{+ Name: "aws-with-github",+ ProjectId: proj.ID,+ ConnectionId: conn.ID,+ Environment: "dev",+ SecretPath: "/",+ }+ body.DestinationConfig.Region = "us-east-1"+ body.DestinationConfig.Path = "/app/"+ body.SyncOptions.InitialSyncBehavior = "overwrite-destination"++ // Action+ res, err := tn.Admin.API.CreateAwsParameterStoreSecretSyncWithResponse(t.Context(), body)++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t,+ fmt.Sprintf("GitHub Connection with ID %s cannot be used to connect to AWS", conn.ID),+ message(res.Body))+ list, err := tn.Admin.API.ListAwsParameterStoreSecretSyncsWithResponse(t.Context(),+ &api.ListAwsParameterStoreSecretSyncsParams{ProjectId: proj.ID})+ require.NoError(t, err)+ require.NotNilf(t, list.JSON200, "listing returned %d: %s", list.StatusCode(), apierr.Body(list.Body))+ require.Empty(t, list.JSON200.SecretSyncs)+ })++ t.Run("should refuse and create nothing when the connection belongs to another tenant", func(t *testing.T) {+ t.Parallel()++ // Setup+ mine, theirs := h.NewTenant(t), h.NewTenant(t)+ proj := fixture.NewProject(t, mine, fixture.WithProjectType("secret-manager"))+ foreign := fixture.NewAppConnection(t, theirs, fixture.GitHubPATAppConnection)++ // Action+ res := createSync(t, proj, foreign, repoScope("acme", "app"))++ // Assert+ require.NotEqual(t, http.StatusOK, res.StatusCode(), "a sync was created over another tenant's connection")+ require.NotContains(t, string(res.Body), foreign.Name, "the refusal revealed the other tenant's connection")+ require.Empty(t, listSyncNames(t, mine.Admin.API, proj))+ })++ t.Run("should refuse and create nothing when the key schema has no secret key placeholder", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "app"), keySchema("INFISICAL_"))++ // Assert+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())+ require.Contains(t, message(res.Body), "Key schema must include exactly one {{secretKey}} placeholder")+ require.Empty(t, listSyncNames(t, proj.Tenant().Admin.API, proj))+ })++ t.Run("should refuse and create nothing when the key schema has a character outside the allowed set", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "app"), keySchema("INFISICAL.{{secretKey}}"))++ // Assert+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())+ require.Contains(t, message(res.Body), "Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed")+ require.Empty(t, listSyncNames(t, proj.Tenant().Admin.API, proj))+ })++ t.Run("should accept a key schema holding the secret key placeholder twice although the rule says exactly one", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `[BUG?] The validation message promises "exactly one {{secretKey}}", but the+ check only tests that one is present. Pinned as today's behaviour so the fix+ updates this claim.`)++ // Setup+ proj, conn, _ := setup(t)++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "app"), keySchema("{{secretKey}}_{{secretKey}}"))++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating returned %s", apierr.Body(res.Body))+ require.Equal(t, "{{secretKey}}_{{secretKey}}", *res.JSON200.SecretSync.SyncOptions.KeySchema)+ })++ t.Run("should refuse and create nothing when subfolders are combined with an import on the first sync", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `GitHub cannot import at all, so the rule is reached through a destination+ that can. The body is refused before the connection is looked at.`)++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ raw, err := json.Marshal(map[string]any{+ "name": "recursive-import",+ "projectId": proj.ID,+ "connectionId": conn.ID,+ "environment": "dev",+ "secretPath": "/",+ "destinationConfig": map[string]any{"region": "us-east-1", "path": "/app/"},+ "syncOptions": map[string]any{+ "initialSyncBehavior": "import-prioritize-source",+ "includeAllSubFolders": true,+ },+ })+ require.NoError(t, err)++ // Action+ res, err := tn.Admin.API.CreateAwsParameterStoreSecretSyncWithBodyWithResponse(t.Context(),+ "application/json", bytes.NewReader(raw))++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())+ require.Contains(t, message(res.Body), "A sync that includes subfolders cannot also import existing secrets from the destination")+ list, err := tn.Admin.API.ListAwsParameterStoreSecretSyncsWithResponse(t.Context(),+ &api.ListAwsParameterStoreSecretSyncsParams{ProjectId: proj.ID})+ require.NoError(t, err)+ require.NotNilf(t, list.JSON200, "listing returned %d: %s", list.StatusCode(), apierr.Body(list.Body))+ require.Empty(t, list.JSON200.SecretSyncs)+ })++ t.Run("should refuse a second sync to the same repository when the organization blocks duplicate destinations", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ first := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ second := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ blockDuplicateDestinations(t, tn)+ newSync(t, first, conn, repoScope("acme", "app"))++ // Action+ res := createSync(t, second, conn, repoScope("acme", "app"))++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, fmt.Sprintf("A secret sync with this destination already exists in project %s.", first.ID), message(res.Body))+ require.Empty(t, listSyncNames(t, tn.Admin.API, second))+ })++ t.Run("should report a duplicate from check-destination when another project already syncs to the repository", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ first := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ second := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ blockDuplicateDestinations(t, tn)+ newSync(t, first, conn, repoScope("acme", "app"))++ // Action+ res, err := tn.Admin.API.CheckGitHubSecretSyncDestinationWithResponse(t.Context(),+ api.CheckGitHubSecretSyncDestinationJSONRequestBody{+ ProjectId: second.ID,+ ConnectionId: &conn.ID,+ DestinationConfig: map[string]any{"scope": "repository", "owner": "acme", "repo": "app"},+ })++ // Assert+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "checking returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ require.True(t, res.JSON200.HasDuplicate)+ require.NotNil(t, res.JSON200.DuplicateProjectId)+ require.Equal(t, first.ID, *res.JSON200.DuplicateProjectId)+ })+}++func blockDuplicateDestinations(tt *testing.T, tn *harness.Tenant) {+ tt.Helper()+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(tt.Context(), tn.OrgID.String(),+ api.UpdateOrganizationJSONRequestBody{BlockDuplicateSecretSyncDestinations: new(true)})+ require.NoError(tt, err)+ require.Equalf(tt, http.StatusOK, res.StatusCode(), "blocking duplicate destinations returned %s", apierr.Body(res.Body))+}diff --git a/tests/suites/secretmanager/syncs/delete_test.go b/tests/suites/secretmanager/syncs/delete_test.gonew file mode 100644index 0000000000..c43921ee5e--- /dev/null+++ b/tests/suites/secretmanager/syncs/delete_test.go@@ -0,0 +1,142 @@+package syncs_test++import (+ "fmt"+ "net/http"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestSecretSync_Delete(t *testing.T) {+ t.Parallel()++ t.Run("should leave the destination secrets in place when a sync is deleted without removing them", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ secretmanager.CreateSecret(t, proj, "dev", "KEEP", "1")+ s.trigger(t)+ mark := gh.Mark(t)++ // Action+ res := s.delete(t, proj.Tenant().Admin.API, false)++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deleting returned %s", apierr.Body(res.Body))+ gh.ExpectNoEvent[github.SecretDeleted](t, nil, fakenet.Since(mark))+ require.Equal(t, "1", gh.Repo(t, "acme/app").Secrets["KEEP"].Value)+ s.awaitGone(t)+ })++ t.Run("should remove the synced secrets and then the sync when the delete removes secrets", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ gh.Seed(t, github.RepoSecret("acme/app", "UNMANAGED", "not ours"))+ s := newSync(t, proj, conn, repoScope("acme", "app"), disableSecretDeletion())+ secretmanager.CreateSecret(t, proj, "dev", "MANAGED", "1")+ s.trigger(t)++ // Action+ s.deleteRemovingSecrets(t)++ // Assert+ gh.ExpectEvent[github.SecretDeleted](t, named("MANAGED"), syncBudget)+ s.awaitGone(t)+ got := gh.Repo(t, "acme/app").Secrets+ require.NotContains(t, got, "MANAGED")+ require.Equal(t, "not ours", got["UNMANAGED"].Value)+ })++ t.Run("should keep the sync with the provider's reason when removing its secrets on delete fails", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ secretmanager.CreateSecret(t, proj, "dev", "MANAGED", "1")+ s.trigger(t)+ gh.Fail(t, "DELETE", "/repos/acme/app/actions/secrets/*", http.StatusForbidden,+ fakenet.Body(`{"message":"Resource not accessible by personal access token"}`))++ // Action+ s.deleteRemovingSecrets(t)++ // Assert+ got := s.awaitRemoveOutcome(t)+ require.Equal(t, "failed", got.status)+ require.Contains(t, got.message, "Resource not accessible by personal access token")+ require.Equal(t, "1", gh.Repo(t, "acme/app").Secrets["MANAGED"].Value)+ })++ t.Run("should cut the provider's message to 1024 characters when a remove fails with a long one", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ secretmanager.CreateSecret(t, proj, "dev", "MANAGED", "1")+ s.trigger(t)+ gh.Fail(t, "DELETE", "/repos/acme/app/actions/secrets/*", http.StatusUnprocessableEntity,+ fakenet.Body(fmt.Sprintf(`{"message":"%s"}`, strings.Repeat("x", 2000))))++ // Action+ s.removeSecrets(t)++ // Assert+ got := s.awaitRemoveOutcome(t)+ require.Equal(t, "failed", got.status)+ require.Len(t, got.message, 1024)+ require.True(t, strings.HasSuffix(got.message, "..."), "the cut message does not say it was cut: %s", got.message)+ })++ t.Run("should clear only the synced keys from the destination and leave Infisical unchanged on remove-secrets", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ gh.Seed(t, github.RepoSecret("acme/app", "UNMANAGED", "not ours"))+ s := newSync(t, proj, conn, repoScope("acme", "app"), disableSecretDeletion())+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")+ s.trigger(t)++ // Action+ s.removeSecrets(t)++ // Assert+ got := s.awaitRemoveOutcome(t)+ require.Equalf(t, "succeeded", got.status, "the remove failed: %s", got.message)+ dest := gh.Repo(t, "acme/app").Secrets+ require.NotContains(t, dest, "API_KEY")+ require.Equal(t, "not ours", dest["UNMANAGED"].Value)+ require.Equal(t, "api-value", secretmanager.GetSecret(t, proj, "dev", "API_KEY").Value)+ })++ t.Run("should refuse an import naming GitHub's limitation and start no job", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))++ // Action+ res, err := proj.Tenant().Admin.API.ImportGitHubSecretSyncSecretsWithResponse(t.Context(), s.ID,+ &api.ImportGitHubSecretSyncSecretsParams{ImportBehavior: api.ImportGitHubSecretSyncSecretsParamsImportBehaviorPrioritizeSource})++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, "GitHub does not support importing secrets.", message(res.Body))+ require.Nil(t, s.get(t).JSON200.SecretSync.ImportStatus)+ })+}diff --git a/tests/suites/secretmanager/syncs/helpers_test.go b/tests/suites/secretmanager/syncs/helpers_test.goindex e8649d8fb6..e973e00404 100644--- a/tests/suites/secretmanager/syncs/helpers_test.go+++ b/tests/suites/secretmanager/syncs/helpers_test.go@@ -1,11 +1,20 @@package syncs_testimport (+ "bytes""context"+ "encoding/json"+ "net/http"+ "path"+ "slices""testing"+ "time""github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/github""github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/fakenet""github.com/Infisical/infisical/tests/internal/apierr""github.com/Infisical/infisical/tests/internal/wait""github.com/google/uuid"@@ -24,8 +33,11 @@ type syncConfig struct {autoSync boolkeySchema stringdisableSecretDeletion bool+ includeSubFolders boolenvironment stringsecretPath string+ name string+ as *harness.Principal}type syncOption func(*syncConfig)@@ -40,6 +52,17 @@ func disableSecretDeletion() syncOption {return func(c *syncConfig) { c.disableSecretDeletion = true }}+func includeSubFolders() syncOption { return func(c *syncConfig) { c.includeSubFolders = true } }++func fromEnv(env string) syncOption { return func(c *syncConfig) { c.environment = env } }++func fromPath(p string) syncOption { return func(c *syncConfig) { c.secretPath = p } }++func withName(n string) syncOption { return func(c *syncConfig) { c.name = n } }++// as creates the sync as a principal other than the tenant administrator.+func as(p *harness.Principal) syncOption { return func(c *syncConfig) { c.as = p } }+type destination func(*testing.T) api.CreateGitHubSecretSyncJSONBody_DestinationConfig// repoScope is capped at 100 secrets by GitHub.@@ -66,13 +89,27 @@ func newSync(tt *testing.T, p *fixture.Project, conn *fixture.AppConnection,dest destination, opts ...syncOption) *sync {tt.Helper()- cfg := syncConfig{autoSync: false, environment: "dev", secretPath: "/"}+ res := createSync(tt, p, conn, dest, opts...)+ require.NotNilf(tt, res.JSON200, "creating a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return &sync{ID: res.JSON200.SecretSync.Id, proj: p}+}++// createSync is newSync for a test about whether the create is accepted.+func createSync(tt *testing.T, p *fixture.Project, conn *fixture.AppConnection,+ dest destination, opts ...syncOption) *api.CreateGitHubSecretSyncResponse {+ tt.Helper()++ cfg := syncConfig{autoSync: false, environment: "dev", secretPath: "/", name: "sync-" + uuid.NewString()[:8]}for _, o := range opts {o(&cfg)}+ client := p.Tenant().Admin.API+ if cfg.as != nil {+ client = cfg.as.API+ }body := api.CreateGitHubSecretSyncJSONRequestBody{- Name: "sync-" + uuid.NewString()[:8],+ Name: cfg.name,ProjectId: p.ID,ConnectionId: conn.ID,Environment: cfg.environment,@@ -88,11 +125,13 @@ func newSync(tt *testing.T, p *fixture.Project, conn *fixture.AppConnection,if cfg.disableSecretDeletion {body.SyncOptions.DisableSecretDeletion = &cfg.disableSecretDeletion}+ if cfg.includeSubFolders {+ body.SyncOptions.IncludeAllSubFolders = &cfg.includeSubFolders+ }- res, err := p.Tenant().Admin.API.CreateGitHubSecretSyncWithResponse(tt.Context(), body)+ res, err := client.CreateGitHubSecretSyncWithResponse(tt.Context(), body)require.NoError(tt, err, "creating a sync")- require.NotNilf(tt, res.JSON200, "creating a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))- return &sync{ID: res.JSON200.SecretSync.Id, proj: p}+ return res}// trigger runs the sync and waits on its status rather than the destination, so a@@ -112,11 +151,67 @@ func (s *sync) triggerExpectingFailure(tt *testing.T) outcome {func (s *sync) start(tt *testing.T) {tt.Helper()- res, err := s.proj.Tenant().Admin.API.SyncGitHubSecretSyncWithResponse(tt.Context(), s.ID)- require.NoError(tt, err, "triggering a sync")+ var res *api.SyncGitHubSecretSyncResponse+ whenIdle(tt, "triggering a sync", func(ctx context.Context) (int, []byte, error) {+ var err error+ res, err = s.proj.Tenant().Admin.API.SyncGitHubSecretSyncWithResponse(ctx, s.ID)+ if err != nil {+ return 0, nil, err+ }+ return res.StatusCode(), res.Body, nil+ })require.NotNilf(tt, res.JSON200, "triggering a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))}+func (s *sync) removeSecrets(tt *testing.T) {+ tt.Helper()+ var res *api.RemoveGitHubSecretSyncSecretsResponse+ whenIdle(tt, "removing synced secrets", func(ctx context.Context) (int, []byte, error) {+ var err error+ res, err = s.proj.Tenant().Admin.API.RemoveGitHubSecretSyncSecretsWithResponse(ctx, s.ID)+ if err != nil {+ return 0, nil, err+ }+ return res.StatusCode(), res.Body, nil+ })+ require.NotNilf(tt, res.JSON200, "removing synced secrets returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++// deleteRemovingSecrets is a delete with removeSecrets, which runs on the queue.+func (s *sync) deleteRemovingSecrets(tt *testing.T) {+ tt.Helper()+ param := api.DeleteGitHubSecretSyncParamsRemoveSecretsTrue+ var res *api.DeleteGitHubSecretSyncResponse+ whenIdle(tt, "deleting a sync", func(ctx context.Context) (int, []byte, error) {+ var err error+ res, err = s.proj.Tenant().Admin.API.DeleteGitHubSecretSyncWithResponse(ctx, s.ID,+ &api.DeleteGitHubSecretSyncParams{RemoveSecrets: ¶m})+ if err != nil {+ return 0, nil, err+ }+ return res.StatusCode(), res.Body, nil+ })+ require.NotNilf(tt, res.JSON200, "deleting a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+}++// whenIdle retries a call the sync's job lock refuses. A job records its final status+// a moment before it releases the lock, so a call made as soon as the status reads+// terminal can still find the previous job holding it.+func whenIdle(tt *testing.T, what string, call func(context.Context) (int, []byte, error)) {+ tt.Helper()+ var body []byte+ _, err := wait.For(tt.Context(), func(ctx context.Context) (struct{}, bool, error) {+ status, b, err := call(ctx)+ if err != nil {+ return struct{}{}, false, err+ }+ body = b+ busy := status == http.StatusBadRequest && bytes.Contains(b, []byte("A job for this sync is already in progress"))+ return struct{}{}, !busy, nil+ })+ require.NoErrorf(tt, err, "%s: %s", what, apierr.Body(body))+}+type outcome struct {status stringmessage string@@ -130,6 +225,23 @@ func (s *sync) awaitTerminal(tt *testing.T) {func (s *sync) awaitOutcome(tt *testing.T) outcome {tt.Helper()+ return s.await(tt, "the sync to finish", func(r *api.GetGitHubSecretSyncResponse) (*string, *string) {+ return r.JSON200.SecretSync.SyncStatus, r.JSON200.SecretSync.LastSyncMessage+ })+}++// awaitRemoveOutcome waits on the remove job, which records its own status beside+// the sync's.+func (s *sync) awaitRemoveOutcome(tt *testing.T) outcome {+ tt.Helper()+ return s.await(tt, "the remove to finish", func(r *api.GetGitHubSecretSyncResponse) (*string, *string) {+ return r.JSON200.SecretSync.RemoveStatus, r.JSON200.SecretSync.LastRemoveMessage+ })+}++func (s *sync) await(tt *testing.T, what string,+ read func(*api.GetGitHubSecretSyncResponse) (status, message *string)) outcome {+ tt.Helper()got, err := wait.For(tt.Context(), func(ctx context.Context) (outcome, bool, error) {res, err := s.proj.Tenant().Admin.API.GetGitHubSecretSyncWithResponse(ctx, s.ID)@@ -140,14 +252,120 @@ func (s *sync) awaitOutcome(tt *testing.T) outcome {return outcome{}, false, nil}var out outcome- if v := res.JSON200.SecretSync.SyncStatus; v != nil {- out.status = *v+ status, message := read(res)+ if status != nil {+ out.status = *status}- if v := res.JSON200.SecretSync.LastSyncMessage; v != nil {- out.message = *v+ if message != nil {+ out.message = *message}return out, out.status == "succeeded" || out.status == "failed", nil})- require.NoError(tt, err, "waiting for the sync to finish")+ require.NoError(tt, err, "waiting for "+what)return got}++// awaitGone waits for a delete that runs on the queue, such as one that removes the+// destination secrets first.+func (s *sync) awaitGone(tt *testing.T) {+ tt.Helper()+ wait.Until(tt, "the sync to be deleted", func() bool {+ res, err := s.proj.Tenant().Admin.API.GetGitHubSecretSyncWithResponse(tt.Context(), s.ID)+ return err == nil && res.StatusCode() == http.StatusNotFound+ })+}++func (s *sync) get(tt *testing.T) *api.GetGitHubSecretSyncResponse {+ tt.Helper()+ res, err := s.proj.Tenant().Admin.API.GetGitHubSecretSyncWithResponse(tt.Context(), s.ID)+ require.NoError(tt, err, "reading a sync")+ require.NotNilf(tt, res.JSON200, "reading a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ return res+}++// update sends the body as JSON, because the generated body's destination config is+// a union and would serialise as {}.+func (s *sync) update(tt *testing.T, client *api.ClientWithResponses, body map[string]any) *api.UpdateGitHubSecretSyncResponse {+ tt.Helper()+ raw, err := json.Marshal(body)+ require.NoError(tt, err)+ res, err := client.UpdateGitHubSecretSyncWithBodyWithResponse(tt.Context(), s.ID, "application/json", bytes.NewReader(raw))+ require.NoError(tt, err, "updating a sync")+ return res+}++func (s *sync) delete(tt *testing.T, client *api.ClientWithResponses, removeSecrets bool) *api.DeleteGitHubSecretSyncResponse {+ tt.Helper()+ param := api.DeleteGitHubSecretSyncParamsRemoveSecretsFalse+ if removeSecrets {+ param = api.DeleteGitHubSecretSyncParamsRemoveSecretsTrue+ }+ res, err := client.DeleteGitHubSecretSyncWithResponse(tt.Context(), s.ID,+ &api.DeleteGitHubSecretSyncParams{RemoveSecrets: ¶m})+ require.NoError(tt, err, "deleting a sync")+ return res+}++func listSyncNames(tt *testing.T, client *api.ClientWithResponses, p *fixture.Project) []string {+ tt.Helper()+ res, err := client.ListGitHubSecretSyncsWithResponse(tt.Context(), &api.ListGitHubSecretSyncsParams{ProjectId: p.ID})+ require.NoError(tt, err, "listing syncs")+ require.NotNilf(tt, res.JSON200, "listing syncs returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ names := make([]string, 0, len(res.JSON200.SecretSyncs))+ for _, s := range res.JSON200.SecretSyncs {+ names = append(names, s.Name)+ }+ return names+}++// deleteFolder force-deletes a folder at an absolute path such as "/app/api".+func deleteFolder(tt *testing.T, p *fixture.Project, env, folderPath string) {+ tt.Helper()+ parent, name := path.Split(path.Clean(folderPath))+ res, err := p.Tenant().Admin.API.DeleteSecretFolderWithResponse(tt.Context(), name, api.DeleteSecretFolderJSONRequestBody{+ ProjectId: p.ID,+ Environment: env,+ Path: &parent,+ ForceDelete: new(true),+ })+ require.NoErrorf(tt, err, "deleting folder %s", folderPath)+ require.Equalf(tt, http.StatusOK, res.StatusCode(), "deleting folder %s returned %s", folderPath, apierr.Body(res.Body))+}++// message is an error body's message. A validation failure carries a list of+// issues there, which comes back as its JSON text.+func message(body []byte) string {+ var out struct {+ Message json.RawMessage `json:"message"`+ }+ if err := json.Unmarshal(body, &out); err != nil {+ return string(body)+ }+ var s string+ if err := json.Unmarshal(out.Message, &s); err == nil {+ return s+ }+ return string(out.Message)+}++// syncBudget is how long a fake event takes to follow a change Infisical queues: up+// to 10 s of start jitter on every sync job, plus a 3 s debounce before an auto-sync.+var syncBudget = fakenet.Within(30 * time.Second)++func created(name string) func(github.SecretCreated) bool {+ return func(e github.SecretCreated) bool { return e.SecretName == name }+}++func createdIn(scope, name string) func(github.SecretCreated) bool {+ return func(e github.SecretCreated) bool { return e.Scope == scope && e.SecretName == name }+}++// keysOf is the sorted key set a destination store holds.+func keysOf(secrets map[string]github.Secret) []string {+ keys := make([]string, 0, len(secrets))+ for k := range secrets {+ keys = append(keys, k)+ }+ slices.Sort(keys)+ return keys+}diff --git a/tests/suites/secretmanager/syncs/license_test.go b/tests/suites/secretmanager/syncs/license_test.gonew file mode 100644index 0000000000..04e72cc8a4--- /dev/null+++ b/tests/suites/secretmanager/syncs/license_test.go@@ -0,0 +1,121 @@+package syncs_test++import (+ "fmt"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++const enterpriseSyncRefusal = "Failed to create secret sync due to plan restriction. Upgrade plan to access enterprise secret syncs."++func TestSecretSync_License(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse a create past the plan's sync limit and keep the syncs there are", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().With(license.SecretSyncLimit, 1)))+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ newSync(t, proj, conn, repoScope("acme", "app"), withName("only"))++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "other"))++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, "Failed to create secret sync due to plan limit reached. Upgrade plan to add more secret syncs.", message(res.Body))+ require.Equal(t, []string{"only"}, listSyncNames(t, tn.Admin.API, proj))+ })++ t.Run("should refuse a Chef sync when the plan does not include enterprise syncs", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `The plan is checked before the connection is looked at, so the refusal needs+ no Chef connection. A GitHub one stands in.`)++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.EnterpriseSecretSyncs)))+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)++ // Action+ res, err := tn.Admin.API.CreateChefSecretSyncWithResponse(t.Context(), chefSyncBody(proj, conn))++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, enterpriseSyncRefusal, message(res.Body))+ })++ t.Run("should refuse an OCI Vault sync when the plan does not include enterprise syncs", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.EnterpriseSecretSyncs)))+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)++ // Action+ res, err := tn.Admin.API.CreateOciVaultSecretSyncWithResponse(t.Context(), ociVaultSyncBody(proj, conn))++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, enterpriseSyncRefusal, message(res.Body))+ })++ t.Run("should pass the plan check and refuse the connection when the plan includes enterprise syncs", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)++ // Action+ res, err := tn.Admin.API.CreateChefSecretSyncWithResponse(t.Context(), chefSyncBody(proj, conn))++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t, fmt.Sprintf("GitHub Connection with ID %s cannot be used to connect to Chef", conn.ID), message(res.Body))+ })+}++func chefSyncBody(p *fixture.Project, conn *fixture.AppConnection) api.CreateChefSecretSyncJSONRequestBody {+ body := api.CreateChefSecretSyncJSONRequestBody{+ Name: "chef",+ ProjectId: p.ID,+ ConnectionId: conn.ID,+ Environment: "dev",+ SecretPath: "/",+ }+ body.DestinationConfig.DataBagName = "app"+ body.DestinationConfig.DataBagItemName = "secrets"+ body.SyncOptions.InitialSyncBehavior = "overwrite-destination"+ return body+}++func ociVaultSyncBody(p *fixture.Project, conn *fixture.AppConnection) api.CreateOciVaultSecretSyncJSONRequestBody {+ body := api.CreateOciVaultSecretSyncJSONRequestBody{+ Name: "oci-vault",+ ProjectId: p.ID,+ ConnectionId: conn.ID,+ Environment: "dev",+ SecretPath: "/",+ }+ body.DestinationConfig.CompartmentOcid = "ocid1.compartment.oc1..aaaa"+ body.DestinationConfig.VaultOcid = "ocid1.vault.oc1..aaaa"+ body.DestinationConfig.KeyOcid = "ocid1.key.oc1..aaaa"+ body.SyncOptions.InitialSyncBehavior = "overwrite-destination"+ return body+}diff --git a/tests/suites/secretmanager/syncs/permission_test.go b/tests/suites/secretmanager/syncs/permission_test.gonew file mode 100644index 0000000000..3991a63142--- /dev/null+++ b/tests/suites/secretmanager/syncs/permission_test.go@@ -0,0 +1,215 @@+package syncs_test++import (+ "fmt"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestSecretSync_Access(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should refuse every operation on another tenant's sync and change nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"), withName("victim"))+ outsider := h.NewTenant(t).Admin.API+ ctx := t.Context()++ // Action+ get, err := outsider.GetGitHubSecretSyncWithResponse(ctx, s.ID)+ require.NoError(t, err)+ trigger, err := outsider.SyncGitHubSecretSyncWithResponse(ctx, s.ID)+ require.NoError(t, err)+ update := s.update(t, outsider, map[string]any{"name": "taken-over"})+ del := s.delete(t, outsider, false)++ // Assert+ for op, res := range map[string]struct {+ status int+ body []byte+ }{+ "get": {get.StatusCode(), get.Body},+ "trigger": {trigger.StatusCode(), trigger.Body},+ "update": {update.StatusCode(), update.Body},+ "delete": {del.StatusCode(), del.Body},+ } {+ require.NotEqualf(t, http.StatusOK, res.status, "%s on another tenant's sync was accepted", op)+ require.NotContainsf(t, string(res.body), "victim", "%s revealed the sync's name", op)+ }+ got := s.get(t).JSON200.SecretSync+ require.Equal(t, "victim", got.Name)+ require.Nil(t, got.SyncStatus, "a sync was queued")+ })++ t.Run("should refuse a sync id on another destination's route and queue nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ admin := proj.Tenant().Admin.API++ // Action+ get, err := admin.GetAwsParameterStoreSecretSyncWithResponse(t.Context(), s.ID)+ require.NoError(t, err)+ trigger, err := admin.SyncAwsParameterStoreSecretSyncWithResponse(t.Context(), s.ID)+ require.NoError(t, err)++ // Assert+ want := fmt.Sprintf(`Secret sync with ID "%s" is not configured for AWS Parameter Store`, s.ID)+ require.Equal(t, http.StatusBadRequest, get.StatusCode())+ require.Equal(t, want, message(get.Body))+ require.Equal(t, http.StatusBadRequest, trigger.StatusCode())+ require.Equal(t, want, message(trigger.Body))+ require.Nil(t, s.get(t).JSON200.SecretSync.SyncStatus, "the sync was queued through the wrong route")+ })++ t.Run("should let a viewer read and list syncs", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"), withName("visible"))+ viewer := proj.NewMachineIdentity(t, fixture.WithRoles("viewer"))++ // Action+ res, err := viewer.API.GetGitHubSecretSyncWithResponse(t.Context(), s.ID)++ // Assert+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "a viewer reading a sync got %d: %s", res.StatusCode(), apierr.Body(res.Body))+ require.Equal(t, "visible", res.JSON200.SecretSync.Name)+ require.Equal(t, []string{"visible"}, listSyncNames(t, viewer.API, proj))+ })++ t.Run("should refuse a viewer's create, update, trigger and delete and change nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"), withName("guarded"))+ viewer := proj.NewMachineIdentity(t, fixture.WithRoles("viewer"))++ // Action+ create := createSync(t, proj, conn, repoScope("acme", "other"), as(viewer))+ update := s.update(t, viewer.API, map[string]any{"name": "renamed"})+ trigger, err := viewer.API.SyncGitHubSecretSyncWithResponse(t.Context(), s.ID)+ require.NoError(t, err)+ del := s.delete(t, viewer.API, false)++ // Assert+ require.Equal(t, http.StatusForbidden, create.StatusCode())+ require.Equal(t, http.StatusForbidden, update.StatusCode())+ require.Equal(t, http.StatusForbidden, trigger.StatusCode())+ require.Equal(t, http.StatusForbidden, del.StatusCode())+ got := s.get(t).JSON200.SecretSync+ require.Equal(t, "guarded", got.Name)+ require.Nil(t, got.SyncStatus, "a sync was queued")+ require.Equal(t, []string{"guarded"}, listSyncNames(t, proj.Tenant().Admin.API, proj))+ })++ t.Run("should refuse and create nothing when the role allows a different connection", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ allowed := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ other := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ creator := connectionScopedCreator(t, proj, allowed)++ // Action+ res := createSync(t, proj, other, repoScope("acme", "app"), as(creator))++ // Assert+ require.Equalf(t, http.StatusForbidden, res.StatusCode(), "creating returned %s", apierr.Body(res.Body))+ require.Empty(t, listSyncNames(t, tn.Admin.API, proj))+ })++ t.Run("should accept a create when the connection is the one the role allows", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ allowed := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)+ creator := connectionScopedCreator(t, proj, allowed)++ // Action+ res := createSync(t, proj, allowed, repoScope("acme", "app"), as(creator), withName("scoped"))++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating returned %s", apierr.Body(res.Body))+ require.Equal(t, []string{"scoped"}, listSyncNames(t, tn.Admin.API, proj))+ })++ t.Run("should list only the syncs whose source path the role allows", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ secretmanager.CreateFolder(t, proj, "dev", "/a")+ secretmanager.CreateFolder(t, proj, "dev", "/b")+ newSync(t, proj, conn, repoScope("acme", "a"), fromPath("/a"), withName("on-a"))+ hidden := newSync(t, proj, conn, repoScope("acme", "b"), fromPath("/b"), withName("on-b"))+ proj.NewRole(t, "a-sync-reader", fixture.Permission{Subject: "secret-syncs", Action: []string{"read"},+ Conditions: map[string]any{"secretPath": map[string]any{"$eq": "/a"}}})+ reader := proj.NewMachineIdentity(t, fixture.WithRoles("a-sync-reader"))++ // Action+ names := listSyncNames(t, reader.API, proj)++ // Assert+ require.Equal(t, []string{"on-a"}, names)+ res, err := reader.API.GetGitHubSecretSyncWithResponse(t.Context(), hidden.ID)+ require.NoError(t, err)+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ })++ t.Run("should refuse deleting a connection a sync uses and keep both", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ admin := proj.Tenant().Admin.API++ // Action+ res, err := admin.DeleteGitHubAppConnectionWithResponse(t.Context(), conn.ID)++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t,+ "Cannot delete App Connection with existing connections. Remove all existing connections and try again.",+ message(res.Body))+ still, err := admin.GetGitHubAppConnectionWithResponse(t.Context(), conn.ID)+ require.NoError(t, err)+ require.Equal(t, http.StatusOK, still.StatusCode(), "the connection is gone")+ require.Equal(t, conn.ID, s.get(t).JSON200.SecretSync.ConnectionId)+ })+}++// connectionScopedCreator is a project member whose role creates syncs only over one+// connection. An organization member, because using an organization connection is an+// organization permission the project role cannot grant.+func connectionScopedCreator(tt *testing.T, p *fixture.Project, conn *fixture.AppConnection) *harness.Principal {+ tt.Helper()+ p.NewRole(tt, "one-connection-sync-creator",+ fixture.Permission{Subject: "secret-syncs", Action: []string{"read", "create"},+ Conditions: map[string]any{"connectionId": map[string]any{"$eq": conn.ID.String()}}},+ fixture.Permission{Subject: "secrets", Action: []string{"describeSecret", "readValue"}})+ creator := p.Tenant().NewMachineIdentity(tt, harness.OrgRole("member"))+ p.Grant(tt, creator, "one-connection-sync-creator")+ return creator+}diff --git a/tests/suites/secretmanager/syncs/recursive_test.go b/tests/suites/secretmanager/syncs/recursive_test.gonew file mode 100644index 0000000000..c47ba29ce5--- /dev/null+++ b/tests/suites/secretmanager/syncs/recursive_test.go@@ -0,0 +1,271 @@+package syncs_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++const deniedSubfolder = `You do not have permission to read secrets at path "/backend/api" in environment "dev".`++func TestSecretSync_RecursivePermissions(t *testing.T) {+ t.Parallel()++ t.Run("should refuse and create nothing when subfolders include one the actor cannot read", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `The sync worker reads every folder a sync covers with access checks off,+ so create is the only gate. A folder grant gives read on a parent while the base+ role denies the child.`)++ // Setup+ proj, conn, actor := deniedSubtree(t)++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "app"), fromPath("/backend"), includeSubFolders(), as(actor))++ // Assert+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Equal(t, deniedSubfolder, message(res.Body))+ require.Empty(t, listSyncNames(t, proj.Tenant().Admin.API, proj))+ })++ t.Run("should refuse and keep the destination when the actor repoints a recursive sync over a subfolder they cannot read", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `The administrator could read the whole subtree, so the sync is legitimate.+ Without this check an actor with Edit on the source alone sends the denied+ folder to a destination of their choosing.`)++ // Setup+ proj, conn, actor := deniedSubtree(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/backend"), includeSubFolders())++ // Action+ res := s.update(t, actor.API, map[string]any{+ "destinationConfig": map[string]any{"scope": "repository", "owner": "acme", "repo": "actor-controlled"},+ })++ // Assert+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Equal(t, deniedSubfolder, message(res.Body))+ require.Contains(t, string(s.get(t).Body), `"repo":"app"`)+ })++ t.Run("should refuse and keep subfolders off when the actor turns them on over a subfolder they cannot read", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, actor := deniedSubtree(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/backend"))++ // Action+ res := s.update(t, actor.API, map[string]any{+ "syncOptions": map[string]any{"initialSyncBehavior": "overwrite-destination", "includeAllSubFolders": true},+ })++ // Assert+ require.Equal(t, http.StatusForbidden, res.StatusCode())+ require.Equal(t, deniedSubfolder, message(res.Body))+ require.False(t, includesSubFolders(t, s))+ })+}++func TestSecretSync_RecursiveConflicts(t *testing.T) {+ t.Parallel()++ t.Run("should refuse and create nothing when two folders hold the same key, naming the key and both folders", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ duplicateUnder(t, proj, "/backend", "DB_URL")++ // Action+ res := createSync(t, proj, conn, repoScope("acme", "app"), fromPath("/backend"), includeSubFolders())++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, message(res.Body), `"DB_URL" in /backend and /backend/child`)+ require.Empty(t, listSyncNames(t, proj.Tenant().Admin.API, proj))+ })++ t.Run("should accept turning subfolders off although the subtree now holds a duplicate key", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `The checks an update runs read the options it is about to store. A request+ that carries syncOptions replaces them outright, so this one stores a sync+ without subfolders and has nothing to flatten.`)++ // Setup+ proj, conn, _ := setup(t)+ s := recursiveSyncWithLateDuplicate(t, proj, conn, "/reports")++ // Action+ res := s.update(t, proj.Tenant().Admin.API, map[string]any{+ "syncOptions": map[string]any{"initialSyncBehavior": "overwrite-destination"},+ })++ // Assert+ require.Equalf(t, http.StatusOK, res.StatusCode(), "turning subfolders off returned %s", apierr.Body(res.Body))+ require.False(t, includesSubFolders(t, s))+ })++ t.Run("should refuse and keep the name when an update that leaves the options alone meets a duplicate key", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `An update without syncOptions keeps the stored ones, so it is still checked+ as a sync that includes subfolders.`)++ // Setup+ proj, conn, _ := setup(t)+ s := recursiveSyncWithLateDuplicate(t, proj, conn, "/metrics")+ before := s.get(t).JSON200.SecretSync.Name++ // Action+ res := s.update(t, proj.Tenant().Admin.API, map[string]any{"name": "renamed"})++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, message(res.Body), `"LATE_KEY" in /metrics and /metrics/child`)+ require.Equal(t, before, s.get(t).JSON200.SecretSync.Name)+ })++ t.Run("should refuse and keep subfolders off when turning them on meets a duplicate key", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ duplicateUnder(t, proj, "/backend", "DB_URL")+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/backend"))++ // Action+ res := s.update(t, proj.Tenant().Admin.API, map[string]any{+ "syncOptions": map[string]any{"initialSyncBehavior": "overwrite-destination", "includeAllSubFolders": true},+ })++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, message(res.Body), `"DB_URL" in /backend and /backend/child`)+ require.False(t, includesSubFolders(t, s))+ })++ t.Run("should list every duplicate key with its folders from the conflict check", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, _, _ := setup(t)+ duplicateUnder(t, proj, "/backend", "DB_URL")+ for _, at := range []string{"/backend", "/backend/child"} {+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "v"+at, secretmanager.WithPath(at))+ }+ secretmanager.CreateSecret(t, proj, "dev", "UNIQUE_KEY", "v", secretmanager.WithPath("/backend"))++ // Action+ res, err := proj.Tenant().Admin.API.CheckGitHubSecretSyncRecursiveConflictsWithResponse(t.Context(),+ api.CheckGitHubSecretSyncRecursiveConflictsJSONRequestBody{ProjectId: proj.ID, Environment: "dev", SecretPath: "/backend"})++ // Assert+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "checking returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ got := map[string][]string{}+ for _, c := range res.JSON200.Conflicts {+ got[c.Key] = c.Paths+ }+ require.Len(t, got, 2)+ require.ElementsMatch(t, []string{"/backend", "/backend/child"}, got["DB_URL"])+ require.ElementsMatch(t, []string{"/backend", "/backend/child"}, got["API_KEY"])+ })+}++func TestSecretSync_RecursiveTrigger(t *testing.T) {+ t.Parallel()++ t.Run("should push a secret written in a subfolder to the recursive sync above it", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateFolder(t, proj, "dev", "/backend/api")+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/backend"), includeSubFolders(), autoSync(true))+ s.awaitTerminal(t)++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "SUBFOLDER_KEY", "subfolder-value", secretmanager.WithPath("/backend/api"))++ // Assert+ gh.ExpectEvent[github.SecretCreated](t, created("SUBFOLDER_KEY"), syncBudget)+ require.Equal(t, "subfolder-value", gh.Repo(t, "acme/app").Secrets["SUBFOLDER_KEY"].Value)+ })++ t.Run("should remove a deleted subfolder's secrets from the recursive sync above it", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `No secret-level write carries a folder delete, so the run has to be queued+ by the delete itself. The sync exists before the secret is written, so the only+ runs are the one for that write and the one for the delete.`)++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateFolder(t, proj, "dev", "/audit/reports")+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/audit"), includeSubFolders(), autoSync(true))+ s.awaitTerminal(t)+ secretmanager.CreateSecret(t, proj, "dev", "AUDIT_KEY", "audit-value", secretmanager.WithPath("/audit/reports"))+ gh.ExpectEvent[github.SecretCreated](t, created("AUDIT_KEY"), syncBudget)+ mark := gh.Mark(t)++ // Action+ deleteFolder(t, proj, "dev", "/audit/reports")++ // Assert+ gh.ExpectEvent[github.SecretDeleted](t, named("AUDIT_KEY"), fakenet.Since(mark), syncBudget)+ require.NotContains(t, gh.Repo(t, "acme/app").Secrets, "AUDIT_KEY")+ })+}++// deniedSubtree is /backend and /backend/api, each holding a secret, and an actor+// whose base role grants nothing and whose folder grant is Manage on /backend only.+// Manage is the lowest tier that creates syncs, and a folder grant does not reach the+// folders below it.+func deniedSubtree(tt *testing.T) (*fixture.Project, *fixture.AppConnection, *harness.Principal) {+ tt.Helper()+ proj, conn, _ := setup(tt)+ secretmanager.CreateFolder(tt, proj, "dev", "/backend/api")+ secretmanager.CreateSecret(tt, proj, "dev", "BACKEND_KEY", "backend-value", secretmanager.WithPath("/backend"))+ secretmanager.CreateSecret(tt, proj, "dev", "API_KEY", "api-value", secretmanager.WithPath("/backend/api"))+ actor := proj.NewMachineIdentity(tt, fixture.WithRoles("no-access"))+ secretmanager.GrantFolderAccess(tt, proj, actor, secretmanager.Location{Env: "dev", Path: "/backend"}, secretmanager.FolderManage)+ return proj, conn, actor+}++// duplicateUnder writes the same key into a folder and its child folder.+func duplicateUnder(tt *testing.T, p *fixture.Project, folder, key string) {+ tt.Helper()+ secretmanager.CreateFolder(tt, p, "dev", folder+"/child")+ for _, at := range []string{folder, folder + "/child"} {+ secretmanager.CreateSecret(tt, p, "dev", key, "value-for-"+at, secretmanager.WithPath(at))+ }+}++// recursiveSyncWithLateDuplicate is a recursive sync whose subtree was clean when it+// was saved and has held a duplicate key since. A create over an existing duplicate is+// refused, so this is the only way a sync gets into that state.+func recursiveSyncWithLateDuplicate(tt *testing.T, p *fixture.Project, conn *fixture.AppConnection, folder string) *sync {+ tt.Helper()+ secretmanager.CreateFolder(tt, p, "dev", folder+"/child")+ s := newSync(tt, p, conn, repoScope("acme", "app"), fromPath(folder), includeSubFolders())+ for _, at := range []string{folder, folder + "/child"} {+ secretmanager.CreateSecret(tt, p, "dev", "LATE_KEY", "value-for-"+at, secretmanager.WithPath(at))+ }+ return s+}++func includesSubFolders(tt *testing.T, s *sync) bool {+ tt.Helper()+ v := s.get(tt).JSON200.SecretSync.SyncOptions.IncludeAllSubFolders+ return v != nil && *v+}diff --git a/tests/suites/secretmanager/syncs/status_test.go b/tests/suites/secretmanager/syncs/status_test.gonew file mode 100644index 0000000000..c58430dc10--- /dev/null+++ b/tests/suites/secretmanager/syncs/status_test.go@@ -0,0 +1,151 @@+package syncs_test++import (+ "bytes"+ "encoding/json"+ "fmt"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++func TestSecretSync_Status(t *testing.T) {+ t.Parallel()++ t.Run("should end succeeded and deliver the value when the destination fails once", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `A provider error is retried by the queue with backoff. One failure costs a+ 3 s retry, which fits the wait; a failure on every attempt would not.`)++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ gh.Fail(t, "PUT", "/repos/acme/app/actions/secrets/*", http.StatusInternalServerError, fakenet.Times(1))++ // Action+ got := s.triggerExpectingFailure(t)++ // Assert+ require.Equalf(t, "succeeded", got.status, "the sync did not recover: %s", got.message)+ require.Equal(t, "api-value", gh.Repo(t, "acme/app").Secrets["API_KEY"].Value)+ require.Equal(t, 2, gh.Received(t, "PUT", "/repos/acme/app/actions/secrets/API_KEY"))+ })++ t.Run("should leave lastSyncedAt empty after a failed run and set it after a successful one", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ createSecrets(t, proj, 101)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ require.Equal(t, "failed", s.triggerExpectingFailure(t).status)+ require.Nil(t, s.get(t).JSON200.SecretSync.LastSyncedAt, "a failed run recorded a sync time")+ secretmanager.DeleteSecret(t, proj, "dev", "BULK_000")++ // Action+ s.trigger(t)++ // Assert+ require.NotNil(t, s.get(t).JSON200.SecretSync.LastSyncedAt)+ })++ t.Run("should keep lastSyncedAt at the last success when a later run fails", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ createSecrets(t, proj, 100)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ s.trigger(t)+ synced := s.get(t).JSON200.SecretSync.LastSyncedAt+ require.NotNil(t, synced)+ secretmanager.CreateSecret(t, proj, "dev", "ONE_TOO_MANY", "v")++ // Action+ got := s.triggerExpectingFailure(t)++ // Assert+ require.Equal(t, "failed", got.status)+ after := s.get(t).JSON200.SecretSync.LastSyncedAt+ require.NotNil(t, after)+ require.True(t, synced.Equal(*after), "lastSyncedAt moved from %s to %s on a failed run", synced, after)+ })++ t.Run("should fail saying the folder no longer exists while the source environment is deleted, and succeed once it is restored", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `[BUG?] The folder still exists; its environment is soft-deleted. The message+ blames the folder, so the fix updates this claim.`)++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateSecret(t, proj, "staging", "API_KEY", "api-value")+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromEnv("staging"))+ envID := environmentID(t, proj, "staging")+ admin := proj.Tenant().Admin.API+ deleted, err := admin.DeleteEnvironmentWithResponse(t.Context(), proj.ID, envID, nil)+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, deleted.StatusCode(), "deleting the environment returned %s", apierr.Body(deleted.Body))++ // Action+ failed := s.triggerExpectingFailure(t)+ restored, err := admin.RestoreEnvironmentWithResponse(t.Context(), proj.ID, envID)+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, restored.StatusCode(), "restoring the environment returned %s", apierr.Body(restored.Body))+ recovered := s.triggerExpectingFailure(t)++ // Assert+ require.Equal(t, "failed", failed.status)+ require.Contains(t, failed.message, "folder no longer exists")+ require.Equalf(t, "succeeded", recovered.status, "the sync did not recover: %s", recovered.message)+ require.Equal(t, "api-value", gh.Repo(t, "acme/app").Secrets["API_KEY"].Value)+ })++ t.Run("should hide a sync once its project is deleted", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))+ admin := proj.Tenant().Admin.API+ res, err := admin.DeleteProjectWithResponse(t.Context(), proj.ID)+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deleting the project returned %s", apierr.Body(res.Body))++ // Action+ got, err := admin.GetGitHubSecretSyncWithResponse(t.Context(), s.ID)++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusNotFound, got.StatusCode())+ require.Equal(t, fmt.Sprintf(`Could not find GitHub Sync with ID "%s"`, s.ID), message(got.Body))+ })+}++// createSecrets creates BULK_000 to BULK_<n-1> at the root of dev in one request.+func createSecrets(tt *testing.T, p *fixture.Project, n int) {+ tt.Helper()+ secrets := make([]map[string]string, 0, n)+ for i := range n {+ secrets = append(secrets, map[string]string{"secretKey": fmt.Sprintf("BULK_%03d", i), "secretValue": "v"})+ }+ raw, err := json.Marshal(map[string]any{"projectId": p.ID, "environment": "dev", "secrets": secrets})+ require.NoError(tt, err)+ res, err := p.Tenant().Admin.API.CreateManySecretsV4WithBodyWithResponse(tt.Context(), "application/json", bytes.NewReader(raw))+ require.NoError(tt, err)+ require.Equalf(tt, http.StatusOK, res.StatusCode(), "creating %d secrets returned %s", n, apierr.Body(res.Body))+}++func environmentID(tt *testing.T, p *fixture.Project, slug string) string {+ tt.Helper()+ res, err := p.Tenant().Admin.API.GetEnvironmentBySlugWithResponse(tt.Context(), p.ID, slug)+ require.NoError(tt, err)+ require.NotNilf(tt, res.JSON200, "reading environment %s returned %d: %s", slug, res.StatusCode(), apierr.Body(res.Body))+ return res.JSON200.Environment.Id.String()+}diff --git a/tests/suites/secretmanager/syncs/trigger_test.go b/tests/suites/secretmanager/syncs/trigger_test.gonew file mode 100644index 0000000000..b5c7353c1e--- /dev/null+++ b/tests/suites/secretmanager/syncs/trigger_test.go@@ -0,0 +1,175 @@+package syncs_test++import (+ "net/http"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++func TestSecretSync_Trigger(t *testing.T) {+ t.Parallel()++ t.Run("should refuse a manual trigger saying the folder no longer exists when the source folder is gone", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ secretmanager.CreateFolder(t, proj, "dev", "/doomed")+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "v", secretmanager.WithPath("/doomed"))+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/doomed"))+ deleteFolder(t, proj, "dev", "/doomed")++ // Action+ res, err := proj.Tenant().Admin.API.SyncGitHubSecretSyncWithResponse(t.Context(), s.ID)++ // Assert+ require.NoError(t, err)+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t,+ "Invalid source configuration: folder no longer exists. Please configure a valid source and try again.",+ message(res.Body))+ require.Nil(t, s.get(t).JSON200.SecretSync.SyncStatus, "a sync with no source was queued")+ })++ t.Run("should push a secret created at the source when auto-sync is on", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"), autoSync(true))+ s.awaitTerminal(t)++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "NEW_KEY", "new-value")++ // Assert+ gh.ExpectEvent[github.SecretCreated](t, created("NEW_KEY"), syncBudget)+ require.Equal(t, "new-value", gh.Repo(t, "acme/app").Secrets["NEW_KEY"].Value)+ })++ t.Run("should not push a secret created at the source when auto-sync is off", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Absence needs a window that covers the delay a queued sync would have had.+ A second sync on the same folder with auto-sync on proves the write was seen;+ once it lands, any job queued at the same moment has at most 10 s of start+ jitter left.`)++ // Setup+ proj, conn, gh := setup(t)+ on := newSync(t, proj, conn, repoScope("acme", "on"), autoSync(true))+ on.awaitTerminal(t)+ newSync(t, proj, conn, repoScope("acme", "off"), autoSync(false))++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "NEW_KEY", "new-value")++ // Assert+ gh.ExpectEvent[github.SecretCreated](t, createdIn("repos/acme/on", "NEW_KEY"), syncBudget)+ gh.ExpectNoEvent[github.SecretCreated](t, createdIn("repos/acme/off", "NEW_KEY"), fakenet.Within(11*time.Second))+ })++ t.Run("should send the source folder's secrets and not its child folders' when subfolders are off", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateFolder(t, proj, "dev", "/services/api")+ secretmanager.CreateSecret(t, proj, "dev", "PARENT_KEY", "parent-value", secretmanager.WithPath("/services"))+ secretmanager.CreateSecret(t, proj, "dev", "CHILD_KEY", "child-value", secretmanager.WithPath("/services/api"))+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/services"))++ // Action+ s.trigger(t)++ // Assert+ got := gh.Repo(t, "acme/app").Secrets+ require.Equal(t, []string{"PARENT_KEY"}, keysOf(got))+ require.Equal(t, "parent-value", got["PARENT_KEY"].Value)+ })++ t.Run("should send imported and referenced secrets with their values resolved", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateSecret(t, proj, "dev", "SHARED_KEY", "shared-value")+ secretmanager.CreateFolder(t, proj, "dev", "/services")+ secretmanager.CreateSecret(t, proj, "dev", "OWN_KEY", "own-value", secretmanager.WithPath("/services"))+ secretmanager.CreateSecret(t, proj, "dev", "REF_KEY", "${OWN_KEY}+${dev.SHARED_KEY}", secretmanager.WithPath("/services"))+ secretmanager.CreateImport(t, proj, "dev", secretmanager.Location{Env: "dev", Path: "/"}, secretmanager.IntoPath("/services"))+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/services"))++ // Action+ s.trigger(t)++ // Assert+ got := gh.Repo(t, "acme/app").Secrets+ require.Equal(t, []string{"OWN_KEY", "REF_KEY", "SHARED_KEY"}, keysOf(got))+ require.Equal(t, "shared-value", got["SHARED_KEY"].Value)+ require.Equal(t, "own-value+shared-value", got["REF_KEY"].Value)+ })++ t.Run("should name keys by the schema with the source environment filled in and keep keys outside it", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ gh.Seed(t, github.RepoSecret("acme/app", "UNMANAGED_KEY", "not ours"))+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")+ s := newSync(t, proj, conn, repoScope("acme", "app"), keySchema("INFISICAL_{{environment}}_{{secretKey}}"))++ // Action+ s.trigger(t)++ // Assert+ got := gh.Repo(t, "acme/app").Secrets+ require.Equal(t, []string{"INFISICAL_DEV_API_KEY", "UNMANAGED_KEY"}, keysOf(got))+ require.Equal(t, "api-value", got["INFISICAL_DEV_API_KEY"].Value)+ require.Equal(t, "not ours", got["UNMANAGED_KEY"].Value)+ })++ t.Run("should remove destination secrets Infisical does not have on the first overwrite", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ gh.Seed(t, github.RepoSecret("acme/app", "STALE_KEY", "stale-value"))+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")+ s := newSync(t, proj, conn, repoScope("acme", "app"))++ // Action+ s.trigger(t)++ // Assert+ got := gh.Repo(t, "acme/app").Secrets+ require.Equal(t, []string{"API_KEY"}, keysOf(got))+ require.Equal(t, "api-value", got["API_KEY"].Value)+ })++ t.Run("should push to a sync whose folder imports the folder where a secret changed", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `The change reaches the importing folder's sync through the integration+ sync job, a second queue hop after the folder's own debounce.`)++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateFolder(t, proj, "dev", "/a")+ secretmanager.CreateFolder(t, proj, "dev", "/b")+ secretmanager.CreateImport(t, proj, "dev", secretmanager.Location{Env: "dev", Path: "/b"}, secretmanager.IntoPath("/a"))+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/a"), autoSync(true))+ s.awaitTerminal(t)++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "LATE_KEY", "late-value", secretmanager.WithPath("/b"))++ // Assert+ gh.ExpectEvent[github.SecretCreated](t, created("LATE_KEY"), syncBudget)+ require.Equal(t, "late-value", gh.Repo(t, "acme/app").Secrets["LATE_KEY"].Value)+ })+}diff --git a/tests/suites/secretmanager/syncs/update_test.go b/tests/suites/secretmanager/syncs/update_test.gonew file mode 100644index 0000000000..b42109d9ae--- /dev/null+++ b/tests/suites/secretmanager/syncs/update_test.go@@ -0,0 +1,93 @@+package syncs_test++import (+ "fmt"+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestSecretSync_Update(t *testing.T) {+ t.Parallel()++ t.Run("should refuse and keep the old name when a sync is renamed to a name another sync holds", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ newSync(t, proj, conn, repoScope("acme", "app"), withName("alpha"))+ beta := newSync(t, proj, conn, repoScope("acme", "other"), withName("beta"))++ // Action+ res := beta.update(t, proj.Tenant().Admin.API, map[string]any{"name": "alpha"})++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Equal(t,+ fmt.Sprintf(`A Secret Sync with the name "alpha" already exists for the project with ID "%s"`, proj.ID),+ message(res.Body))+ require.Equal(t, "beta", beta.get(t).JSON200.SecretSync.Name)+ })++ t.Run("should refuse and keep the source when the new source folder does not exist", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ s := newSync(t, proj, conn, repoScope("acme", "app"))++ // Action+ res := s.update(t, proj.Tenant().Admin.API, map[string]any{"secretPath": "/missing"})++ // Assert+ require.Equal(t, http.StatusBadRequest, res.StatusCode())+ require.Contains(t, message(res.Body), `Could not find folder with path "/missing" in environment "dev"`)+ require.Equal(t, "/", s.get(t).JSON200.SecretSync.Folder.Path)+ })++ t.Run("should refuse and keep the source when the actor may not edit syncs at the new path", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, _ := setup(t)+ secretmanager.CreateFolder(t, proj, "dev", "/a")+ secretmanager.CreateFolder(t, proj, "dev", "/b")+ proj.NewRole(t, "a-sync-editor",+ fixture.Permission{Subject: "secret-syncs", Action: []string{"read", "edit"},+ Conditions: map[string]any{"secretPath": map[string]any{"$eq": "/a"}}},+ fixture.Permission{Subject: "secrets", Action: []string{"describeSecret", "readValue"}})+ editor := proj.NewMachineIdentity(t, fixture.WithRoles("a-sync-editor"))+ s := newSync(t, proj, conn, repoScope("acme", "app"), fromPath("/a"))++ // Action+ res := s.update(t, editor.API, map[string]any{"secretPath": "/b"})++ // Assert+ require.Equalf(t, http.StatusForbidden, res.StatusCode(), "moving the source returned %s", apierr.Body(res.Body))+ require.Equal(t, "/a", s.get(t).JSON200.SecretSync.Folder.Path)+ })++ t.Run("should report pending and push the source when auto-sync is turned on", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj, conn, gh := setup(t)+ secretmanager.CreateSecret(t, proj, "dev", "PRESENT", "1")+ s := newSync(t, proj, conn, repoScope("acme", "app"))++ // Action+ res := s.update(t, proj.Tenant().Admin.API, map[string]any{"isAutoSyncEnabled": true})++ // Assert+ require.NotNilf(t, res.JSON200, "turning auto-sync on returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ require.NotNil(t, res.JSON200.SecretSync.SyncStatus)+ require.Equal(t, "pending", *res.JSON200.SecretSync.SyncStatus)+ gh.ExpectEvent[github.SecretCreated](t, created("PRESENT"), syncBudget)+ require.Equal(t, "1", gh.Repo(t, "acme/app").Secrets["PRESENT"].Value)+ })+}