Skip to content

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

test(e2e): add an AWS fake and cover AWS syncs, IAM user rotation and honey tokens

varonix8118ab83c53b
diff --git a/backend/e2e-test/fakes/aws-parameter-store-sync-fns.ts b/backend/e2e-test/fakes/aws-parameter-store-sync-fns.ts
deleted file mode 100644
index 1a2bd93bd5..0000000000
--- a/backend/e2e-test/fakes/aws-parameter-store-sync-fns.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { TAwsParameterStoreSyncWithCredentials } from "@app/services/secret-sync/aws-parameter-store/aws-parameter-store-sync-types";
-import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
-import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
-import { TSecretSyncPayload } from "@app/services/secret-sync/secret-sync-payload";
-import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";
-
-// Type-only, and by a path the aliases do not match, so this does not resolve back to here.
-import type * as RealProvider from "../../src/services/secret-sync/aws-parameter-store/aws-parameter-store-sync-fns";
-
-// Stands in for the AWS Parameter Store provider so the specs can assert what Infisical hands
-// to a destination without reaching AWS. Wired up by test.alias in vitest.e2e.config.mts;
-// nothing under src/ references this file.
-//
-// The reconciliation rules below are copied from the real module
-// (aws-parameter-store-sync-fns.ts:356-479). They are the behavior under test, so a fake that
-// only recorded its input would let a deletion or key schema regression pass unnoticed.
-
-type TFakeStore = {
- secrets: Record<string, string>;
- writeError: string | null;
- runCount: number;
-};
-
-// The state hangs off globalThis rather than module scope on purpose. The alias makes this
-// module reachable by more than one specifier (the server reaches it through the barrel's
-// relative import, a spec through its own path), and the bundler then instantiates it twice:
-// the sync writes to one copy of the store while the spec reads an empty other one, and the
-// only symptom is an assertion that never comes true. Sharing through globalThis makes that
-// impossible, and matches how the harness already shares testServer and testDb.
-const globalScope = globalThis as typeof globalThis & {
- infisicalFakeParameterStore?: Map<string, TFakeStore>;
-};
-
-globalScope.infisicalFakeParameterStore ??= new Map<string, TFakeStore>();
-
-const stores = globalScope.infisicalFakeParameterStore;
-
-const storeKeyFor = (region: string, path: string) => `${region}|${path}`;
-
-const storeFor = (region: string, path: string): TFakeStore => {
- const key = storeKeyFor(region, path);
- let store = stores.get(key);
-
- if (!store) {
- store = { secrets: {}, writeError: null, runCount: 0 };
- stores.set(key, store);
- }
-
- return store;
-};
-
-const storeForSync = (secretSync: TAwsParameterStoreSyncWithCredentials) =>
- storeFor(secretSync.destinationConfig.region, secretSync.destinationConfig.path);
-
-// Behavior a spec can change. Everything resets between test files, so a spec never inherits
-// another's state or configuration. See e2e-test/setup/reset-fakes.ts.
-export const fakeParameterStore = {
- reset: () => {
- stores.clear();
- },
-
- // A destination is addressed by the region and path the spec passes as destinationConfig
- // when it creates the sync, so it can be seeded before the sync exists.
- at: (region: string, path: string) => ({
- // Secrets already sitting at the destination before Infisical touches it.
- seed: (secrets: Record<string, string>) => {
- Object.assign(storeFor(region, path).secrets, secrets);
- },
-
- // What the destination holds now.
- read: (): Record<string, string> => ({ ...storeFor(region, path).secrets }),
-
- // Make every write fail, as a destination rejecting the request would.
- // Pass null to go back to accepting.
- rejectWritesWith: (message: string | null) => {
- storeFor(region, path).writeError = message;
- },
-
- // How many sync runs have reached this destination. Lets a spec assert that a change
- // did *not* trigger a run, which absence of a secret cannot prove on its own.
- runCount: (): number => storeFor(region, path).runCount
- })
-};
-
-export const AwsParameterStoreSyncFns = {
- syncSecrets: (secretSync: TAwsParameterStoreSyncWithCredentials, payload: TSecretSyncPayload) => {
- const secretMap = payload.flatten();
- const { syncOptions, environment } = secretSync;
- const store = storeForSync(secretSync);
-
- store.runCount += 1;
-
- if (store.writeError) {
- throw new SecretSyncError({ message: store.writeError, shouldRetry: false });
- }
-
- const createdSecretKeys: string[] = [];
- const updatedSecretKeys: string[] = [];
- const deletedSecretKeys: string[] = [];
-
- for (const [key, { value }] of Object.entries(secretMap)) {
- // AWS rejects an empty parameter value, so the real module skips the write and lets the
- // deletion pass below remove the key instead.
- // eslint-disable-next-line no-continue
- if (!value) continue;
-
- if (Object.hasOwn(store.secrets, key)) {
- if (store.secrets[key] !== value) updatedSecretKeys.push(key);
- } else {
- createdSecretKeys.push(key);
- }
-
- store.secrets[key] = value;
- }
-
- if (syncOptions.disableSecretDeletion) {
- return Promise.resolve({ createdSecretKeys, updatedSecretKeys, deletedSecretKeys });
- }
-
- for (const key of Object.keys(store.secrets)) {
- // eslint-disable-next-line no-continue
- if (!matchesSchema(key, environment?.slug || "", syncOptions.keySchema)) continue;
-
- // The real module deletes a key that is absent from the map *or* present with an empty
- // value, so an emptied secret does not linger at the destination.
- if (!Object.hasOwn(secretMap, key) || !secretMap[key].value) {
- delete store.secrets[key];
- deletedSecretKeys.push(key);
- }
- }
-
- return Promise.resolve({ createdSecretKeys, updatedSecretKeys, deletedSecretKeys });
- },
-
- // Returns the destination as it stands. Key schema filtering and stripping is the caller's
- // job (secret-sync-fns.ts:643-645), so doing it here too would hide a bug in that wrapper.
- getSecrets: (secretSync: TAwsParameterStoreSyncWithCredentials): Promise<TSecretMap> =>
- Promise.resolve(
- Object.fromEntries(Object.entries(storeForSync(secretSync).secrets).map(([key, value]) => [key, { value }]))
- ),
-
- removeSecrets: (secretSync: TAwsParameterStoreSyncWithCredentials, payload: TSecretSyncPayload) => {
- const secretMap = payload.flatten();
- const store = storeForSync(secretSync);
-
- if (store.writeError) {
- throw new SecretSyncError({ message: store.writeError, shouldRetry: false });
- }
-
- for (const key of Object.keys(store.secrets)) {
- if (Object.hasOwn(secretMap, key)) delete store.secrets[key];
- }
-
- return Promise.resolve();
- }
-};
-
-// Nothing forces a module replaced by an alias to match the module it replaces, so a signature
-// change in the real provider would otherwise leave this fake quietly wrong. This assignment
-// fails type-checking instead.
-export const assertFakeMatchesRealProvider: Pick<typeof RealProvider, "AwsParameterStoreSyncFns"> = {
- AwsParameterStoreSyncFns
-};
diff --git a/backend/e2e-test/routes/v1/secret-sync.spec.ts b/backend/e2e-test/routes/v1/secret-sync.spec.ts
deleted file mode 100644
index c653ef6707..0000000000
--- a/backend/e2e-test/routes/v1/secret-sync.spec.ts
+++ /dev/null
@@ -1,276 +0,0 @@
-import { randomUUID } from "crypto";
-import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";
-import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";
-import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
-import { createFolder } from "e2e-test/testUtils/folders";
-import {
- createSecretSync,
- deleteSecretSync,
- importSecretsForSync,
- triggerSecretSync
-} from "e2e-test/testUtils/secret-syncs";
-import { createSecretV2, deleteSecretV2, getSecretsV2 } from "e2e-test/testUtils/secrets";
-
-import { SecretSyncInitialSyncBehavior } from "@app/services/secret-sync/secret-sync-enums";
-import { SecretSyncStatus } from "@app/services/secret-sync/secret-sync-types";
-
-// Covers the @e2e scenarios of "Feature: Secret Syncs" in the Test Specifications for Secrets
-// Management. Each describe is one Rule and each test name is one Scenario, so a behavior
-// change should show up here as an edited assertion rather than a silent pass.
-//
-// The destination is AWS Parameter Store, faked for the whole run (e2e-test/fakes/ and the
-// alias block in vitest.e2e.config.mts). What is under test is Infisical resolving a set of
-// secrets and handing them over, not AWS.
-
-const REGION = "us-east-1";
-const ENV = "dev";
-
-// A distinct destination path per test, so a store leaking out of one test cannot be mistaken
-// for another's result.
-const pathFor = (name: string) => `/${name}/`;
-
-describe("Secret syncs", async () => {
- // A sync run is a queue round trip, so it takes longer than the 5s default. The helpers give
- // up after 20s of their own, and this has to outlast that or the test dies first and reports
- // a timeout instead of whatever the sync actually did.
- vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });
-
- let projectId: string;
- let authToken: string;
- let cleanupOrg: () => Promise<void>;
- let connectionId: string;
- let createdSyncIds: string[] = [];
-
- const newFolder = (parentPath: string, name: string) =>
- createFolder({
- authToken,
- workspaceId: projectId,
- environmentSlug: ENV,
- secretPath: parentPath,
- name
- });
-
- const addSecret = (secretPath: string, key: string, value: string) =>
- createSecretV2({ authToken, workspaceId: projectId, environmentSlug: ENV, secretPath, key, value });
-
- const removeSecret = (secretPath: string, key: string) =>
- deleteSecretV2({ authToken, workspaceId: projectId, environmentSlug: ENV, secretPath, key });
-
- const secretKeysAt = async (secretPath: string) => {
- const { secrets } = await getSecretsV2({
- authToken,
- workspaceId: projectId,
- environmentSlug: ENV,
- secretPath
- });
- return Object.fromEntries(secrets.map((secret) => [secret.secretKey, secret.secretValue]));
- };
-
- const newSync = async (
- name: string,
- overrides: Partial<Parameters<typeof createSecretSync>[0]> & { secretPath: string }
- ) => {
- const result = await createSecretSync({
- name,
- projectId,
- connectionId,
- environmentSlug: ENV,
- region: REGION,
- destinationPath: pathFor(name),
- authToken,
- ...overrides
- });
-
- // Tracked so afterEach can clear them before the connection. Absent when a test asserts
- // that creation is refused.
- if (result.secretSync) createdSyncIds.push(result.secretSync.id);
-
- return result;
- };
-
- // Everything a test touches is built here and torn down after it, so no test can be reached by
- // another's writes or teardown. That matters more than usual for secret syncs: auto sync reacts
- // to any write at a sync's source path, secret imports outlive the test that made them, and an
- // app connection is org-scoped rather than project-scoped, so sharing one would leave a single
- // row that every test's syncs hang off. A fresh org per test (not just a fresh project) closes
- // that off completely rather than relying on the shared seeded org staying tidy.
- beforeEach(async () => {
- fakeParameterStore.reset();
- createdSyncIds = [];
-
- ({ projectId, authToken, cleanup: cleanupOrg } = await createIsolatedOrgAndProject("secret-sync-e2e"));
-
- connectionId = await createAwsAppConnection({
- name: `secret-sync-e2e-${randomUUID().slice(0, 8)}`,
- authToken
- });
-
- await newFolder("/", "services");
- await newFolder("/services", "api");
- });
-
- afterEach(async () => {
- // Order matters. A sync holds a foreign key to the connection, and deleting a project only
- // soft deletes it, leaving the sync rows in place, so the connection delete would fail on the
- // constraint if the syncs went second.
- for (const syncId of createdSyncIds) {
- // eslint-disable-next-line no-await-in-loop
- await deleteSecretSync({ syncId, authToken });
- }
-
- await deleteAwsAppConnection({ connectionId, authToken });
- await cleanupOrg();
- });
-
- describe("The initial sync behavior decides what happens to secrets already at the destination", () => {
- test('Initial sync behavior "import-prioritize-source" keeps the Infisical value for a shared secret key', async () => {
- await addSecret("/services", "API_KEY", "infisical-value");
- fakeParameterStore.at(REGION, pathFor("prioritize-source")).seed({ API_KEY: "destination-value" });
-
- const { secretSync } = await newSync("prioritize-source", {
- secretPath: "/services",
- initialSyncBehavior: SecretSyncInitialSyncBehavior.ImportPrioritizeSource
- });
- await triggerSecretSync({
- syncId: secretSync!.id,
- region: REGION,
- destinationPath: pathFor("prioritize-source"),
- authToken
- });
-
- expect(fakeParameterStore.at(REGION, pathFor("prioritize-source")).read()).toEqual({
- API_KEY: "infisical-value"
- });
- expect(await secretKeysAt("/services")).toEqual({ API_KEY: "infisical-value" });
-
- await removeSecret("/services", "API_KEY");
- });
-
- test('Initial sync behavior "import-prioritize-destination" takes the destination value into Infisical', async () => {
- await addSecret("/services", "API_KEY", "infisical-value");
- fakeParameterStore.at(REGION, pathFor("prioritize-destination")).seed({ API_KEY: "destination-value" });
-
- const { secretSync } = await newSync("prioritize-destination", {
- secretPath: "/services",
- initialSyncBehavior: SecretSyncInitialSyncBehavior.ImportPrioritizeDestination
- });
- await triggerSecretSync({
- syncId: secretSync!.id,
- region: REGION,
- destinationPath: pathFor("prioritize-destination"),
- authToken
- });
-
- // The import writes back into the project, which is the surprising half of this option.
- expect(await secretKeysAt("/services")).toEqual({ API_KEY: "destination-value" });
- expect(fakeParameterStore.at(REGION, pathFor("prioritize-destination")).read()).toEqual({
- API_KEY: "destination-value"
- });
-
- await removeSecret("/services", "API_KEY");
- });
-
- test("The initial sync behavior applies only to the first sync run", async () => {
- await addSecret("/services", "API_KEY", "api-value");
-
- const { secretSync } = await newSync("first-run-only", {
- secretPath: "/services",
- initialSyncBehavior: SecretSyncInitialSyncBehavior.ImportPrioritizeDestination
- });
- await triggerSecretSync({
- syncId: secretSync!.id,
- region: REGION,
- destinationPath: pathFor("first-run-only"),
- authToken
- });
-
- // Arrives at the destination outside Infisical, after the first run has happened.
- fakeParameterStore.at(REGION, pathFor("first-run-only")).seed({ LATE_KEY: "late-value" });
-
- await triggerSecretSync({
- syncId: secretSync!.id,
- region: REGION,
- destinationPath: pathFor("first-run-only"),
- authToken
- });
-
- expect(await secretKeysAt("/services")).toEqual({ API_KEY: "api-value" });
- expect(fakeParameterStore.at(REGION, pathFor("first-run-only")).read()).toEqual({ API_KEY: "api-value" });
-
- await removeSecret("/services", "API_KEY");
- });
- });
-
- describe("Importing from a destination brings its secrets into the source secret path", () => {
- test("An import creates secrets the source secret path does not have", async () => {
- fakeParameterStore.at(REGION, pathFor("import-creates")).seed({ DESTINATION_KEY: "destination-value" });
-
- const { secretSync } = await newSync("import-creates", { secretPath: "/services" });
- const { secretSync: imported } = await importSecretsForSync({
- syncId: secretSync!.id,
- importBehavior: "prioritize-source",
- authToken
- });
-
- expect(imported!.importStatus).toBe(SecretSyncStatus.Succeeded);
- expect(await secretKeysAt("/services")).toEqual({ DESTINATION_KEY: "destination-value" });
-
- await removeSecret("/services", "DESTINATION_KEY");
- });
-
- test('An import with behavior "prioritize-destination" overwrites the Infisical value', async () => {
- await addSecret("/services", "API_KEY", "infisical-value");
- fakeParameterStore.at(REGION, pathFor("import-overwrites")).seed({ API_KEY: "destination-value" });
-
- const { secretSync } = await newSync("import-overwrites", { secretPath: "/services" });
- await importSecretsForSync({
- syncId: secretSync!.id,
- importBehavior: "prioritize-destination",
- authToken
- });
-
- expect(await secretKeysAt("/services")).toEqual({ API_KEY: "destination-value" });
-
- await removeSecret("/services", "API_KEY");
- });
-
- test("An import fails when a destination secret key is not a valid Infisical secret key", async () => {
- // SecretNameSchema rejects only a colon or a forward slash, so a name with spaces would
- // import cleanly. This has to be one Infisical genuinely refuses.
- fakeParameterStore.at(REGION, pathFor("import-invalid-name")).seed({ "BAD:KEY": "destination-value" });
-
- const { secretSync } = await newSync("import-invalid-name", { secretPath: "/services" });
- const { secretSync: imported } = await importSecretsForSync({
- syncId: secretSync!.id,
- importBehavior: "prioritize-source",
- authToken
- });
-
- expect(imported!.importStatus).toBe(SecretSyncStatus.Failed);
- expect(imported!.lastImportMessage).toContain("invalid secret name");
- expect(await secretKeysAt("/services")).toEqual({});
- });
- });
-
- describe("A failed sync run is reported on the sync and changes nothing", () => {
- test("A destination failure marks the sync failed and records the reason", async () => {
- const destinationPath = pathFor("destination-rejects");
- await addSecret("/services", "API_KEY", "api-value");
- fakeParameterStore.at(REGION, destinationPath).rejectWritesWith("Destination refused the write");
-
- const { secretSync } = await newSync("destination-rejects", { secretPath: "/services" });
- const sync = await triggerSecretSync({
- syncId: secretSync!.id,
- region: REGION,
- destinationPath,
- authToken
- });
-
- expect(sync.syncStatus).toBe(SecretSyncStatus.Failed);
- expect(sync.lastSyncMessage).toContain("Destination refused the write");
- expect(await secretKeysAt("/services")).toEqual({ API_KEY: "api-value" });
-
- await removeSecret("/services", "API_KEY");
- });
- });
-});
diff --git a/backend/e2e-test/testUtils/secret-syncs.ts b/backend/e2e-test/testUtils/secret-syncs.ts
deleted file mode 100644
index 840d3bc846..0000000000
--- a/backend/e2e-test/testUtils/secret-syncs.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";
-
-import { SecretSyncInitialSyncBehavior } from "@app/services/secret-sync/secret-sync-enums";
-import { SecretSyncStatus } from "@app/services/secret-sync/secret-sync-types";
-
-import { pollUntil } from "./poll";
-
-// Every spec drives AWS Parameter Store, which is faked for the whole e2e run. See
-// e2e-test/fakes/ and the alias block in vitest.e2e.config.mts.
-const DESTINATION = "aws-parameter-store";
-
-type TSecretSyncRecord = {
- id: string;
- name: string;
- syncOptions: {
- initialSyncBehavior: string;
- includeAllSubFolders?: boolean;
- keySchema?: string;
- disableSecretDeletion?: boolean;
- };
- syncStatus: string | null;
- importStatus: string | null;
- removeStatus: string | null;
- lastSyncMessage: string | null;
- lastImportMessage: string | null;
- lastRemoveMessage: string | null;
- lastSyncedAt: string | null;
-};
-
-const TERMINAL_STATUSES: string[] = [SecretSyncStatus.Succeeded, SecretSyncStatus.Failed];
-
-export const createSecretSync = async (dto: {
- name: string;
- projectId: string;
- connectionId: string;
- environmentSlug: string;
- secretPath: string;
- // The region and path address the fake destination, so a spec can seed it before the sync
- // exists. Creating a sync with auto sync on runs it immediately.
- region: string;
- destinationPath: string;
- initialSyncBehavior?: SecretSyncInitialSyncBehavior;
- keySchema?: string;
- disableSecretDeletion?: boolean;
- includeAllSubFolders?: boolean;
- isAutoSyncEnabled?: boolean;
- authToken: string;
- expectStatusCode?: number;
-}) => {
- const res = await testServer.inject({
- method: "POST",
- url: `/api/v1/secret-syncs/${DESTINATION}`,
- headers: { authorization: `Bearer ${dto.authToken}` },
- body: {
- name: dto.name,
- projectId: dto.projectId,
- connectionId: dto.connectionId,
- environment: dto.environmentSlug,
- secretPath: dto.secretPath,
- isAutoSyncEnabled: dto.isAutoSyncEnabled ?? false,
- syncOptions: {
- initialSyncBehavior: dto.initialSyncBehavior ?? SecretSyncInitialSyncBehavior.OverwriteDestination,
- ...(dto.keySchema ? { keySchema: dto.keySchema } : {}),
- ...(dto.disableSecretDeletion === undefined ? {} : { disableSecretDeletion: dto.disableSecretDeletion }),
- ...(dto.includeAllSubFolders === undefined ? {} : { includeAllSubFolders: dto.includeAllSubFolders })
- },
- destinationConfig: { region: dto.region, path: dto.destinationPath }
- }
- });
-
- expect(res.statusCode).toBe(dto.expectStatusCode ?? 200);
-
- // A spec asserting a rejection wants the body, not an id.
- if ((dto.expectStatusCode ?? 200) !== 200) return { error: res.json() };
-
- return { secretSync: res.json().secretSync as TSecretSyncRecord };
-};
-
-export const getSecretSync = async (dto: { syncId: string; authToken: string }) => {
- const res = await testServer.inject({
- method: "GET",
- url: `/api/v1/secret-syncs/${DESTINATION}/${dto.syncId}`,
- headers: { authorization: `Bearer ${dto.authToken}` }
- });
-
- expect(res.statusCode).toBe(200);
- return res.json().secretSync as TSecretSyncRecord;
-};
-
-export const deleteSecretSync = async (dto: { syncId: string; authToken: string }) => {
- const res = await testServer.inject({
- method: "DELETE",
- url: `/api/v1/secret-syncs/${DESTINATION}/${dto.syncId}`,
- headers: { authorization: `Bearer ${dto.authToken}` },
- body: { removeSecrets: false }
- });
-
- expect(res.statusCode).toBe(200);
-};
-
-// Waits on the fake's own run counter before reading the record, rather than on the record
-// alone. triggerSecretSyncSyncSecretsById writes syncStatus "pending" *after* enqueuing the job
-// (secret-sync-service.ts:800), so a status-only wait races that write and can sit on a stale
-// "succeeded" from an earlier run.
-export const waitForSyncRun = async (dto: {
- syncId: string;
- region: string;
- destinationPath: string;
- runCountBefore: number;
- authToken: string;
-}) => {
- await pollUntil({
- describe: `a sync run to reach the destination at ${dto.region}${dto.destinationPath}`,
- read: () => fakeParameterStore.at(dto.region, dto.destinationPath).runCount(),
- done: (runCount) => runCount > dto.runCountBefore
- });
-
- return pollUntil({
- describe: `secret sync "${dto.syncId}" to report a terminal sync status`,
- read: () => getSecretSync({ syncId: dto.syncId, authToken: dto.authToken }),
- done: (sync) => TERMINAL_STATUSES.includes(sync.syncStatus ?? "")
- });
-};
-
-export const triggerSecretSync = async (dto: {
- syncId: string;
- region: string;
- destinationPath: string;
- authToken: string;
-}) => {
- const runCountBefore = fakeParameterStore.at(dto.region, dto.destinationPath).runCount();
-
- const res = await testServer.inject({
- method: "POST",
- url: `/api/v1/secret-syncs/${DESTINATION}/${dto.syncId}/sync-secrets`,
- headers: { authorization: `Bearer ${dto.authToken}` }
- });
-
- expect(res.statusCode).toBe(200);
-
- return waitForSyncRun({ ...dto, runCountBefore });
-};
-
-export const importSecretsForSync = async (dto: {
- syncId: string;
- importBehavior: "prioritize-source" | "prioritize-destination";
- authToken: string;
- expectStatusCode?: number;
-}) => {
- const res = await testServer.inject({
- method: "POST",
- url: `/api/v1/secret-syncs/${DESTINATION}/${dto.syncId}/import-secrets`,
- headers: { authorization: `Bearer ${dto.authToken}` },
- // A querystring parameter on this route, not a body field.
- query: { importBehavior: dto.importBehavior }
- });
-
- expect(res.statusCode).toBe(dto.expectStatusCode ?? 200);
-
- if ((dto.expectStatusCode ?? 200) !== 200) return { error: res.json() };
-
- const sync = await pollUntil({
- describe: `secret sync "${dto.syncId}" to report a terminal import status`,
- read: () => getSecretSync({ syncId: dto.syncId, authToken: dto.authToken }),
- done: (record) => TERMINAL_STATUSES.includes(record.importStatus ?? "")
- });
-
- return { secretSync: sync };
-};
diff --git a/tests/cmd/fakenet/main.go b/tests/cmd/fakenet/main.go
index e6c12e3a6e..d8b5c82f67 100644
--- a/tests/cmd/fakenet/main.go
+++ b/tests/cmd/fakenet/main.go
@@ -14,6 +14,7 @@ import (
"net/http"
"os"
+ "github.com/Infisical/infisical/tests/fakes/aws"
"github.com/Infisical/infisical/tests/fakes/github"
"github.com/Infisical/infisical/tests/fakes/license"
"github.com/Infisical/infisical/tests/fakes/smtp"
@@ -37,6 +38,7 @@ func main() {
license.Service,
webhook.Service,
webhook.Slack,
+ aws.STS, aws.SSM, aws.SecretsManager, aws.IAM, aws.CloudFormation,
)
mail := smtp.New(func(domain string) fakenet.Emitter { return srv.Emitter(smtp.Host, domain) })
diff --git a/tests/fakes/aws/aws.go b/tests/fakes/aws/aws.go
new file mode 100644
index 0000000000..4888fbd286
--- /dev/null
+++ b/tests/fakes/aws/aws.go
@@ -0,0 +1,420 @@
+// Package aws fakes the parts of AWS that Infisical calls: STS, SSM Parameter Store,
+// Secrets Manager, IAM access keys and CloudFormation stacks.
+//
+// One fake for the provider, served on each hostname the SDK resolves. Each host is its
+// own fakenet scope, so a test reads Parameter Store state from the SSM host and access
+// keys from the IAM host. What AWS shares across services, the credentials IAM issues,
+// lives in a keyring every host reads, so a key IAM deleted is refused by STS too.
+//
+// Requests are authenticated the way AWS does it: the SigV4 signature is checked
+// against the secret for the access key id. A connection's secret is derived from its
+// access key id (SecretAccessKey), and a key IAM issued is checked against the secret
+// IAM handed out, so a product that stored the wrong half of a key pair fails here.
+package aws
+
+import (
+ "bytes"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/xml"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// Region is the only region served. A sync configured for another one reaches a host
+// with no fake and fails with a 501 naming it.
+const Region = "us-east-1"
+
+var (
+ STS = service{host: "sts." + Region + ".amazonaws.com", name: "sts", region: Region, newFake: newSTS}
+ SSM = service{host: "ssm." + Region + ".amazonaws.com", name: "ssm", region: Region, newFake: newParameterStore}
+ SecretsManager = service{host: "secretsmanager." + Region + ".amazonaws.com", name: "secretsmanager", region: Region, newFake: newSecretsManager}
+ CloudFormation = service{host: "cloudformation." + Region + ".amazonaws.com", name: "cloudformation", region: Region, newFake: newCloudFormation}
+
+ // IAM is global, and signed for us-east-1.
+ IAM = service{host: "iam.amazonaws.com", name: "iam", region: "us-east-1", newFake: newIAM}
+)
+
+// Services is every AWS host fakenet answers for.
+var Services = []fakenet.Service{STS, SSM, SecretsManager, IAM, CloudFormation}
+
+type service struct {
+ host string
+ name string
+ region string
+ newFake func(service, fakenet.Emitter) fakenet.Fake
+}
+
+func (s service) Host() string { return s.host }
+
+// Scope is the account the signing key belongs to: the access key id itself for a
+// credential a test invented, and the account that created it for a key IAM issued.
+func (service) Scope(r *http.Request) (string, bool) {
+ cred, ok := parseAuthorization(r.Header.Get("Authorization"))
+ if !ok {
+ return "", false
+ }
+ return owner(cred.accessKeyID), true
+}
+
+func (s service) New(events fakenet.Emitter) fakenet.Fake { return s.newFake(s, events) }
+
+// SecretAccessKey is the secret that goes with an access key id a test invented. Derived
+// rather than registered, so a connection can be created before fakenet has heard of
+// its credential, and a wrong secret is refused the way AWS refuses one.
+func SecretAccessKey(accessKeyID string) string {
+ sum := sha256.Sum256([]byte("infisical-fake-aws/" + accessKeyID))
+ return hex.EncodeToString(sum[:])[:40]
+}
+
+// AccountID is the 12-digit account an access key id belongs to.
+func AccountID(credential string) string {
+ sum := sha256.Sum256([]byte("infisical-fake-aws-account/" + owner(credential)))
+ out := make([]byte, 12)
+ for i := range out {
+ out[i] = '0' + sum[i]%10
+ }
+ return string(out)
+}
+
+// issued is an access key IAM handed out.
+type issued struct {
+ owner string
+ user string
+ secret string
+ active bool
+}
+
+// keyring is AWS's credential store, shared by every host. A process-wide value because
+// fakenet builds one fake per host and scope, and IAM and STS have to agree on which
+// keys exist.
+var keyring = struct {
+ mu sync.Mutex
+ keys map[string]*issued
+}{keys: map[string]*issued{}}
+
+func issueKey(ownerKey, user string) (id, secret string) {
+ id = "AKIA" + randomBase32(16)
+ secret = randomBase64(40)
+ keyring.mu.Lock()
+ defer keyring.mu.Unlock()
+ keyring.keys[id] = &issued{owner: ownerKey, user: user, secret: secret, active: true}
+ return id, secret
+}
+
+func revokeKey(id string) {
+ keyring.mu.Lock()
+ defer keyring.mu.Unlock()
+ if k, ok := keyring.keys[id]; ok {
+ k.active = false
+ }
+}
+
+func lookupKey(id string) (issued, bool) {
+ keyring.mu.Lock()
+ defer keyring.mu.Unlock()
+ k, ok := keyring.keys[id]
+ if !ok {
+ return issued{}, false
+ }
+ return *k, true
+}
+
+func owner(accessKeyID string) string {
+ if k, ok := lookupKey(accessKeyID); ok {
+ return k.owner
+ }
+ return accessKeyID
+}
+
+// Policy is what the credential is not allowed to do, as "<service>:<Action>", such as
+// "ssm:ListTagsForResource". AWS answers those with AccessDenied, which is how a
+// destination refuses a call for a reason a retry cannot fix.
+type Policy struct {
+ Denied []string `json:"denied,omitempty"`
+}
+
+func (p *Policy) denies(svc, action string) bool {
+ return slices.Contains(p.Denied, svc+":"+action)
+}
+
+func (p *Policy) merge(in Policy) {
+ for _, d := range in.Denied {
+ if !slices.Contains(p.Denied, d) {
+ p.Denied = append(p.Denied, d)
+ }
+ }
+}
+
+// call is one authenticated request.
+type call struct {
+ svc service
+ accessKeyID string
+ owner string
+ action string
+ body []byte
+ form url.Values
+}
+
+func (c call) account() string { return AccountID(c.owner) }
+
+// apiError is an AWS error, rendered in whichever protocol the service speaks.
+type apiError struct {
+ status int
+ code string
+ message string
+}
+
+func (e *apiError) Error() string { return e.code + ": " + e.message }
+
+func errf(status int, code, format string, args ...any) *apiError {
+ return &apiError{status: status, code: code, message: fmt.Sprintf(format, args...)}
+}
+
+// authenticate checks a request the way AWS does before any action runs: a signature
+// over the canonical request, a credential scope naming this service and region, and a
+// key that is still active.
+func authenticate(svc service, r *http.Request, body []byte) (string, *apiError) {
+ cred, ok := parseAuthorization(r.Header.Get("Authorization"))
+ if !ok {
+ return "", errf(http.StatusForbidden, "MissingAuthenticationToken", "Request is missing Authentication Token")
+ }
+ if cred.service != svc.name || cred.region != svc.region {
+ return "", errf(http.StatusForbidden, "SignatureDoesNotMatch",
+ "Credential should be scoped to a valid region and service, not '%s/%s'. Expected %s/%s.",
+ cred.region, cred.service, svc.region, svc.name)
+ }
+
+ secret := SecretAccessKey(cred.accessKeyID)
+ if k, issuedByIAM := lookupKey(cred.accessKeyID); issuedByIAM {
+ if !k.active {
+ return "", invalidToken(svc)
+ }
+ secret = k.secret
+ }
+
+ want, canonical := signature(r, body, cred, secret)
+ if want != cred.signature {
+ return "", errf(http.StatusForbidden, "SignatureDoesNotMatch",
+ "The request signature we calculated does not match the signature you provided. "+
+ "Check your AWS Secret Access Key and signing method. The Canonical String for this request should have been\n'%s'", canonical)
+ }
+ return cred.accessKeyID, nil
+}
+
+func invalidToken(svc service) *apiError {
+ if svc.json() {
+ return errf(http.StatusBadRequest, "UnrecognizedClientException", "The security token included in the request is invalid.")
+ }
+ return errf(http.StatusForbidden, "InvalidClientTokenId", "The security token included in the request is invalid.")
+}
+
+func (s service) json() bool { return s.name == "ssm" || s.name == "secretsmanager" }
+
+func (s service) targetPrefix() string {
+ switch s.name {
+ case "ssm":
+ return "AmazonSSM."
+ case "secretsmanager":
+ return "secretsmanager."
+ }
+ return ""
+}
+
+// handler is one fake's dispatch table and the lock over its state.
+type handler struct {
+ svc service
+ mu *sync.Mutex
+ policy func() *Policy
+ actions map[string]func(call) (any, *apiError)
+}
+
+// serve authenticates, resolves the action, applies the policy and renders the answer
+// in the service's protocol: JSON 1.1 with X-Amz-Target for SSM and Secrets Manager,
+// Query in and XML out for the rest.
+func (h handler) serve(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ h.fail(w, errf(http.StatusBadRequest, "SerializationException", "reading the body: %v", err))
+ return
+ }
+ akid, aErr := authenticate(h.svc, r, body)
+ if aErr != nil {
+ h.fail(w, aErr)
+ return
+ }
+
+ c := call{svc: h.svc, accessKeyID: akid, owner: owner(akid), body: body}
+ if h.svc.json() {
+ target, found := strings.CutPrefix(r.Header.Get("X-Amz-Target"), h.svc.targetPrefix())
+ if !found {
+ h.fail(w, errf(http.StatusBadRequest, "UnknownOperationException", "unknown target %q", r.Header.Get("X-Amz-Target")))
+ return
+ }
+ c.action = target
+ } else {
+ form, pErr := url.ParseQuery(string(body))
+ if pErr != nil {
+ h.fail(w, errf(http.StatusBadRequest, "MalformedQueryString", "%v", pErr))
+ return
+ }
+ c.form = form
+ c.action = form.Get("Action")
+ }
+
+ fn, ok := h.actions[c.action]
+ if !ok {
+ h.fail(w, errf(http.StatusBadRequest, "InvalidAction", "The action %s is not valid for this endpoint.", c.action))
+ return
+ }
+
+ h.mu.Lock()
+ var out any
+ if h.policy().denies(h.svc.name, c.action) {
+ aErr = errf(http.StatusBadRequest, "AccessDeniedException",
+ "User: arn:aws:iam::%s:user/infisical is not authorized to perform: %s:%s because no identity-based policy allows the %s:%s action",
+ c.account(), h.svc.name, c.action, h.svc.name, c.action)
+ if !h.svc.json() {
+ aErr.status, aErr.code = http.StatusForbidden, "AccessDenied"
+ }
+ } else {
+ out, aErr = fn(c)
+ }
+ h.mu.Unlock()
+
+ if aErr != nil {
+ h.fail(w, aErr)
+ return
+ }
+ if h.svc.json() {
+ writeJSON(w, http.StatusOK, out)
+ return
+ }
+ writeQueryResult(w, h.svc, c.action, out)
+}
+
+func (h handler) fail(w http.ResponseWriter, e *apiError) {
+ w.Header().Set("x-amzn-RequestId", requestID())
+ if h.svc.json() {
+ w.Header().Set("x-amzn-ErrorType", e.code)
+ w.Header().Set("Content-Type", "application/x-amz-json-1.1")
+ w.WriteHeader(e.status)
+ _ = json.NewEncoder(w).Encode(map[string]string{"__type": e.code, "message": e.message})
+ return
+ }
+ kind := "Sender"
+ if e.status >= 500 {
+ kind = "Receiver"
+ }
+ w.Header().Set("Content-Type", "text/xml")
+ w.WriteHeader(e.status)
+ _ = xml.NewEncoder(w).Encode(struct {
+ XMLName xml.Name `xml:"ErrorResponse"`
+ Xmlns string `xml:"xmlns,attr"`
+ Error struct {
+ Type string `xml:"Type"`
+ Code string `xml:"Code"`
+ Message string `xml:"Message"`
+ } `xml:"Error"`
+ RequestID string `xml:"RequestId"`
+ }{
+ Xmlns: namespace(h.svc),
+ Error: struct {
+ Type string `xml:"Type"`
+ Code string `xml:"Code"`
+ Message string `xml:"Message"`
+ }{kind, e.code, e.message},
+ RequestID: requestID(),
+ })
+}
+
+func namespace(s service) string {
+ switch s.name {
+ case "sts":
+ return "https://sts.amazonaws.com/doc/2011-06-15/"
+ case "iam":
+ return "https://iam.amazonaws.com/doc/2010-05-08/"
+ case "cloudformation":
+ return "http://cloudformation.amazonaws.com/doc/2010-05-15/"
+ }
+ return ""
+}
+
+func writeJSON(w http.ResponseWriter, status int, body any) {
+ w.Header().Set("Content-Type", "application/x-amz-json-1.1")
+ w.Header().Set("x-amzn-RequestId", requestID())
+ w.WriteHeader(status)
+ if body == nil {
+ body = struct{}{}
+ }
+ _ = json.NewEncoder(w).Encode(body)
+}
+
+// writeQueryResult wraps a result the way the Query protocol does:
+// <ActionResponse><ActionResult>...</ActionResult><ResponseMetadata/></ActionResponse>.
+func writeQueryResult(w http.ResponseWriter, svc service, action string, result any) {
+ var inner bytes.Buffer
+ if result != nil {
+ enc := xml.NewEncoder(&inner)
+ if err := enc.EncodeElement(result, xml.StartElement{Name: xml.Name{Local: action + "Result"}}); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+ w.Header().Set("Content-Type", "text/xml")
+ w.WriteHeader(http.StatusOK)
+ _, _ = fmt.Fprintf(w, `<%sResponse xmlns="%s">%s<ResponseMetadata><RequestId>%s</RequestId></ResponseMetadata></%sResponse>`,
+ action, namespace(svc), inner.String(), requestID(), action)
+}
+
+func decodeJSON(c call, into any) *apiError {
+ if len(c.body) == 0 {
+ return nil
+ }
+ if err := json.Unmarshal(c.body, into); err != nil {
+ return errf(http.StatusBadRequest, "SerializationException", "%v", err)
+ }
+ return nil
+}
+
+func epoch(t time.Time) float64 { return float64(t.UnixMilli()) / 1000 }
+
+func requestID() string {
+ b := make([]byte, 16)
+ _, _ = rand.Read(b)
+ h := hex.EncodeToString(b)
+ return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:]
+}
+
+func randomBase32(n int) string {
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
+ b := make([]byte, n)
+ _, _ = rand.Read(b)
+ for i := range b {
+ b[i] = alphabet[int(b[i])%len(alphabet)]
+ }
+ return string(b)
+}
+
+func randomBase64(n int) string {
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+ b := make([]byte, n)
+ _, _ = rand.Read(b)
+ for i := range b {
+ b[i] = alphabet[int(b[i])%len(alphabet)]
+ }
+ return string(b)
+}
+
+// now is second precision, as AWS reports creation dates.
+func now() time.Time { return time.Now().UTC().Truncate(time.Second) }
diff --git a/tests/fakes/aws/cloudformation.go b/tests/fakes/aws/cloudformation.go
new file mode 100644
index 0000000000..c2f80e91de
--- /dev/null
+++ b/tests/fakes/aws/cloudformation.go
@@ -0,0 +1,102 @@
+package aws
+
+import (
+ "encoding/json"
+ "net/http"
+ "slices"
+ "sync"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// CloudFormationAccount is one account's stacks in the served region. Nothing Infisical
+// calls changes a stack, so they exist only by seeding.
+type CloudFormationAccount struct {
+ Policy
+ Stacks map[string]*Stack `json:"stacks"`
+
+ mu sync.Mutex
+ h handler
+}
+
+type Stack struct {
+ StackName string `json:"stackName"`
+ StackID string `json:"stackId"`
+ StackStatus string `json:"stackStatus"`
+ CreationTime time.Time `json:"creationTime"`
+}
+
+func newCloudFormation(svc service, _ fakenet.Emitter) fakenet.Fake {
+ a := &CloudFormationAccount{Stacks: map[string]*Stack{}}
+ a.h = handler{svc: svc, mu: &a.mu, policy: func() *Policy { return &a.Policy }, actions: map[string]func(call) (any, *apiError){
+ "DescribeStacks": a.describeStacks,
+ }}
+ return a
+}
+
+func (a *CloudFormationAccount) ServeHTTP(w http.ResponseWriter, r *http.Request) { a.h.serve(w, r) }
+
+func (a *CloudFormationAccount) Snapshot() ([]byte, error) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return json.Marshal(struct {
+ Policy
+ Stacks map[string]*Stack `json:"stacks"`
+ }{a.Policy, a.Stacks})
+}
+
+func (a *CloudFormationAccount) Seed(raw []byte) error {
+ var in struct {
+ Policy
+ Stacks map[string]*Stack `json:"stacks"`
+ }
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return err
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.merge(in.Policy)
+ for name, st := range in.Stacks {
+ st.StackName = name
+ if st.StackID == "" {
+ st.StackID = "arn:aws:cloudformation:" + Region + ":000000000000:stack/" + name + "/" + requestID()
+ }
+ if st.CreationTime.IsZero() {
+ st.CreationTime = now()
+ }
+ a.Stacks[name] = st
+ }
+ return nil
+}
+
+type xmlStack struct {
+ StackName string `xml:"StackName"`
+ StackID string `xml:"StackId"`
+ StackStatus string `xml:"StackStatus"`
+ CreationTime string `xml:"CreationTime"`
+}
+
+func (a *CloudFormationAccount) describeStacks(c call) (any, *apiError) {
+ name := c.form.Get("StackName")
+ var names []string
+ if name == "" {
+ for n := range a.Stacks {
+ names = append(names, n)
+ }
+ slices.Sort(names)
+ } else {
+ if _, ok := a.Stacks[name]; !ok {
+ return nil, errf(http.StatusBadRequest, "ValidationError", "Stack with id %s does not exist", name)
+ }
+ names = []string{name}
+ }
+ out := make([]xmlStack, 0, len(names))
+ for _, n := range names {
+ st := a.Stacks[n]
+ out = append(out, xmlStack{st.StackName, st.StackID, st.StackStatus, iso(st.CreationTime)})
+ }
+ return struct {
+ Stacks []xmlStack `xml:"Stacks>member"`
+ }{out}, nil
+}
diff --git a/tests/fakes/aws/controlplane.go b/tests/fakes/aws/controlplane.go
new file mode 100644
index 0000000000..dd2c4c786a
--- /dev/null
+++ b/tests/fakes/aws/controlplane.go
@@ -0,0 +1,121 @@
+package aws
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// ControlPlane is a test's view of one AWS account inside fakenet, one scope per
+// service host. Events, failures and the call log are per service, so a test waits on
+// cp.SSM.ExpectEvent and fails cp.IAM.Fail.
+//
+// Every AWS JSON and Query call is a POST to "/", so a fakenet.Fail rule cannot pick
+// one action. To refuse a single action, seed Deny, which answers the way AWS answers
+// a policy that does not allow it.
+type ControlPlane struct {
+ STS *fakenet.Scope[STSAccount]
+ SSM *fakenet.Scope[ParameterStore]
+ SecretsManager *fakenet.Scope[SecretsStore]
+ IAM *fakenet.Scope[IAMAccount]
+ CloudFormation *fakenet.Scope[CloudFormationAccount]
+}
+
+// Open returns the account an access key id addresses, and starts collecting its
+// events on every host but STS, whose events the App Connection fixture already
+// tracks. Call it once per credential, before Infisical is handed anything that
+// writes to AWS.
+func Open(tt *testing.T, adminURL, accessKeyID string) *ControlPlane {
+ tt.Helper()
+ for _, svc := range []service{SSM, SecretsManager, IAM, CloudFormation} {
+ fakenet.Track(tt, adminURL, svc.Host(), accessKeyID)
+ }
+ return &ControlPlane{
+ STS: fakenet.Open[STSAccount](tt, adminURL, STS.Host(), accessKeyID),
+ SSM: fakenet.Open[ParameterStore](tt, adminURL, SSM.Host(), accessKeyID),
+ SecretsManager: fakenet.Open[SecretsStore](tt, adminURL, SecretsManager.Host(), accessKeyID),
+ IAM: fakenet.Open[IAMAccount](tt, adminURL, IAM.Host(), accessKeyID),
+ CloudFormation: fakenet.Open[CloudFormationAccount](tt, adminURL, CloudFormation.Host(), accessKeyID),
+ }
+}
+
+// Fragment is a piece of state that belongs to one service.
+type Fragment struct {
+ svc service
+ body any
+}
+
+// Seed merges fragments into the services they belong to.
+func (cp *ControlPlane) Seed(tt *testing.T, fragments ...Fragment) {
+ tt.Helper()
+ for _, f := range fragments {
+ cp.seeder(f.svc).Seed(tt, f.body)
+ }
+}
+
+func (cp *ControlPlane) seeder(svc service) interface{ Seed(*testing.T, ...any) } {
+ switch svc.name {
+ case SSM.name:
+ return cp.SSM
+ case SecretsManager.name:
+ return cp.SecretsManager
+ case IAM.name:
+ return cp.IAM
+ case CloudFormation.name:
+ return cp.CloudFormation
+ }
+ return cp.STS
+}
+
+// Parameters is every parameter the account holds, by stored name.
+func (cp *ControlPlane) Parameters(tt *testing.T) map[string]*Parameter {
+ tt.Helper()
+ return cp.SSM.State(tt).Parameters
+}
+
+// Secrets is every Secrets Manager secret the account holds, by name.
+func (cp *ControlPlane) Secrets(tt *testing.T) map[string]*Secret {
+ tt.Helper()
+ return cp.SecretsManager.State(tt).Secrets
+}
+
+// User is an IAM user, nil when it does not exist.
+func (cp *ControlPlane) User(tt *testing.T, name string) *User {
+ tt.Helper()
+ return cp.IAM.State(tt).Users[name]
+}
+
+// SeedParameter seeds a SecureString parameter under its full name, such as /app/DB_URL.
+func SeedParameter(name, value string) Fragment {
+ return Fragment{SSM, map[string]any{"parameters": map[string]any{name: map[string]any{"value": value}}}}
+}
+
+// SeedSecret seeds a Secrets Manager secret holding a string.
+func SeedSecret(name, value string) Fragment {
+ return Fragment{SecretsManager, map[string]any{"secrets": map[string]any{name: map[string]any{"secretString": value}}}}
+}
+
+// SeedUser seeds a user, holding the given access keys if any.
+func SeedUser(name string, accessKeyIDs ...string) Fragment {
+ keys := make([]map[string]any, 0, len(accessKeyIDs))
+ for _, id := range accessKeyIDs {
+ keys = append(keys, map[string]any{"accessKeyId": id})
+ }
+ return Fragment{IAM, map[string]any{"users": map[string]any{name: map[string]any{"accessKeys": keys}}}}
+}
+
+// RemoveAccessKey deletes a key behind Infisical's back, as an operator would in the
+// console.
+func RemoveAccessKey(accessKeyID string) Fragment {
+ return Fragment{IAM, map[string]any{"removedAccessKeys": []string{accessKeyID}}}
+}
+
+// SeedStack seeds a stack in a status such as CREATE_COMPLETE.
+func SeedStack(name, status string) Fragment {
+ return Fragment{CloudFormation, map[string]any{"stacks": map[string]any{name: map[string]any{"stackStatus": status}}}}
+}
+
+// Deny makes the account's policy refuse one action, such as Deny(SSM, "PutParameter").
+func Deny(svc service, action string) Fragment {
+ return Fragment{svc, Policy{Denied: []string{svc.name + ":" + action}}}
+}
diff --git a/tests/fakes/aws/events.go b/tests/fakes/aws/events.go
new file mode 100644
index 0000000000..a469a22c9d
--- /dev/null
+++ b/tests/fakes/aws/events.go
@@ -0,0 +1,61 @@
+package aws
+
+// ParameterDetail names a Parameter Store parameter by its full name, such as /app/DB_URL.
+type ParameterDetail struct {
+ Name string `json:"name"`
+}
+
+// ParameterPut is a PutParameter that stored a value, new or overwritten.
+type ParameterPut struct {
+ ParameterDetail
+ Version int64 `json:"version"`
+}
+
+type ParameterDeleted struct{ ParameterDetail }
+type ParameterTagged struct{ ParameterDetail }
+type ParameterUntagged struct{ ParameterDetail }
+
+func (ParameterPut) EventName() string { return "aws.parameter-put" }
+func (ParameterDeleted) EventName() string { return "aws.parameter-deleted" }
+func (ParameterTagged) EventName() string { return "aws.parameter-tagged" }
+func (ParameterUntagged) EventName() string { return "aws.parameter-untagged" }
+
+// SecretDetail names a Secrets Manager secret.
+type SecretDetail struct {
+ Name string `json:"name"`
+}
+
+type SecretCreated struct{ SecretDetail }
+type SecretUpdated struct{ SecretDetail }
+type SecretDeleted struct{ SecretDetail }
+type SecretTagged struct{ SecretDetail }
+type SecretUntagged struct{ SecretDetail }
+
+func (SecretCreated) EventName() string { return "aws.secret-created" }
+func (SecretUpdated) EventName() string { return "aws.secret-updated" }
+func (SecretDeleted) EventName() string { return "aws.secret-deleted" }
+func (SecretTagged) EventName() string { return "aws.secret-tagged" }
+func (SecretUntagged) EventName() string { return "aws.secret-untagged" }
+
+// UserDetail names an IAM user.
+type UserDetail struct {
+ UserName string `json:"userName"`
+}
+
+type UserCreated struct{ UserDetail }
+type UserDeleted struct{ UserDetail }
+
+func (UserCreated) EventName() string { return "aws.user-created" }
+func (UserDeleted) EventName() string { return "aws.user-deleted" }
+
+// AccessKeyDetail names one of an IAM user's access keys.
+type AccessKeyDetail struct {
+ UserName string `json:"userName"`
+ AccessKeyID string `json:"accessKeyId"`
+}
+
+type AccessKeyCreated struct{ AccessKeyDetail }
+type AccessKeyDeleted struct{ AccessKeyDetail }
+
+func (AccessKeyCreated) EventName() string { return "aws.access-key-created" }
+func (AccessKeyDeleted) EventName() string { return "aws.access-key-deleted" }
diff --git a/tests/fakes/aws/fake_test.go b/tests/fakes/aws/fake_test.go
new file mode 100644
index 0000000000..45c34af264
--- /dev/null
+++ b/tests/fakes/aws/fake_test.go
@@ -0,0 +1,431 @@
+package aws_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/xml"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/stretchr/testify/require"
+)
+
+// A fake is a plain http.Handler, so it is provable without Docker.
+type rig struct {
+ fakes *httptest.Server
+ admin string
+}
+
+const keyPrefix = "awsfaketest"
+
+func newRig(t *testing.T) *rig {
+ t.Helper()
+ srv := fakenet.New(aws.Services...)
+ ca, err := fakenet.LoadOrCreateCA(filepath.Join(t.TempDir(), "ca.pem"))
+ require.NoError(t, err)
+ fakes := httptest.NewServer(srv)
+ admin := httptest.NewServer(srv.Admin(ca))
+ t.Cleanup(fakes.Close)
+ t.Cleanup(admin.Close)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ require.NoError(t, fakenet.Listen(ctx, admin.URL, keyPrefix))
+ return &rig{fakes: fakes, admin: admin.URL}
+}
+
+// account is a credential a test invented, signing with the secret the fake derives.
+type account struct {
+ r *rig
+ id string
+ secret string
+}
+
+func (r *rig) account(t *testing.T) *account {
+ t.Helper()
+ id := fmt.Sprintf("%s%d", keyPrefix, time.Now().UnixNano())
+ return &account{r: r, id: id, secret: aws.SecretAccessKey(id)}
+}
+
+func (a *account) as(id, secret string) *account { return &account{r: a.r, id: id, secret: secret} }
+
+// send signs the way the SDK does: every header it sends, and the payload hash.
+func (a *account) send(t *testing.T, host, svc, region string, headers map[string]string, body []byte) (int, []byte) {
+ t.Helper()
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, a.r.fakes.URL+"/", bytes.NewReader(body))
+ require.NoError(t, err)
+ req.Host = host
+ stamp := time.Now().UTC().Format("20060102T150405Z")
+ req.Header.Set("X-Amz-Date", stamp)
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+
+ signed := []string{"content-type", "host", "x-amz-date"}
+ if _, ok := headers["X-Amz-Target"]; ok {
+ signed = append(signed, "x-amz-target")
+ }
+ var canon strings.Builder
+ for _, h := range signed {
+ v := req.Header.Get(h)
+ if h == "host" {
+ v = host
+ }
+ canon.WriteString(h + ":" + v + "\n")
+ }
+ payload := sha256.Sum256(body)
+ canonical := strings.Join([]string{"POST", "/", "", canon.String(), strings.Join(signed, ";"), hex.EncodeToString(payload[:])}, "\n")
+ scope := stamp[:8] + "/" + region + "/" + svc + "/aws4_request"
+ sum := sha256.Sum256([]byte(canonical))
+ toSign := "AWS4-HMAC-SHA256\n" + stamp + "\n" + scope + "\n" + hex.EncodeToString(sum[:])
+ key := mac([]byte("AWS4"+a.secret), stamp[:8])
+ for _, part := range []string{region, svc, "aws4_request"} {
+ key = mac(key, part)
+ }
+ req.Header.Set("Authorization", fmt.Sprintf("AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s",
+ a.id, scope, strings.Join(signed, ";"), hex.EncodeToString(mac(key, toSign))))
+
+ res, err := http.DefaultClient.Do(req)
+ require.NoError(t, err)
+ defer func() { _ = res.Body.Close() }()
+ out, err := io.ReadAll(res.Body)
+ require.NoError(t, err)
+ return res.StatusCode, out
+}
+
+func mac(key []byte, data string) []byte {
+ m := hmac.New(sha256.New, key)
+ m.Write([]byte(data))
+ return m.Sum(nil)
+}
+
+// json1 calls a JSON 1.1 action, as SSM and Secrets Manager are called.
+func (a *account) json1(t *testing.T, host, svc, target string, in any) (int, map[string]any) {
+ t.Helper()
+ body, err := json.Marshal(in)
+ require.NoError(t, err)
+ status, raw := a.send(t, host, svc, aws.Region, map[string]string{
+ "Content-Type": "application/x-amz-json-1.1",
+ "X-Amz-Target": target,
+ }, body)
+ var out map[string]any
+ require.NoErrorf(t, json.Unmarshal(raw, &out), "%s", raw)
+ return status, out
+}
+
+func (a *account) ssm(t *testing.T, action string, in any) (int, map[string]any) {
+ t.Helper()
+ return a.json1(t, aws.SSM.Host(), "ssm", "AmazonSSM."+action, in)
+}
+
+func (a *account) secrets(t *testing.T, action string, in any) (int, map[string]any) {
+ t.Helper()
+ return a.json1(t, aws.SecretsManager.Host(), "secretsmanager", "secretsmanager."+action, in)
+}
+
+// query calls a Query action, as STS, IAM and CloudFormation are called.
+func (a *account) query(t *testing.T, host, svc string, form url.Values) (int, string) {
+ t.Helper()
+ status, raw := a.send(t, host, svc, aws.Region,
+ map[string]string{"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"}, []byte(form.Encode()))
+ return status, string(raw)
+}
+
+func (a *account) iam(t *testing.T, action string, params ...string) (int, string) {
+ t.Helper()
+ form := url.Values{"Action": {action}, "Version": {"2010-05-08"}}
+ for i := 0; i+1 < len(params); i += 2 {
+ form.Set(params[i], params[i+1])
+ }
+ return a.query(t, aws.IAM.Host(), "iam", form)
+}
+
+func (a *account) callerIdentity(t *testing.T) (int, string) {
+ t.Helper()
+ return a.query(t, aws.STS.Host(), "sts", url.Values{"Action": {"GetCallerIdentity"}, "Version": {"2011-06-15"}})
+}
+
+func (a *account) cp(t *testing.T) *aws.ControlPlane {
+ t.Helper()
+ fakenet.Track(t, a.r.admin, aws.STS.Host(), a.id)
+ return aws.Open(t, a.r.admin, a.id)
+}
+
+func errorCode(t *testing.T, raw string) string {
+ t.Helper()
+ var out struct {
+ Error struct {
+ Code string `xml:"Code"`
+ } `xml:"Error"`
+ }
+ require.NoErrorf(t, xml.Unmarshal([]byte(raw), &out), "%s", raw)
+ return out.Error.Code
+}
+
+func TestAWSFake_Authentication(t *testing.T) {
+ t.Run("should name the account when the request is signed with the derived secret", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+
+ // Action
+ status, body := a.callerIdentity(t)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, status, "%s", body)
+ require.Contains(t, body, "<Account>"+aws.AccountID(a.id)+"</Account>")
+ })
+
+ t.Run("should refuse with SignatureDoesNotMatch when the secret is wrong", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+
+ // Action
+ status, body := a.as(a.id, "not-the-secret").callerIdentity(t)
+
+ // Assert
+ require.Equal(t, http.StatusForbidden, status)
+ require.Equal(t, "SignatureDoesNotMatch", errorCode(t, body))
+ })
+
+ t.Run("should refuse when the credential is scoped to another region", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+
+ // Action
+ status, raw := a.send(t, aws.STS.Host(), "sts", "eu-west-1",
+ map[string]string{"Content-Type": "application/x-www-form-urlencoded"}, []byte("Action=GetCallerIdentity&Version=2011-06-15"))
+
+ // Assert
+ require.Equal(t, http.StatusForbidden, status)
+ require.Contains(t, string(raw), "eu-west-1")
+ })
+}
+
+func TestAWSFake_ParameterStore(t *testing.T) {
+ t.Run("should page one level of a path and leave deeper parameters out", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ for i := range 25 {
+ status, out := a.ssm(t, "PutParameter", map[string]any{
+ "Name": fmt.Sprintf("/app/K%02d", i), "Value": "v", "Type": "SecureString", "Overwrite": true})
+ require.Equalf(t, http.StatusOK, status, "%v", out)
+ }
+ a.ssm(t, "PutParameter", map[string]any{"Name": "/app/sub/DEEP", "Value": "v", "Type": "String"})
+
+ // Action
+ var names []string
+ pages := 0
+ token := ""
+ for {
+ in := map[string]any{"Path": "/app/", "Recursive": false, "WithDecryption": true, "MaxResults": 10}
+ if token != "" {
+ in["NextToken"] = token
+ }
+ status, out := a.ssm(t, "GetParametersByPath", in)
+ require.Equalf(t, http.StatusOK, status, "%v", out)
+ pages++
+ for _, p := range out["Parameters"].([]any) {
+ names = append(names, p.(map[string]any)["Name"].(string))
+ }
+ next, ok := out["NextToken"].(string)
+ if !ok {
+ break
+ }
+ token = next
+ }
+
+ // Assert
+ require.Equal(t, 3, pages)
+ require.Len(t, names, 25)
+ require.NotContains(t, names, "/app/sub/DEEP")
+ })
+
+ t.Run("should store a root-level name without its leading slash", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ cp := a.cp(t)
+
+ // Action
+ status, out := a.ssm(t, "PutParameter", map[string]any{"Name": "/ROOT", "Value": "v", "Type": "SecureString"})
+
+ // Assert
+ require.Equalf(t, http.StatusOK, status, "%v", out)
+ require.Contains(t, cp.Parameters(t), "ROOT")
+ cp.SSM.ExpectEvent[aws.ParameterPut](t, func(e aws.ParameterPut) bool { return e.Name == "ROOT" })
+ })
+
+ t.Run("should refuse an empty value and an overwrite that was not asked for", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ a.ssm(t, "PutParameter", map[string]any{"Name": "/app/K", "Value": "first", "Type": "SecureString"})
+
+ // Action
+ emptyStatus, empty := a.ssm(t, "PutParameter", map[string]any{"Name": "/app/E", "Value": "", "Type": "SecureString"})
+ againStatus, again := a.ssm(t, "PutParameter", map[string]any{"Name": "/app/K", "Value": "second", "Type": "SecureString"})
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, emptyStatus)
+ require.Equal(t, "ValidationException", empty["__type"])
+ require.Equal(t, http.StatusBadRequest, againStatus)
+ require.Equal(t, "ParameterAlreadyExists", again["__type"])
+ })
+
+ t.Run("should refuse an action the policy denies with AccessDeniedException", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ cp := a.cp(t)
+ cp.Seed(t, aws.SeedParameter("/app/K", "v"), aws.Deny(aws.SSM, "ListTagsForResource"))
+
+ // Action
+ status, out := a.ssm(t, "ListTagsForResource", map[string]any{"ResourceType": "Parameter", "ResourceId": "/app/K"})
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, status)
+ require.Equal(t, "AccessDeniedException", out["__type"])
+ })
+}
+
+func TestAWSFake_SecretsManager(t *testing.T) {
+ t.Run("should refuse a second create of one name and keep the first value", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ cp := a.cp(t)
+ a.secrets(t, "CreateSecret", map[string]any{"Name": "app/db", "SecretString": "first"})
+
+ // Action
+ status, out := a.secrets(t, "CreateSecret", map[string]any{"Name": "app/db", "SecretString": "second"})
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, status)
+ require.Equal(t, "ResourceExistsException", out["__type"])
+ require.Equal(t, "first", cp.Secrets(t)["app/db"].SecretString)
+ })
+
+ t.Run("should return values in a batch and name the ids it cannot find", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ a.secrets(t, "CreateSecret", map[string]any{"Name": "A", "SecretString": "1"})
+
+ // Action
+ status, out := a.secrets(t, "BatchGetSecretValue", map[string]any{"SecretIdList": []string{"A", "MISSING"}})
+
+ // Assert
+ require.Equalf(t, http.StatusOK, status, "%v", out)
+ require.Len(t, out["SecretValues"], 1)
+ require.Equal(t, "MISSING", out["Errors"].([]any)[0].(map[string]any)["SecretId"])
+ })
+
+ t.Run("should forget a secret at once when it is force deleted", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ cp := a.cp(t)
+ a.secrets(t, "CreateSecret", map[string]any{"Name": "GONE", "SecretString": "1"})
+
+ // Action
+ a.secrets(t, "DeleteSecret", map[string]any{"SecretId": "GONE", "ForceDeleteWithoutRecovery": true})
+
+ // Assert
+ status, out := a.secrets(t, "DescribeSecret", map[string]any{"SecretId": "GONE"})
+ require.Equal(t, http.StatusBadRequest, status)
+ require.Equal(t, "ResourceNotFoundException", out["__type"])
+ cp.SecretsManager.ExpectEvent[aws.SecretDeleted](t, func(e aws.SecretDeleted) bool { return e.Name == "GONE" })
+ })
+}
+
+func TestAWSFake_IAM(t *testing.T) {
+ t.Run("should refuse a third access key with LimitExceeded", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ a.iam(t, "CreateUser", "UserName", "app")
+ a.iam(t, "CreateAccessKey", "UserName", "app")
+ a.iam(t, "CreateAccessKey", "UserName", "app")
+
+ // Action
+ status, body := a.iam(t, "CreateAccessKey", "UserName", "app")
+
+ // Assert
+ require.Equal(t, http.StatusConflict, status)
+ require.Equal(t, "LimitExceeded", errorCode(t, body))
+ })
+
+ t.Run("should accept an issued key at STS until it is deleted", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ cp := a.cp(t)
+ a.iam(t, "CreateUser", "UserName", "app")
+ _, created := a.iam(t, "CreateAccessKey", "UserName", "app")
+ var res struct {
+ Result struct {
+ AccessKey struct {
+ AccessKeyID string `xml:"AccessKeyId"`
+ SecretAccessKey string `xml:"SecretAccessKey"`
+ } `xml:"AccessKey"`
+ } `xml:"CreateAccessKeyResult"`
+ }
+ require.NoError(t, xml.Unmarshal([]byte(created), &res))
+ key := a.as(res.Result.AccessKey.AccessKeyID, res.Result.AccessKey.SecretAccessKey)
+ liveStatus, live := key.callerIdentity(t)
+
+ // Action
+ a.iam(t, "DeleteAccessKey", "UserName", "app", "AccessKeyId", key.id)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, liveStatus, "%s", live)
+ require.Contains(t, live, "user/app", "an issued key names the user it belongs to")
+ status, body := key.callerIdentity(t)
+ require.Equal(t, http.StatusForbidden, status)
+ require.Equal(t, "InvalidClientTokenId", errorCode(t, body))
+ require.Empty(t, cp.User(t, "app").AccessKeys)
+ require.Equal(t, 2, cp.STS.Received(t, "POST", "/"), "an issued key's calls belong to the account that created it")
+ })
+
+ t.Run("should refuse deleting a user that still holds keys", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ cp := a.cp(t)
+ cp.Seed(t, aws.SeedUser("app", "AKIASEEDEDKEY0000001"))
+
+ // Action
+ status, body := a.iam(t, "DeleteUser", "UserName", "app")
+
+ // Assert
+ require.Equal(t, http.StatusConflict, status)
+ require.Equal(t, "DeleteConflict", errorCode(t, body))
+ require.NotNil(t, cp.User(t, "app"))
+ })
+}
+
+func TestAWSFake_CloudFormation(t *testing.T) {
+ t.Run("should report a seeded stack's status and refuse an unknown one", func(t *testing.T) {
+ // Setup
+ a := newRig(t).account(t)
+ a.cp(t).Seed(t, aws.SeedStack("honey", "CREATE_COMPLETE"))
+ describe := func(name string) (int, string) {
+ return a.query(t, aws.CloudFormation.Host(), "cloudformation",
+ url.Values{"Action": {"DescribeStacks"}, "Version": {"2010-05-15"}, "StackName": {name}})
+ }
+
+ // Action
+ status, body := describe("honey")
+ missingStatus, missing := describe("nope")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, status, "%s", body)
+ require.Contains(t, body, "<StackStatus>CREATE_COMPLETE</StackStatus>")
+ require.Equal(t, http.StatusBadRequest, missingStatus)
+ require.Equal(t, "ValidationError", errorCode(t, missing))
+ })
+}
diff --git a/tests/fakes/aws/iam.go b/tests/fakes/aws/iam.go
new file mode 100644
index 0000000000..22198220ef
--- /dev/null
+++ b/tests/fakes/aws/iam.go
@@ -0,0 +1,243 @@
+package aws
+
+import (
+ "encoding/json"
+ "net/http"
+ "regexp"
+ "slices"
+ "sync"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// IAMAccount is one account's IAM users and their access keys.
+type IAMAccount struct {
+ Policy
+ Users map[string]*User `json:"users"`
+
+ mu sync.Mutex
+ events fakenet.Emitter
+ h handler
+}
+
+type User struct {
+ UserName string `json:"userName"`
+ UserID string `json:"userId"`
+ CreateDate time.Time `json:"createDate"`
+ AccessKeys []AccessKey `json:"accessKeys"`
+}
+
+// AccessKey carries its secret so a test can tell which credential a product published.
+type AccessKey struct {
+ AccessKeyID string `json:"accessKeyId"`
+ SecretAccessKey string `json:"secretAccessKey"`
+ Status string `json:"status"`
+ CreateDate time.Time `json:"createDate"`
+}
+
+// accessKeysPerUser is IAM's hard quota.
+const accessKeysPerUser = 2
+
+func newIAM(svc service, events fakenet.Emitter) fakenet.Fake {
+ a := &IAMAccount{Users: map[string]*User{}, events: events}
+ a.h = handler{svc: svc, mu: &a.mu, policy: func() *Policy { return &a.Policy }, actions: map[string]func(call) (any, *apiError){
+ "CreateUser": a.createUser,
+ "DeleteUser": a.deleteUser,
+ "ListAccessKeys": a.listAccessKeys,
+ "CreateAccessKey": a.createAccessKey,
+ "DeleteAccessKey": a.deleteAccessKey,
+ }}
+ return a
+}
+
+func (a *IAMAccount) ServeHTTP(w http.ResponseWriter, r *http.Request) { a.h.serve(w, r) }
+
+func (a *IAMAccount) Snapshot() ([]byte, error) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return json.Marshal(struct {
+ Policy
+ Users map[string]*User `json:"users"`
+ }{a.Policy, a.Users})
+}
+
+// Seed merges users, and any keys they already hold, that exist before Infisical
+// touches the account. A seeded key with no secret gets the derived one, so it signs
+// like a credential a test invented. A removed access key is deleted the way an
+// operator deletes one in the console: behind Infisical's back.
+func (a *IAMAccount) Seed(raw []byte) error {
+ var in struct {
+ Policy
+ Users map[string]*User `json:"users"`
+ RemovedAccessKeys []string `json:"removedAccessKeys"`
+ }
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return err
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.merge(in.Policy)
+ for name, u := range in.Users {
+ u.UserName = name
+ if u.UserID == "" {
+ u.UserID = "AIDA" + randomBase32(16)
+ }
+ if u.CreateDate.IsZero() {
+ u.CreateDate = now()
+ }
+ for i := range u.AccessKeys {
+ k := &u.AccessKeys[i]
+ if k.SecretAccessKey == "" {
+ k.SecretAccessKey = SecretAccessKey(k.AccessKeyID)
+ }
+ if k.Status == "" {
+ k.Status = "Active"
+ }
+ if k.CreateDate.IsZero() {
+ k.CreateDate = u.CreateDate
+ }
+ registerSeededKey(k.AccessKeyID, name, k.SecretAccessKey, k.Status == "Active")
+ }
+ if existing, ok := a.Users[name]; ok {
+ existing.AccessKeys = append(existing.AccessKeys, u.AccessKeys...)
+ continue
+ }
+ a.Users[name] = u
+ }
+ for _, id := range in.RemovedAccessKeys {
+ for _, u := range a.Users {
+ u.AccessKeys = slices.DeleteFunc(u.AccessKeys, func(k AccessKey) bool { return k.AccessKeyID == id })
+ }
+ revokeKey(id)
+ }
+ return nil
+}
+
+// registerSeededKey puts a seeded key in the keyring as its own owner, so it scopes to
+// itself and a later delete still revokes it everywhere.
+func registerSeededKey(id, user, secret string, active bool) {
+ keyring.mu.Lock()
+ defer keyring.mu.Unlock()
+ keyring.keys[id] = &issued{owner: id, user: user, secret: secret, active: active}
+}
+
+var userNamePattern = regexp.MustCompile(`^[\w+=,.@-]{1,64}$`)
+
+func (a *IAMAccount) user(c call) (*User, *apiError) {
+ name := c.form.Get("UserName")
+ if name == "" {
+ return nil, errf(http.StatusBadRequest, "ValidationError",
+ "1 validation error detected: Value null at 'userName' failed to satisfy constraint: Member must not be null")
+ }
+ u, ok := a.Users[name]
+ if !ok {
+ return nil, errf(http.StatusNotFound, "NoSuchEntity", "The user with name %s cannot be found.", name)
+ }
+ return u, nil
+}
+
+type xmlUser struct {
+ Path string `xml:"Path"`
+ UserName string `xml:"UserName"`
+ UserID string `xml:"UserId"`
+ Arn string `xml:"Arn"`
+ CreateDate string `xml:"CreateDate"`
+}
+
+func iso(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05Z") }
+
+func (a *IAMAccount) createUser(c call) (any, *apiError) {
+ name := c.form.Get("UserName")
+ if !userNamePattern.MatchString(name) {
+ return nil, errf(http.StatusBadRequest, "ValidationError",
+ "The specified value for userName is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-")
+ }
+ if _, ok := a.Users[name]; ok {
+ return nil, errf(http.StatusConflict, "EntityAlreadyExists", "User with name %s already exists.", name)
+ }
+ u := &User{UserName: name, UserID: "AIDA" + randomBase32(16), CreateDate: now(), AccessKeys: []AccessKey{}}
+ a.Users[name] = u
+ a.events.Publish(UserCreated{UserDetail{UserName: name}})
+ return struct {
+ User xmlUser `xml:"User"`
+ }{xmlUser{"/", u.UserName, u.UserID, "arn:aws:iam::" + c.account() + ":user/" + u.UserName, iso(u.CreateDate)}}, nil
+}
+
+func (a *IAMAccount) deleteUser(c call) (any, *apiError) {
+ u, err := a.user(c)
+ if err != nil {
+ return nil, err
+ }
+ if len(u.AccessKeys) > 0 {
+ return nil, errf(http.StatusConflict, "DeleteConflict", "Cannot delete entity, must delete access keys first.")
+ }
+ delete(a.Users, u.UserName)
+ a.events.Publish(UserDeleted{UserDetail{UserName: u.UserName}})
+ return nil, nil
+}
+
+type xmlAccessKeyMetadata struct {
+ UserName string `xml:"UserName"`
+ AccessKeyID string `xml:"AccessKeyId"`
+ Status string `xml:"Status"`
+ CreateDate string `xml:"CreateDate"`
+}
+
+// listAccessKeys answers in creation order. Two keys made in the same second carry
+// the same CreateDate, and creation order is what a stable sort then keeps.
+func (a *IAMAccount) listAccessKeys(c call) (any, *apiError) {
+ u, err := a.user(c)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]xmlAccessKeyMetadata, 0, len(u.AccessKeys))
+ for _, k := range u.AccessKeys {
+ out = append(out, xmlAccessKeyMetadata{u.UserName, k.AccessKeyID, k.Status, iso(k.CreateDate)})
+ }
+ return struct {
+ AccessKeyMetadata []xmlAccessKeyMetadata `xml:"AccessKeyMetadata>member"`
+ IsTruncated bool `xml:"IsTruncated"`
+ }{out, false}, nil
+}
+
+type xmlAccessKey struct {
+ UserName string `xml:"UserName"`
+ AccessKeyID string `xml:"AccessKeyId"`
+ Status string `xml:"Status"`
+ SecretAccessKey string `xml:"SecretAccessKey"`
+ CreateDate string `xml:"CreateDate"`
+}
+
+func (a *IAMAccount) createAccessKey(c call) (any, *apiError) {
+ u, err := a.user(c)
+ if err != nil {
+ return nil, err
+ }
+ if len(u.AccessKeys) >= accessKeysPerUser {
+ return nil, errf(http.StatusConflict, "LimitExceeded", "Cannot exceed quota for AccessKeysPerUser: %d", accessKeysPerUser)
+ }
+ id, secret := issueKey(c.owner, u.UserName)
+ k := AccessKey{AccessKeyID: id, SecretAccessKey: secret, Status: "Active", CreateDate: now()}
+ u.AccessKeys = append(u.AccessKeys, k)
+ a.events.Publish(AccessKeyCreated{AccessKeyDetail{UserName: u.UserName, AccessKeyID: id}})
+ return struct {
+ AccessKey xmlAccessKey `xml:"AccessKey"`
+ }{xmlAccessKey{u.UserName, id, k.Status, secret, iso(k.CreateDate)}}, nil
+}
+
+func (a *IAMAccount) deleteAccessKey(c call) (any, *apiError) {
+ u, err := a.user(c)
+ if err != nil {
+ return nil, err
+ }
+ id := c.form.Get("AccessKeyId")
+ i := slices.IndexFunc(u.AccessKeys, func(k AccessKey) bool { return k.AccessKeyID == id })
+ if i < 0 {
+ return nil, errf(http.StatusNotFound, "NoSuchEntity", "The Access Key with id %s cannot be found.", id)
+ }
+ u.AccessKeys = slices.Delete(u.AccessKeys, i, i+1)
+ revokeKey(id)
+ a.events.Publish(AccessKeyDeleted{AccessKeyDetail{UserName: u.UserName, AccessKeyID: id}})
+ return nil, nil
+}
diff --git a/tests/fakes/aws/secretsmanager.go b/tests/fakes/aws/secretsmanager.go
new file mode 100644
index 0000000000..725a7bd748
--- /dev/null
+++ b/tests/fakes/aws/secretsmanager.go
@@ -0,0 +1,419 @@
+package aws
+
+import (
+ "encoding/json"
+ "maps"
+ "net/http"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// SecretsStore is one account's Secrets Manager secrets in the served region.
+type SecretsStore struct {
+ Policy
+ Secrets map[string]*Secret `json:"secrets"`
+
+ mu sync.Mutex
+ events fakenet.Emitter
+ h handler
+}
+
+// Secret is keyed by its name. A secret deleted with a recovery window stays here with
+// DeletedDate set, as it does in AWS, until the window passes.
+type Secret struct {
+ Name string `json:"name"`
+ ARN string `json:"arn"`
+ SecretString string `json:"secretString"`
+ KmsKeyID string `json:"kmsKeyId,omitempty"`
+ VersionID string `json:"versionId"`
+ Tags map[string]string `json:"tags,omitempty"`
+ CreatedDate time.Time `json:"createdDate"`
+ LastChanged time.Time `json:"lastChangedDate"`
+ DeletedDate *time.Time `json:"deletedDate,omitempty"`
+}
+
+const (
+ smMaxList = 100
+ smMaxBatch = 20
+ smMaxNameLength = 512
+ smMaxValueBytes = 65536
+)
+
+func newSecretsManager(svc service, events fakenet.Emitter) fakenet.Fake {
+ sm := &SecretsStore{Secrets: map[string]*Secret{}, events: events}
+ sm.h = handler{svc: svc, mu: &sm.mu, policy: func() *Policy { return &sm.Policy }, actions: map[string]func(call) (any, *apiError){
+ "ListSecrets": sm.listSecrets,
+ "BatchGetSecretValue": sm.batchGetSecretValue,
+ "DescribeSecret": sm.describeSecret,
+ "GetSecretValue": sm.getSecretValue,
+ "CreateSecret": sm.createSecret,
+ "UpdateSecret": sm.updateSecret,
+ "DeleteSecret": sm.deleteSecret,
+ "TagResource": sm.tagResource,
+ "UntagResource": sm.untagResource,
+ }}
+ return sm
+}
+
+func (sm *SecretsStore) ServeHTTP(w http.ResponseWriter, r *http.Request) { sm.h.serve(w, r) }
+
+func (sm *SecretsStore) Snapshot() ([]byte, error) {
+ sm.mu.Lock()
+ defer sm.mu.Unlock()
+ return json.Marshal(struct {
+ Policy
+ Secrets map[string]*Secret `json:"secrets"`
+ }{sm.Policy, sm.Secrets})
+}
+
+// Seed merges secrets that exist before Infisical touches the store, without the API's
+// validation: a seed is whatever someone else put there.
+func (sm *SecretsStore) Seed(raw []byte) error {
+ var in struct {
+ Policy
+ Secrets map[string]*Secret `json:"secrets"`
+ }
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return err
+ }
+ sm.mu.Lock()
+ defer sm.mu.Unlock()
+ sm.merge(in.Policy)
+ for name, s := range in.Secrets {
+ s.Name = name
+ if s.ARN == "" {
+ s.ARN = "arn:aws:secretsmanager:" + Region + ":000000000000:secret:" + name + "-" + randomBase32(6)
+ }
+ if s.VersionID == "" {
+ s.VersionID = requestID()
+ }
+ if s.CreatedDate.IsZero() {
+ s.CreatedDate = now()
+ }
+ if s.LastChanged.IsZero() {
+ s.LastChanged = s.CreatedDate
+ }
+ sm.Secrets[name] = s
+ }
+ return nil
+}
+
+var secretNamePattern = regexp.MustCompile(`^[a-zA-Z0-9/_+=.@\-]+$`)
+
+func notFound() *apiError {
+ return errf(http.StatusBadRequest, "ResourceNotFoundException", "Secrets Manager can't find the specified secret.")
+}
+
+// find resolves a SecretId, which may be the name or the ARN.
+func (sm *SecretsStore) find(id string) (*Secret, *apiError) {
+ if s, ok := sm.Secrets[id]; ok {
+ return s, nil
+ }
+ for _, s := range sm.Secrets {
+ if s.ARN == id {
+ return s, nil
+ }
+ }
+ return nil, notFound()
+}
+
+func (sm *SecretsStore) live(id string) (*Secret, *apiError) {
+ s, err := sm.find(id)
+ if err != nil {
+ return nil, err
+ }
+ if s.DeletedDate != nil {
+ return nil, errf(http.StatusBadRequest, "InvalidRequestException",
+ "You can't perform this operation on the secret because it was marked for deletion.")
+ }
+ return s, nil
+}
+
+func tagList(tags map[string]string) []tag {
+ keys := slices.Sorted(maps.Keys(tags))
+ out := make([]tag, 0, len(keys))
+ for _, k := range keys {
+ out = append(out, tag{Key: k, Value: tags[k]})
+ }
+ return out
+}
+
+func (sm *SecretsStore) entry(s *Secret) map[string]any {
+ out := map[string]any{
+ "ARN": s.ARN,
+ "Name": s.Name,
+ "Tags": tagList(s.Tags),
+ "CreatedDate": epoch(s.CreatedDate),
+ "LastChangedDate": epoch(s.LastChanged),
+ "SecretVersionsToStages": map[string][]string{
+ s.VersionID: {"AWSCURRENT"},
+ },
+ }
+ if s.KmsKeyID != "" {
+ out["KmsKeyId"] = s.KmsKeyID
+ }
+ if s.DeletedDate != nil {
+ out["DeletedDate"] = epoch(*s.DeletedDate)
+ }
+ return out
+}
+
+func (sm *SecretsStore) listSecrets(c call) (any, *apiError) {
+ var in struct {
+ MaxResults *int
+ NextToken string
+ IncludePlannedDeletion bool
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ limit, err := maxResults(in.MaxResults, smMaxList, smMaxList, "maxResults")
+ if err != nil {
+ return nil, err
+ }
+ var names []string
+ for name, s := range sm.Secrets {
+ if s.DeletedDate == nil || in.IncludePlannedDeletion {
+ names = append(names, name)
+ }
+ }
+ got, next, err := page(names, in.NextToken, limit)
+ if err != nil {
+ return nil, err
+ }
+ list := make([]map[string]any, 0, len(got))
+ for _, name := range got {
+ list = append(list, sm.entry(sm.Secrets[name]))
+ }
+ res := map[string]any{"SecretList": list}
+ if next != "" {
+ res["NextToken"] = next
+ }
+ return res, nil
+}
+
+func (sm *SecretsStore) value(s *Secret) map[string]any {
+ return map[string]any{
+ "ARN": s.ARN,
+ "Name": s.Name,
+ "VersionId": s.VersionID,
+ "SecretString": s.SecretString,
+ "VersionStages": []string{"AWSCURRENT"},
+ "CreatedDate": epoch(s.LastChanged),
+ }
+}
+
+func (sm *SecretsStore) batchGetSecretValue(c call) (any, *apiError) {
+ var in struct{ SecretIdList []string }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ if len(in.SecretIdList) < 1 || len(in.SecretIdList) > smMaxBatch {
+ return nil, errf(http.StatusBadRequest, "InvalidParameterException",
+ "SecretIdList must contain between 1 and 20 secret IDs.")
+ }
+ values, errs := []map[string]any{}, []map[string]any{}
+ for _, id := range in.SecretIdList {
+ s, err := sm.live(id)
+ if err != nil {
+ errs = append(errs, map[string]any{"SecretId": id, "ErrorCode": err.code, "Message": err.message})
+ continue
+ }
+ values = append(values, sm.value(s))
+ }
+ return map[string]any{"SecretValues": values, "Errors": errs}, nil
+}
+
+func (sm *SecretsStore) describeSecret(c call) (any, *apiError) {
+ var in struct{ SecretId string }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ s, err := sm.find(in.SecretId)
+ if err != nil {
+ return nil, err
+ }
+ return sm.entry(s), nil
+}
+
+func (sm *SecretsStore) getSecretValue(c call) (any, *apiError) {
+ var in struct{ SecretId string }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ s, err := sm.live(in.SecretId)
+ if err != nil {
+ return nil, err
+ }
+ return sm.value(s), nil
+}
+
+func validateSecretValue(v *string) *apiError {
+ if v != nil && len(*v) > smMaxValueBytes {
+ return errf(http.StatusBadRequest, "InvalidParameterException",
+ "The SecretString parameter exceeds the maximum size of 65536 bytes.")
+ }
+ return nil
+}
+
+func (sm *SecretsStore) createSecret(c call) (any, *apiError) {
+ var in struct {
+ Name string
+ SecretString *string
+ KmsKeyId string
+ Tags []tag
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ if in.Name == "" || len(in.Name) > smMaxNameLength || !secretNamePattern.MatchString(in.Name) {
+ return nil, errf(http.StatusBadRequest, "ValidationException",
+ "Invalid name. Must be a valid name containing alphanumeric characters, or any of the following: -/_+=.@!")
+ }
+ if err := validateSecretValue(in.SecretString); err != nil {
+ return nil, err
+ }
+ if existing, ok := sm.Secrets[in.Name]; ok {
+ if existing.DeletedDate != nil {
+ return nil, errf(http.StatusBadRequest, "InvalidRequestException",
+ "You can't create this secret because a secret with this name is already scheduled for deletion.")
+ }
+ return nil, errf(http.StatusBadRequest, "ResourceExistsException",
+ "The operation failed because the secret %s already exists.", in.Name)
+ }
+
+ at := now()
+ s := &Secret{
+ Name: in.Name,
+ ARN: "arn:aws:secretsmanager:" + c.svc.region + ":" + c.account() + ":secret:" + in.Name + "-" + randomBase32(6),
+ KmsKeyID: in.KmsKeyId,
+ VersionID: requestID(),
+ CreatedDate: at,
+ LastChanged: at,
+ }
+ if in.SecretString != nil {
+ s.SecretString = *in.SecretString
+ }
+ if len(in.Tags) > 0 {
+ s.Tags = map[string]string{}
+ for _, t := range in.Tags {
+ s.Tags[t.Key] = t.Value
+ }
+ }
+ sm.Secrets[in.Name] = s
+ sm.events.Publish(SecretCreated{SecretDetail{Name: s.Name}})
+ return map[string]any{"ARN": s.ARN, "Name": s.Name, "VersionId": s.VersionID}, nil
+}
+
+func (sm *SecretsStore) updateSecret(c call) (any, *apiError) {
+ var in struct {
+ SecretId string
+ SecretString *string
+ KmsKeyId *string
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ s, err := sm.live(in.SecretId)
+ if err != nil {
+ return nil, err
+ }
+ if err := validateSecretValue(in.SecretString); err != nil {
+ return nil, err
+ }
+ if in.KmsKeyId != nil {
+ s.KmsKeyID = *in.KmsKeyId
+ }
+ out := map[string]any{"ARN": s.ARN, "Name": s.Name}
+ if in.SecretString != nil {
+ s.SecretString = *in.SecretString
+ s.VersionID = requestID()
+ out["VersionId"] = s.VersionID
+ }
+ s.LastChanged = now()
+ sm.events.Publish(SecretUpdated{SecretDetail{Name: s.Name}})
+ return out, nil
+}
+
+func (sm *SecretsStore) deleteSecret(c call) (any, *apiError) {
+ var in struct {
+ SecretId string
+ ForceDeleteWithoutRecovery bool
+ RecoveryWindowInDays *int
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ if in.ForceDeleteWithoutRecovery && in.RecoveryWindowInDays != nil {
+ return nil, errf(http.StatusBadRequest, "InvalidParameterException",
+ "You can't use ForceDeleteWithoutRecovery in conjunction with RecoveryWindowInDays.")
+ }
+ s, err := sm.find(in.SecretId)
+ if err != nil {
+ return nil, err
+ }
+ at := now()
+ if in.ForceDeleteWithoutRecovery {
+ delete(sm.Secrets, s.Name)
+ } else {
+ days := 30
+ if in.RecoveryWindowInDays != nil {
+ days = *in.RecoveryWindowInDays
+ }
+ at = at.AddDate(0, 0, days)
+ s.DeletedDate = &at
+ }
+ sm.events.Publish(SecretDeleted{SecretDetail{Name: s.Name}})
+ return map[string]any{"ARN": s.ARN, "Name": s.Name, "DeletionDate": epoch(at)}, nil
+}
+
+func (sm *SecretsStore) tagResource(c call) (any, *apiError) {
+ var in struct {
+ SecretId string
+ Tags []tag
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ s, err := sm.live(in.SecretId)
+ if err != nil {
+ return nil, err
+ }
+ tags := maps.Clone(s.Tags)
+ if tags == nil {
+ tags = map[string]string{}
+ }
+ for _, t := range in.Tags {
+ tags[t.Key] = t.Value
+ }
+ if len(tags) > 50 {
+ return nil, errf(http.StatusBadRequest, "ValidationException", "Number of tags exceeds the limit of 50.")
+ }
+ s.Tags = tags
+ sm.events.Publish(SecretTagged{SecretDetail{Name: s.Name}})
+ return struct{}{}, nil
+}
+
+func (sm *SecretsStore) untagResource(c call) (any, *apiError) {
+ var in struct {
+ SecretId string
+ TagKeys []string
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ s, err := sm.live(in.SecretId)
+ if err != nil {
+ return nil, err
+ }
+ for _, k := range in.TagKeys {
+ delete(s.Tags, strings.TrimSpace(k))
+ }
+ sm.events.Publish(SecretUntagged{SecretDetail{Name: s.Name}})
+ return struct{}{}, nil
+}
diff --git a/tests/fakes/aws/sigv4.go b/tests/fakes/aws/sigv4.go
new file mode 100644
index 0000000000..39f10203c4
--- /dev/null
+++ b/tests/fakes/aws/sigv4.go
@@ -0,0 +1,144 @@
+package aws
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "net/http"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+type credential struct {
+ accessKeyID string
+ date string
+ region string
+ service string
+ signedHeaders []string
+ signature string
+}
+
+// parseAuthorization reads
+// "AWS4-HMAC-SHA256 Credential=AKID/20240101/us-east-1/ssm/aws4_request, SignedHeaders=host;x-amz-date, Signature=hex".
+func parseAuthorization(header string) (credential, bool) {
+ rest, ok := strings.CutPrefix(header, "AWS4-HMAC-SHA256 ")
+ if !ok {
+ return credential{}, false
+ }
+ var c credential
+ for part := range strings.SplitSeq(rest, ",") {
+ k, v, found := strings.Cut(strings.TrimSpace(part), "=")
+ if !found {
+ return credential{}, false
+ }
+ switch k {
+ case "Credential":
+ scope := strings.Split(v, "/")
+ if len(scope) != 5 || scope[4] != "aws4_request" {
+ return credential{}, false
+ }
+ c.accessKeyID, c.date, c.region, c.service = scope[0], scope[1], scope[2], scope[3]
+ case "SignedHeaders":
+ c.signedHeaders = strings.Split(v, ";")
+ case "Signature":
+ c.signature = v
+ }
+ }
+ return c, c.accessKeyID != "" && c.signature != "" && len(c.signedHeaders) > 0
+}
+
+// signature is SigV4 over the request as it arrived, and the canonical request it
+// signed, which AWS quotes back when the two disagree.
+func signature(r *http.Request, body []byte, c credential, secret string) (sig, canonical string) {
+ payloadHash := r.Header.Get("X-Amz-Content-Sha256")
+ if payloadHash == "" {
+ sum := sha256.Sum256(body)
+ payloadHash = hex.EncodeToString(sum[:])
+ }
+
+ var headers strings.Builder
+ for _, name := range c.signedHeaders {
+ headers.WriteString(name + ":" + headerValue(r, name) + "\n")
+ }
+
+ canonical = strings.Join([]string{
+ r.Method,
+ canonicalURI(r.URL.EscapedPath()),
+ canonicalQuery(r.URL.Query()),
+ headers.String(),
+ strings.Join(c.signedHeaders, ";"),
+ payloadHash,
+ }, "\n")
+
+ scope := c.date + "/" + c.region + "/" + c.service + "/aws4_request"
+ sum := sha256.Sum256([]byte(canonical))
+ toSign := strings.Join([]string{"AWS4-HMAC-SHA256", r.Header.Get("X-Amz-Date"), scope, hex.EncodeToString(sum[:])}, "\n")
+
+ key := hmacSHA256([]byte("AWS4"+secret), c.date)
+ key = hmacSHA256(key, c.region)
+ key = hmacSHA256(key, c.service)
+ key = hmacSHA256(key, "aws4_request")
+ return hex.EncodeToString(hmacSHA256(key, toSign)), canonical
+}
+
+func headerValue(r *http.Request, name string) string {
+ if strings.EqualFold(name, "host") {
+ return r.Host
+ }
+ values := r.Header.Values(name)
+ if len(values) == 0 && strings.EqualFold(name, "content-length") && r.ContentLength >= 0 {
+ values = []string{strconv.FormatInt(r.ContentLength, 10)}
+ }
+ trimmed := make([]string, len(values))
+ for i, v := range values {
+ trimmed[i] = strings.Join(strings.Fields(v), " ")
+ }
+ return strings.Join(trimmed, ",")
+}
+
+func canonicalURI(p string) string {
+ if p == "" {
+ return "/"
+ }
+ return p
+}
+
+func canonicalQuery(q url.Values) string {
+ keys := make([]string, 0, len(q))
+ for k := range q {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ var parts []string
+ for _, k := range keys {
+ vs := append([]string(nil), q[k]...)
+ sort.Strings(vs)
+ for _, v := range vs {
+ parts = append(parts, uriEncode(k)+"="+uriEncode(v))
+ }
+ }
+ return strings.Join(parts, "&")
+}
+
+// uriEncode is RFC 3986 encoding with only the unreserved characters left alone.
+func uriEncode(s string) string {
+ var b strings.Builder
+ for i := 0; i < len(s); i++ {
+ ch := s[i]
+ if ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') || ('0' <= ch && ch <= '9') ||
+ ch == '-' || ch == '_' || ch == '.' || ch == '~' {
+ b.WriteByte(ch)
+ continue
+ }
+ b.WriteString("%" + strings.ToUpper(hex.EncodeToString([]byte{ch})))
+ }
+ return b.String()
+}
+
+func hmacSHA256(key []byte, data string) []byte {
+ m := hmac.New(sha256.New, key)
+ m.Write([]byte(data))
+ return m.Sum(nil)
+}
diff --git a/tests/fakes/aws/sigv4_test.go b/tests/fakes/aws/sigv4_test.go
new file mode 100644
index 0000000000..26dc2af583
--- /dev/null
+++ b/tests/fakes/aws/sigv4_test.go
@@ -0,0 +1,31 @@
+package aws
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestSigV4_Signature(t *testing.T) {
+ t.Run("should match AWS's published signature when given the get-vanilla request", func(t *testing.T) {
+ // Setup: aws-sig-v4-test-suite/get-vanilla.
+ req, err := http.NewRequest(http.MethodGet, "https://example.amazonaws.com/", nil)
+ require.NoError(t, err)
+ req.Host = "example.amazonaws.com"
+ req.Header.Set("X-Amz-Date", "20150830T123600Z")
+ cred := credential{
+ accessKeyID: "AKIDEXAMPLE",
+ date: "20150830",
+ region: "us-east-1",
+ service: "service",
+ signedHeaders: []string{"host", "x-amz-date"},
+ }
+
+ // Action
+ got, _ := signature(req, nil, cred, "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY")
+
+ // Assert
+ require.Equal(t, "5fa00fa31553b73ebf1942676e86291e8372ff2a2260956d9b8aae1d763fbf31", got)
+ })
+}
diff --git a/tests/fakes/aws/ssm.go b/tests/fakes/aws/ssm.go
new file mode 100644
index 0000000000..c269cd17d8
--- /dev/null
+++ b/tests/fakes/aws/ssm.go
@@ -0,0 +1,513 @@
+package aws
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "maps"
+ "net/http"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// ParameterStore is one account's SSM parameters in the served region.
+type ParameterStore struct {
+ Policy
+ Parameters map[string]*Parameter `json:"parameters"`
+
+ mu sync.Mutex
+ events fakenet.Emitter
+ h handler
+}
+
+// Parameter is keyed by its full name. SSM stores a root-level name without its
+// leading slash, so "/DB_URL" is held as "DB_URL" while "/app/DB_URL" keeps it.
+type Parameter struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Value string `json:"value"`
+ KeyID string `json:"keyId,omitempty"`
+ Version int64 `json:"version"`
+ Tags map[string]string `json:"tags,omitempty"`
+ LastModifiedDate time.Time `json:"lastModifiedDate"`
+}
+
+const (
+ ssmDefaultKeyID = "alias/aws/ssm"
+ ssmMaxByPath = 10
+ ssmMaxDescribe = 50
+ ssmMaxDeleteBatch = 10
+ ssmMaxValueLength = 4096
+ ssmMaxHierarchyDeep = 15
+)
+
+func newParameterStore(svc service, events fakenet.Emitter) fakenet.Fake {
+ ps := &ParameterStore{Parameters: map[string]*Parameter{}, events: events}
+ ps.h = handler{svc: svc, mu: &ps.mu, policy: func() *Policy { return &ps.Policy }, actions: map[string]func(call) (any, *apiError){
+ "GetParametersByPath": ps.getParametersByPath,
+ "DescribeParameters": ps.describeParameters,
+ "PutParameter": ps.putParameter,
+ "DeleteParameters": ps.deleteParameters,
+ "ListTagsForResource": ps.listTagsForResource,
+ "AddTagsToResource": ps.addTagsToResource,
+ "RemoveTagsFromResource": ps.removeTagsFromResource,
+ }}
+ return ps
+}
+
+func (ps *ParameterStore) ServeHTTP(w http.ResponseWriter, r *http.Request) { ps.h.serve(w, r) }
+
+func (ps *ParameterStore) Snapshot() ([]byte, error) {
+ ps.mu.Lock()
+ defer ps.mu.Unlock()
+ return json.Marshal(struct {
+ Policy
+ Parameters map[string]*Parameter `json:"parameters"`
+ }{ps.Policy, ps.Parameters})
+}
+
+// Seed merges parameters that exist before Infisical touches the store. It skips the
+// API's validation on purpose: a seed is whatever someone else put there.
+func (ps *ParameterStore) Seed(raw []byte) error {
+ var in struct {
+ Policy
+ Parameters map[string]*Parameter `json:"parameters"`
+ }
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return err
+ }
+ ps.mu.Lock()
+ defer ps.mu.Unlock()
+ ps.merge(in.Policy)
+ for name, p := range in.Parameters {
+ name = normalizeParameterName(name)
+ if p.Type == "" {
+ p.Type = "SecureString"
+ }
+ if p.Type == "SecureString" && p.KeyID == "" {
+ p.KeyID = ssmDefaultKeyID
+ }
+ if p.Version == 0 {
+ p.Version = 1
+ }
+ if p.LastModifiedDate.IsZero() {
+ p.LastModifiedDate = now()
+ }
+ p.Name = name
+ ps.Parameters[name] = p
+ }
+ return nil
+}
+
+func normalizeParameterName(name string) string {
+ if rest, ok := strings.CutPrefix(name, "/"); ok && !strings.Contains(rest, "/") {
+ return rest
+ }
+ return name
+}
+
+var parameterNamePattern = regexp.MustCompile(`^[a-zA-Z0-9_.\-/]+$`)
+
+func validateParameterName(name string) *apiError {
+ invalid := errf(http.StatusBadRequest, "ValidationException",
+ `Parameter name: can't be prefixed with "aws" or "ssm" (case-insensitive). If formed as a path, it can consist of `+
+ `sub-paths divided by slash symbol; each sub-path can be formed as a mix of letters, numbers and the following 3 symbols .-_`)
+ if name == "" || !parameterNamePattern.MatchString(name) || strings.Contains(name, "//") || strings.HasSuffix(name, "/") {
+ return invalid
+ }
+ first := strings.ToLower(strings.SplitN(strings.TrimPrefix(name, "/"), "/", 2)[0])
+ if strings.HasPrefix(first, "aws") || strings.HasPrefix(first, "ssm") {
+ return invalid
+ }
+ if strings.Contains(name, "/") && !strings.HasPrefix(name, "/") {
+ return errf(http.StatusBadRequest, "ValidationException",
+ "Parameter name must be a fully qualified name.")
+ }
+ if strings.Count(name, "/") > ssmMaxHierarchyDeep {
+ return errf(http.StatusBadRequest, "HierarchyLevelLimitExceededException",
+ "A hierarchy can have a maximum of 15 levels.")
+ }
+ return nil
+}
+
+// inPath reports whether a stored name sits at path, or anywhere below it when
+// recursive.
+func inPath(name, path string, recursive bool) bool {
+ if path == "/" {
+ if recursive {
+ return true
+ }
+ return !strings.Contains(name, "/")
+ }
+ rest, ok := strings.CutPrefix(name, path)
+ if !ok {
+ return false
+ }
+ return recursive || !strings.Contains(rest, "/")
+}
+
+func validatePath(path string) (string, *apiError) {
+ if !strings.HasPrefix(path, "/") {
+ return "", errf(http.StatusBadRequest, "ValidationException",
+ "The parameter doesn't meet the parameter name requirements. The parameter name must begin with a forward slash \"/\".")
+ }
+ if !strings.HasSuffix(path, "/") {
+ path += "/"
+ }
+ return path, nil
+}
+
+// page sorts names and returns one page after the token, with the token for the next.
+func page(names []string, token string, limit int) ([]string, string, *apiError) {
+ slices.Sort(names)
+ start := 0
+ if token != "" {
+ raw, err := base64.StdEncoding.DecodeString(token)
+ if err != nil {
+ return nil, "", errf(http.StatusBadRequest, "InvalidNextToken", "The specified token isn't valid.")
+ }
+ after := string(raw)
+ start, _ = slices.BinarySearch(names, after)
+ if start < len(names) && names[start] == after {
+ start++
+ }
+ }
+ end := min(start+limit, len(names))
+ next := ""
+ if end < len(names) {
+ next = base64.StdEncoding.EncodeToString([]byte(names[end-1]))
+ }
+ return names[start:end], next, nil
+}
+
+func maxResults(given *int, limit, def int, field string) (int, *apiError) {
+ if given == nil {
+ return def, nil
+ }
+ if *given < 1 || *given > limit {
+ return 0, errf(http.StatusBadRequest, "ValidationException",
+ "1 validation error detected: Value '%d' at '%s' failed to satisfy constraint: Member must have value less than or equal to %d",
+ *given, field, limit)
+ }
+ return *given, nil
+}
+
+func (ps *ParameterStore) arn(c call, name string) string {
+ if !strings.HasPrefix(name, "/") {
+ name = "/" + name
+ }
+ return "arn:aws:ssm:" + c.svc.region + ":" + c.account() + ":parameter" + name
+}
+
+func (ps *ParameterStore) getParametersByPath(c call) (any, *apiError) {
+ var in struct {
+ Path string
+ Recursive bool
+ WithDecryption bool
+ MaxResults *int
+ NextToken string
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ path, err := validatePath(in.Path)
+ if err != nil {
+ return nil, err
+ }
+ limit, err := maxResults(in.MaxResults, ssmMaxByPath, ssmMaxByPath, "maxResults")
+ if err != nil {
+ return nil, err
+ }
+
+ var names []string
+ for name := range ps.Parameters {
+ if inPath(name, path, in.Recursive) {
+ names = append(names, name)
+ }
+ }
+ got, next, err := page(names, in.NextToken, limit)
+ if err != nil {
+ return nil, err
+ }
+
+ out := make([]map[string]any, 0, len(got))
+ for _, name := range got {
+ p := ps.Parameters[name]
+ value := p.Value
+ if p.Type == "SecureString" && !in.WithDecryption {
+ value = base64.StdEncoding.EncodeToString([]byte("kms:" + p.KeyID + ":" + p.Value))
+ }
+ out = append(out, map[string]any{
+ "Name": p.Name,
+ "Type": p.Type,
+ "Value": value,
+ "Version": p.Version,
+ "LastModifiedDate": epoch(p.LastModifiedDate),
+ "ARN": ps.arn(c, p.Name),
+ "DataType": "text",
+ })
+ }
+ res := map[string]any{"Parameters": out}
+ if next != "" {
+ res["NextToken"] = next
+ }
+ return res, nil
+}
+
+func (ps *ParameterStore) describeParameters(c call) (any, *apiError) {
+ var in struct {
+ MaxResults *int
+ NextToken string
+ ParameterFilters []struct {
+ Key string
+ Option string
+ Values []string
+ }
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ limit, err := maxResults(in.MaxResults, ssmMaxDescribe, ssmMaxDescribe, "maxResults")
+ if err != nil {
+ return nil, err
+ }
+
+ var names []string
+ for name := range ps.Parameters {
+ keep := true
+ for _, f := range in.ParameterFilters {
+ switch f.Key {
+ case "Path":
+ match := false
+ for _, v := range f.Values {
+ path, pErr := validatePath(v)
+ if pErr != nil {
+ return nil, pErr
+ }
+ if inPath(name, path, f.Option == "Recursive") {
+ match = true
+ }
+ }
+ keep = keep && match
+ case "Name":
+ keep = keep && slices.ContainsFunc(f.Values, func(v string) bool {
+ if f.Option == "BeginsWith" {
+ return strings.HasPrefix(name, normalizeParameterName(v))
+ }
+ return name == normalizeParameterName(v)
+ })
+ default:
+ return nil, errf(http.StatusBadRequest, "InvalidFilterKey", "The specified key isn't valid.")
+ }
+ }
+ if keep {
+ names = append(names, name)
+ }
+ }
+ got, next, err := page(names, in.NextToken, limit)
+ if err != nil {
+ return nil, err
+ }
+
+ out := make([]map[string]any, 0, len(got))
+ for _, name := range got {
+ p := ps.Parameters[name]
+ meta := map[string]any{
+ "Name": p.Name,
+ "Type": p.Type,
+ "Version": p.Version,
+ "LastModifiedDate": epoch(p.LastModifiedDate),
+ "ARN": ps.arn(c, p.Name),
+ "Tier": "Standard",
+ "DataType": "text",
+ }
+ if p.KeyID != "" {
+ meta["KeyId"] = p.KeyID
+ }
+ out = append(out, meta)
+ }
+ res := map[string]any{"Parameters": out}
+ if next != "" {
+ res["NextToken"] = next
+ }
+ return res, nil
+}
+
+func (ps *ParameterStore) putParameter(c call) (any, *apiError) {
+ var in struct {
+ Name string
+ Value *string
+ Type string
+ Overwrite bool
+ KeyId string
+ Tags []tag
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ if err := validateParameterName(in.Name); err != nil {
+ return nil, err
+ }
+ if in.Value == nil || *in.Value == "" {
+ return nil, errf(http.StatusBadRequest, "ValidationException",
+ "1 validation error detected: Value '' at 'value' failed to satisfy constraint: Member must have length greater than or equal to 1")
+ }
+ if len(*in.Value) > ssmMaxValueLength {
+ return nil, errf(http.StatusBadRequest, "ValidationException",
+ "Standard tier parameters support a maximum parameter value of 4096 characters. "+
+ "To create a larger parameter value, upgrade the parameter to use the advanced-parameter tier.")
+ }
+ if in.Overwrite && len(in.Tags) > 0 {
+ return nil, errf(http.StatusBadRequest, "ValidationException",
+ "Invalid request: tags and overwrite can't be used together. To create a parameter with tags, please remove overwrite flag. "+
+ "To update tags for an existing parameter, please use AddTagsToResource or RemoveTagsFromResource.")
+ }
+
+ name := normalizeParameterName(in.Name)
+ existing, exists := ps.Parameters[name]
+ if exists && !in.Overwrite {
+ return nil, errf(http.StatusBadRequest, "ParameterAlreadyExists",
+ "The parameter already exists. To overwrite this value, set the overwrite option in the request to true.")
+ }
+
+ typ := in.Type
+ if typ == "" {
+ if !exists {
+ return nil, errf(http.StatusBadRequest, "ValidationException", "A parameter type is required when you create a parameter.")
+ }
+ typ = existing.Type
+ }
+ keyID := ""
+ if typ == "SecureString" {
+ keyID = in.KeyId
+ if keyID == "" {
+ keyID = ssmDefaultKeyID
+ }
+ } else if in.KeyId != "" {
+ return nil, errf(http.StatusBadRequest, "ValidationException", "KeyId is required for SecureString type parameter only.")
+ }
+
+ p := &Parameter{Name: name, Type: typ, Value: *in.Value, KeyID: keyID, Version: 1, LastModifiedDate: now()}
+ if exists {
+ p.Version = existing.Version + 1
+ p.Tags = existing.Tags
+ } else if len(in.Tags) > 0 {
+ p.Tags = map[string]string{}
+ for _, t := range in.Tags {
+ p.Tags[t.Key] = t.Value
+ }
+ }
+ ps.Parameters[name] = p
+ ps.events.Publish(ParameterPut{ParameterDetail{Name: name}, p.Version})
+ return map[string]any{"Version": p.Version, "Tier": "Standard"}, nil
+}
+
+func (ps *ParameterStore) deleteParameters(c call) (any, *apiError) {
+ var in struct{ Names []string }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ if len(in.Names) < 1 || len(in.Names) > ssmMaxDeleteBatch {
+ return nil, errf(http.StatusBadRequest, "ValidationException",
+ "1 validation error detected: Value at 'names' failed to satisfy constraint: Member must have length less than or equal to 10")
+ }
+ deleted, invalid := []string{}, []string{}
+ for _, raw := range in.Names {
+ name := normalizeParameterName(raw)
+ if _, ok := ps.Parameters[name]; !ok {
+ invalid = append(invalid, raw)
+ continue
+ }
+ delete(ps.Parameters, name)
+ deleted = append(deleted, raw)
+ ps.events.Publish(ParameterDeleted{ParameterDetail{Name: name}})
+ }
+ return map[string]any{"DeletedParameters": deleted, "InvalidParameters": invalid}, nil
+}
+
+type tag struct {
+ Key string
+ Value string
+}
+
+func (ps *ParameterStore) taggable(resourceType, resourceID string) (*Parameter, *apiError) {
+ if resourceType != "Parameter" {
+ return nil, errf(http.StatusBadRequest, "InvalidResourceType", "The resource type isn't valid.")
+ }
+ p, ok := ps.Parameters[normalizeParameterName(resourceID)]
+ if !ok {
+ return nil, errf(http.StatusBadRequest, "InvalidResourceId", "The resource ID isn't valid. Verify that you entered the correct ID and try again.")
+ }
+ return p, nil
+}
+
+func (ps *ParameterStore) listTagsForResource(c call) (any, *apiError) {
+ var in struct{ ResourceType, ResourceId string }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ p, err := ps.taggable(in.ResourceType, in.ResourceId)
+ if err != nil {
+ return nil, err
+ }
+ keys := make([]string, 0, len(p.Tags))
+ for k := range p.Tags {
+ keys = append(keys, k)
+ }
+ slices.Sort(keys)
+ out := make([]tag, 0, len(keys))
+ for _, k := range keys {
+ out = append(out, tag{Key: k, Value: p.Tags[k]})
+ }
+ return map[string]any{"TagList": out}, nil
+}
+
+func (ps *ParameterStore) addTagsToResource(c call) (any, *apiError) {
+ var in struct {
+ ResourceType, ResourceId string
+ Tags []tag
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ p, err := ps.taggable(in.ResourceType, in.ResourceId)
+ if err != nil {
+ return nil, err
+ }
+ tags := maps.Clone(p.Tags)
+ if tags == nil {
+ tags = map[string]string{}
+ }
+ for _, t := range in.Tags {
+ tags[t.Key] = t.Value
+ }
+ if len(tags) > 50 {
+ return nil, errf(http.StatusBadRequest, "TooManyTagsError", "The Targets parameter includes too many tags. Remove one or more tags and try the command again.")
+ }
+ p.Tags = tags
+ ps.events.Publish(ParameterTagged{ParameterDetail{Name: p.Name}})
+ return struct{}{}, nil
+}
+
+func (ps *ParameterStore) removeTagsFromResource(c call) (any, *apiError) {
+ var in struct {
+ ResourceType, ResourceId string
+ TagKeys []string
+ }
+ if err := decodeJSON(c, &in); err != nil {
+ return nil, err
+ }
+ p, err := ps.taggable(in.ResourceType, in.ResourceId)
+ if err != nil {
+ return nil, err
+ }
+ for _, k := range in.TagKeys {
+ delete(p.Tags, k)
+ }
+ ps.events.Publish(ParameterUntagged{ParameterDetail{Name: p.Name}})
+ return struct{}{}, nil
+}
diff --git a/tests/fakes/aws/sts.go b/tests/fakes/aws/sts.go
new file mode 100644
index 0000000000..7fef62a5c7
--- /dev/null
+++ b/tests/fakes/aws/sts.go
@@ -0,0 +1,59 @@
+package aws
+
+import (
+ "encoding/json"
+ "net/http"
+ "sync"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// STSAccount answers who a credential is. It holds no state of its own beyond the
+// policy: whether a key is valid is the keyring's to say.
+type STSAccount struct {
+ Policy
+
+ mu sync.Mutex
+ h handler
+}
+
+func newSTS(svc service, _ fakenet.Emitter) fakenet.Fake {
+ a := &STSAccount{}
+ a.h = handler{svc: svc, mu: &a.mu, policy: func() *Policy { return &a.Policy }, actions: map[string]func(call) (any, *apiError){
+ "GetCallerIdentity": a.getCallerIdentity,
+ }}
+ return a
+}
+
+func (a *STSAccount) ServeHTTP(w http.ResponseWriter, r *http.Request) { a.h.serve(w, r) }
+
+func (a *STSAccount) Snapshot() ([]byte, error) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return json.Marshal(a.Policy)
+}
+
+func (a *STSAccount) Seed(raw []byte) error {
+ var in Policy
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return err
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.merge(in)
+ return nil
+}
+
+// getCallerIdentity names the IAM user a key IAM issued belongs to, and a user called
+// infisical for a credential a test invented.
+func (a *STSAccount) getCallerIdentity(c call) (any, *apiError) {
+ user := "infisical"
+ if k, ok := lookupKey(c.accessKeyID); ok && k.user != "" {
+ user = k.user
+ }
+ return struct {
+ Arn string `xml:"Arn"`
+ UserID string `xml:"UserId"`
+ Account string `xml:"Account"`
+ }{"arn:aws:iam::" + c.account() + ":user/" + user, "AIDA" + randomBase32(16), c.account()}, nil
+}
diff --git a/tests/fixture/appconnection_aws.go b/tests/fixture/appconnection_aws.go
new file mode 100644
index 0000000000..904d591a0e
--- /dev/null
+++ b/tests/fixture/appconnection_aws.go
@@ -0,0 +1,61 @@
+package fixture
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "github.com/google/uuid"
+)
+
+// AWSAccessKeyAppConnection is an AWS App Connection over an IAM access key.
+//
+// Access key rather than assume-role because assume-role needs the instance's own AWS
+// credentials to call STS AssumeRole, which the harness does not configure. The access
+// key id is the nonce, so the fake scopes the account by it, and the secret is the one
+// the fake derives from it, so every request Infisical signs is checked.
+//
+// Host is STS, the call that validates the credential. Drive the account's other
+// services with aws.Open(t, conn.FakenetAdmin(t), conn.Nonce()).
+var AWSAccessKeyAppConnection = AppConnectionKind{
+ App: "aws",
+ Host: aws.STS.Host(),
+ create: createAWSAccessKeyAppConnection,
+}
+
+func createAWSAccessKeyAppConnection(ctx context.Context, c *api.ClientWithResponses, name, credential string) (uuid.UUID, error) {
+ raw, err := AWSAccessKeyAppConnectionBody(name, credential, aws.SecretAccessKey(credential))
+ if err != nil {
+ return uuid.Nil, err
+ }
+ res, err := c.CreateAwsAppConnectionWithBodyWithResponse(ctx, "application/json", bytes.NewReader(raw))
+ if err != nil {
+ return uuid.Nil, err
+ }
+ var out struct {
+ AppConnection struct {
+ ID uuid.UUID `json:"id"`
+ } `json:"appConnection"`
+ }
+ if res.StatusCode() != http.StatusOK || json.Unmarshal(res.Body, &out) != nil || out.AppConnection.ID == uuid.Nil {
+ return uuid.Nil, fmt.Errorf("creating the connection returned %d: %s", res.StatusCode(), res.Body)
+ }
+ return out.AppConnection.ID, nil
+}
+
+// AWSAccessKeyAppConnectionBody is the create request, for a test that calls the route
+// itself, such as one about a refused secret.
+func AWSAccessKeyAppConnectionBody(name, accessKeyID, secretAccessKey string) ([]byte, error) {
+ return json.Marshal(map[string]any{
+ "name": name,
+ "method": "access-key",
+ "credentials": map[string]string{
+ "accessKeyId": accessKeyID,
+ "secretAccessKey": secretAccessKey,
+ },
+ })
+}
diff --git a/tests/suites/secretmanager/honeytokens/helpers_test.go b/tests/suites/secretmanager/honeytokens/helpers_test.go
new file mode 100644
index 0000000000..50bd9d162c
--- /dev/null
+++ b/tests/suites/secretmanager/honeytokens/helpers_test.go
@@ -0,0 +1,210 @@
+package honeytokens_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "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/Infisical/infisical/tests/internal/id"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ stackName = "infisical-honey-tokens"
+ accessKeyIDKey = "AWS_ACCESS_KEY_ID"
+ secretAccessKeyKey = "AWS_SECRET_ACCESS_KEY"
+)
+
+type env struct {
+ tn *harness.Tenant
+ proj *fixture.Project
+ cp *aws.ControlPlane
+ signingKey string
+}
+
+type setupConfig struct {
+ stackStatus string
+}
+
+type setupOption func(*setupConfig)
+
+// stackIn seeds the CloudFormation stack in a status other than CREATE_COMPLETE, or
+// leaves it out when the status is empty.
+func stackIn(status string) setupOption { return func(c *setupConfig) { c.stackStatus = status } }
+
+// setup returns a project and an organization whose AWS honey token configuration is
+// saved against an AWS connection, with the stack deployed unless told otherwise.
+func setup(t *testing.T, opts ...setupOption) env {
+ t.Helper()
+ cfg := setupConfig{stackStatus: "CREATE_COMPLETE"}
+ for _, o := range opts {
+ o(&cfg)
+ }
+ tn := harness.From(t).NewTenant(t)
+ conn := fixture.NewAppConnection(t, tn, fixture.AWSAccessKeyAppConnection)
+ e := env{
+ tn: tn,
+ proj: fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager")),
+ cp: aws.Open(t, conn.FakenetAdmin(t), conn.Nonce()),
+ signingKey: randomHex(t, 32),
+ }
+ if cfg.stackStatus != "" {
+ e.cp.Seed(t, aws.SeedStack(stackName, cfg.stackStatus))
+ }
+
+ raw, err := json.Marshal(map[string]any{
+ "connectionId": conn.ID,
+ "config": map[string]any{"webhookSigningKey": e.signingKey, "stackName": stackName, "awsRegion": aws.Region},
+ })
+ require.NoError(t, err)
+ res, err := tn.Admin.API.UpsertAwsHoneyTokenConfigWithBodyWithResponse(t.Context(), "application/json", bytes.NewReader(raw))
+ require.NoError(t, err, "saving the honey token configuration")
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "saving the honey token configuration: %s", apierr.Body(res.Body))
+ return e
+}
+
+func randomHex(t *testing.T, n int) string {
+ t.Helper()
+ b := make([]byte, n)
+ _, err := rand.Read(b)
+ require.NoError(t, err)
+ return hex.EncodeToString(b)
+}
+
+func (e env) create(t *testing.T) *api.CreateHoneyTokenResponse {
+ t.Helper()
+ raw, err := json.Marshal(map[string]any{
+ "projectId": e.proj.ID,
+ "type": "aws",
+ "name": "ht-" + id.Short(),
+ "environment": "dev",
+ "secretPath": "/",
+ "secretsMapping": map[string]string{"accessKeyId": accessKeyIDKey, "secretAccessKey": secretAccessKeyKey},
+ })
+ require.NoError(t, err)
+ res, err := e.tn.Admin.API.CreateHoneyTokenWithBodyWithResponse(t.Context(), "application/json", bytes.NewReader(raw))
+ require.NoError(t, err, "creating a honey token")
+ return res
+}
+
+func (e env) newHoneyToken(t *testing.T) uuid.UUID {
+ t.Helper()
+ res := e.create(t)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating a honey token: %s", apierr.Body(res.Body))
+ return res.JSON200.HoneyToken.Id
+}
+
+// planted is the access key id the mapped secrets hold.
+func (e env) planted(t *testing.T) string {
+ t.Helper()
+ for _, s := range secretmanager.ListSecrets(t, e.proj, "dev") {
+ if s.Key == accessKeyIDKey {
+ return s.Value
+ }
+ }
+ t.Fatalf("the mapped secret %s is missing", accessKeyIDKey)
+ return ""
+}
+
+func (e env) secretKeys(t *testing.T) []string {
+ t.Helper()
+ keys := []string{}
+ for _, s := range secretmanager.ListSecrets(t, e.proj, "dev") {
+ keys = append(keys, s.Key)
+ }
+ return keys
+}
+
+// honeyUsers is the IAM users the account holds that a honey token created.
+func (e env) honeyUsers(t *testing.T) map[string]*aws.User {
+ t.Helper()
+ out := map[string]*aws.User{}
+ for name, u := range e.cp.IAM.State(t).Users {
+ if strings.HasPrefix(name, "inf_ht_") {
+ out[name] = u
+ }
+ }
+ return out
+}
+
+// trigger posts the alert the deployed stack sends when someone uses the key, signed
+// with the given key the way the stack signs it.
+func (e env) trigger(t *testing.T, accessKeyID, signingKey string) *api.TriggerAwsHoneyTokenResponse {
+ t.Helper()
+ body, err := json.Marshal(map[string]any{
+ "type": "aws",
+ "event": map[string]any{
+ "accessKeyId": accessKeyID,
+ "eventName": "GetCallerIdentity",
+ "eventTime": time.Now().UTC().Format(time.RFC3339),
+ "awsRegion": aws.Region,
+ "sourceIp": "203.0.113.7",
+ },
+ })
+ require.NoError(t, err)
+ stamp := fmt.Sprint(time.Now().Unix())
+ m := hmac.New(sha256.New, []byte(signingKey))
+ m.Write([]byte(stamp + "." + string(body)))
+ signature := "t=" + stamp + ",v1=" + hex.EncodeToString(m.Sum(nil))
+
+ withBody := func(_ context.Context, req *http.Request) error {
+ req.Body = io.NopCloser(bytes.NewReader(body))
+ req.ContentLength = int64(len(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Infisical-Signature", signature)
+ return nil
+ }
+ res, err := e.tn.Anonymous(t).TriggerAwsHoneyTokenWithResponse(t.Context(), withBody)
+ require.NoError(t, err, "triggering a honey token")
+ return res
+}
+
+func (e env) status(t *testing.T, tokenID uuid.UUID) string {
+ t.Helper()
+ res, err := e.tn.Admin.API.GetHoneyTokenWithResponse(t.Context(), tokenID)
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "reading a honey token: %s", apierr.Body(res.Body))
+ var out struct {
+ HoneyToken struct {
+ Status string `json:"status"`
+ } `json:"honeyToken"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body, &out))
+ return out.HoneyToken.Status
+}
+
+func (e env) eventCount(t *testing.T, tokenID uuid.UUID) int {
+ t.Helper()
+ res, err := e.tn.Admin.API.ListHoneyTokenEventsWithResponse(t.Context(), tokenID, nil)
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "listing honey token events: %s", apierr.Body(res.Body))
+ var out struct {
+ TotalCount int `json:"totalCount"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body, &out))
+ return out.TotalCount
+}
+
+func (e env) revoke(t *testing.T, tokenID uuid.UUID) *api.RevokeHoneyTokenResponse {
+ t.Helper()
+ res, err := e.tn.Admin.API.RevokeHoneyTokenWithResponse(t.Context(), tokenID)
+ require.NoError(t, err, "revoking a honey token")
+ return res
+}
diff --git a/tests/suites/secretmanager/honeytokens/honeytoken_test.go b/tests/suites/secretmanager/honeytokens/honeytoken_test.go
new file mode 100644
index 0000000000..53a60dab1c
--- /dev/null
+++ b/tests/suites/secretmanager/honeytokens/honeytoken_test.go
@@ -0,0 +1,132 @@
+package honeytokens_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "github.com/Infisical/infisical/tests/fakes/license"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
+)
+
+func TestHoneyToken_Create(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should create an IAM user with one key and plant the key in the mapped secrets", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setup(t)
+
+ // Action
+ res := e.create(t)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ users := e.honeyUsers(t)
+ require.Len(t, users, 1)
+ for _, u := range users {
+ require.Len(t, u.AccessKeys, 1)
+ require.Equal(t, u.AccessKeys[0].AccessKeyID, e.planted(t))
+ }
+ require.ElementsMatch(t, []string{accessKeyIDKey, secretAccessKeyKey}, e.secretKeys(t))
+ })
+
+ t.Run("should refuse naming the pending verification and create nothing when the stack is not deployed", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setup(t, stackIn(""))
+
+ // Action
+ res := e.create(t)
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, apierr.Body(res.Body), "stack verification is still pending")
+ require.Empty(t, e.honeyUsers(t))
+ require.Empty(t, e.secretKeys(t))
+ })
+}
+
+func TestHoneyToken_Trigger(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should record the event and mark the token triggered when the signature is valid", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setup(t)
+ tokenID := e.newHoneyToken(t)
+
+ // Action
+ res := e.trigger(t, e.planted(t), e.signingKey)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.True(t, res.JSON200.Acknowledged)
+ require.Equal(t, "triggered", e.status(t, tokenID))
+ require.Equal(t, 1, e.eventCount(t, tokenID))
+ })
+
+ t.Run("should refuse with 401 and record nothing when the signature is made with another key", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setup(t)
+ tokenID := e.newHoneyToken(t)
+
+ // Action
+ res := e.trigger(t, e.planted(t), randomHex(t, 32))
+
+ // Assert
+ require.Equal(t, http.StatusUnauthorized, res.StatusCode())
+ require.Equal(t, "active", e.status(t, tokenID))
+ require.Equal(t, 0, e.eventCount(t, tokenID))
+ })
+}
+
+func TestHoneyToken_Revoke(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should delete the IAM key and user and the mapped secrets when revoked", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setup(t)
+ tokenID := e.newHoneyToken(t)
+
+ // Action
+ res := e.revoke(t, tokenID)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ e.cp.IAM.ExpectEvent[aws.UserDeleted](t, nil)
+ require.Empty(t, e.honeyUsers(t))
+ require.Empty(t, e.secretKeys(t))
+ require.Equal(t, "revoked", e.status(t, tokenID))
+ })
+
+ t.Run("should refuse a revoke and keep the key when the plan does not include honey tokens", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Today's gating, pinned for the license clean-up: a downgrade blocks the
+ revoke, so a planted key stays live in AWS.`)
+
+ // Setup
+ e := setup(t)
+ tokenID := e.newHoneyToken(t)
+ planted := e.planted(t)
+ e.tn.SetPlan(t, license.Enterprise().Without(license.HoneyTokens))
+
+ // Action
+ res := e.revoke(t, tokenID)
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, apierr.Body(res.Body), "Failed to revoke honey token due to plan restriction")
+ require.Equal(t, planted, e.planted(t))
+ require.Len(t, e.honeyUsers(t), 1)
+ })
+}
diff --git a/tests/suites/secretmanager/honeytokens/main_test.go b/tests/suites/secretmanager/honeytokens/main_test.go
new file mode 100644
index 0000000000..8f1fbc74f5
--- /dev/null
+++ b/tests/suites/secretmanager/honeytokens/main_test.go
@@ -0,0 +1,9 @@
+package honeytokens_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/harness"
+)
+
+func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }
diff --git a/tests/suites/secretmanager/rotations/aws_iam_test.go b/tests/suites/secretmanager/rotations/aws_iam_test.go
new file mode 100644
index 0000000000..0931071f6b
--- /dev/null
+++ b/tests/suites/secretmanager/rotations/aws_iam_test.go
@@ -0,0 +1,250 @@
+package rotations_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "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/Infisical/infisical/tests/internal/id"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+// Provider logic for AWS IAM user secrets only. The rotation plumbing is covered on
+// PostgreSQL.
+
+const (
+ iamUser = "app"
+ accessKeyIDKey = "AWS_ACCESS_KEY_ID"
+ secretAccessKeyKey = "AWS_SECRET_ACCESS_KEY"
+)
+
+type iamEnv struct {
+ tn *harness.Tenant
+ proj *fixture.Project
+ conn *fixture.AppConnection
+ cp *aws.ControlPlane
+}
+
+// setupIAM returns a project, an AWS connection, and an account holding the IAM user a
+// rotation takes over, with any access keys it already holds.
+func setupIAM(t *testing.T, existingKeys ...string) iamEnv {
+ t.Helper()
+ tn := harness.From(t).NewTenant(t)
+ conn := fixture.NewAppConnection(t, tn, fixture.AWSAccessKeyAppConnection)
+ e := iamEnv{
+ tn: tn,
+ proj: fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager")),
+ conn: conn,
+ cp: aws.Open(t, conn.FakenetAdmin(t), conn.Nonce()),
+ }
+ e.cp.Seed(t, aws.SeedUser(iamUser, existingKeys...))
+ return e
+}
+
+func (e iamEnv) newRotation(t *testing.T) uuid.UUID {
+ t.Helper()
+ body := api.CreateAWSIAMUserSecretRotationJSONRequestBody{
+ Name: "rot-" + id.Short(),
+ ProjectId: e.proj.ID,
+ ConnectionId: e.conn.ID,
+ Environment: "dev",
+ SecretPath: "/",
+ IsAutoRotationEnabled: new(false),
+ RotationInterval: 1,
+ }
+ body.Parameters.UserName = iamUser
+ body.SecretsMapping.AccessKeyId = accessKeyIDKey
+ body.SecretsMapping.SecretAccessKey = secretAccessKeyKey
+ res, err := e.tn.Admin.API.CreateAWSIAMUserSecretRotationWithResponse(t.Context(), body)
+ require.NoError(t, err, "creating a rotation")
+ require.NotNilf(t, res.JSON200, "creating a rotation returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.SecretRotation.Id
+}
+
+func (e iamEnv) rotate(t *testing.T, rotationID uuid.UUID) *api.RotateAWSIAMUserSecretRotationResponse {
+ t.Helper()
+ res, err := e.tn.Admin.API.RotateAWSIAMUserSecretRotationWithResponse(t.Context(), rotationID)
+ require.NoError(t, err, "rotating")
+ return res
+}
+
+func (e iamEnv) mustRotate(t *testing.T, rotationID uuid.UUID) view {
+ t.Helper()
+ res := e.rotate(t, rotationID)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ return decode(t, res.Body)
+}
+
+func (e iamEnv) view(t *testing.T, rotationID uuid.UUID) view {
+ t.Helper()
+ res, err := e.tn.Admin.API.GetAWSIAMUserSecretRotationWithResponse(t.Context(), rotationID)
+ require.NoError(t, err, "getting a rotation")
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ return decode(t, res.Body)
+}
+
+func (e iamEnv) check(t *testing.T, rotationID uuid.UUID) *api.CheckAWSIAMUserSecretRotationCredentialsResponse {
+ t.Helper()
+ res, err := e.tn.Admin.API.CheckAWSIAMUserSecretRotationCredentialsWithResponse(t.Context(), rotationID)
+ require.NoError(t, err, "checking credentials")
+ return res
+}
+
+// published is the access key the mapped secrets hold.
+func (e iamEnv) published(t *testing.T) aws.AccessKey {
+ t.Helper()
+ got := map[string]string{}
+ for _, s := range secretmanager.ListSecrets(t, e.proj, "dev") {
+ got[s.Key] = s.Value
+ }
+ require.Contains(t, got, accessKeyIDKey, "the mapped access key id is missing: %v", got)
+ return aws.AccessKey{AccessKeyID: got[accessKeyIDKey], SecretAccessKey: got[secretAccessKeyKey]}
+}
+
+// liveKeys is the user's access keys at IAM, oldest first.
+func (e iamEnv) liveKeys(t *testing.T) []aws.AccessKey {
+ t.Helper()
+ u := e.cp.User(t, iamUser)
+ require.NotNil(t, u, "the IAM user is gone")
+ out := make([]aws.AccessKey, 0, len(u.AccessKeys))
+ for _, k := range u.AccessKeys {
+ out = append(out, aws.AccessKey{AccessKeyID: k.AccessKeyID, SecretAccessKey: k.SecretAccessKey})
+ }
+ return out
+}
+
+func TestAwsIamUserSecretRotation_Rotate(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should publish a new key, keep the previous one live, and delete the one before it on each rotation", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `IAM allows two keys a user, so the provider deletes the oldest before it
+ creates the next. The oldest is the inactive slot's, never the published one.`)
+
+ // Setup
+ e := setupIAM(t)
+ r := e.newRotation(t)
+ first := e.published(t)
+
+ // Action
+ afterOne := e.mustRotate(t, r)
+ second := e.published(t)
+ keysAfterOne := e.liveKeys(t)
+ afterTwo := e.mustRotate(t, r)
+
+ // Assert
+ require.Equal(t, 1, afterOne.ActiveIndex)
+ require.Equal(t, []aws.AccessKey{first, second}, keysAfterOne)
+ require.Equal(t, 0, afterTwo.ActiveIndex)
+ third := e.published(t)
+ require.Equal(t, []aws.AccessKey{second, third}, e.liveKeys(t))
+ })
+
+ t.Run("should delete the user's oldest key to make room when it already holds two at create", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setupIAM(t, "AKIAOLDEST"+id.Short(), "AKIANEWER"+id.Short())
+ existing := e.liveKeys(t)
+
+ // Action
+ e.newRotation(t)
+
+ // Assert
+ require.Equal(t, []aws.AccessKey{existing[1], e.published(t)}, e.liveKeys(t))
+ })
+
+ t.Run("should answer 500, keep the published key live and lose only the inactive key when IAM refuses the new key", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Today's behaviour, pinned so the planned fix finds it: a manual rotation
+ failure is wrapped in an InternalServerError. The provider deletes the oldest key
+ before it creates the next, so a refused create still costs the inactive key.`)
+
+ // Setup
+ e := setupIAM(t)
+ r := e.newRotation(t)
+ e.mustRotate(t, r)
+ before := e.published(t)
+ e.cp.Seed(t, aws.Deny(aws.IAM, "CreateAccessKey"))
+
+ // Action
+ res := e.rotate(t, r)
+
+ // Assert
+ requireStatus(t, http.StatusInternalServerError, res.StatusCode(), res.Body)
+ require.Contains(t, apierr.Body(res.Body), "iam:CreateAccessKey")
+ require.Equal(t, before, e.published(t))
+ require.Equal(t, []aws.AccessKey{before}, e.liveKeys(t))
+ got := e.view(t, r)
+ require.Equal(t, "failed", got.RotationStatus)
+ require.Equal(t, 1, got.ActiveIndex)
+ })
+}
+
+func TestAwsIamUserSecretRotation_CheckCredentials(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should pass when STS accepts the published key", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setupIAM(t)
+ r := e.newRotation(t)
+
+ // Action
+ res := e.check(t, r)
+
+ // Assert
+ requireStatus(t, http.StatusNoContent, res.StatusCode(), res.Body)
+ })
+
+ t.Run("should fail naming STS's refusal and leave the secrets when the published key was deleted in AWS", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setupIAM(t)
+ r := e.newRotation(t)
+ published := e.published(t)
+ e.cp.Seed(t, aws.RemoveAccessKey(published.AccessKeyID))
+
+ // Action
+ res := e.check(t, r)
+
+ // Assert
+ requireStatus(t, http.StatusBadRequest, res.StatusCode(), res.Body)
+ require.Contains(t, apierr.Body(res.Body), "Unable to validate credentials")
+ require.Contains(t, apierr.Body(res.Body), "security token included in the request is invalid")
+ require.Equal(t, published, e.published(t))
+ })
+}
+
+func TestAwsIamUserSecretRotation_Delete(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should delete both keys at IAM when deleted revoking the generated credentials", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setupIAM(t)
+ r := e.newRotation(t)
+ e.mustRotate(t, r)
+ ds := api.DeleteAWSIAMUserSecretRotationParamsDeleteSecrets("false")
+ rv := api.DeleteAWSIAMUserSecretRotationParamsRevokeGeneratedCredentials("true")
+
+ // Action
+ res, err := e.tn.Admin.API.DeleteAWSIAMUserSecretRotationWithResponse(t.Context(), r,
+ &api.DeleteAWSIAMUserSecretRotationParams{DeleteSecrets: &ds, RevokeGeneratedCredentials: &rv})
+
+ // Assert
+ require.NoError(t, err)
+ requireStatus(t, http.StatusOK, res.StatusCode(), res.Body)
+ require.Empty(t, e.liveKeys(t))
+ })
+}
diff --git a/tests/suites/secretmanager/syncs/aws_helpers_test.go b/tests/suites/secretmanager/syncs/aws_helpers_test.go
new file mode 100644
index 0000000000..4a6a4f5619
--- /dev/null
+++ b/tests/suites/secretmanager/syncs/aws_helpers_test.go
@@ -0,0 +1,298 @@
+package syncs_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "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/Infisical/infisical/tests/internal/id"
+ "github.com/Infisical/infisical/tests/internal/wait"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+// AWS syncs exist for what GitHub cannot do: import from the destination, and the
+// provider rules of Parameter Store and Secrets Manager. Kept apart from helpers_test.go
+// because every generated AWS type differs from GitHub's, so the two share only the
+// options and whenIdle.
+
+// setupAWS returns a project, an AWS connection, and a handle on the account it uses.
+func setupAWS(t *testing.T) (*fixture.Project, *fixture.AppConnection, *aws.ControlPlane) {
+ t.Helper()
+ tn := harness.From(t).NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ conn := fixture.NewAppConnection(t, tn, fixture.AWSAccessKeyAppConnection)
+ return proj, conn, aws.Open(t, conn.FakenetAdmin(t), conn.Nonce())
+}
+
+type awsDestination struct {
+ parameterStore bool
+ config map[string]any
+}
+
+// parameterStorePath is a Parameter Store destination, a path such as "/app/".
+func parameterStorePath(path string) awsDestination {
+ return awsDestination{parameterStore: true, config: map[string]any{"region": aws.Region, "path": path}}
+}
+
+// oneToOne holds each secret as its own Secrets Manager secret.
+func oneToOne() awsDestination {
+ return awsDestination{config: map[string]any{"region": aws.Region, "mappingBehavior": "one-to-one"}}
+}
+
+// manyToOne holds every secret as one JSON document in the named secret.
+func manyToOne(secretName string) awsDestination {
+ return awsDestination{config: map[string]any{"region": aws.Region, "mappingBehavior": "many-to-one", "secretName": secretName}}
+}
+
+type awsSyncConfig struct {
+ syncConfig
+ initial string
+ tags map[string]string
+}
+
+// awsOption is either a shared syncOption or one only AWS syncs take.
+type awsOption interface{ applyAWS(*awsSyncConfig) }
+
+func (o syncOption) applyAWS(c *awsSyncConfig) { o(&c.syncConfig) }
+
+type awsOnly func(*awsSyncConfig)
+
+func (o awsOnly) applyAWS(c *awsSyncConfig) { o(c) }
+
+// initialSync sets what the first run does with secrets already at the destination.
+func initialSync(behavior string) awsOption {
+ return awsOnly(func(c *awsSyncConfig) { c.initial = behavior })
+}
+
+func withTag(key, value string) awsOption {
+ return awsOnly(func(c *awsSyncConfig) {
+ if c.tags == nil {
+ c.tags = map[string]string{}
+ }
+ c.tags[key] = value
+ })
+}
+
+type awsSync struct {
+ ID uuid.UUID
+ proj *fixture.Project
+ dest awsDestination
+}
+
+func newAWSSync(tt *testing.T, p *fixture.Project, conn *fixture.AppConnection, dest awsDestination, opts ...awsOption) *awsSync {
+ tt.Helper()
+ cfg := awsSyncConfig{
+ syncConfig: syncConfig{environment: "dev", secretPath: "/", name: "sync-" + id.Short()},
+ initial: "overwrite-destination",
+ }
+ for _, o := range opts {
+ o.applyAWS(&cfg)
+ }
+
+ options := map[string]any{"initialSyncBehavior": cfg.initial}
+ if cfg.keySchema != "" {
+ options["keySchema"] = cfg.keySchema
+ }
+ if cfg.disableSecretDeletion {
+ options["disableSecretDeletion"] = true
+ }
+ if len(cfg.tags) > 0 {
+ tags := []map[string]string{}
+ for k, v := range cfg.tags {
+ tags = append(tags, map[string]string{"key": k, "value": v})
+ }
+ options["tags"] = tags
+ }
+ raw, err := json.Marshal(map[string]any{
+ "name": cfg.name,
+ "projectId": p.ID,
+ "connectionId": conn.ID,
+ "environment": cfg.environment,
+ "secretPath": cfg.secretPath,
+ "isAutoSyncEnabled": cfg.autoSync,
+ "destinationConfig": dest.config,
+ "syncOptions": options,
+ })
+ require.NoError(tt, err)
+
+ client := p.Tenant().Admin.API
+ var status int
+ var body []byte
+ if dest.parameterStore {
+ res, cErr := client.CreateAwsParameterStoreSecretSyncWithBodyWithResponse(tt.Context(), "application/json", bytes.NewReader(raw))
+ require.NoError(tt, cErr, "creating a sync")
+ status, body = res.StatusCode(), res.Body
+ } else {
+ res, cErr := client.CreateAwsSecretsManagerSecretSyncWithBodyWithResponse(tt.Context(), "application/json", bytes.NewReader(raw))
+ require.NoError(tt, cErr, "creating a sync")
+ status, body = res.StatusCode(), res.Body
+ }
+ require.Equalf(tt, http.StatusOK, status, "creating a sync: %s", apierr.Body(body))
+
+ var out struct {
+ SecretSync struct {
+ ID uuid.UUID `json:"id"`
+ } `json:"secretSync"`
+ }
+ require.NoError(tt, json.Unmarshal(body, &out))
+ return &awsSync{ID: out.SecretSync.ID, proj: p, dest: dest}
+}
+
+type awsSyncView struct {
+ SyncStatus *string `json:"syncStatus"`
+ LastSyncMessage *string `json:"lastSyncMessage"`
+ ImportStatus *string `json:"importStatus"`
+ LastImportMessage *string `json:"lastImportMessage"`
+}
+
+func (s *awsSync) view(ctx context.Context) (awsSyncView, error) {
+ client := s.proj.Tenant().Admin.API
+ var body []byte
+ if s.dest.parameterStore {
+ res, err := client.GetAwsParameterStoreSecretSyncWithResponse(ctx, s.ID)
+ if err != nil {
+ return awsSyncView{}, err
+ }
+ body = res.Body
+ } else {
+ res, err := client.GetAwsSecretsManagerSecretSyncWithResponse(ctx, s.ID)
+ if err != nil {
+ return awsSyncView{}, err
+ }
+ body = res.Body
+ }
+ var out struct {
+ SecretSync awsSyncView `json:"secretSync"`
+ }
+ err := json.Unmarshal(body, &out)
+ return out.SecretSync, err
+}
+
+func (s *awsSync) start(tt *testing.T) {
+ tt.Helper()
+ client := s.proj.Tenant().Admin.API
+ var status int
+ var body []byte
+ whenIdle(tt, "triggering a sync", func(ctx context.Context) (int, []byte, error) {
+ if s.dest.parameterStore {
+ res, err := client.SyncAwsParameterStoreSecretSyncWithResponse(ctx, s.ID)
+ if err != nil {
+ return 0, nil, err
+ }
+ status, body = res.StatusCode(), res.Body
+ } else {
+ res, err := client.SyncAwsSecretsManagerSecretSyncWithResponse(ctx, s.ID)
+ if err != nil {
+ return 0, nil, err
+ }
+ status, body = res.StatusCode(), res.Body
+ }
+ return status, body, nil
+ })
+ require.Equalf(tt, http.StatusOK, status, "triggering a sync: %s", apierr.Body(body))
+}
+
+// trigger runs the sync and requires it to succeed.
+func (s *awsSync) trigger(tt *testing.T) {
+ tt.Helper()
+ got := s.triggerExpectingFailure(tt)
+ require.NotEqualf(tt, "failed", got.status, "the sync failed: %s", got.message)
+}
+
+func (s *awsSync) triggerExpectingFailure(tt *testing.T) outcome {
+ tt.Helper()
+ s.start(tt)
+ return s.await(tt, "the sync to finish", func(v awsSyncView) (*string, *string) { return v.SyncStatus, v.LastSyncMessage })
+}
+
+// importSecrets runs an import from the destination and returns how it ended.
+func (s *awsSync) importSecrets(tt *testing.T, behavior string) outcome {
+ tt.Helper()
+ client := s.proj.Tenant().Admin.API
+ var status int
+ var body []byte
+ whenIdle(tt, "importing secrets", func(ctx context.Context) (int, []byte, error) {
+ if s.dest.parameterStore {
+ res, err := client.ImportAwsParameterStoreSecretSyncSecretsWithResponse(ctx, s.ID,
+ &api.ImportAwsParameterStoreSecretSyncSecretsParams{
+ ImportBehavior: api.ImportAwsParameterStoreSecretSyncSecretsParamsImportBehavior(behavior)})
+ if err != nil {
+ return 0, nil, err
+ }
+ status, body = res.StatusCode(), res.Body
+ } else {
+ res, err := client.ImportAwsSecretsManagerSecretSyncSecretsWithResponse(ctx, s.ID,
+ &api.ImportAwsSecretsManagerSecretSyncSecretsParams{
+ ImportBehavior: api.ImportAwsSecretsManagerSecretSyncSecretsParamsImportBehavior(behavior)})
+ if err != nil {
+ return 0, nil, err
+ }
+ status, body = res.StatusCode(), res.Body
+ }
+ return status, body, nil
+ })
+ require.Equalf(tt, http.StatusOK, status, "importing secrets: %s", apierr.Body(body))
+ return s.await(tt, "the import to finish", func(v awsSyncView) (*string, *string) { return v.ImportStatus, v.LastImportMessage })
+}
+
+func (s *awsSync) await(tt *testing.T, what string, read func(awsSyncView) (status, message *string)) outcome {
+ tt.Helper()
+ got, err := wait.For(tt.Context(), func(ctx context.Context) (outcome, bool, error) {
+ v, err := s.view(ctx)
+ if err != nil {
+ return outcome{}, false, err
+ }
+ var out outcome
+ status, message := read(v)
+ if status != nil {
+ out.status = *status
+ }
+ if message != nil {
+ out.message = *message
+ }
+ return out, out.status == "succeeded" || out.status == "failed", nil
+ })
+ require.NoError(tt, err, "waiting for "+what)
+ return got
+}
+
+// secretsAt is what an application reading the folder gets from Infisical.
+func secretsAt(tt *testing.T, p *fixture.Project, path string) map[string]string {
+ tt.Helper()
+ out := map[string]string{}
+ for _, s := range secretmanager.ListSecrets(tt, p, "dev", secretmanager.WithPath(path)) {
+ out[s.Key] = s.Value
+ }
+ return out
+}
+
+// parameterValues is the parameters the account holds, by stored name.
+func parameterValues(tt *testing.T, cp *aws.ControlPlane) map[string]string {
+ tt.Helper()
+ out := map[string]string{}
+ for name, p := range cp.Parameters(tt) {
+ out[name] = p.Value
+ }
+ return out
+}
+
+// secretValues is the Secrets Manager secrets the account holds, by name.
+func secretValues(tt *testing.T, cp *aws.ControlPlane) map[string]string {
+ tt.Helper()
+ out := map[string]string{}
+ for name, s := range cp.Secrets(tt) {
+ if s.DeletedDate == nil {
+ out[name] = s.SecretString
+ }
+ }
+ return out
+}
diff --git a/tests/suites/secretmanager/syncs/aws_parameter_store_test.go b/tests/suites/secretmanager/syncs/aws_parameter_store_test.go
new file mode 100644
index 0000000000..6e38c1e548
--- /dev/null
+++ b/tests/suites/secretmanager/syncs/aws_parameter_store_test.go
@@ -0,0 +1,179 @@
+package syncs_test
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
+)
+
+// Provider logic only. The plumbing every sync shares is covered on GitHub.
+func TestAwsParameterStoreSync_SyncSecrets(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should remove every parameter Infisical does not hold when the path spans several pages", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `GetParametersByPath answers at most 10 a page and DeleteParameters takes
+ at most 10 names, so a sync that stopped at the first page or sent one batch
+ would leave stale parameters behind.`)
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ for i := range 25 {
+ cp.Seed(t, aws.SeedParameter(fmt.Sprintf("/app/STALE_%02d", i), "old"))
+ }
+ secretmanager.CreateSecret(t, proj, "dev", "KEEP", "v")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"/app/KEEP": "v"}, parameterValues(t, cp))
+ })
+
+ t.Run("should leave parameters below the path alone when syncing to it", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedParameter("/app/team/OTHER", "theirs"))
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"/app/A": "1", "/app/team/OTHER": "theirs"}, parameterValues(t, cp))
+ })
+
+ t.Run("should place parameters under the path segment the key schema names and prune only there", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedParameter("/app/OUTSIDE", "theirs"), aws.SeedParameter("/app/dev/STALE", "old"))
+ secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "postgres://db")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), keySchema("{{environment}}/{{secretKey}}"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"/app/dev/DB_URL": "postgres://db", "/app/OUTSIDE": "theirs"}, parameterValues(t, cp))
+ })
+
+ t.Run("should fail naming the rule and write nothing when the key schema starts with a slash", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `The create schema allows a slash anywhere, so this is refused only when
+ the sync runs.`)
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), keySchema("/{{secretKey}}"))
+
+ // Action
+ got := s.triggerExpectingFailure(t)
+
+ // Assert
+ require.Equal(t, "failed", got.status)
+ require.Contains(t, got.message, "Key schema cannot contain leading '/'")
+ require.Empty(t, cp.Parameters(t))
+ })
+
+ t.Run("should fail naming the rule and write nothing when the key schema has a slash after the secret key", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), keySchema("{{secretKey}}/value"))
+
+ // Action
+ got := s.triggerExpectingFailure(t)
+
+ // Assert
+ require.Equal(t, "failed", got.status)
+ require.Contains(t, got.message, "Key schema cannot contain '/' after {{secretKey}}")
+ require.Empty(t, cp.Parameters(t))
+ })
+
+ t.Run("should skip an empty value and remove the parameter it held", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Parameter Store refuses an empty value, so the sync deletes the parameter
+ rather than leave the old value behind.`)
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedParameter("/app/EMPTIED", "old"))
+ secretmanager.CreateSecret(t, proj, "dev", "EMPTIED", "")
+ secretmanager.CreateSecret(t, proj, "dev", "FULL", "v")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"/app/FULL": "v"}, parameterValues(t, cp))
+ })
+
+ t.Run("should fail naming the missing tag permissions and change nothing when tags are set and listing tags is denied", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `The one destination refusal the sync does not retry, so the failure lands
+ within one run rather than after five attempts and their backoff.`)
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedParameter("/app/API_KEY", "old"), aws.Deny(aws.SSM, "ListTagsForResource"))
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), withTag("team", "core"))
+
+ // Action
+ got := s.triggerExpectingFailure(t)
+
+ // Assert
+ require.Equal(t, "failed", got.status)
+ require.Contains(t, got.message, "IAM role has inadequate permissions to manage resource tags")
+ require.Equal(t, map[string]string{"/app/API_KEY": "old"}, parameterValues(t, cp))
+ require.Equal(t, map[string]string{"API_KEY": "api-value"}, secretsAt(t, proj, "/"))
+ })
+
+ t.Run("should sync without tag permissions when no tags are set", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedParameter("/app/API_KEY", "old"), aws.Deny(aws.SSM, "ListTagsForResource"))
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"/app/API_KEY": "api-value"}, parameterValues(t, cp))
+ })
+
+ t.Run("should tag the parameters it writes when tags are set", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), withTag("team", "core"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ got := cp.Parameters(t)["/app/API_KEY"]
+ require.NotNil(t, got, "the parameter was not written")
+ require.Equal(t, map[string]string{"team": "core"}, got.Tags)
+ require.Equal(t, "SecureString", got.Type)
+ })
+}
diff --git a/tests/suites/secretmanager/syncs/aws_secrets_manager_test.go b/tests/suites/secretmanager/syncs/aws_secrets_manager_test.go
new file mode 100644
index 0000000000..422a744bed
--- /dev/null
+++ b/tests/suites/secretmanager/syncs/aws_secrets_manager_test.go
@@ -0,0 +1,118 @@
+package syncs_test
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/stretchr/testify/require"
+)
+
+func secretNamed(name string) func(aws.SecretDeleted) bool {
+ return func(e aws.SecretDeleted) bool { return e.Name == name }
+}
+
+// document decodes a many-to-one secret's JSON body.
+func document(t *testing.T, raw string) map[string]string {
+ t.Helper()
+ var out map[string]string
+ require.NoErrorf(t, json.Unmarshal([]byte(raw), &out), "the secret is not a key-value document: %s", raw)
+ return out
+}
+
+// Provider logic only. The plumbing every sync shares is covered on GitHub.
+func TestAwsSecretsManagerSync_SyncSecrets(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should hold each secret as its own AWS secret and delete one Infisical no longer holds when mapped one to one", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedSecret("STALE", "old"))
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
+ secretmanager.CreateSecret(t, proj, "dev", "B", "2")
+ s := newAWSSync(t, proj, conn, oneToOne())
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ cp.SecretsManager.ExpectEvent[aws.SecretDeleted](t, secretNamed("STALE"))
+ require.Equal(t, map[string]string{"A": "1", "B": "2"}, secretValues(t, cp))
+ })
+
+ t.Run("should hold every secret as one JSON document under the configured name when mapped many to one", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
+ secretmanager.CreateSecret(t, proj, "dev", "B", "2")
+ s := newAWSSync(t, proj, conn, manyToOne("bundle"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ got := secretValues(t, cp)
+ require.Len(t, got, 1, "many to one wrote more than one secret: %v", got)
+ require.Equal(t, map[string]string{"A": "1", "B": "2"}, document(t, got["bundle"]))
+ })
+
+ t.Run("should name the document by the key schema and keep the keys inside it as they are when mapped many to one", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
+ s := newAWSSync(t, proj, conn, manyToOne("bundle"), keySchema("INF_{{secretKey}}"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ got := secretValues(t, cp)
+ require.Contains(t, got, "INF_bundle")
+ require.Equal(t, map[string]string{"A": "1"}, document(t, got["INF_bundle"]))
+ })
+
+ t.Run("should update the one document in place when a value changes and it is mapped many to one", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
+ s := newAWSSync(t, proj, conn, manyToOne("bundle"))
+ s.trigger(t)
+ mark := cp.SecretsManager.Mark(t)
+ secretmanager.UpdateSecret(t, proj, "dev", "A", "2")
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ cp.SecretsManager.ExpectEvent[aws.SecretUpdated](t, func(e aws.SecretUpdated) bool { return e.Name == "bundle" }, fakenet.Since(mark))
+ cp.SecretsManager.ExpectNoEvent[aws.SecretCreated](t, nil, fakenet.Since(mark))
+ require.Equal(t, map[string]string{"A": "2"}, document(t, secretValues(t, cp)["bundle"]))
+ })
+
+ t.Run("should fail the import naming the format when the many to one document is not key-value JSON", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedSecret("bundle", "not json"))
+ s := newAWSSync(t, proj, conn, manyToOne("bundle"))
+
+ // Action
+ got := s.importSecrets(t, "prioritize-source")
+
+ // Assert
+ require.Equal(t, "failed", got.status)
+ require.Contains(t, got.message, "Invalid format for Many-To-One mapping behavior")
+ require.Empty(t, secretsAt(t, proj, "/"))
+ })
+}
diff --git a/tests/suites/secretmanager/syncs/import_test.go b/tests/suites/secretmanager/syncs/import_test.go
new file mode 100644
index 0000000000..dcf7e8a8af
--- /dev/null
+++ b/tests/suites/secretmanager/syncs/import_test.go
@@ -0,0 +1,103 @@
+package syncs_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSecretSync_ImportSecrets(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should create secrets the source path does not have", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedParameter("/app/DESTINATION_KEY", "destination-value"))
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"))
+
+ // Action
+ got := s.importSecrets(t, "prioritize-source")
+
+ // Assert
+ require.Equalf(t, "succeeded", got.status, "the import failed: %s", got.message)
+ require.Equal(t, map[string]string{"DESTINATION_KEY": "destination-value"}, secretsAt(t, proj, "/"))
+ })
+
+ t.Run("should keep the Infisical value when the import prioritizes the source", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "infisical-value")
+ cp.Seed(t, aws.SeedParameter("/app/API_KEY", "destination-value"))
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"))
+
+ // Action
+ got := s.importSecrets(t, "prioritize-source")
+
+ // Assert
+ require.Equalf(t, "succeeded", got.status, "the import failed: %s", got.message)
+ require.Equal(t, map[string]string{"API_KEY": "infisical-value"}, secretsAt(t, proj, "/"))
+ })
+
+ t.Run("should overwrite the Infisical value when the import prioritizes the destination", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "infisical-value")
+ cp.Seed(t, aws.SeedParameter("/app/API_KEY", "destination-value"))
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"))
+
+ // Action
+ got := s.importSecrets(t, "prioritize-destination")
+
+ // Assert
+ require.Equalf(t, "succeeded", got.status, "the import failed: %s", got.message)
+ require.Equal(t, map[string]string{"API_KEY": "destination-value"}, secretsAt(t, proj, "/"))
+ })
+
+ t.Run("should keep the Infisical value when the destination holds the key empty", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Parameter Store refuses empty values, so the empty value comes from a key
+ inside a many-to-one Secrets Manager document.`)
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "infisical-value")
+ cp.Seed(t, aws.SeedSecret("bundle", `{"API_KEY":"","NEW_KEY":"new-value"}`))
+ s := newAWSSync(t, proj, conn, manyToOne("bundle"))
+
+ // Action
+ got := s.importSecrets(t, "prioritize-destination")
+
+ // Assert
+ require.Equalf(t, "succeeded", got.status, "the import failed: %s", got.message)
+ require.Equal(t, map[string]string{"API_KEY": "infisical-value", "NEW_KEY": "new-value"}, secretsAt(t, proj, "/"))
+ })
+
+ t.Run("should fail naming the rule and import nothing when a destination key is not a valid secret name", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Secrets Manager allows a slash in a name and Infisical does not, so the
+ invalid name comes from there.`)
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ cp.Seed(t, aws.SeedSecret("team/API_KEY", "destination-value"), aws.SeedSecret("VALID_KEY", "valid-value"))
+ s := newAWSSync(t, proj, conn, oneToOne())
+
+ // Action
+ got := s.importSecrets(t, "prioritize-source")
+
+ // Assert
+ require.Equal(t, "failed", got.status)
+ require.Contains(t, got.message, "Found 1 invalid secret name")
+ require.Contains(t, got.message, "cannot contain colon or forward slash")
+ require.Empty(t, secretsAt(t, proj, "/"))
+ })
+}
diff --git a/tests/suites/secretmanager/syncs/initial_test.go b/tests/suites/secretmanager/syncs/initial_test.go
new file mode 100644
index 0000000000..fb9def71be
--- /dev/null
+++ b/tests/suites/secretmanager/syncs/initial_test.go
@@ -0,0 +1,70 @@
+package syncs_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/aws"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
+)
+
+// The initial sync behaviours are plumbing, tested once. They run on Parameter Store
+// because GitHub cannot import.
+func TestSecretSync_InitialSyncBehavior(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should keep the Infisical value for a shared key when the first run imports prioritizing the source", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "infisical-value")
+ cp.Seed(t, aws.SeedParameter("/app/API_KEY", "destination-value"))
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), initialSync("import-prioritize-source"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"/app/API_KEY": "infisical-value"}, parameterValues(t, cp))
+ require.Equal(t, map[string]string{"API_KEY": "infisical-value"}, secretsAt(t, proj, "/"))
+ })
+
+ t.Run("should take the destination value into Infisical when the first run imports prioritizing the destination", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `The import writes back into the project, which is the surprising half of
+ this option.`)
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "infisical-value")
+ cp.Seed(t, aws.SeedParameter("/app/API_KEY", "destination-value"))
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), initialSync("import-prioritize-destination"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"API_KEY": "destination-value"}, secretsAt(t, proj, "/"))
+ require.Equal(t, map[string]string{"/app/API_KEY": "destination-value"}, parameterValues(t, cp))
+ })
+
+ t.Run("should overwrite the destination on later runs when the initial behavior imports", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, conn, cp := setupAWS(t)
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "api-value")
+ s := newAWSSync(t, proj, conn, parameterStorePath("/app/"), initialSync("import-prioritize-destination"))
+ s.trigger(t)
+ cp.Seed(t, aws.SeedParameter("/app/LATE_KEY", "late-value"))
+
+ // Action
+ s.trigger(t)
+
+ // Assert
+ require.Equal(t, map[string]string{"API_KEY": "api-value"}, secretsAt(t, proj, "/"))
+ require.Equal(t, map[string]string{"/app/API_KEY": "api-value"}, parameterValues(t, cp))
+ })
+}