Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
test(e2e): cover metadata search, filters and limits
varonix44374cf4008f
diff --git a/backend/e2e-test/routes/v1/dashboard-secret-metadata.spec.ts b/backend/e2e-test/routes/v1/dashboard-secret-metadata.spec.tsdeleted file mode 100644index 6666f218e6..0000000000--- a/backend/e2e-test/routes/v1/dashboard-secret-metadata.spec.ts+++ /dev/null@@ -1,292 +0,0 @@-import qs from "qs";--import { SecretType } from "@app/db/schemas";-import { seedData1 } from "@app/db/seed-data";--type TRawSecretWithId = {- id: string;- secretKey: string;- secretValue: string;- version: number;-};--type TMetadataSearchResult = {- secretId: string;- secretKey: string;- environment: string;- secretPath: string;- metadata: { key: string; value: string }[];-}[];--// distinctive keys so the org-wide search only ever matches the secrets seeded by this spec-const ENV_KEY = "e2e-search-env";-const TEAM_KEY = "e2e-search-team";-const TEST_PATH = "/";--const createSecretWithMetadata = async (dto: {- key: string;- metadata: { key: string; value: string; isEncrypted?: boolean }[];-}) => {- const res = await testServer.inject({- method: "POST",- url: `/api/v3/secrets/raw/${dto.key}`,- headers: {- authorization: `Bearer ${jwtAuthToken}`- },- body: {- workspaceId: seedData1.projectV3.id,- environment: seedData1.environment.slug,- type: SecretType.Shared,- secretPath: TEST_PATH,- secretKey: dto.key,- secretValue: "test-value",- secretMetadata: dto.metadata- }- });- expect(res.statusCode).toBe(200);- const payload = JSON.parse(res.payload);- expect(payload).toHaveProperty("secret");- return payload.secret as TRawSecretWithId;-};--const deleteSecret = async (dto: { key: string }) => {- const res = await testServer.inject({- method: "DELETE",- url: `/api/v3/secrets/raw/${dto.key}`,- headers: {- authorization: `Bearer ${jwtAuthToken}`- },- body: {- workspaceId: seedData1.projectV3.id,- environment: seedData1.environment.slug,- secretPath: TEST_PATH- }- });- expect(res.statusCode).toBe(200);-};--const searchSecretMetadata = async (dto: { operator: "and" | "or"; filters: { key: string; value: string }[] }) => {- const queryString = qs.stringify({- projectId: seedData1.projectV3.id,- operator: dto.operator,- filters: dto.filters.map((filter) => ({ ...filter, operator: "is" }))- });- const res = await testServer.inject({- method: "GET",- url: `/api/v1/dashboard/secrets-by-metadata?${queryString}`,- headers: {- authorization: `Bearer ${jwtAuthToken}`- }- });- expect(res.statusCode).toBe(200);- return JSON.parse(res.payload).secrets as TMetadataSearchResult;-};--describe("Dashboard - search secrets by metadata", async () => {- const secretKeys = {- a: "E2E_METADATA_SEARCH_A",- b: "E2E_METADATA_SEARCH_B",- c: "E2E_METADATA_SEARCH_C"- };-- let secretAId = "";- let secretBId = "";- let secretCId = "";-- beforeAll(async () => {- // A -> env=prod, team=backend | B -> env=prod, team=frontend | C -> env=staging, team=backend- const [secretA, secretB, secretC] = await Promise.all([- createSecretWithMetadata({- key: secretKeys.a,- metadata: [- { key: ENV_KEY, value: "prod" },- { key: TEAM_KEY, value: "backend" }- ]- }),- createSecretWithMetadata({- key: secretKeys.b,- metadata: [- { key: ENV_KEY, value: "prod" },- { key: TEAM_KEY, value: "frontend" }- ]- }),- createSecretWithMetadata({- key: secretKeys.c,- metadata: [- { key: ENV_KEY, value: "staging" },- { key: TEAM_KEY, value: "backend" }- ]- })- ]);-- secretAId = secretA.id;- secretBId = secretB.id;- secretCId = secretC.id;- });-- afterAll(() => Promise.all(Object.values(secretKeys).map((key) => deleteSecret({ key }))));-- test("OR operator returns secrets matching any condition", async () => {- const secrets = await searchSecretMetadata({- operator: "or",- filters: [- { key: ENV_KEY, value: "prod" },- { key: TEAM_KEY, value: "backend" }- ]- });-- const matchedIds = secrets.map((secret) => secret.secretId);- // A (env=prod & team=backend), B (env=prod), C (team=backend) all match at least one condition- expect(matchedIds).toEqual(expect.arrayContaining([secretAId, secretBId, secretCId]));-- // B only matched env=prod, so it should not carry the team=backend pair- const secretB = secrets.find((secret) => secret.secretId === secretBId);- expect(secretB?.metadata).toEqual(expect.arrayContaining([{ key: ENV_KEY, value: "prod" }]));- expect(secretB?.metadata).toEqual(expect.not.arrayContaining([{ key: TEAM_KEY, value: "frontend" }]));- });-- test("AND operator returns only secrets matching every condition", async () => {- const secrets = await searchSecretMetadata({- operator: "and",- filters: [- { key: ENV_KEY, value: "prod" },- { key: TEAM_KEY, value: "backend" }- ]- });-- const matchedIds = secrets.map((secret) => secret.secretId);- // only A has BOTH env=prod and team=backend- expect(matchedIds).toEqual(expect.arrayContaining([secretAId]));- expect(matchedIds).toEqual(expect.not.arrayContaining([secretBId, secretCId]));-- const secretA = secrets.find((secret) => secret.secretId === secretAId);- expect(secretA?.metadata).toEqual(- expect.arrayContaining([- { key: ENV_KEY, value: "prod" },- { key: TEAM_KEY, value: "backend" }- ])- );-- // enriched fields used by the dashboard UI to group + render + navigate- expect(secretA?.secretKey).toBe(secretKeys.a);- expect(secretA?.environment).toBe(seedData1.environment.slug);- expect(secretA?.secretPath).toBe(TEST_PATH);- });-- test("single condition returns only exact matches", async () => {- const secrets = await searchSecretMetadata({- operator: "and",- filters: [{ key: ENV_KEY, value: "staging" }]- });-- const matchedIds = secrets.map((secret) => secret.secretId);- // only C has env=staging- expect(matchedIds).toEqual(expect.arrayContaining([secretCId]));- expect(matchedIds).toEqual(expect.not.arrayContaining([secretAId, secretBId]));- });-});--// distinctive keys so the org-wide search only ever matches the secrets seeded by this block-const ENC_ENV_KEY = "e2e-search-enc-env";-const ENC_TEAM_KEY = "e2e-search-enc-team";--describe("Dashboard - search secrets by encrypted metadata", async () => {- const secretKeys = {- d: "E2E_METADATA_SEARCH_ENC_D",- e: "E2E_METADATA_SEARCH_ENC_E",- f: "E2E_METADATA_SEARCH_ENC_F"- };-- let secretDId = "";- let secretEId = "";- let secretFId = "";-- beforeAll(async () => {- // D -> env=prod, team=payments (both encrypted)- // E -> env=prod (plaintext) + team=payments (encrypted) — mixed, exercises the and-across-storage path- // F -> env=staging, team=billing (both encrypted)- const [secretD, secretE, secretF] = await Promise.all([- createSecretWithMetadata({- key: secretKeys.d,- metadata: [- { key: ENC_ENV_KEY, value: "prod", isEncrypted: true },- { key: ENC_TEAM_KEY, value: "payments", isEncrypted: true }- ]- }),- createSecretWithMetadata({- key: secretKeys.e,- metadata: [- { key: ENC_ENV_KEY, value: "prod", isEncrypted: false },- { key: ENC_TEAM_KEY, value: "payments", isEncrypted: true }- ]- }),- createSecretWithMetadata({- key: secretKeys.f,- metadata: [- { key: ENC_ENV_KEY, value: "staging", isEncrypted: true },- { key: ENC_TEAM_KEY, value: "billing", isEncrypted: true }- ]- })- ]);-- secretDId = secretD.id;- secretEId = secretE.id;- secretFId = secretF.id;- });-- afterAll(() => Promise.all(Object.values(secretKeys).map((key) => deleteSecret({ key }))));-- test("OR matches encrypted values by decrypting server-side", async () => {- const secrets = await searchSecretMetadata({- operator: "or",- filters: [- { key: ENC_ENV_KEY, value: "prod" },- { key: ENC_TEAM_KEY, value: "payments" }- ]- });-- const matchedIds = secrets.map((secret) => secret.secretId);- // D and E both hold env=prod / team=payments; F (staging/billing) matches neither- expect(matchedIds).toEqual(expect.arrayContaining([secretDId, secretEId]));- expect(matchedIds).toEqual(expect.not.arrayContaining([secretFId]));-- // the decrypted value is surfaced in the response, not the ciphertext- const secretD = secrets.find((secret) => secret.secretId === secretDId);- expect(secretD?.metadata).toEqual(expect.arrayContaining([{ key: ENC_ENV_KEY, value: "prod" }]));- });-- test("AND matches every condition, including across mixed plaintext + encrypted rows", async () => {- const secrets = await searchSecretMetadata({- operator: "and",- filters: [- { key: ENC_ENV_KEY, value: "prod" },- { key: ENC_TEAM_KEY, value: "payments" }- ]- });-- const matchedIds = secrets.map((secret) => secret.secretId);- // D (both encrypted) and E (env plaintext + team encrypted) satisfy both conditions; F does not- expect(matchedIds).toEqual(expect.arrayContaining([secretDId, secretEId]));- expect(matchedIds).toEqual(expect.not.arrayContaining([secretFId]));-- const secretE = secrets.find((secret) => secret.secretId === secretEId);- expect(secretE?.metadata).toEqual(- expect.arrayContaining([- { key: ENC_ENV_KEY, value: "prod" },- { key: ENC_TEAM_KEY, value: "payments" }- ])- );- });-- test("does not match a non-matching encrypted value", async () => {- const secrets = await searchSecretMetadata({- operator: "and",- filters: [{ key: ENC_TEAM_KEY, value: "billing" }]- });-- const matchedIds = secrets.map((secret) => secret.secretId);- // only F has team=billing- expect(matchedIds).toEqual(expect.arrayContaining([secretFId]));- expect(matchedIds).toEqual(expect.not.arrayContaining([secretDId, secretEId]));- });-});diff --git a/tests/suites/secretmanager/metadata/filter_test.go b/tests/suites/secretmanager/metadata/filter_test.gonew file mode 100644index 0000000000..4147ef6a2f--- /dev/null+++ b/tests/suites/secretmanager/metadata/filter_test.go@@ -0,0 +1,68 @@+package metadata_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/spec"+ "github.com/stretchr/testify/require"+)++func TestSecretMetadata_ListFilter(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should not match encrypted metadata in the v4 metadata filter while the dashboard search does", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ createWithMetadata(t, proj, "PLAIN", plain("env", "prod"))+ createWithMetadata(t, proj, "ENCRYPTED", encrypted("env", "prod"))++ // Action+ status, keys, body := listFiltered(t, proj, "key=env,value=prod")++ // Assert+ require.Equalf(t, http.StatusOK, status, "filtered list returned %s", body)+ require.Equal(t, []string{"PLAIN"}, keys)+ require.ElementsMatch(t, []string{"PLAIN", "ENCRYPTED"}, keysOf(searchDashboard(t, tn.Admin, proj, "and", [2]string{"env", "prod"})))+ })++ t.Run("should return every secret when a metadata filter has only a key", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `[BUG?] A pair without a value is dropped while parsing, which leaves no filter+ at all, so the list is not narrowed. A later fix updates this claim.`)++ // Setup+ proj := fixture.NewProject(t, h.NewTenant(t), fixture.WithProjectType("secret-manager"))+ createWithMetadata(t, proj, "LABELLED", plain("env", "prod"))+ createWithMetadata(t, proj, "UNLABELLED")++ // Action+ status, keys, body := listFiltered(t, proj, "key=env")++ // Assert+ require.Equalf(t, http.StatusOK, status, "filtered list returned %s", body)+ require.ElementsMatch(t, []string{"LABELLED", "UNLABELLED"}, keys)+ })++ t.Run("should refuse more than 10 filter pairs", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj := fixture.NewProject(t, h.NewTenant(t), fixture.WithProjectType("secret-manager"))+ createWithMetadata(t, proj, "LABELLED", plain("k0", "v0"))++ // Action+ status, keys, body := listFiltered(t, proj, filterPairs(11))++ // Assert+ require.Equalf(t, http.StatusUnprocessableEntity, status, "filtered list returned %s", body)+ require.Contains(t, string(body), "You can only filter by up to 10 metadata fields")+ require.Empty(t, keys)+ })+}diff --git a/tests/suites/secretmanager/metadata/helpers_test.go b/tests/suites/secretmanager/metadata/helpers_test.gonew file mode 100644index 0000000000..7faedc494c--- /dev/null+++ b/tests/suites/secretmanager/metadata/helpers_test.go@@ -0,0 +1,137 @@+package metadata_test++import (+ "context"+ "fmt"+ "net/http"+ "strings"+ "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 metadata as an anonymous struct; an identical alias is+// assignable to it.+type entry = struct {+ IsEncrypted *bool `json:"isEncrypted,omitempty"`+ Key string `json:"key"`+ Value *string `json:"value,omitempty"`+}++func plain(key, value string) entry { return entry{Key: key, Value: &value} }++func encrypted(key, value string) entry {+ return entry{Key: key, Value: &value, IsEncrypted: new(true)}+}++// createWithMetadata creates a secret at the dev root.+func createWithMetadata(t *testing.T, proj *fixture.Project, key string, metadata ...entry) {+ t.Helper()+ body := api.CreateSecretV4JSONRequestBody{ProjectId: proj.ID, Environment: "dev", SecretValue: "v"}+ if len(metadata) > 0 {+ body.SecretMetadata = &metadata+ }+ res, err := proj.Tenant().Admin.API.CreateSecretV4WithResponse(t.Context(), key, body)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "creating %s returned %d: %s", key, res.StatusCode(), apierr.Body(res.Body))+ created, err := res.JSON200.AsCreateSecretV4200JSONResponseBody0()+ require.NoError(t, err)+ require.NotEmptyf(t, created.Secret.Id, "creating %s was not applied: %s", key, res.Body)+}++// metadataOf reads a secret's metadata as key to value.+func metadataOf(t *testing.T, proj *fixture.Project, key string) map[string]string {+ t.Helper()+ res, err := proj.Tenant().Admin.API.GetSecretByNameV4WithResponse(t.Context(), key, &api.GetSecretByNameV4Params{+ ProjectId: proj.ID, Environment: new("dev"),+ })+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "reading %s returned %d: %s", key, res.StatusCode(), apierr.Body(res.Body))+ out := map[string]string{}+ if res.JSON200.Secret.SecretMetadata != nil {+ for _, m := range *res.JSON200.Secret.SecretMetadata {+ v := ""+ if m.Value != nil {+ v = *m.Value+ }+ out[m.Key] = v+ }+ }+ return out+}++type match struct {+ Environment string+ Path string+ Metadata map[string]string+}++// searchDashboard runs the dashboard metadata search. Its filters are nested qs+// parameters the generated client cannot express, so they are appended to the query.+func searchDashboard(t *testing.T, pr *harness.Principal, proj *fixture.Project, operator string, filters ...[2]string) map[string]match {+ t.Helper()+ appendFilters := func(_ context.Context, req *http.Request) error {+ q := req.URL.Query()+ q.Set("operator", operator)+ for i, f := range filters {+ q.Set(fmt.Sprintf("filters[%d][key]", i), f[0])+ q.Set(fmt.Sprintf("filters[%d][value]", i), f[1])+ q.Set(fmt.Sprintf("filters[%d][operator]", i), "is")+ }+ req.URL.RawQuery = q.Encode()+ return nil+ }+ res, err := pr.API.SearchSecretsByMetadataWithResponse(t.Context(), &api.SearchSecretsByMetadataParams{ProjectId: proj.ID}, appendFilters)+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "searching by metadata returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ out := map[string]match{}+ for _, s := range res.JSON200.Secrets {+ md := map[string]string{}+ for _, m := range s.Metadata {+ v := ""+ if m.Value != nil {+ v = *m.Value+ }+ md[m.Key] = v+ }+ out[s.SecretKey] = match{Environment: s.Environment, Path: s.SecretPath, Metadata: md}+ }+ return out+}++func keysOf(matches map[string]match) []string {+ out := []string{}+ for k := range matches {+ out = append(out, k)+ }+ return out+}++// listFiltered lists dev's root through the v4 metadataFilter.+func listFiltered(t *testing.T, proj *fixture.Project, filter string) (int, []string, []byte) {+ t.Helper()+ res, err := proj.Tenant().Admin.API.ListSecretsV4WithResponse(t.Context(), &api.ListSecretsV4Params{+ ProjectId: &proj.ID, Environment: new("dev"), MetadataFilter: &filter,+ })+ require.NoError(t, err)+ keys := []string{}+ if res.JSON200 != nil {+ for _, s := range res.JSON200.Secrets {+ keys = append(keys, s.SecretKey)+ }+ }+ return res.StatusCode(), keys, res.Body+}++// filterPairs builds a metadataFilter with n distinct key and value pairs.+func filterPairs(n int) string {+ out := make([]string, n)+ for i := range out {+ out[i] = fmt.Sprintf("key=k%d,value=v%d", i, i)+ }+ return strings.Join(out, "|")+}diff --git a/tests/suites/secretmanager/metadata/main_test.go b/tests/suites/secretmanager/metadata/main_test.gonew file mode 100644index 0000000000..1f8b16663d--- /dev/null+++ b/tests/suites/secretmanager/metadata/main_test.go@@ -0,0 +1,9 @@+package metadata_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/metadata/search_test.go b/tests/suites/secretmanager/metadata/search_test.gonew file mode 100644index 0000000000..37d2c44d36--- /dev/null+++ b/tests/suites/secretmanager/metadata/search_test.go@@ -0,0 +1,129 @@+package metadata_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++func TestSecretMetadata_DashboardSearch(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ // A is env=prod and team=backend, B is env=prod and team=frontend, C is+ // env=staging and team=backend.+ seedPlain := func(t *testing.T, proj *fixture.Project) {+ t.Helper()+ createWithMetadata(t, proj, "SECRET_A", plain("env", "prod"), plain("team", "backend"))+ createWithMetadata(t, proj, "SECRET_B", plain("env", "prod"), plain("team", "frontend"))+ createWithMetadata(t, proj, "SECRET_C", plain("env", "staging"), plain("team", "backend"))+ }++ // D is all encrypted, E mixes a plaintext env with an encrypted team, F is all+ // encrypted with other values.+ seedEncrypted := func(t *testing.T, proj *fixture.Project) {+ t.Helper()+ createWithMetadata(t, proj, "SECRET_D", encrypted("env", "prod"), encrypted("team", "payments"))+ createWithMetadata(t, proj, "SECRET_E", plain("env", "prod"), encrypted("team", "payments"))+ createWithMetadata(t, proj, "SECRET_F", encrypted("env", "staging"), encrypted("team", "billing"))+ }++ t.Run("should return secrets matching any condition, with only the matching pairs, when the operator is or", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ seedPlain(t, proj)++ // Action+ matches := searchDashboard(t, tn.Admin, proj, "or", [2]string{"env", "prod"}, [2]string{"team", "backend"})++ // Assert+ require.ElementsMatch(t, []string{"SECRET_A", "SECRET_B", "SECRET_C"}, keysOf(matches))+ require.Equal(t, map[string]string{"env": "prod"}, matches["SECRET_B"].Metadata)+ })++ t.Run("should return only secrets matching every condition, with where they live, when the operator is and", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ seedPlain(t, proj)++ // Action+ matches := searchDashboard(t, tn.Admin, proj, "and", [2]string{"env", "prod"}, [2]string{"team", "backend"})++ // Assert+ require.Equal(t, []string{"SECRET_A"}, keysOf(matches))+ a := matches["SECRET_A"]+ require.Equal(t, map[string]string{"env": "prod", "team": "backend"}, a.Metadata)+ require.Equal(t, "dev", a.Environment)+ require.Equal(t, "/", a.Path)+ })++ t.Run("should return only exact matches for a single condition", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ seedPlain(t, proj)++ // Action+ matches := searchDashboard(t, tn.Admin, proj, "and", [2]string{"env", "staging"})++ // Assert+ require.Equal(t, []string{"SECRET_C"}, keysOf(matches))+ })++ t.Run("should match encrypted values and return them decrypted when the operator is or", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ seedEncrypted(t, proj)++ // Action+ matches := searchDashboard(t, tn.Admin, proj, "or", [2]string{"env", "prod"}, [2]string{"team", "payments"})++ // Assert+ require.ElementsMatch(t, []string{"SECRET_D", "SECRET_E"}, keysOf(matches))+ require.Equal(t, "prod", matches["SECRET_D"].Metadata["env"])+ })++ t.Run("should match every condition across plaintext and encrypted values when the operator is and", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ seedEncrypted(t, proj)++ // Action+ matches := searchDashboard(t, tn.Admin, proj, "and", [2]string{"env", "prod"}, [2]string{"team", "payments"})++ // Assert+ require.ElementsMatch(t, []string{"SECRET_D", "SECRET_E"}, keysOf(matches))+ require.Equal(t, map[string]string{"env": "prod", "team": "payments"}, matches["SECRET_E"].Metadata)+ })++ t.Run("should not match an encrypted value that differs", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ seedEncrypted(t, proj)++ // Action+ matches := searchDashboard(t, tn.Admin, proj, "and", [2]string{"team", "billing"})++ // Assert+ require.Equal(t, []string{"SECRET_F"}, keysOf(matches))+ })+}diff --git a/tests/suites/secretmanager/metadata/write_test.go b/tests/suites/secretmanager/metadata/write_test.gonew file mode 100644index 0000000000..59ded2faf1--- /dev/null+++ b/tests/suites/secretmanager/metadata/write_test.go@@ -0,0 +1,77 @@+package metadata_test++import (+ "net/http"+ "strings"+ "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 TestSecretMetadata_Write(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ create := func(t *testing.T, proj *fixture.Project, metadata entry) *api.CreateSecretV4Response {+ t.Helper()+ res, err := proj.Tenant().Admin.API.CreateSecretV4WithResponse(t.Context(), "LABELLED", api.CreateSecretV4JSONRequestBody{+ ProjectId: proj.ID, Environment: "dev", SecretValue: "v", SecretMetadata: &[]entry{metadata},+ })+ require.NoError(t, err)+ return res+ }++ t.Run("should refuse a metadata key over 255 characters and create nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj := fixture.NewProject(t, h.NewTenant(t), fixture.WithProjectType("secret-manager"))++ // Action+ res := create(t, proj, plain(strings.Repeat("k", 256), "v"))++ // Assert+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "creating returned %s", res.Body)+ require.Contains(t, string(res.Body), "String must contain at most 255 character(s)")+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))+ })++ t.Run("should refuse a metadata value over 1020 characters and create nothing", func(t *testing.T) {+ t.Parallel()++ // Setup+ proj := fixture.NewProject(t, h.NewTenant(t), fixture.WithProjectType("secret-manager"))++ // Action+ res := create(t, proj, plain("k", strings.Repeat("v", 1021)))++ // Assert+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "creating returned %s", res.Body)+ require.Contains(t, string(res.Body), "String must contain at most 1020 character(s)")+ require.Empty(t, secretmanager.ListSecrets(t, proj, "dev"))+ })++ t.Run("should replace the metadata set on update", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ createWithMetadata(t, proj, "LABELLED", plain("dropped", "1"), plain("changed", "2"))+ replacement := []entry{plain("changed", "3"), plain("added", "4")}++ // Action+ res, err := tn.Admin.API.UpdateSecretV4WithResponse(t.Context(), "LABELLED", api.UpdateSecretV4JSONRequestBody{+ ProjectId: proj.ID, Environment: "dev", SecretMetadata: &replacement,+ })++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "updating returned %s", res.Body)+ require.Equal(t, map[string]string{"changed": "3", "added": "4"}, metadataOf(t, proj, "LABELLED"))+ })+}