Skip to content

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

test(e2e): cover shared secrets, secret requests and secret validation rules

varonix0185ad348a30
diff --git a/backend/e2e-test/routes/v1/secret-validation-rules.spec.ts b/backend/e2e-test/routes/v1/secret-validation-rules.spec.ts
deleted file mode 100644
index 543a775999..0000000000
--- a/backend/e2e-test/routes/v1/secret-validation-rules.spec.ts
+++ /dev/null
@@ -1,511 +0,0 @@
-import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";
-import { createFolder } from "e2e-test/testUtils/folders";
-import { createStaticSecretsValidationRule } from "e2e-test/testUtils/secret-validation-rules";
-import { createSecretV2, getSecretsV2, updateSecretV2 } from "e2e-test/testUtils/secrets";
-
-import { seedData1 } from "@app/db/seed-data";
-import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
-
-const PROD_ENV = "prod";
-const STAGING_ENV = "staging";
-
-describe("Secret validation rules", () => {
- // A rule preventing reuse of a value another secret already holds is scoped like every other
- // validation rule: only writes inside the rule's environment and path are held against it.
- describe("Preventing reuse of a value another secret holds", () => {
- let projectId: string;
- let authToken: string;
- let cleanup: () => Promise<void>;
-
- beforeAll(async () => {
- ({ projectId, authToken, cleanup } = await createIsolatedOrgAndProject("secret-validation-rules-e2e"));
-
- await createStaticSecretsValidationRule({
- projectId,
- name: "no-duplicate-values-in-prod",
- environment: PROD_ENV,
- secretPath: "/",
- valueConstraints: { uniqueWithinScope: true },
- authToken
- });
- });
-
- afterAll(async () => {
- await cleanup();
- });
-
- test("accepts distinct values in the rule's environment, and a repeated value outside it", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "UNIQUE_A",
- value: "unique-value-a",
- authToken
- });
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "UNIQUE_B",
- value: "unique-value-b",
- authToken
- });
-
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "SHARED_ACROSS_ENVS",
- value: "shared-across-envs",
- authToken
- });
- // The rule only covers production, so staging can hold a value production already holds.
- const staged = await createSecretV2({
- workspaceId: projectId,
- environmentSlug: STAGING_ENV,
- secretPath: "/",
- key: "SHARED_ACROSS_ENVS_COPY",
- value: "shared-across-envs",
- authToken
- });
- expect(staged.secretValue).toBe("shared-across-envs");
- });
-
- test("accepts a repeated value at a path the rule does not reach", async () => {
- await createFolder({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- name: "folder",
- authToken
- });
-
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "SHARED_ACROSS_PATHS",
- value: "shared-across-paths",
- authToken
- });
- // The rule covers "/" alone, not the folders under it, so "/folder" is outside its scope.
- const nested = await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/folder",
- key: "SHARED_ACROSS_PATHS_COPY",
- value: "shared-across-paths",
- authToken
- });
- expect(nested.secretValue).toBe("shared-across-paths");
- });
-
- test("rejects a second secret holding a value production already holds", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "ORIGINAL",
- value: "duplicated-value",
- authToken
- });
-
- // The writer is a project admin here, so the message names where the value is already held.
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "DUPLICATE",
- value: "duplicated-value",
- authToken
- }).expect((res) => {
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain('Secret "DUPLICATE"');
- expect(res.json().message).toContain('value is already used by secret "ORIGINAL"');
- expect(res.json().message).toContain(`environment "${PROD_ENV}"`);
- });
- });
-
- test("rejects updating a secret to a value production already holds", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "UPDATE_TARGET",
- value: "value-before-update",
- authToken
- });
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "UPDATE_HOLDER",
- value: "value-held-by-another-secret",
- authToken
- });
-
- await updateSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "UPDATE_TARGET",
- value: "value-held-by-another-secret",
- authToken
- }).expect((res) => {
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain('Secret "UPDATE_TARGET"');
- expect(res.json().message).toContain('value is already used by secret "UPDATE_HOLDER"');
- expect(res.json().message).toContain(`environment "${PROD_ENV}"`);
- });
- });
-
- test("accepts re-saving a secret with the value it already holds", async () => {
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "SELF_UPDATE",
- value: "self-update-value",
- authToken
- });
-
- // The secret being written is excluded from the lookup, so it does not collide with itself.
- const updated = await updateSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- key: "SELF_UPDATE",
- value: "self-update-value",
- comment: "touched",
- authToken
- });
-
- expect(updated.secretValue).toBe("self-update-value");
- });
- });
-
- // A move writes its secrets at the destination, so they are held to the destination's rules like any
- // other write there, whether a single secret or a whole folder is moved.
- describe("Moving secrets and folders into a path with rules", () => {
- let projectId: string;
- let authToken: string;
- let cleanup: () => Promise<void>;
-
- const moveSecrets = (dto: {
- environment: string;
- sourceSecretPath: string;
- destinationSecretPath: string;
- secretIds: string[];
- }) =>
- testServer.inject({
- method: "POST",
- url: `/api/v4/secrets/move`,
- headers: {
- authorization: `Bearer ${authToken}`
- },
- body: {
- projectId,
- sourceEnvironment: dto.environment,
- sourceSecretPath: dto.sourceSecretPath,
- destinationEnvironment: dto.environment,
- destinationSecretPath: dto.destinationSecretPath,
- secretIds: dto.secretIds
- }
- });
-
- const moveFolder = (dto: { folderId: string; environment: string; destinationPath: string }) =>
- testServer.inject({
- method: "POST",
- url: `/api/v2/folders/move`,
- headers: {
- authorization: `Bearer ${authToken}`
- },
- body: {
- projectId,
- folderId: dto.folderId,
- destinationEnvironment: dto.environment,
- destinationPath: dto.destinationPath
- }
- });
-
- const secretKeysAt = async (secretPath: string, environment: string) => {
- const { secrets } = await getSecretsV2({
- workspaceId: projectId,
- environmentSlug: environment,
- secretPath,
- authToken
- });
- return secrets.map((secret) => secret.secretKey);
- };
-
- const folderNamesAt = async (secretPath: string, environment: string) => {
- const res = await testServer.inject({
- method: "GET",
- url: `/api/v2/folders`,
- headers: {
- authorization: `Bearer ${authToken}`
- },
- query: {
- projectId,
- environment,
- path: secretPath
- }
- });
- expect(res.statusCode).toBe(200);
- return (res.json().folders as { id: string; name: string }[]).map((folder) => folder.name);
- };
-
- const createSecretApprovalPolicy = async (dto: { name: string; environment: string; secretPath: string }) => {
- const res = await testServer.inject({
- method: "POST",
- url: `/api/v1/secret-approvals`,
- headers: {
- authorization: `Bearer ${authToken}`
- },
- body: {
- workspaceId: projectId,
- environment: dto.environment,
- name: dto.name,
- secretPath: dto.secretPath,
- approvers: [{ id: seedData1.id, type: ApproverType.User }],
- approvals: 1
- }
- });
- expect(res.statusCode).toBe(200);
- return res.json().approval as { id: string };
- };
-
- const deleteSecretApprovalPolicy = async (id: string) => {
- const res = await testServer.inject({
- method: "DELETE",
- url: `/api/v1/secret-approvals/${id}`,
- headers: {
- authorization: `Bearer ${authToken}`
- }
- });
- expect(res.statusCode).toBe(200);
- };
-
- const openChangeRequestCount = async (policyId: string) => {
- const res = await testServer.inject({
- method: "GET",
- url: `/api/v1/secret-approval-requests/count`,
- headers: {
- authorization: `Bearer ${authToken}`
- },
- query: {
- projectId,
- policyId
- }
- });
- expect(res.statusCode).toBe(200);
- return res.json().approvals.open as number;
- };
-
- beforeAll(async () => {
- ({ projectId, authToken, cleanup } = await createIsolatedOrgAndProject("secret-validation-rules-move-e2e"));
-
- // In production, "/strict" and everything under it requires values of at least 3 characters, while
- // "/lenient" has no rules.
- await createFolder({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- name: "strict",
- authToken
- });
- await createFolder({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/",
- name: "lenient",
- authToken
- });
- await createStaticSecretsValidationRule({
- projectId,
- name: "min-length-under-strict",
- environment: PROD_ENV,
- secretPath: "/strict/**",
- valueConstraints: { minLength: 3 },
- authToken
- });
-
- // In staging, no two secrets anywhere may hold the same value.
- await createFolder({
- workspaceId: projectId,
- environmentSlug: STAGING_ENV,
- secretPath: "/",
- name: "from",
- authToken
- });
- await createFolder({
- workspaceId: projectId,
- environmentSlug: STAGING_ENV,
- secretPath: "/",
- name: "to",
- authToken
- });
- await createStaticSecretsValidationRule({
- projectId,
- name: "no-duplicate-values-in-staging",
- environment: STAGING_ENV,
- secretPath: "/**",
- valueConstraints: { uniqueWithinScope: true },
- authToken
- });
- });
-
- afterAll(async () => {
- await cleanup();
- });
-
- test("rejects moving a secret whose value breaks the destination's rule", async () => {
- const secret = await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/lenient",
- key: "TOO_SHORT",
- value: "x",
- authToken
- });
-
- const res = await moveSecrets({
- environment: PROD_ENV,
- sourceSecretPath: "/lenient",
- destinationSecretPath: "/strict",
- secretIds: [secret.id]
- });
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain('Secret "TOO_SHORT"');
- expect(res.json().message).toContain("value must be at least 3 characters");
-
- // the secret is untouched because the move was rejected before anything was written
- expect(await secretKeysAt("/lenient", PROD_ENV)).toContain("TOO_SHORT");
- expect(await secretKeysAt("/strict", PROD_ENV)).not.toContain("TOO_SHORT");
- }, 10_000);
-
- test("accepts moving a secret whose value meets the destination's rule", async () => {
- const secret = await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/lenient",
- key: "LONG_ENOUGH",
- value: "long-enough-value",
- authToken
- });
-
- const res = await moveSecrets({
- environment: PROD_ENV,
- sourceSecretPath: "/lenient",
- destinationSecretPath: "/strict",
- secretIds: [secret.id]
- });
- expect(res.statusCode).toBe(200);
-
- expect(await secretKeysAt("/strict", PROD_ENV)).toContain("LONG_ENOUGH");
- expect(await secretKeysAt("/lenient", PROD_ENV)).not.toContain("LONG_ENOUGH");
- }, 10_000);
-
- test("rejects moving a folder holding a secret that breaks the destination's rule", async () => {
- const folder = await createFolder({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/lenient",
- name: "short-values",
- authToken
- });
- await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/lenient/short-values",
- key: "NESTED_TOO_SHORT",
- value: "x",
- authToken
- });
-
- const res = await moveFolder({
- folderId: folder.id,
- environment: PROD_ENV,
- destinationPath: "/strict"
- });
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain('Secret "NESTED_TOO_SHORT"');
- expect(res.json().message).toContain("value must be at least 3 characters");
-
- // the folder and its secret are untouched because the move was rejected before anything was written
- expect(await folderNamesAt("/lenient", PROD_ENV)).toContain("short-values");
- expect(await folderNamesAt("/strict", PROD_ENV)).not.toContain("short-values");
- expect(await secretKeysAt("/lenient/short-values", PROD_ENV)).toContain("NESTED_TOO_SHORT");
- }, 10_000);
-
- test("accepts moving a secret within a no-duplicates scope that also covers its source", async () => {
- const secret = await createSecretV2({
- workspaceId: projectId,
- environmentSlug: STAGING_ENV,
- secretPath: "/from",
- key: "MOVED_UNIQUE",
- value: "moved-unique-value",
- authToken
- });
-
- // The source copy still holds the value while the move runs, so it must not count as a duplicate.
- const res = await moveSecrets({
- environment: STAGING_ENV,
- sourceSecretPath: "/from",
- destinationSecretPath: "/to",
- secretIds: [secret.id]
- });
- expect(res.statusCode).toBe(200);
-
- expect(await secretKeysAt("/to", STAGING_ENV)).toContain("MOVED_UNIQUE");
- expect(await secretKeysAt("/from", STAGING_ENV)).not.toContain("MOVED_UNIQUE");
- }, 10_000);
-
- test("rejects moving a secret that breaks the destination's rule into a path with a change policy", async () => {
- await createFolder({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/strict",
- name: "guarded",
- authToken
- });
- const policy = await createSecretApprovalPolicy({
- name: "guarded-under-strict",
- environment: PROD_ENV,
- secretPath: "/strict/guarded"
- });
-
- // Registered rather than left at the end of the body so a failing assertion can't leak the policy into
- // the tests that share this project.
- onTestFinished(async () => {
- await deleteSecretApprovalPolicy(policy.id);
- });
-
- const secret = await createSecretV2({
- workspaceId: projectId,
- environmentSlug: PROD_ENV,
- secretPath: "/lenient",
- key: "GUARDED_TOO_SHORT",
- value: "x",
- authToken
- });
-
- // A move into a path with a change policy opens a change request instead of writing directly, so the rules
- // have to be enforced before that request is opened.
- const res = await moveSecrets({
- environment: PROD_ENV,
- sourceSecretPath: "/lenient",
- destinationSecretPath: "/strict/guarded",
- secretIds: [secret.id]
- });
- expect(res.statusCode).toBe(400);
- expect(res.json().message).toContain('Secret "GUARDED_TOO_SHORT"');
- expect(res.json().message).toContain("value must be at least 3 characters");
-
- // no change request was opened and the secret is untouched
- expect(await openChangeRequestCount(policy.id)).toBe(0);
- expect(await secretKeysAt("/lenient", PROD_ENV)).toContain("GUARDED_TOO_SHORT");
- }, 10_000);
- });
-});
diff --git a/backend/e2e-test/testUtils/secret-validation-rules.ts b/backend/e2e-test/testUtils/secret-validation-rules.ts
deleted file mode 100644
index 01fc9eb2e9..0000000000
--- a/backend/e2e-test/testUtils/secret-validation-rules.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-type TStaticSecretsValidationRule = {
- id: string;
- name: string;
- secretPath: string;
- environment: { id: string; name: string; slug: string } | null;
-};
-
-export const createStaticSecretsValidationRule = async (dto: {
- projectId: string;
- name: string;
- environment?: string;
- secretPath?: string;
- valueConstraints?: Record<string, unknown>;
- keyConstraints?: Record<string, unknown>;
- authToken: string;
-}) => {
- const res = await testServer.inject({
- method: "POST",
- url: "/api/v1/secret-validation-rules/static-secrets",
- headers: { authorization: `Bearer ${dto.authToken}` },
- body: {
- projectId: dto.projectId,
- name: dto.name,
- environment: dto.environment,
- secretPath: dto.secretPath ?? "/",
- keyConstraints: dto.keyConstraints,
- valueConstraints: dto.valueConstraints
- }
- });
- expect(res.statusCode).toBe(200);
- return res.json().secretValidationRule as TStaticSecretsValidationRule;
-};
diff --git a/tests/suites/secretmanager/sharedsecrets/access_test.go b/tests/suites/secretmanager/sharedsecrets/access_test.go
new file mode 100644
index 0000000000..5a7bf05a53
--- /dev/null
+++ b/tests/suites/secretmanager/sharedsecrets/access_test.go
@@ -0,0 +1,148 @@
+package sharedsecrets_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSharedSecret_Access(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse an organization-access share without a token", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ id := share(t, tn.Admin.API, api.CreateSharedSecretJSONRequestBody{SecretValue: "org-only", MaxViews: new(float32(1))})
+
+ // Action
+ res := access(t, tn.Anonymous(t), id, nil)
+
+ // Assert
+ require.Equal(t, http.StatusUnauthorized, res.StatusCode())
+ require.NotContains(t, string(res.Body), "org-only")
+ require.Equal(t, "org-only", revealed(t, access(t, tn.Admin.API, id, nil)), "the refused access used up the only view")
+ })
+
+ t.Run("should refuse a member of another organization and reveal nothing", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ mine, theirs := h.NewTenant(t), h.NewTenant(t)
+ id := share(t, theirs.Admin.API, api.CreateSharedSecretJSONRequestBody{SecretValue: "org-only", MaxViews: new(float32(1))})
+
+ // Action
+ res := access(t, mine.Admin.API, id, nil)
+
+ // Assert
+ require.NotEqualf(t, http.StatusOK, res.StatusCode(),
+ "tenant %s read tenant %s's organization share", mine.OrgSlug, theirs.OrgSlug)
+ require.NotContains(t, string(res.Body), "org-only")
+ require.Equal(t, "org-only", revealed(t, access(t, theirs.Admin.API, id, nil)), "the refused access used up the only view")
+ })
+
+ t.Run("should refuse a member who is not on the email list and reveal to one who is", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ listed := tn.NewUser(t, harness.WithName("listed"))
+ unlisted := tn.NewUser(t, harness.WithName("unlisted"))
+ id := share(t, tn.Admin.API, api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "for-listed",
+ AuthorizedEmails: emails(listed.Email),
+ })
+
+ // Action
+ res := access(t, unlisted.API, id, nil)
+
+ // Assert
+ require.Equal(t, http.StatusForbidden, res.StatusCode())
+ require.Equal(t, "You are not authorized to view this secret", res.JSON403.Message)
+ require.Equal(t, "for-listed", revealed(t, access(t, listed.API, id, nil)))
+ })
+
+ t.Run("should require the password and refuse a wrong one without using up a view", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ id := share(t, tn.Admin.API, api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "guarded",
+ AccessType: anyoneAccess(),
+ Password: new("correct horse"),
+ MaxViews: new(float32(1)),
+ })
+ anon := tn.Anonymous(t)
+
+ // Action
+ missing := access(t, anon, id, nil)
+ wrong := access(t, anon, id, new("wrong"))
+
+ // Assert
+ require.Equal(t, http.StatusUnauthorized, missing.StatusCode())
+ require.Equal(t, "Password is required to access this secret", missing.JSON401.Message)
+ require.Equal(t, http.StatusUnauthorized, wrong.StatusCode())
+ require.Equal(t, "Invalid credentials", wrong.JSON401.Message)
+ require.NotContains(t, string(wrong.Body), "guarded")
+ require.Equal(t, "guarded", revealed(t, access(t, anon, id, new("correct horse"))),
+ "a refused password used up the only view")
+ })
+
+ t.Run("should return the value once and then refuse with the view-limit message when maxViews is 1", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ id := share(t, tn.Admin.API, api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "once",
+ AccessType: anyoneAccess(),
+ MaxViews: new(float32(1)),
+ })
+ anon := tn.Anonymous(t)
+
+ // Action
+ first := access(t, anon, id, nil)
+ second := access(t, anon, id, nil)
+
+ // Assert
+ require.Equal(t, "once", revealed(t, first))
+ require.Equal(t, http.StatusNotFound, second.StatusCode())
+ require.Equal(t, "The shared secret has reached its view limit", second.JSON404.Message)
+ })
+
+ t.Run("should create a share with access forced to anyone through the public route even when organization access is asked for", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ anon := tn.Anonymous(t)
+ body, err := json.Marshal(map[string]any{
+ "secretValue": "public",
+ "expiresIn": "1h",
+ "accessType": "organization",
+ })
+ require.NoError(t, err)
+
+ // Action
+ created, err := anon.CreatePublicSharedSecretWithBodyWithResponse(t.Context(), "application/json", bytes.NewReader(body))
+ require.NoError(t, err)
+ require.NotNilf(t, created.JSON200, "sharing publicly returned %d: %s", created.StatusCode(), apierr.Body(created.Body))
+
+ // Assert
+ got, err := anon.GetSharedSecretByIdWithResponse(t.Context(), created.JSON200.Id)
+ require.NoError(t, err)
+ require.NotNilf(t, got.JSON200, "reading the share returned %d: %s", got.StatusCode(), apierr.Body(got.Body))
+ require.NotNil(t, got.JSON200.AccessType)
+ require.Equal(t, "anyone", *got.JSON200.AccessType)
+ require.Equal(t, "public", revealed(t, access(t, anon, created.JSON200.Id, nil)))
+ })
+}
diff --git a/tests/suites/secretmanager/sharedsecrets/create_test.go b/tests/suites/secretmanager/sharedsecrets/create_test.go
new file mode 100644
index 0000000000..8c7d904039
--- /dev/null
+++ b/tests/suites/secretmanager/sharedsecrets/create_test.go
@@ -0,0 +1,184 @@
+package sharedsecrets_test
+
+import (
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/smtp"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSharedSecret_Create(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse and create nothing when the expiry is under 5 minutes, over 30 days, or in the past", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ cases := map[string]string{
+ "4m": "Expiration time cannot be less than 5 minutes",
+ "31d": "Expiration time cannot exceed 30 days",
+ "-1h": "Expiration time cannot be less than 5 minutes",
+ }
+
+ for expiresIn, message := range cases {
+ // Action
+ res, err := tn.Admin.API.CreateSharedSecretWithResponse(t.Context(), api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "value",
+ ExpiresIn: new(expiresIn),
+ })
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "expiresIn %s: %s", expiresIn, res.Body)
+ require.Containsf(t, string(res.Body), message, "expiresIn %s", expiresIn)
+ }
+ _, total := shareNames(t, tn.Admin, nil)
+ require.Zero(t, total)
+ })
+
+ t.Run("should refuse and create nothing when the value, the name or the view limit is out of bounds", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ cases := map[string]api.CreateSharedSecretJSONRequestBody{
+ "value over 10,000 characters": {SecretValue: strings.Repeat("v", 10_001)},
+ "name over 50 characters": {SecretValue: "value", Name: new(strings.Repeat("n", 51))},
+ "maxViews under 1": {SecretValue: "value", MaxViews: new(float32(0))},
+ }
+
+ for name, body := range cases {
+ // Action
+ res, err := tn.Admin.API.CreateSharedSecretWithResponse(t.Context(), body)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "%s: %s", name, res.Body)
+ }
+ _, total := shareNames(t, tn.Admin, nil)
+ require.Zero(t, total)
+ })
+
+ t.Run("should refuse anyone-access when the organization does not allow sharing outside it", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ updateOrg(t, tn, api.UpdateOrganizationJSONRequestBody{AllowSecretSharingOutsideOrganization: new(false)})
+
+ // Action
+ res, err := tn.Admin.API.CreateSharedSecretWithResponse(t.Context(), api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "value",
+ AccessType: anyoneAccess(),
+ })
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Equal(t, "Organization does not allow sharing secrets to members outside of this organization", res.JSON400.Message)
+ _, total := shareNames(t, tn.Admin, nil)
+ require.Zero(t, total)
+ })
+
+ t.Run("should refuse a lifetime over the organization limit", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ updateOrg(t, tn, api.UpdateOrganizationJSONRequestBody{MaxSharedSecretLifetime: new(float32(3600))})
+
+ // Action
+ res, err := tn.Admin.API.CreateSharedSecretWithResponse(t.Context(), api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "value",
+ ExpiresIn: new("2h"),
+ })
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Equal(t, "Secret lifetime exceeds organization limit", res.JSON400.Message)
+ _, total := shareNames(t, tn.Admin, nil)
+ require.Zero(t, total)
+ })
+
+ t.Run("should refuse a share with no maxViews as over the view limit when the organization sets one", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ updateOrg(t, tn, api.UpdateOrganizationJSONRequestBody{MaxSharedSecretViewLimit: new(float32(5))})
+
+ // Action
+ unset, err := tn.Admin.API.CreateSharedSecretWithResponse(t.Context(), api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "value",
+ })
+ require.NoError(t, err)
+ over, err := tn.Admin.API.CreateSharedSecretWithResponse(t.Context(), api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "value",
+ MaxViews: new(float32(6)),
+ })
+ require.NoError(t, err)
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, unset.StatusCode())
+ require.Equal(t, "Secret max views parameter exceeds organization limit", unset.JSON400.Message)
+ require.Equal(t, http.StatusBadRequest, over.StatusCode())
+ require.Equal(t, "Secret max views parameter exceeds organization limit", over.JSON400.Message)
+ _, total := shareNames(t, tn.Admin, nil)
+ require.Zero(t, total)
+ })
+
+ t.Run("should refuse external emails without a password", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+
+ // Action
+ res, err := tn.Admin.API.CreateSharedSecretWithResponse(t.Context(), api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "value",
+ AccessType: anyoneAccess(),
+ AuthorizedEmails: emails(tn.Email("outsider")),
+ AllowExternalEmails: new(true),
+ })
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Equal(t, "A password is required when sharing secrets with users outside of Infisical", res.JSON400.Message)
+ _, total := shareNames(t, tn.Admin, nil)
+ require.Zero(t, total)
+ })
+
+ t.Run("should mail each listed address with the link, naming the sender only to an organization member", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ member := tn.NewUser(t, harness.WithName("member"))
+ outsider := tn.Email("outsider")
+
+ // Action
+ id := share(t, tn.Admin.API, api.CreateSharedSecretJSONRequestBody{
+ SecretValue: "value",
+ Name: new("db-password"),
+ AccessType: anyoneAccess(),
+ AuthorizedEmails: emails(member.Email, outsider),
+ })
+
+ // Assert
+ toMember := tn.Mail(t).Expect(t, member.Email, smtp.Subject("A secret has been shared with you"))
+ toOutsider := tn.Mail(t).Expect(t, outsider, smtp.Subject("A secret has been shared with you"))
+ require.Contains(t, toMember.Body, "/shared/secret/"+id)
+ require.Contains(t, toOutsider.Body, "/shared/secret/"+id)
+ require.Contains(t, toMember.Body, tn.Admin.Email)
+ require.NotContains(t, toOutsider.Body, tn.Admin.Email)
+ require.Contains(t, toOutsider.Body, "Someone")
+ })
+}
diff --git a/tests/suites/secretmanager/sharedsecrets/delete_test.go b/tests/suites/secretmanager/sharedsecrets/delete_test.go
new file mode 100644
index 0000000000..e5e4e92653
--- /dev/null
+++ b/tests/suites/secretmanager/sharedsecrets/delete_test.go
@@ -0,0 +1,54 @@
+package sharedsecrets_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSharedSecret_Delete(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse another user deleting a share and keep it", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ other := tn.NewUser(t, harness.WithName("other"))
+ id := share(t, tn.Admin.API, api.CreateSharedSecretJSONRequestBody{SecretValue: "kept", Name: new("kept")})
+
+ // Action
+ res, err := other.API.DeleteSharedSecretWithResponse(t.Context(), id)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusForbidden, res.StatusCode())
+ require.Equal(t, "User does not have permission to delete shared secret", res.JSON403.Message)
+ names, _ := shareNames(t, tn.Admin, nil)
+ require.Equal(t, []string{"kept"}, names)
+ require.Equal(t, "kept", revealed(t, access(t, tn.Admin.API, id, nil)))
+ })
+
+ t.Run("should let a machine identity delete its own share", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ identity := tn.NewMachineIdentity(t)
+ id := share(t, identity.API, api.CreateSharedSecretJSONRequestBody{SecretValue: "gone", Name: new("gone")})
+
+ // Action
+ res, err := identity.API.DeleteSharedSecretWithResponse(t.Context(), id)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deleting returned %s", res.Body)
+ _, total := shareNames(t, identity, nil)
+ require.Zero(t, total)
+ require.Equal(t, http.StatusNotFound, access(t, identity.API, id, nil).StatusCode())
+ })
+}
diff --git a/tests/suites/secretmanager/sharedsecrets/helpers_test.go b/tests/suites/secretmanager/sharedsecrets/helpers_test.go
new file mode 100644
index 0000000000..6c20703ca8
--- /dev/null
+++ b/tests/suites/secretmanager/sharedsecrets/helpers_test.go
@@ -0,0 +1,96 @@
+package sharedsecrets_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ openapi_types "github.com/oapi-codegen/runtime/types"
+ "github.com/stretchr/testify/require"
+)
+
+func anyoneAccess() *api.CreateSharedSecretJSONBodyAccessType {
+ return new(api.CreateSharedSecretJSONBodyAccessType("anyone"))
+}
+
+func emails(addrs ...string) *[]openapi_types.Email {
+ out := make([]openapi_types.Email, len(addrs))
+ for i, a := range addrs {
+ out[i] = openapi_types.Email(a)
+ }
+ return &out
+}
+
+func share(t *testing.T, client *api.ClientWithResponses, body api.CreateSharedSecretJSONRequestBody) string {
+ t.Helper()
+ res, err := client.CreateSharedSecretWithResponse(t.Context(), body)
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "sharing returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.Id
+}
+
+func access(t *testing.T, client *api.ClientWithResponses, id string, password *string) *api.AccessSharedSecretResponse {
+ t.Helper()
+ res, err := client.AccessSharedSecretWithResponse(t.Context(), id, api.AccessSharedSecretJSONRequestBody{Password: password})
+ require.NoError(t, err)
+ return res
+}
+
+// revealed fails unless the access answered with the value, and returns it.
+func revealed(t *testing.T, res *api.AccessSharedSecretResponse) string {
+ t.Helper()
+ require.NotNilf(t, res.JSON200, "accessing returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ require.NotNil(t, res.JSON200.SecretValue)
+ return *res.JSON200.SecretValue
+}
+
+func shareNames(t *testing.T, pr *harness.Principal, limit *float32) ([]string, int) {
+ t.Helper()
+ res, err := pr.API.ListSharedSecretsWithResponse(t.Context(), &api.ListSharedSecretsParams{Limit: limit})
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "listing shares returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ names := make([]string, 0, len(res.JSON200.Secrets))
+ for _, s := range res.JSON200.Secrets {
+ name := ""
+ if s.Name != nil {
+ name = *s.Name
+ }
+ names = append(names, name)
+ }
+ return names, int(res.JSON200.TotalCount)
+}
+
+func updateOrg(t *testing.T, tn *harness.Tenant, body api.UpdateOrganizationJSONRequestBody) {
+ t.Helper()
+ res, err := tn.Admin.API.UpdateOrganizationWithResponse(t.Context(), tn.OrgID.String(), body)
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "updating the organization returned %s", apierr.Body(res.Body))
+}
+
+func requestSecret(t *testing.T, requester *harness.Principal, accessType string) string {
+ t.Helper()
+ res, err := requester.API.CreateSecretRequestWithResponse(t.Context(), api.CreateSecretRequestJSONRequestBody{
+ ExpiresIn: "1h",
+ Name: new("db-password"),
+ AccessType: new(api.CreateSecretRequestJSONBodyAccessType(accessType)),
+ })
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "requesting a secret returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.Id
+}
+
+func setRequestValue(t *testing.T, client *api.ClientWithResponses, id, value string) *api.SetSecretRequestValueResponse {
+ t.Helper()
+ res, err := client.SetSecretRequestValueWithResponse(t.Context(), id, api.SetSecretRequestValueJSONRequestBody{SecretValue: value})
+ require.NoError(t, err)
+ return res
+}
+
+func reveal(t *testing.T, pr *harness.Principal, id string) *api.RevealSecretRequestValueResponse {
+ t.Helper()
+ res, err := pr.API.RevealSecretRequestValueWithResponse(t.Context(), id)
+ require.NoError(t, err)
+ return res
+}
diff --git a/tests/suites/secretmanager/sharedsecrets/list_test.go b/tests/suites/secretmanager/sharedsecrets/list_test.go
new file mode 100644
index 0000000000..b041831ea5
--- /dev/null
+++ b/tests/suites/secretmanager/sharedsecrets/list_test.go
@@ -0,0 +1,33 @@
+package sharedsecrets_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSharedSecret_List(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should list only the caller's own shares, newest first, up to the limit", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ other := tn.NewMachineIdentity(t)
+ for _, name := range []string{"first", "second", "third"} {
+ share(t, tn.Admin.API, api.CreateSharedSecretJSONRequestBody{SecretValue: "v", Name: new(name)})
+ }
+ share(t, other.API, api.CreateSharedSecretJSONRequestBody{SecretValue: "v", Name: new("not-mine")})
+
+ // Action
+ names, total := shareNames(t, tn.Admin, new(float32(2)))
+
+ // Assert
+ require.Equal(t, []string{"third", "second"}, names)
+ require.Equal(t, 3, total)
+ })
+}
diff --git a/tests/suites/secretmanager/sharedsecrets/main_test.go b/tests/suites/secretmanager/sharedsecrets/main_test.go
new file mode 100644
index 0000000000..da40bb28b0
--- /dev/null
+++ b/tests/suites/secretmanager/sharedsecrets/main_test.go
@@ -0,0 +1,9 @@
+package sharedsecrets_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/sharedsecrets/request_test.go b/tests/suites/secretmanager/sharedsecrets/request_test.go
new file mode 100644
index 0000000000..2b1c4ce2eb
--- /dev/null
+++ b/tests/suites/secretmanager/sharedsecrets/request_test.go
@@ -0,0 +1,95 @@
+package sharedsecrets_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/smtp"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSecretRequest_SetValue(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse setting a value twice and keep the first", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ id := requestSecret(t, tn.Admin, "anyone")
+ anon := tn.Anonymous(t)
+ first := setRequestValue(t, anon, id, "first")
+ require.Equalf(t, http.StatusOK, first.StatusCode(), "setting the value returned %s", apierr.Body(first.Body))
+
+ // Action
+ second := setRequestValue(t, anon, id, "second")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, second.StatusCode())
+ require.Equal(t, "Secret request already has a value set", second.JSON400.Message)
+ got := reveal(t, tn.Admin, id)
+ require.NotNilf(t, got.JSON200, "revealing returned %d: %s", got.StatusCode(), apierr.Body(got.Body))
+ require.Equal(t, "first", got.JSON200.SecretRequest.SecretValue)
+ })
+
+ t.Run("should mail the requester when a value is set", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ id := requestSecret(t, tn.Admin, "anyone")
+
+ // Action
+ res := setRequestValue(t, tn.Anonymous(t), id, "answered")
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "setting the value returned %s", apierr.Body(res.Body))
+
+ // Assert
+ msg := tn.Mail(t).Expect(t, tn.Admin.Email, smtp.Subject("Secret Request Completed"))
+ require.Contains(t, msg.Body, "secret-sharing?selectedTab=request-secret",
+ "the mail does not link to the requester's secret requests")
+ })
+}
+
+func TestSecretRequest_Reveal(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse a reveal by an organization member who is not the requester", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ other := tn.NewUser(t, harness.WithName("other"))
+ id := requestSecret(t, tn.Admin, "organization")
+ set := setRequestValue(t, other.API, id, "for-requester")
+ require.Equalf(t, http.StatusOK, set.StatusCode(), "setting the value returned %s", apierr.Body(set.Body))
+
+ // Action
+ res := reveal(t, other, id)
+
+ // Assert
+ require.Equal(t, http.StatusForbidden, res.StatusCode())
+ require.NotContains(t, string(res.Body), "for-requester")
+ got := reveal(t, tn.Admin, id)
+ require.NotNilf(t, got.JSON200, "revealing returned %d: %s", got.StatusCode(), apierr.Body(got.Body))
+ require.Equal(t, "for-requester", got.JSON200.SecretRequest.SecretValue)
+ })
+
+ t.Run("should refuse a reveal before a value is set", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ id := requestSecret(t, tn.Admin, "organization")
+
+ // Action
+ res := reveal(t, tn.Admin, id)
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Equal(t, "Secret request has no value set", res.JSON400.Message)
+ })
+}
diff --git a/tests/suites/secretmanager/validation/enforcement_test.go b/tests/suites/secretmanager/validation/enforcement_test.go
new file mode 100644
index 0000000000..2c691caf2c
--- /dev/null
+++ b/tests/suites/secretmanager/validation/enforcement_test.go
@@ -0,0 +1,211 @@
+package validation_test
+
+import (
+ "net/http"
+ "slices"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSecretValidationRule_Enforce(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse a value under the minimum or over the maximum length, quoting the lengths", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "length-window", onValues(valueConstraints{MinLength: new(4), MaxLength: new(8)}))
+
+ // Action
+ short := createSecret(t, tn.Admin, proj, "dev", "/", "SHORT", "abc")
+ long := createSecret(t, tn.Admin, proj, "dev", "/", "LONG", "123456789")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, short.StatusCode())
+ require.Equal(t, "Secret validation failed:\n"+
+ `Secret "SHORT": value must be at least 4 characters (got 3) (rule: "length-window", constraint: Minimum length)`,
+ short.JSON400.Message)
+ require.Equal(t, http.StatusBadRequest, long.StatusCode())
+ require.Equal(t, "Secret validation failed:\n"+
+ `Secret "LONG": value must be at most 8 characters (got 9) (rule: "length-window", constraint: Maximum length)`,
+ long.JSON400.Message)
+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))
+ })
+
+ t.Run("should refuse a value that breaks the rule's regex", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "lowercase", onValues(valueConstraints{RegexPattern: new("^[a-z]+$")}))
+
+ // Action
+ res := createSecret(t, tn.Admin, proj, "dev", "/", "TOKEN", "Not-Lowercase")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `Secret "TOKEN": value must match pattern ^[a-z]+$ (rule: "lowercase", constraint: Regex pattern)`)
+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))
+ })
+
+ t.Run("should refuse a value without the required prefix or suffix, naming both", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "affixes", onValues(valueConstraints{RequiredPrefix: new("sk_"), RequiredSuffix: new("_end")}))
+
+ // Action
+ res := createSecret(t, tn.Admin, proj, "dev", "/", "STRIPE_KEY", "plain")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `value must start with "sk_" (rule: "affixes", constraint: Required prefix)`)
+ require.Contains(t, res.JSON400.Message, `value must end with "_end" (rule: "affixes", constraint: Required suffix)`)
+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))
+ })
+
+ t.Run("should refuse reusing any of the last N values and keep the current one", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "no-reuse", onValues(valueConstraints{UniqueAcrossLastVersions: new(2)}))
+ secretmanager.CreateSecret(t, proj, "dev", "DB_PASSWORD", "first")
+ secretmanager.UpdateSecret(t, proj, "dev", "DB_PASSWORD", "second")
+
+ // Action
+ res := updateSecret(t, tn.Admin, proj, "dev", "DB_PASSWORD", "first")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message,
+ `Secret "DB_PASSWORD": value cannot reuse any of the last 2 values (rule: "no-reuse", constraint: Prevent reuse of previous secret values)`)
+ require.Equal(t, "second", secretmanager.GetSecret(t, proj, "dev", "DB_PASSWORD").Value)
+ })
+
+ t.Run("should not enforce an inactive rule", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "dormant", inactive(), onValues(valueConstraints{MinLength: new(20)}))
+
+ // Action
+ res := createSecret(t, tn.Admin, proj, "dev", "/", "SHORT", "abc")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating returned %s", res.Body)
+ require.Equal(t, "abc", secretmanager.GetSecret(t, proj, "dev", "SHORT").Value)
+ })
+
+ t.Run("should refuse the whole batch create when one secret breaks the rule", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "app-prefix", onKeys(keyConstraints{RequiredPrefix: new("APP_")}))
+ body := api.CreateManySecretsV4JSONRequestBody{ProjectId: proj.ID, Environment: "dev"}
+ body.Secrets = slices.Grow(body.Secrets, 2)[:2]
+ body.Secrets[0].SecretKey, body.Secrets[0].SecretValue = "APP_NAME", "a"
+ body.Secrets[1].SecretKey, body.Secrets[1].SecretValue = "STRAY", "b"
+
+ // Action
+ res, err := tn.Admin.API.CreateManySecretsV4WithResponse(t.Context(), body)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `Secret "STRAY": key must start with "APP_" (rule: "app-prefix", constraint: Required prefix)`)
+ require.NotContains(t, res.JSON400.Message, `Secret "APP_NAME"`)
+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))
+ })
+
+ t.Run("should refuse a rename in a batch update when the new key breaks the rule", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ secretmanager.CreateSecret(t, proj, "dev", "APP_NAME", "a")
+ newRule(t, proj, "app-prefix", onKeys(keyConstraints{RequiredPrefix: new("APP_")}))
+ body := api.UpdateManySecretsV4JSONRequestBody{ProjectId: proj.ID, Environment: "dev"}
+ body.Secrets = slices.Grow(body.Secrets, 1)[:1]
+ body.Secrets[0].SecretKey, body.Secrets[0].NewSecretName = "APP_NAME", new("NAME")
+
+ // Action
+ res, err := tn.Admin.API.UpdateManySecretsV4WithResponse(t.Context(), body)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `Secret "NAME": key must start with "APP_" (rule: "app-prefix", constraint: Required prefix)`)
+ keys := []string{}
+ for _, s := range secretmanager.ListSecrets(t, proj, "dev") {
+ keys = append(keys, s.Key)
+ }
+ require.Equal(t, []string{"APP_NAME"}, keys)
+ })
+
+ t.Run("should validate the expanded value of a reference, not the reference itself", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ secretmanager.CreateSecret(t, proj, "staging", "BASE", "ab")
+ newRule(t, proj, "min-five", onValues(valueConstraints{MinLength: new(5)}))
+
+ // Action
+ res := createSecret(t, tn.Admin, proj, "dev", "/", "REF", "${staging.BASE}")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `Secret "REF": value must be at least 5 characters (got 2)`)
+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))
+ })
+
+ t.Run("should name where a duplicated value is held only to a writer who may describe that location", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ secretmanager.CreateFolder(t, proj, "dev", "/hidden")
+ secretmanager.CreateSecret(t, proj, "dev", "ORIGINAL", "duplicated", secretmanager.WithPath("/hidden"))
+ newRule(t, proj, "unique-in-dev", atPath("/**"), onValues(valueConstraints{UniqueWithinScope: new(true)}))
+ proj.NewRole(t, "root-writer", fixture.Permission{
+ Subject: "secrets",
+ Action: []string{"describeSecret", "readValue", "create"},
+ Conditions: map[string]any{"environment": map[string]any{"$eq": "dev"}, "secretPath": map[string]any{"$eq": "/"}},
+ })
+ writer := proj.NewMachineIdentity(t, fixture.WithRoles("root-writer"))
+
+ // Action
+ restricted := createSecret(t, writer, proj, "dev", "/", "COPY", "duplicated")
+ admin := createSecret(t, tn.Admin, proj, "dev", "/", "COPY", "duplicated")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, restricted.StatusCode())
+ require.Contains(t, restricted.JSON400.Message, `Secret "COPY": value is already used by another secret in this project`)
+ require.NotContains(t, restricted.JSON400.Message, "ORIGINAL")
+ require.NotContains(t, restricted.JSON400.Message, "/hidden")
+ require.Equal(t, http.StatusBadRequest, admin.StatusCode())
+ require.Contains(t, admin.JSON400.Message,
+ `Secret "COPY": value is already used by secret "ORIGINAL" in environment "dev" at path "/hidden"`)
+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))
+ })
+}
diff --git a/tests/suites/secretmanager/validation/helpers_test.go b/tests/suites/secretmanager/validation/helpers_test.go
new file mode 100644
index 0000000000..ef3d17acd3
--- /dev/null
+++ b/tests/suites/secretmanager/validation/helpers_test.go
@@ -0,0 +1,142 @@
+package validation_test
+
+import (
+ "net/http"
+ "path"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/stretchr/testify/require"
+)
+
+// The generated bodies declare the constraints as anonymous structs; identical aliases are
+// assignable to them.
+type keyConstraints = struct {
+ MaxLength *int `json:"maxLength,omitempty"`
+ MinLength *int `json:"minLength,omitempty"`
+ RegexPattern *string `json:"regexPattern,omitempty"`
+ RequiredPrefix *string `json:"requiredPrefix,omitempty"`
+ RequiredSuffix *string `json:"requiredSuffix,omitempty"`
+}
+
+type valueConstraints = struct {
+ MaxLength *int `json:"maxLength,omitempty"`
+ MinLength *int `json:"minLength,omitempty"`
+ RegexPattern *string `json:"regexPattern,omitempty"`
+ RequiredPrefix *string `json:"requiredPrefix,omitempty"`
+ RequiredSuffix *string `json:"requiredSuffix,omitempty"`
+ UniqueAcrossLastVersions *int `json:"uniqueAcrossLastVersions,omitempty"`
+ UniqueWithinScope *bool `json:"uniqueWithinScope,omitempty"`
+}
+
+type ruleOption func(*api.CreateStaticSecretsValidationRuleJSONRequestBody)
+
+func inEnv(env string) ruleOption {
+ return func(b *api.CreateStaticSecretsValidationRuleJSONRequestBody) { b.Environment = &env }
+}
+
+func atPath(p string) ruleOption {
+ return func(b *api.CreateStaticSecretsValidationRuleJSONRequestBody) { b.SecretPath = p }
+}
+
+func onValues(c valueConstraints) ruleOption {
+ return func(b *api.CreateStaticSecretsValidationRuleJSONRequestBody) { b.ValueConstraints = &c }
+}
+
+func onKeys(c keyConstraints) ruleOption {
+ return func(b *api.CreateStaticSecretsValidationRuleJSONRequestBody) { b.KeyConstraints = &c }
+}
+
+func inactive() ruleOption {
+ return func(b *api.CreateStaticSecretsValidationRuleJSONRequestBody) { b.IsActive = new(false) }
+}
+
+// ruleBody scopes a rule to dev:/ unless an option says otherwise.
+func ruleBody(proj *fixture.Project, name string, opts ...ruleOption) api.CreateStaticSecretsValidationRuleJSONRequestBody {
+ body := api.CreateStaticSecretsValidationRuleJSONRequestBody{
+ Name: name,
+ ProjectId: proj.ID,
+ Environment: new("dev"),
+ SecretPath: "/",
+ }
+ for _, o := range opts {
+ o(&body)
+ }
+ return body
+}
+
+func newRule(t *testing.T, proj *fixture.Project, name string, opts ...ruleOption) {
+ t.Helper()
+ res, err := proj.Tenant().Admin.API.CreateStaticSecretsValidationRuleWithResponse(t.Context(), ruleBody(proj, name, opts...))
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating rule %s: %s", name, apierr.Body(res.Body))
+}
+
+func ruleNames(t *testing.T, proj *fixture.Project) []string {
+ t.Helper()
+ res, err := proj.Tenant().Admin.API.ListStaticSecretsValidationRulesWithResponse(t.Context(),
+ &api.ListStaticSecretsValidationRulesParams{ProjectId: proj.ID})
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "listing rules returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ names := []string{}
+ for _, r := range res.JSON200.SecretValidationRules {
+ names = append(names, r.Name)
+ }
+ return names
+}
+
+func createSecret(t *testing.T, pr *harness.Principal, proj *fixture.Project, env, secretPath, key, value string) *api.CreateSecretV4Response {
+ t.Helper()
+ res, err := pr.API.CreateSecretV4WithResponse(t.Context(), key, api.CreateSecretV4JSONRequestBody{
+ ProjectId: proj.ID,
+ Environment: env,
+ SecretPath: &secretPath,
+ SecretValue: value,
+ })
+ require.NoError(t, err)
+ return res
+}
+
+func updateSecret(t *testing.T, pr *harness.Principal, proj *fixture.Project, env, key, value string) *api.UpdateSecretV4Response {
+ t.Helper()
+ res, err := pr.API.UpdateSecretV4WithResponse(t.Context(), key, api.UpdateSecretV4JSONRequestBody{
+ ProjectId: proj.ID,
+ Environment: env,
+ SecretValue: &value,
+ })
+ require.NoError(t, err)
+ return res
+}
+
+func newFolder(t *testing.T, proj *fixture.Project, env, folderPath string) string {
+ t.Helper()
+ parent, name := path.Split(path.Clean(folderPath))
+ res, err := proj.Tenant().Admin.API.CreateSecretFolderWithResponse(t.Context(), api.CreateSecretFolderJSONRequestBody{
+ ProjectId: proj.ID,
+ Environment: env,
+ Name: name,
+ Path: &parent,
+ })
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "creating folder %s returned %d: %s", folderPath, res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.Folder.Id.String()
+}
+
+func folderNamesAt(t *testing.T, proj *fixture.Project, env, folderPath string) []string {
+ t.Helper()
+ res, err := proj.Tenant().Admin.API.ListSecretFoldersWithResponse(t.Context(), &api.ListSecretFoldersParams{
+ ProjectId: proj.ID,
+ Environment: env,
+ Path: folderPath,
+ })
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "listing folders at %s returned %d: %s", folderPath, res.StatusCode(), apierr.Body(res.Body))
+ names := []string{}
+ for _, f := range res.JSON200.Folders {
+ names = append(names, f.Name)
+ }
+ return names
+}
diff --git a/tests/suites/secretmanager/validation/main_test.go b/tests/suites/secretmanager/validation/main_test.go
new file mode 100644
index 0000000000..b717a8d1b1
--- /dev/null
+++ b/tests/suites/secretmanager/validation/main_test.go
@@ -0,0 +1,9 @@
+package validation_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/validation/move_test.go b/tests/suites/secretmanager/validation/move_test.go
new file mode 100644
index 0000000000..f1f24ea52e
--- /dev/null
+++ b/tests/suites/secretmanager/validation/move_test.go
@@ -0,0 +1,170 @@
+package validation_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "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/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSecretValidationRule_Move(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ strictProject := func(t *testing.T) (*harness.Tenant, *fixture.Project) {
+ t.Helper()
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ secretmanager.CreateFolder(t, proj, "prod", "/strict")
+ secretmanager.CreateFolder(t, proj, "prod", "/lenient")
+ newRule(t, proj, "min-length-under-strict", inEnv("prod"), atPath("/strict/**"),
+ onValues(valueConstraints{MinLength: new(3)}))
+ return tn, proj
+ }
+
+ moveSecret := func(t *testing.T, tn *harness.Tenant, proj *fixture.Project, env, from, to, secretID string) *api.MoveSecretsV4Response {
+ t.Helper()
+ res, err := tn.Admin.API.MoveSecretsV4WithResponse(t.Context(), api.MoveSecretsV4JSONRequestBody{
+ ProjectId: proj.ID,
+ SourceEnvironment: env,
+ SourceSecretPath: &from,
+ DestinationEnvironment: env,
+ DestinationSecretPath: &to,
+ SecretIds: []string{secretID},
+ })
+ require.NoError(t, err)
+ return res
+ }
+
+ keysAt := func(t *testing.T, proj *fixture.Project, env, secretPath string) []string {
+ t.Helper()
+ keys := []string{}
+ for _, s := range secretmanager.ListSecrets(t, proj, env, secretmanager.WithPath(secretPath)) {
+ keys = append(keys, s.Key)
+ }
+ return keys
+ }
+
+ t.Run("should refuse and move nothing when the secret's value breaks the destination's rule", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn, proj := strictProject(t)
+ secret := secretmanager.CreateSecret(t, proj, "prod", "TOO_SHORT", "x", secretmanager.WithPath("/lenient"))
+
+ // Action
+ res := moveSecret(t, tn, proj, "prod", "/lenient", "/strict", secret.ID)
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `Secret "TOO_SHORT": value must be at least 3 characters`)
+ require.Equal(t, []string{"TOO_SHORT"}, keysAt(t, proj, "prod", "/lenient"))
+ require.Empty(t, keysAt(t, proj, "prod", "/strict"))
+ })
+
+ t.Run("should move a secret whose value meets the destination's rule", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn, proj := strictProject(t)
+ secret := secretmanager.CreateSecret(t, proj, "prod", "LONG_ENOUGH", "long-enough-value", secretmanager.WithPath("/lenient"))
+
+ // Action
+ res := moveSecret(t, tn, proj, "prod", "/lenient", "/strict", secret.ID)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "moving returned %s", res.Body)
+ require.Equal(t, []string{"LONG_ENOUGH"}, keysAt(t, proj, "prod", "/strict"))
+ require.Empty(t, keysAt(t, proj, "prod", "/lenient"))
+ })
+
+ t.Run("should refuse and move nothing when a folder holds a secret that breaks the destination's rule", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn, proj := strictProject(t)
+ folderID := newFolder(t, proj, "prod", "/lenient/short-values")
+ secretmanager.CreateSecret(t, proj, "prod", "NESTED_TOO_SHORT", "x", secretmanager.WithPath("/lenient/short-values"))
+
+ // Action
+ res, err := tn.Admin.API.MoveSecretFolderWithResponse(t.Context(), api.MoveSecretFolderJSONRequestBody{
+ ProjectId: proj.ID,
+ FolderId: uuid.MustParse(folderID),
+ DestinationEnvironment: "prod",
+ DestinationPath: new("/strict"),
+ })
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `Secret "NESTED_TOO_SHORT": value must be at least 3 characters`)
+ require.Equal(t, []string{"short-values"}, folderNamesAt(t, proj, "prod", "/lenient"))
+ require.Empty(t, folderNamesAt(t, proj, "prod", "/strict"))
+ require.Equal(t, []string{"NESTED_TOO_SHORT"}, keysAt(t, proj, "prod", "/lenient/short-values"))
+ })
+
+ t.Run("should move a secret within a no-duplicates scope that also covers its source", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ secretmanager.CreateFolder(t, proj, "staging", "/from")
+ secretmanager.CreateFolder(t, proj, "staging", "/to")
+ newRule(t, proj, "no-duplicate-values-in-staging", inEnv("staging"), atPath("/**"),
+ onValues(valueConstraints{UniqueWithinScope: new(true)}))
+ secret := secretmanager.CreateSecret(t, proj, "staging", "MOVED_UNIQUE", "moved-unique-value", secretmanager.WithPath("/from"))
+
+ // Action
+ res := moveSecret(t, tn, proj, "staging", "/from", "/to", secret.ID)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "moving returned %s", res.Body)
+ require.Equal(t, []string{"MOVED_UNIQUE"}, keysAt(t, proj, "staging", "/to"))
+ require.Empty(t, keysAt(t, proj, "staging", "/from"))
+ })
+
+ t.Run("should refuse and open no change request when the destination has a change policy and the value breaks its rule", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn, proj := strictProject(t)
+ secretmanager.CreateFolder(t, proj, "prod", "/strict/guarded")
+ var approver api.CreateSecretApprovalPolicyJSONBody_Approvers_Item
+ require.NoError(t, approver.FromCreateSecretApprovalPolicyJSONBodyApprovers1(api.CreateSecretApprovalPolicyJSONBodyApprovers1{
+ Type: api.CreateSecretApprovalPolicyJSONBodyApprovers1TypeUser,
+ Id: new(tn.Admin.ID.String()),
+ }))
+ policy, err := tn.Admin.API.CreateSecretApprovalPolicyWithResponse(t.Context(), api.CreateSecretApprovalPolicyJSONRequestBody{
+ ProjectId: proj.ID,
+ Environment: new("prod"),
+ SecretPath: "/strict/guarded",
+ Approvals: new(float32(1)),
+ Approvers: []api.CreateSecretApprovalPolicyJSONBody_Approvers_Item{approver},
+ })
+ require.NoError(t, err)
+ require.NotNilf(t, policy.JSON200, "creating the policy returned %d: %s", policy.StatusCode(), apierr.Body(policy.Body))
+ secret := secretmanager.CreateSecret(t, proj, "prod", "GUARDED_TOO_SHORT", "x", secretmanager.WithPath("/lenient"))
+
+ // Action
+ res := moveSecret(t, tn, proj, "prod", "/lenient", "/strict/guarded", secret.ID)
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message, `Secret "GUARDED_TOO_SHORT": value must be at least 3 characters`)
+ count, err := tn.Admin.API.GetSecretApprovalRequestCountWithResponse(t.Context(),
+ &api.GetSecretApprovalRequestCountParams{ProjectId: proj.ID})
+ require.NoError(t, err)
+ require.NotNilf(t, count.JSON200, "counting requests returned %d: %s", count.StatusCode(), apierr.Body(count.Body))
+ if count.JSON200.Approvals.Open != nil {
+ require.Zero(t, *count.JSON200.Approvals.Open, "the refused move still opened a change request")
+ }
+ require.Equal(t, []string{"GUARDED_TOO_SHORT"}, keysAt(t, proj, "prod", "/lenient"))
+ })
+}
diff --git a/tests/suites/secretmanager/validation/reuse_test.go b/tests/suites/secretmanager/validation/reuse_test.go
new file mode 100644
index 0000000000..46d9c832ce
--- /dev/null
+++ b/tests/suites/secretmanager/validation/reuse_test.go
@@ -0,0 +1,116 @@
+package validation_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSecretValidationRule_ReuseWithinScope(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ uniqueInProdRoot := func(t *testing.T, proj *fixture.Project) {
+ t.Helper()
+ newRule(t, proj, "no-duplicate-values-in-prod", inEnv("prod"),
+ onValues(valueConstraints{UniqueWithinScope: new(true)}))
+ }
+
+ t.Run("should accept distinct values in the rule's environment and a repeated value outside it", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ uniqueInProdRoot(t, proj)
+ secretmanager.CreateSecret(t, proj, "prod", "UNIQUE_A", "unique-value-a")
+ secretmanager.CreateSecret(t, proj, "prod", "UNIQUE_B", "unique-value-b")
+ secretmanager.CreateSecret(t, proj, "prod", "SHARED_ACROSS_ENVS", "shared-across-envs")
+
+ // Action
+ res := createSecret(t, tn.Admin, proj, "staging", "/", "SHARED_ACROSS_ENVS_COPY", "shared-across-envs")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating returned %s", res.Body)
+ require.Equal(t, "shared-across-envs", secretmanager.GetSecret(t, proj, "staging", "SHARED_ACROSS_ENVS_COPY").Value)
+ })
+
+ t.Run("should accept a repeated value at a path the rule does not reach", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ uniqueInProdRoot(t, proj)
+ secretmanager.CreateFolder(t, proj, "prod", "/folder")
+ secretmanager.CreateSecret(t, proj, "prod", "SHARED_ACROSS_PATHS", "shared-across-paths")
+
+ // Action
+ res := createSecret(t, tn.Admin, proj, "prod", "/folder", "SHARED_ACROSS_PATHS_COPY", "shared-across-paths")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating returned %s", res.Body)
+ require.Equal(t, "shared-across-paths",
+ secretmanager.GetSecret(t, proj, "prod", "SHARED_ACROSS_PATHS_COPY", secretmanager.WithPath("/folder")).Value)
+ })
+
+ t.Run("should refuse a second secret holding a value the scope already holds and name where to an admin", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ uniqueInProdRoot(t, proj)
+ secretmanager.CreateSecret(t, proj, "prod", "ORIGINAL", "duplicated-value")
+
+ // Action
+ res := createSecret(t, tn.Admin, proj, "prod", "/", "DUPLICATE", "duplicated-value")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message,
+ `Secret "DUPLICATE": value is already used by secret "ORIGINAL" in environment "prod" at path "/"`)
+ require.Len(t, secretmanager.ListSecrets(t, proj, "prod"), 1)
+ })
+
+ t.Run("should refuse updating a secret to a value another secret in scope holds and keep the old value", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ uniqueInProdRoot(t, proj)
+ secretmanager.CreateSecret(t, proj, "prod", "UPDATE_TARGET", "value-before-update")
+ secretmanager.CreateSecret(t, proj, "prod", "UPDATE_HOLDER", "value-held-by-another-secret")
+
+ // Action
+ res := updateSecret(t, tn.Admin, proj, "prod", "UPDATE_TARGET", "value-held-by-another-secret")
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Contains(t, res.JSON400.Message,
+ `Secret "UPDATE_TARGET": value is already used by secret "UPDATE_HOLDER" in environment "prod"`)
+ require.Equal(t, "value-before-update", secretmanager.GetSecret(t, proj, "prod", "UPDATE_TARGET").Value)
+ })
+
+ t.Run("should accept re-saving a secret with the value it already holds", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ uniqueInProdRoot(t, proj)
+ secretmanager.CreateSecret(t, proj, "prod", "SELF_UPDATE", "self-update-value")
+
+ // Action
+ res := updateSecret(t, tn.Admin, proj, "prod", "SELF_UPDATE", "self-update-value")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "updating returned %s", res.Body)
+ require.Equal(t, "self-update-value", secretmanager.GetSecret(t, proj, "prod", "SELF_UPDATE").Value)
+ })
+}
diff --git a/tests/suites/secretmanager/validation/rule_test.go b/tests/suites/secretmanager/validation/rule_test.go
new file mode 100644
index 0000000000..89937020f6
--- /dev/null
+++ b/tests/suites/secretmanager/validation/rule_test.go
@@ -0,0 +1,126 @@
+package validation_test
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSecretValidationRule_Create(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse and create nothing when the rule sets no constraint", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+
+ // Action
+ res, err := tn.Admin.API.CreateStaticSecretsValidationRuleWithResponse(t.Context(),
+ ruleBody(proj, "empty", onValues(valueConstraints{})))
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())
+ require.Contains(t, string(res.Body), "A rule must set at least one key or value constraint")
+ require.Empty(t, ruleNames(t, proj))
+ })
+
+ t.Run("should refuse and create nothing when the minimum length is greater than the maximum", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+
+ // Action
+ res, err := tn.Admin.API.CreateStaticSecretsValidationRuleWithResponse(t.Context(),
+ ruleBody(proj, "inverted", onValues(valueConstraints{MinLength: new(10), MaxLength: new(5)})))
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())
+ require.Contains(t, string(res.Body), "Minimum length (10) cannot be greater than maximum length (5)")
+ require.Empty(t, ruleNames(t, proj))
+ })
+
+ t.Run("should refuse and create nothing when the regex is invalid", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+
+ // Action
+ res, err := tn.Admin.API.CreateStaticSecretsValidationRuleWithResponse(t.Context(),
+ ruleBody(proj, "broken-regex", onValues(valueConstraints{RegexPattern: new("([a-z")})))
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusUnprocessableEntity, res.StatusCode())
+ require.Contains(t, string(res.Body), "Must be a valid regular expression")
+ require.Empty(t, ruleNames(t, proj))
+ })
+
+ t.Run("should refuse a rule that constrains the same field over an overlapping scope and keep the first", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "first", atPath("/**"), onValues(valueConstraints{MinLength: new(4)}))
+
+ // Action
+ res, err := tn.Admin.API.CreateStaticSecretsValidationRuleWithResponse(t.Context(),
+ ruleBody(proj, "second", atPath("/app"), onValues(valueConstraints{MinLength: new(8)})))
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusBadRequest, res.StatusCode())
+ require.Equal(t, `Rule "first" already constrains value.minLength over the same secrets. `+
+ "Change the environment, the secret path, or the constraints so the two rules do not overlap.", res.JSON400.Message)
+ require.Equal(t, []string{"first"}, ruleNames(t, proj))
+ })
+
+ t.Run("should accept a rule over an overlapping scope when it constrains a different field", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ newRule(t, proj, "first", atPath("/**"), onValues(valueConstraints{MinLength: new(4)}))
+
+ // Action
+ res, err := tn.Admin.API.CreateStaticSecretsValidationRuleWithResponse(t.Context(),
+ ruleBody(proj, "second", atPath("/app"), onValues(valueConstraints{MaxLength: new(8)})))
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "creating returned %s", res.Body)
+ require.ElementsMatch(t, []string{"first", "second"}, ruleNames(t, proj))
+ })
+
+ t.Run("should refuse and create nothing when the environment does not exist", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+
+ // Action
+ res, err := tn.Admin.API.CreateStaticSecretsValidationRuleWithResponse(t.Context(),
+ ruleBody(proj, "nowhere", inEnv("nope"), onValues(valueConstraints{MinLength: new(4)})))
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, http.StatusNotFound, res.StatusCode())
+ require.Equal(t, fmt.Sprintf("Environment 'nope' not found in project with ID '%s'", proj.ID), res.JSON404.Message)
+ require.Empty(t, ruleNames(t, proj))
+ })
+}