Skip to content

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

test(e2e): cover folder access tiers, grant rules and lifecycle

varonix96473a960b4e
diff --git a/tests/suites/secretmanager/folderaccess/grant_test.go b/tests/suites/secretmanager/folderaccess/grant_test.go
new file mode 100644
index 0000000000..0fa82cfab6
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/grant_test.go
@@ -0,0 +1,473 @@
+package folderaccess_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/Infisical/infisical/tests/internal/wait"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+// kind builds the principals a grant rule is checked against, once per actor type the
+// folder access routes serve.
+type kind struct {
+ name string
+ label string
+ // member joins the project with the given roles.
+ member func(t *testing.T, proj *fixture.Project, roles ...string) *harness.Principal
+ // orgOnly is in the organization but not the project.
+ orgOnly func(t *testing.T, tn *harness.Tenant) *harness.Principal
+ // joinGroup puts the principal in an organization group.
+ joinGroup func(t *testing.T, tn *harness.Tenant, g *fixture.Group, pr *harness.Principal)
+ // setRoles replaces the principal's project roles.
+ setRoles func(t *testing.T, proj *fixture.Project, pr *harness.Principal, roles ...string)
+ kind harness.Kind
+}
+
+var kinds = []kind{
+ {
+ name: "user",
+ label: "User",
+ member: func(t *testing.T, proj *fixture.Project, roles ...string) *harness.Principal {
+ return proj.NewUser(t, fixture.WithRoles(roles...))
+ },
+ orgOnly: func(t *testing.T, tn *harness.Tenant) *harness.Principal { return tn.NewUser(t) },
+ joinGroup: func(t *testing.T, _ *harness.Tenant, g *fixture.Group, pr *harness.Principal) { g.AddUser(t, pr) },
+ setRoles: setUserRoles,
+ kind: harness.User,
+ },
+ {
+ name: "machine identity",
+ label: "Machine identity",
+ member: func(t *testing.T, proj *fixture.Project, roles ...string) *harness.Principal {
+ return proj.NewMachineIdentity(t, fixture.WithRoles(roles...))
+ },
+ orgOnly: func(t *testing.T, tn *harness.Tenant) *harness.Principal { return tn.NewMachineIdentity(t) },
+ joinGroup: addIdentityToGroup,
+ setRoles: setIdentityRoles,
+ kind: harness.MachineIdentity,
+ },
+}
+
+func TestFolderAccess_GrantRules(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ for _, k := range kinds {
+ t.Run(fmt.Sprintf("should refuse granting or updating a %s with the project admin role", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ admin := k.member(t, proj, "admin")
+
+ // Action
+ created := grantAs(t, proj.Tenant().Admin, proj, admin, at("/app"), secretmanager.FolderRead, nil)
+ updated := updateGrant(t, proj.Tenant().Admin, proj, admin, at("/app"), map[string]any{"permission": "edit"})
+
+ // Assert
+ want := fmt.Sprintf("%s with ID '%s' has the project admin role. Project admins already have full access "+
+ "to every folder, so folder access cannot be granted to them.", k.label, admin.ID)
+ require.Equalf(t, http.StatusBadRequest, created.status, "granting: %s", created.body)
+ require.Equal(t, want, created.message)
+ require.Equalf(t, http.StatusBadRequest, updated.status, "updating: %s", updated.body)
+ require.Equal(t, want, updated.message)
+ require.Empty(t, grantsOf(t, proj, admin))
+ })
+
+ t.Run(fmt.Sprintf("should refuse granting a %s whose admin role comes from a group", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ groupAdmin := k.orgOnly(t, tn)
+ group := fixture.NewGroup(t, tn)
+ k.joinGroup(t, tn, group, groupAdmin)
+ proj.GrantGroup(t, group, "admin")
+
+ // Action
+ res := grantAs(t, tn.Admin, proj, groupAdmin, at("/app"), secretmanager.FolderRead, nil)
+
+ // Assert
+ require.Equalf(t, http.StatusBadRequest, res.status, "granting: %s", res.body)
+ require.Contains(t, res.message, "has the project admin role")
+ require.Empty(t, grantsOf(t, proj, groupAdmin))
+ listed := listAccess(t, tn.Admin, proj, k.kind, at("/app"), page{})
+ require.True(t, listed.with[groupAdmin.ID.String()].IsProjectAdmin)
+ require.NotContains(t, listed.without, groupAdmin.ID.String())
+ })
+
+ t.Run(fmt.Sprintf("should return not found for a %s that is not a project member", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ outsider := k.orgOnly(t, tn)
+
+ // Action
+ res := grantAs(t, tn.Admin, proj, outsider, at("/app"), secretmanager.FolderRead, nil)
+
+ // Assert
+ require.Equalf(t, http.StatusNotFound, res.status, "granting: %s", res.body)
+ require.Equal(t, fmt.Sprintf("%s with ID '%s' is not a member of project with ID '%s'", k.label, outsider.ID, proj.ID),
+ res.message)
+ require.Empty(t, grantsOf(t, proj, outsider))
+ })
+
+ t.Run(fmt.Sprintf("should keep a %s's full-access grant permanent on create and on every update path", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := k.member(t, proj, "no-access")
+ admin := proj.Tenant().Admin
+ expiring := map[string]any{"type": temporary("1h", time.Now())}
+
+ // Action
+ temporaryCreate := grantAs(t, admin, proj, member, at("/app"), secretmanager.FolderFullAccess, expiring)
+ permanentCreate := grantAs(t, admin, proj, member, at("/app"), secretmanager.FolderFullAccess, nil)
+ addExpiry := updateGrant(t, admin, proj, member, at("/app"), expiring)
+ lowered := updateGrant(t, admin, proj, member, at("/app"), map[string]any{"permission": "manage", "type": expiring["type"]})
+ promoted := updateGrant(t, admin, proj, member, at("/app"), map[string]any{"permission": "full-access"})
+ promotedPermanent := updateGrant(t, admin, proj, member, at("/app"),
+ map[string]any{"permission": "full-access", "type": map[string]any{"isTemporary": false}})
+
+ // Assert
+ const msg = "Folder access with the 'full-access' role cannot be temporary. A full-access holder can grant " +
+ "folder access to others, and those grants would outlive the expiration. Grant 'full-access' permanently, " +
+ "or use the 'manage' role for temporary access."
+ require.Equal(t, http.StatusBadRequest, temporaryCreate.status)
+ require.Equal(t, msg, temporaryCreate.message)
+ require.Equalf(t, http.StatusOK, permanentCreate.status, "creating permanently: %s", permanentCreate.body)
+ require.Equal(t, http.StatusBadRequest, addExpiry.status)
+ require.Equal(t, msg, addExpiry.message)
+ require.Equalf(t, http.StatusOK, lowered.status, "lowering to a temporary manage: %s", lowered.body)
+ require.Equal(t, http.StatusBadRequest, promoted.status)
+ require.Equal(t, msg, promoted.message)
+ require.Equalf(t, http.StatusOK, promotedPermanent.status, "promoting permanently: %s", promotedPermanent.body)
+ stored := grantsOf(t, proj, member)
+ require.Len(t, stored, 1)
+ require.Equal(t, "full-access", stored[0].Permission)
+ require.False(t, stored[0].IsTemporary)
+ })
+
+ t.Run(fmt.Sprintf("should refuse a duplicate grant for a %s and keep the first", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := k.member(t, proj, "no-access")
+ secretmanager.GrantFolderAccess(t, proj, member, at("/app"), secretmanager.FolderRead)
+
+ // Action
+ res := grantAs(t, proj.Tenant().Admin, proj, member, at("/app"), secretmanager.FolderEdit, nil)
+
+ // Assert
+ require.Equalf(t, http.StatusBadRequest, res.status, "granting again: %s", res.body)
+ require.Equal(t, fmt.Sprintf("%s with ID '%s' already has folder access on this folder with the 'edit' role "+
+ "or another one. Update the existing access instead of creating a new one.", k.label, member.ID), res.message)
+ stored := grantsOf(t, proj, member)
+ require.Len(t, stored, 1)
+ require.Equal(t, "read", stored[0].Permission)
+ })
+
+ t.Run(fmt.Sprintf("should refuse a %s grant on an unknown path, unknown environment or malformed path", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ member := k.member(t, proj, "no-access")
+ admin := proj.Tenant().Admin
+
+ // Action
+ unknownPath := grantAs(t, admin, proj, member, at("/missing"), secretmanager.FolderRead, nil)
+ unknownEnv := grantAs(t, admin, proj, member, secretmanager.Location{Env: "qa", Path: "/"}, secretmanager.FolderRead, nil)
+ malformed := grantAs(t, admin, proj, member, at("/bad name!"), secretmanager.FolderRead, nil)
+
+ // Assert
+ require.Equal(t, http.StatusNotFound, unknownPath.status)
+ require.Equal(t, fmt.Sprintf("Folder at path '/missing' not found in environment with slug 'dev' in project with ID '%s'", proj.ID),
+ unknownPath.message)
+ require.Equal(t, http.StatusNotFound, unknownEnv.status)
+ require.Equalf(t, http.StatusBadRequest, malformed.status, "granting on a malformed path: %s", malformed.body)
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+
+ t.Run(fmt.Sprintf("should normalize a trailing slash on a %s grant and its revoke", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ folderID := newFolder(t, proj, "dev", "/app")
+ member := k.member(t, proj, "no-access")
+
+ // Action
+ created := grantAs(t, proj.Tenant().Admin, proj, member, at("/app/"), secretmanager.FolderRead, nil)
+ revoked := revokeGrant(t, proj.Tenant().Admin, proj, member, at("/app/"))
+
+ // Assert
+ require.Equalf(t, http.StatusOK, created.status, "granting: %s", created.body)
+ require.Equal(t, "/app", created.grant.SecretPath)
+ require.Equal(t, folderID.String(), created.grant.FolderID)
+ require.Equalf(t, http.StatusOK, revoked.status, "revoking: %s", revoked.body)
+ require.Equal(t, created.grant.ID, revoked.grant.ID)
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+
+ t.Run(fmt.Sprintf("should update a %s's grant between temporary and permanent and revoke it once", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ folderID := newFolder(t, proj, "dev", "/app")
+ member := k.member(t, proj, "no-access")
+ admin := proj.Tenant().Admin
+ created := grantAs(t, admin, proj, member, at("/app"), secretmanager.FolderRead, nil)
+ require.Equalf(t, http.StatusOK, created.status, "granting: %s", created.body)
+ start := time.Now().UTC().Truncate(time.Millisecond)
+
+ // Action
+ toTemporary := updateGrant(t, admin, proj, member, at("/app"),
+ map[string]any{"permission": "edit", "type": temporary("4h", start)})
+ toPermanent := updateGrant(t, admin, proj, member, at("/app"), map[string]any{"type": map[string]any{"isTemporary": false}})
+ empty := updateGrant(t, admin, proj, member, at("/app"), nil)
+ revoked := revokeGrant(t, admin, proj, member, at("/app"))
+ revokedAgain := revokeGrant(t, admin, proj, member, at("/app"))
+
+ // Assert
+ require.Equal(t, grant{
+ ID: created.grant.ID, FolderID: folderID.String(), Permission: "read", Environment: "dev", SecretPath: "/app",
+ }, created.grant)
+ require.Equalf(t, http.StatusOK, toTemporary.status, "making it temporary: %s", toTemporary.body)
+ require.Equal(t, "edit", toTemporary.grant.Permission)
+ require.True(t, toTemporary.grant.IsTemporary)
+ require.Equal(t, "relative", *toTemporary.grant.TemporaryMode)
+ require.Equal(t, "4h", *toTemporary.grant.TemporaryRange)
+ require.True(t, start.Equal(*toTemporary.grant.TemporaryAccessStartTime))
+ require.Equal(t, 4*time.Hour, toTemporary.grant.TemporaryAccessEndTime.Sub(*toTemporary.grant.TemporaryAccessStartTime))
+ require.Equalf(t, http.StatusOK, toPermanent.status, "making it permanent: %s", toPermanent.body)
+ require.Equal(t, grant{
+ ID: created.grant.ID, FolderID: folderID.String(), Permission: "edit", Environment: "dev", SecretPath: "/app",
+ }, toPermanent.grant)
+ require.Equal(t, http.StatusUnprocessableEntity, empty.status)
+ require.Equalf(t, http.StatusOK, revoked.status, "revoking: %s", revoked.body)
+ require.Equal(t, created.grant.ID, revoked.grant.ID)
+ require.Equal(t, http.StatusNotFound, revokedAgain.status)
+ require.Equal(t, fmt.Sprintf("No folder access found for %s with ID '%s' on the folder at path '/app' in environment with slug 'dev'",
+ strings.ToLower(k.label), member.ID), revokedAgain.message)
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+
+ t.Run(fmt.Sprintf("should list every grant a %s holds across the project, sorted by path", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/alpha")
+ secretmanager.CreateFolder(t, proj, "dev", "/beta")
+ member := k.member(t, proj, "no-access")
+ before := grantsOf(t, proj, member)
+ start := time.Now().UTC().Truncate(time.Millisecond)
+ secretmanager.GrantFolderAccess(t, proj, member, at("/beta"), secretmanager.FolderList)
+ temp := grantAs(t, proj.Tenant().Admin, proj, member, at("/alpha"), secretmanager.FolderManage,
+ map[string]any{"type": temporary("30m", start)})
+ require.Equalf(t, http.StatusOK, temp.status, "granting temporarily: %s", temp.body)
+
+ // Action
+ got := grantsOf(t, proj, member)
+
+ // Assert
+ require.Empty(t, before)
+ require.Len(t, got, 2)
+ require.Equal(t, []string{"/alpha", "/beta"}, []string{got[0].SecretPath, got[1].SecretPath})
+ require.Equal(t, "manage", got[0].Permission)
+ require.True(t, got[0].IsTemporary)
+ require.Equal(t, "30m", *got[0].TemporaryRange)
+ require.True(t, start.Equal(*got[0].TemporaryAccessStartTime))
+ require.Equal(t, "list", got[1].Permission)
+ require.False(t, got[1].IsTemporary)
+ require.Nil(t, got[1].TemporaryRange)
+ })
+
+ t.Run(fmt.Sprintf("should grant and revoke a %s on the root folder", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ member := k.member(t, proj, "no-access")
+
+ // Action
+ created := grantAs(t, proj.Tenant().Admin, proj, member, at("/"), secretmanager.FolderRead, nil)
+ revoked := revokeGrant(t, proj.Tenant().Admin, proj, member, at("/"))
+
+ // Assert
+ require.Equalf(t, http.StatusOK, created.status, "granting on the root: %s", created.body)
+ require.Equal(t, "/", created.grant.SecretPath)
+ require.Equalf(t, http.StatusOK, revoked.status, "revoking on the root: %s", revoked.body)
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+
+ t.Run(fmt.Sprintf("should still revoke a %s's grant after they become a project admin, but not update it", k.name), func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := k.member(t, proj, "member")
+ secretmanager.GrantFolderAccess(t, proj, member, at("/app"), secretmanager.FolderRead)
+ k.setRoles(t, proj, member, "admin")
+
+ // Action
+ updated := updateGrant(t, proj.Tenant().Admin, proj, member, at("/app"), map[string]any{"permission": "edit"})
+ revoked := revokeGrant(t, proj.Tenant().Admin, proj, member, at("/app"))
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, updated.status)
+ require.Contains(t, updated.message, "has the project admin role")
+ require.Equalf(t, http.StatusOK, revoked.status, "revoking: %s", revoked.body)
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+ }
+
+ t.Run("should refuse an unknown tier", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+
+ // Action
+ res := grantAs(t, proj.Tenant().Admin, proj, member, at("/app"), secretmanager.FolderTier("owner"), nil)
+
+ // Assert
+ require.Equalf(t, http.StatusUnprocessableEntity, res.status, "granting an unknown tier: %s", res.body)
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+
+ t.Run("should not resolve a folder grant through the legacy user privilege endpoint", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := proj.NewUser(t, fixture.WithRoles("no-access"))
+ created := grantAs(t, proj.Tenant().Admin, proj, member, at("/app"), secretmanager.FolderRead, nil)
+ require.Equalf(t, http.StatusOK, created.status, "granting: %s", created.body)
+
+ // Action
+ res, err := proj.Tenant().Admin.API.GetUserProjectAdditionalPrivilegeWithResponse(t.Context(), created.grant.ID)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusNotFound, res.StatusCode(), "reading the grant as a privilege: %s", res.Body)
+ })
+
+ t.Run("should refuse a grant on a reserved replication folder", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ member := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ importID := secretmanager.CreateImport(t, proj, "dev", secretmanager.Location{Env: "prod", Path: "/"}, secretmanager.Replicated())
+ reserved := at("/__reserve_replication_" + importID)
+
+ // Action
+ res, err := wait.For(t.Context(), func(context.Context) (reply, bool, error) {
+ got := grantAs(t, proj.Tenant().Admin, proj, member, reserved, secretmanager.FolderRead, nil)
+ return got, got.status != http.StatusNotFound, nil
+ })
+
+ // Assert
+ require.NoError(t, err, "waiting for the replication folder to exist")
+ require.Equalf(t, http.StatusBadRequest, res.status, "granting on the reserved folder: %s", res.body)
+ require.Equal(t, "Folder access cannot be granted on a reserved system folder.", res.message)
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+
+ t.Run("should refuse a caller without project access before resolving the folder, so paths cannot be probed", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := proj.NewUser(t, fixture.WithPrincipalName("member"))
+ outsider := tn.NewUser(t, harness.WithName("outsider"))
+
+ // Action
+ statuses := map[string]int{}
+ for name, loc := range map[string]secretmanager.Location{
+ "existing path": at("/app"),
+ "missing path": at("/missing"),
+ "missing env": {Env: "qa", Path: "/app"},
+ } {
+ statuses["list on "+name] = listUsersAs(t, outsider, proj, loc, "").status
+ statuses["grant on "+name] = grantAs(t, outsider, proj, member, loc, secretmanager.FolderRead, nil).status
+ }
+ grantsStatus, _ := listGrantsAs(t, outsider, proj, member)
+ statuses["list a member's grants"] = grantsStatus
+
+ // Assert
+ for name, status := range statuses {
+ require.Equal(t, http.StatusForbidden, status, name)
+ }
+ require.Empty(t, grantsOf(t, proj, member))
+ })
+}
+
+func addIdentityToGroup(t *testing.T, tn *harness.Tenant, g *fixture.Group, pr *harness.Principal) {
+ t.Helper()
+ res, err := tn.Admin.API.AddMachineIdentityToGroupWithResponse(t.Context(), g.ID.String(), pr.ID.String())
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "adding %s to group %s: %s", pr.Name, g.Name, apierr.Body(res.Body))
+}
+
+func setIdentityRoles(t *testing.T, proj *fixture.Project, pr *harness.Principal, roles ...string) {
+ t.Helper()
+ res, err := proj.Tenant().Admin.API.UpdateProjectIdentityMembershipWithBodyWithResponse(t.Context(), proj.ID, pr.ID.String(),
+ "application/json", bytes.NewReader(rolesBody(t, roles)))
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "setting %s's roles: %s", pr.Name, apierr.Body(res.Body))
+}
+
+func setUserRoles(t *testing.T, proj *fixture.Project, pr *harness.Principal, roles ...string) {
+ t.Helper()
+ membership, err := proj.Tenant().Admin.API.GetProjectMembershipByUserIdWithResponse(t.Context(), uuid.MustParse(proj.ID), pr.ID)
+ require.NoError(t, err)
+ require.NotNilf(t, membership.JSON200, "reading %s's membership returned %d: %s", pr.Name, membership.StatusCode(),
+ apierr.Body(membership.Body))
+ res, err := proj.Tenant().Admin.API.UpdateProjectMembershipWithBodyWithResponse(t.Context(), proj.ID,
+ membership.JSON200.Membership.Id.String(), "application/json", bytes.NewReader(rolesBody(t, roles)))
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "setting %s's roles: %s", pr.Name, apierr.Body(res.Body))
+}
+
+func rolesBody(t *testing.T, roles []string) []byte {
+ t.Helper()
+ items := make([]map[string]any, 0, len(roles))
+ for _, r := range roles {
+ items = append(items, map[string]any{"role": r, "isTemporary": false})
+ }
+ raw, err := json.Marshal(map[string]any{"roles": items})
+ require.NoError(t, err)
+ return raw
+}
diff --git a/tests/suites/secretmanager/folderaccess/helpers_test.go b/tests/suites/secretmanager/folderaccess/helpers_test.go
new file mode 100644
index 0000000000..c6a9d5a59f
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/helpers_test.go
@@ -0,0 +1,311 @@
+package folderaccess_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "path"
+ "testing"
+ "time"
+
+ "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 newProject(t *testing.T, tn *harness.Tenant) *fixture.Project {
+ t.Helper()
+ return fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+}
+
+func at(secretPath string) secretmanager.Location {
+ return secretmanager.Location{Env: "dev", Path: secretPath}
+}
+
+// grant is a folder grant as the folder access routes return it.
+type grant struct {
+ ID string `json:"id"`
+ FolderID string `json:"folderId"`
+ Permission string `json:"permission"`
+ Environment string `json:"environment"`
+ SecretPath string `json:"secretPath"`
+ IsTemporary bool `json:"isTemporary"`
+ TemporaryMode *string `json:"temporaryMode"`
+ TemporaryRange *string `json:"temporaryRange"`
+ TemporaryAccessStartTime *time.Time `json:"temporaryAccessStartTime"`
+ TemporaryAccessEndTime *time.Time `json:"temporaryAccessEndTime"`
+}
+
+// reply is one folder access write: its status, its message on failure and the grant on
+// success.
+type reply struct {
+ status int
+ body []byte
+ message string
+ grant grant
+}
+
+func decodeReply(t *testing.T, status int, body []byte) reply {
+ t.Helper()
+ out := reply{status: status, body: body}
+ var parsed struct {
+ Message any `json:"message"`
+ FolderAccess grant `json:"folderAccess"`
+ }
+ require.NoErrorf(t, json.Unmarshal(body, &parsed), "decoding %d: %s", status, apierr.Body(body))
+ if msg, ok := parsed.Message.(string); ok {
+ out.message = msg
+ }
+ out.grant = parsed.FolderAccess
+ return out
+}
+
+func temporary(rangeText string, start time.Time) map[string]any {
+ return map[string]any{
+ "isTemporary": true,
+ "temporaryMode": "relative",
+ "temporaryRange": rangeText,
+ "temporaryAccessStartTime": start.UTC().Format(time.RFC3339Nano),
+ }
+}
+
+// grantAs creates a folder grant for target through the route for its kind. extra adds
+// or overrides body fields, such as a temporary type.
+func grantAs(t *testing.T, actor *harness.Principal, proj *fixture.Project, target *harness.Principal,
+ loc secretmanager.Location, tier secretmanager.FolderTier, extra map[string]any) reply {
+ t.Helper()
+ body := map[string]any{"environmentSlug": loc.Env, "secretPath": loc.Path, "permission": string(tier)}
+ for k, v := range extra {
+ body[k] = v
+ }
+ raw, err := json.Marshal(body)
+ require.NoError(t, err)
+
+ if target.Kind == harness.MachineIdentity {
+ res, err := actor.API.CreateIdentityFolderAccessWithBodyWithResponse(t.Context(), proj.ID, target.ID,
+ "application/json", bytes.NewReader(raw))
+ require.NoError(t, err)
+ return decodeReply(t, res.StatusCode(), res.Body)
+ }
+ res, err := actor.API.CreateUserFolderAccessWithBodyWithResponse(t.Context(), proj.ID, target.ID,
+ "application/json", bytes.NewReader(raw))
+ require.NoError(t, err)
+ return decodeReply(t, res.StatusCode(), res.Body)
+}
+
+func updateGrant(t *testing.T, actor *harness.Principal, proj *fixture.Project, target *harness.Principal,
+ loc secretmanager.Location, fields map[string]any) reply {
+ t.Helper()
+ body := map[string]any{"environmentSlug": loc.Env, "secretPath": loc.Path}
+ for k, v := range fields {
+ body[k] = v
+ }
+ raw, err := json.Marshal(body)
+ require.NoError(t, err)
+
+ if target.Kind == harness.MachineIdentity {
+ res, err := actor.API.UpdateIdentityFolderAccessWithBodyWithResponse(t.Context(), proj.ID, target.ID,
+ "application/json", bytes.NewReader(raw))
+ require.NoError(t, err)
+ return decodeReply(t, res.StatusCode(), res.Body)
+ }
+ res, err := actor.API.UpdateUserFolderAccessWithBodyWithResponse(t.Context(), proj.ID, target.ID,
+ "application/json", bytes.NewReader(raw))
+ require.NoError(t, err)
+ return decodeReply(t, res.StatusCode(), res.Body)
+}
+
+func revokeGrant(t *testing.T, actor *harness.Principal, proj *fixture.Project, target *harness.Principal,
+ loc secretmanager.Location) reply {
+ t.Helper()
+ raw, err := json.Marshal(map[string]any{"environmentSlug": loc.Env, "secretPath": loc.Path})
+ require.NoError(t, err)
+
+ if target.Kind == harness.MachineIdentity {
+ res, err := actor.API.DeleteIdentityFolderAccessWithBodyWithResponse(t.Context(), proj.ID, target.ID,
+ "application/json", bytes.NewReader(raw))
+ require.NoError(t, err)
+ return decodeReply(t, res.StatusCode(), res.Body)
+ }
+ res, err := actor.API.DeleteUserFolderAccessWithBodyWithResponse(t.Context(), proj.ID, target.ID,
+ "application/json", bytes.NewReader(raw))
+ require.NoError(t, err)
+ return decodeReply(t, res.StatusCode(), res.Body)
+}
+
+// grantsOf is every folder grant target holds in the project, as the administrator
+// reads them.
+func grantsOf(t *testing.T, proj *fixture.Project, target *harness.Principal) []grant {
+ t.Helper()
+ status, body := listGrantsAs(t, proj.Tenant().Admin, proj, target)
+ require.Equalf(t, http.StatusOK, status, "listing %s's grants: %s", target.Name, apierr.Body(body))
+ var parsed struct {
+ FolderAccess []grant `json:"folderAccess"`
+ }
+ require.NoError(t, json.Unmarshal(body, &parsed))
+ return parsed.FolderAccess
+}
+
+func listGrantsAs(t *testing.T, actor *harness.Principal, proj *fixture.Project, target *harness.Principal) (int, []byte) {
+ t.Helper()
+ if target.Kind == harness.MachineIdentity {
+ res, err := actor.API.ListIdentityFolderAccessWithResponse(t.Context(), proj.ID, target.ID)
+ require.NoError(t, err)
+ return res.StatusCode(), res.Body
+ }
+ res, err := actor.API.ListUserFolderAccessWithResponse(t.Context(), proj.ID, target.ID)
+ require.NoError(t, err)
+ return res.StatusCode(), res.Body
+}
+
+// newFolder creates a folder and returns its ID, which rename, move and delete take.
+func newFolder(t *testing.T, proj *fixture.Project, env, folderPath string) uuid.UUID {
+ 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
+}
+
+// listing is one v4 list with values requested: its status and each secret's value by
+// key.
+type listing struct {
+ status int
+ body []byte
+ values map[string]string
+}
+
+func listSecrets(t *testing.T, pr *harness.Principal, proj *fixture.Project, secretPath string, recursive bool) listing {
+ t.Helper()
+ params := &api.ListSecretsV4Params{
+ ProjectId: &proj.ID,
+ Environment: new("dev"),
+ SecretPath: &secretPath,
+ ViewSecretValue: new(api.ListSecretsV4ParamsViewSecretValueTrue),
+ }
+ if recursive {
+ params.Recursive = new(api.ListSecretsV4ParamsRecursiveTrue)
+ }
+ res, err := pr.API.ListSecretsV4WithResponse(t.Context(), params)
+ require.NoError(t, err)
+ out := listing{status: res.StatusCode(), body: res.Body, values: map[string]string{}}
+ if res.JSON200 != nil {
+ for _, s := range res.JSON200.Secrets {
+ out.values[s.SecretKey] = s.SecretValue
+ }
+ }
+ return out
+}
+
+func createSecret(t *testing.T, pr *harness.Principal, proj *fixture.Project, secretPath, name, value string) int {
+ t.Helper()
+ res, err := pr.API.CreateSecretV4WithResponse(t.Context(), name, api.CreateSecretV4JSONRequestBody{
+ ProjectId: proj.ID, Environment: "dev", SecretPath: &secretPath, SecretValue: value,
+ })
+ require.NoError(t, err)
+ return res.StatusCode()
+}
+
+// holder is one row of a folder's access list.
+type holder struct {
+ ID string
+ IsProjectAdmin bool
+ Roles []string
+ Grant *grant
+}
+
+// accessList is a folder's access list for one actor type: who has access, who has
+// none, and the roster total.
+type accessList struct {
+ status int
+ body []byte
+ with map[string]holder
+ without map[string]holder
+ total int
+}
+
+type page struct {
+ offset, limit *int
+ search *string
+}
+
+func listUsersAs(t *testing.T, actor *harness.Principal, proj *fixture.Project, loc secretmanager.Location, search string) accessList {
+ t.Helper()
+ p := page{}
+ if search != "" {
+ p.search = &search
+ }
+ return listAccess(t, actor, proj, harness.User, loc, p)
+}
+
+func listAccess(t *testing.T, actor *harness.Principal, proj *fixture.Project, kind harness.Kind, loc secretmanager.Location, p page) accessList {
+ t.Helper()
+ var status int
+ var body []byte
+ if kind == harness.MachineIdentity {
+ res, err := actor.API.ListFolderAccessIdentitiesWithResponse(t.Context(), proj.ID, &api.ListFolderAccessIdentitiesParams{
+ EnvironmentSlug: loc.Env, SecretPath: loc.Path, Offset: p.offset, Limit: p.limit, Search: p.search,
+ })
+ require.NoError(t, err)
+ status, body = res.StatusCode(), res.Body
+ } else {
+ res, err := actor.API.ListFolderAccessUsersWithResponse(t.Context(), proj.ID, &api.ListFolderAccessUsersParams{
+ EnvironmentSlug: loc.Env, SecretPath: loc.Path, Offset: p.offset, Limit: p.limit, Search: p.search,
+ })
+ require.NoError(t, err)
+ status, body = res.StatusCode(), res.Body
+ }
+
+ out := accessList{status: status, body: body, with: map[string]holder{}, without: map[string]holder{}}
+ if status != http.StatusOK {
+ return out
+ }
+ type row struct {
+ UserID string `json:"userId"`
+ IdentityID string `json:"identityId"`
+ Membership struct {
+ IsProjectAdmin bool `json:"isProjectAdmin"`
+ Roles []struct {
+ Slug string `json:"slug"`
+ } `json:"roles"`
+ } `json:"membership"`
+ FolderRBACAccess *grant `json:"folderRBACAccess"`
+ }
+ var parsed struct {
+ Users []row `json:"users"`
+ UsersWithoutAccess []row `json:"usersWithoutAccess"`
+ Identities []row `json:"identities"`
+ IdentitiesWithoutAccess []row `json:"identitiesWithoutAccess"`
+ TotalCount int `json:"totalCount"`
+ }
+ require.NoError(t, json.Unmarshal(body, &parsed))
+ toHolders := func(rows []row, into map[string]holder) {
+ for _, r := range rows {
+ h := holder{ID: r.UserID + r.IdentityID, IsProjectAdmin: r.Membership.IsProjectAdmin, Grant: r.FolderRBACAccess, Roles: []string{}}
+ for _, role := range r.Membership.Roles {
+ h.Roles = append(h.Roles, role.Slug)
+ }
+ require.NotContainsf(t, into, h.ID, "%s is listed twice", h.ID)
+ into[h.ID] = h
+ }
+ }
+ toHolders(append(parsed.Users, parsed.Identities...), out.with)
+ toHolders(append(parsed.UsersWithoutAccess, parsed.IdentitiesWithoutAccess...), out.without)
+ out.total = parsed.TotalCount
+ return out
+}
+
+// secretsAt is what the administrator sees in one dev folder, by key.
+func secretsAt(t *testing.T, proj *fixture.Project, secretPath string) map[string]string {
+ t.Helper()
+ got := listSecrets(t, proj.Tenant().Admin, proj, secretPath, false)
+ require.Equalf(t, http.StatusOK, got.status, "listing dev:%s as the admin: %s", secretPath, apierr.Body(got.body))
+ return got.values
+}
diff --git a/tests/suites/secretmanager/folderaccess/license_test.go b/tests/suites/secretmanager/folderaccess/license_test.go
new file mode 100644
index 0000000000..a0b68fe828
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/license_test.go
@@ -0,0 +1,86 @@
+package folderaccess_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/license"
+ "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 TestFolderAccess_License(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ withoutFolderRBAC := license.Enterprise().Without(license.SecretsFolderRBAC)
+ const planMessage = "Failed to access folder access controls due to plan restriction. Upgrade your Infisical plan."
+
+ t.Run("should refuse a grant create when the plan does not include folder rbac", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t, harness.WithPlan(withoutFolderRBAC))
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+
+ // Action
+ res := grantAs(t, tn.Admin, proj, pr, at("/app"), secretmanager.FolderRead, nil)
+
+ // Assert
+ require.Equalf(t, http.StatusBadRequest, res.status, "granting: %s", res.body)
+ require.Equal(t, planMessage, res.message)
+ tn.SetPlan(t, license.Enterprise())
+ require.Empty(t, grantsOf(t, proj, pr))
+ })
+
+ t.Run("should keep an existing grant working after a downgrade", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "plaintext", secretmanager.WithPath("/app"))
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, pr, at("/app"), secretmanager.FolderRead)
+ tn.SetPlan(t, withoutFolderRBAC)
+
+ // Action
+ got := listSecrets(t, pr, proj, "/app", false)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, got.status, "listing after the downgrade: %s", got.body)
+ require.Equal(t, map[string]string{"API_KEY": "plaintext"}, got.values)
+ })
+
+ t.Run("should refuse listing and revoking grants after a downgrade, naming the plan (license gate on a read path)", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, pr, at("/app"), secretmanager.FolderRead)
+ tn.SetPlan(t, withoutFolderRBAC)
+
+ // Action
+ listed := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{})
+ grantsStatus, grantsBody := listGrantsAs(t, tn.Admin, proj, pr)
+ revoked := revokeGrant(t, tn.Admin, proj, pr, at("/app"))
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, listed.status)
+ require.Contains(t, string(listed.body), planMessage)
+ require.Equal(t, http.StatusBadRequest, grantsStatus)
+ require.Contains(t, string(grantsBody), planMessage)
+ require.Equal(t, http.StatusBadRequest, revoked.status)
+ require.Equal(t, planMessage, revoked.message)
+ tn.SetPlan(t, license.Enterprise())
+ require.Len(t, grantsOf(t, proj, pr), 1)
+ })
+}
diff --git a/tests/suites/secretmanager/folderaccess/lifecycle_test.go b/tests/suites/secretmanager/folderaccess/lifecycle_test.go
new file mode 100644
index 0000000000..74bf38a3cc
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/lifecycle_test.go
@@ -0,0 +1,304 @@
+package folderaccess_test
+
+import (
+ "net/http"
+ "slices"
+ "testing"
+ "time"
+
+ "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/Infisical/infisical/tests/internal/wait"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFolderAccess_Lifecycle(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should let a member granted by a full-access holder read the folder", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "plaintext", secretmanager.WithPath("/app"))
+ owner := proj.NewUser(t, fixture.WithPrincipalName("owner"), fixture.WithRoles("no-access"))
+ reader := proj.NewUser(t, fixture.WithPrincipalName("reader"), fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, owner, at("/app"), secretmanager.FolderFullAccess)
+ granted := grantAs(t, owner, proj, reader, at("/app"), secretmanager.FolderRead, nil)
+ require.Equalf(t, http.StatusOK, granted.status, "granting as the full-access holder: %s", granted.body)
+
+ // Action
+ got := listSecrets(t, reader, proj, "/app", false)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, got.status, "listing as the granted member: %s", got.body)
+ require.Equal(t, map[string]string{"API_KEY": "plaintext"}, got.values)
+ })
+
+ t.Run("should give no access at once when a temporary grant starts in the past and has already ended", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "plaintext", secretmanager.WithPath("/app"))
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ start := time.Now().Add(-2 * time.Hour)
+ created := grantAs(t, proj.Tenant().Admin, proj, pr, at("/app"), secretmanager.FolderRead,
+ map[string]any{"type": temporary("1h", start)})
+ require.Equalf(t, http.StatusOK, created.status, "granting: %s", created.body)
+
+ // Action
+ got := listSecrets(t, pr, proj, "/app", false)
+
+ // Assert
+ require.Equalf(t, http.StatusForbidden, got.status, "listing with an ended grant: %s", got.body)
+ require.NotContains(t, string(got.body), "plaintext")
+ require.True(t, created.grant.IsTemporary)
+ require.NotNil(t, created.grant.TemporaryAccessEndTime)
+ require.WithinDuration(t, start.Add(time.Hour), *created.grant.TemporaryAccessEndTime, time.Second)
+ })
+
+ t.Run("should make the grant follow a rename of its parent and a move of the folder", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ parentID := newFolder(t, proj, "dev", "/a")
+ secretmanager.CreateFolder(t, proj, "dev", "/a/b")
+ secretmanager.CreateFolder(t, proj, "dev", "/dest")
+ secretmanager.CreateSecret(t, proj, "dev", "B_KEY", "b-value", secretmanager.WithPath("/a/b"))
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, pr, at("/a/b"), secretmanager.FolderRead)
+ renamed, err := proj.Tenant().Admin.API.UpdateSecretFolderWithResponse(t.Context(), parentID.String(),
+ api.UpdateSecretFolderJSONRequestBody{ProjectId: proj.ID, Environment: "dev", Name: "renamed", Path: new("/")})
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, renamed.StatusCode(), "renaming: %s", apierr.Body(renamed.Body))
+ afterRename := listSecrets(t, pr, proj, "/renamed/b", false)
+
+ // Action
+ moved, err := proj.Tenant().Admin.API.MoveSecretFolderWithResponse(t.Context(), api.MoveSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, FolderId: parentID, DestinationEnvironment: "dev", DestinationPath: new("/dest"),
+ })
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, moved.StatusCode(), "moving: %s", apierr.Body(moved.Body))
+
+ // Assert
+ require.Equalf(t, http.StatusOK, afterRename.status, "listing after the rename: %s", afterRename.body)
+ require.Equal(t, map[string]string{"B_KEY": "b-value"}, afterRename.values)
+ wait.Until(t, "the grant to apply at the moved path", func() bool {
+ return listSecrets(t, pr, proj, "/dest/renamed/b", false).values["B_KEY"] == "b-value"
+ })
+ stored := grantsOf(t, proj, pr)
+ require.Len(t, stored, 1)
+ require.Equal(t, "/dest/renamed/b", stored[0].SecretPath)
+ })
+
+ t.Run("should remove the grant when its folder or a parent is deleted", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/leaf")
+ secretmanager.CreateFolder(t, proj, "dev", "/parent/child")
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, pr, at("/leaf"), secretmanager.FolderRead)
+ secretmanager.GrantFolderAccess(t, proj, pr, at("/parent/child"), secretmanager.FolderRead)
+
+ // Action
+ for _, name := range []string{"leaf", "parent"} {
+ res, err := proj.Tenant().Admin.API.DeleteSecretFolderWithResponse(t.Context(), name, api.DeleteSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, Environment: "dev", Path: new("/"), ForceDelete: new(true),
+ })
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deleting %s: %s", name, apierr.Body(res.Body))
+ }
+
+ // Assert
+ require.Empty(t, grantsOf(t, proj, pr))
+ })
+
+ t.Run("should let a member without manage-access rename, move and delete folders that hold someone else's grant", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ ids := map[string]string{}
+ for _, p := range []string{"/rename-me", "/describe-me", "/batch-me", "/move-me", "/move-parent/child",
+ "/delete-me", "/delete-parent/child", "/dest"} {
+ ids[p] = newFolder(t, proj, "dev", p).String()
+ }
+ ids["/move-parent"] = folderIDAt(t, proj, "/", "move-parent")
+ holder := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ for _, p := range []string{"/rename-me", "/describe-me", "/batch-me", "/move-me", "/move-parent/child",
+ "/delete-me", "/delete-parent/child"} {
+ secretmanager.GrantFolderAccess(t, proj, holder, at(p), secretmanager.FolderRead)
+ }
+ member := proj.NewUser(t, fixture.WithPrincipalName("member"))
+ statuses := map[string]int{}
+
+ // Action
+ update := func(op, id, name string, description *string) {
+ res, err := member.API.UpdateSecretFolderWithResponse(t.Context(), id, api.UpdateSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, Environment: "dev", Name: name, Path: new("/"), Description: description,
+ })
+ require.NoError(t, err)
+ statuses[op] = res.StatusCode()
+ }
+ update("rename", ids["/rename-me"], "renamed", nil)
+ update("describe", ids["/describe-me"], "describe-me", new("changed by a member"))
+ batch := api.UpdateSecretFoldersBatchJSONRequestBody{ProjectId: proj.ID}
+ batch.Folders = slices.Grow(batch.Folders, 1)[:1]
+ batch.Folders[0].Id, batch.Folders[0].Environment, batch.Folders[0].Name, batch.Folders[0].Path =
+ ids["/batch-me"], "dev", "batch-renamed", new("/")
+ batched, err := member.API.UpdateSecretFoldersBatchWithResponse(t.Context(), batch)
+ require.NoError(t, err)
+ statuses["batch rename"] = batched.StatusCode()
+ for op, p := range map[string]string{"move": "/move-me", "move a parent": "/move-parent"} {
+ res, err := member.API.MoveSecretFolderWithResponse(t.Context(), api.MoveSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, FolderId: uuid.MustParse(ids[p]), DestinationEnvironment: "dev", DestinationPath: new("/dest"),
+ })
+ require.NoError(t, err)
+ statuses[op] = res.StatusCode()
+ }
+ for op, name := range map[string]string{"delete": "delete-me", "delete a parent": "delete-parent"} {
+ res, err := member.API.DeleteSecretFolderWithResponse(t.Context(), name, api.DeleteSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, Environment: "dev", Path: new("/"), ForceDelete: new(true),
+ })
+ require.NoError(t, err)
+ statuses[op] = res.StatusCode()
+ }
+
+ // Assert
+ for op, status := range statuses {
+ require.Equal(t, http.StatusOK, status, op)
+ }
+ paths := []string{}
+ for _, g := range grantsOf(t, proj, holder) {
+ paths = append(paths, g.SecretPath)
+ }
+ require.ElementsMatch(t, []string{"/renamed", "/describe-me", "/batch-renamed", "/dest/move-me", "/dest/move-parent/child"}, paths)
+ })
+
+ t.Run("should let a machine identity without manage-access delete a folder that holds someone else's grant", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ holder := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, holder, at("/app"), secretmanager.FolderRead)
+ member := proj.NewMachineIdentity(t, fixture.WithRoles("member"))
+
+ // Action
+ res, err := member.API.DeleteSecretFolderWithResponse(t.Context(), "app", api.DeleteSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, Environment: "dev", Path: new("/"),
+ })
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "deleting: %s", apierr.Body(res.Body))
+ require.Empty(t, grantsOf(t, proj, holder))
+ })
+
+ t.Run("should let a full-access holder rename and move their granted folder", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ folderID := newFolder(t, proj, "dev", "/mine")
+ secretmanager.CreateFolder(t, proj, "dev", "/dest")
+ owner := proj.NewUser(t, fixture.WithPrincipalName("owner"))
+ secretmanager.GrantFolderAccess(t, proj, owner, at("/mine"), secretmanager.FolderFullAccess)
+
+ // Action
+ renamed, err := owner.API.UpdateSecretFolderWithResponse(t.Context(), folderID.String(), api.UpdateSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, Environment: "dev", Name: "mine-renamed", Path: new("/"),
+ })
+ require.NoError(t, err)
+ moved, err := owner.API.MoveSecretFolderWithResponse(t.Context(), api.MoveSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, FolderId: folderID, DestinationEnvironment: "dev", DestinationPath: new("/dest"),
+ })
+ require.NoError(t, err)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, renamed.StatusCode(), "renaming: %s", apierr.Body(renamed.Body))
+ require.Equalf(t, http.StatusOK, moved.StatusCode(), "moving: %s", apierr.Body(moved.Body))
+ stored := grantsOf(t, proj, owner)
+ require.Len(t, stored, 1)
+ require.Equal(t, "/dest/mine-renamed", stored[0].SecretPath)
+ })
+
+ t.Run("should remove a group-only member's access when they leave the group and keep it for a direct member", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "plaintext", secretmanager.WithPath("/app"))
+ groupOnly := tn.NewUser(t, harness.WithName("grouponly"))
+ direct := proj.NewUser(t, fixture.WithPrincipalName("direct"), fixture.WithRoles("no-access"))
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, groupOnly, direct)
+ proj.GrantGroup(t, group, "no-access")
+ secretmanager.GrantFolderAccess(t, proj, groupOnly, at("/app"), secretmanager.FolderRead)
+ secretmanager.GrantFolderAccess(t, proj, direct, at("/app"), secretmanager.FolderRead)
+ require.Equal(t, "plaintext", listSecrets(t, groupOnly, proj, "/app", false).values["API_KEY"])
+
+ // Action
+ group.RemoveUser(t, groupOnly, direct)
+
+ // Assert
+ wait.Until(t, "the group-only member to lose access", func() bool {
+ return listSecrets(t, groupOnly, proj, "/app", false).status == http.StatusForbidden
+ })
+ require.Empty(t, grantsOf(t, proj, groupOnly))
+ require.Len(t, grantsOf(t, proj, direct), 1)
+ require.Equal(t, "plaintext", listSecrets(t, direct, proj, "/app", false).values["API_KEY"])
+ })
+
+ t.Run("should ignore a grant once its holder becomes a project admin", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("member"))
+ secretmanager.GrantFolderAccess(t, proj, pr, at("/app"), secretmanager.FolderRead)
+ require.Equal(t, http.StatusForbidden, createSecret(t, pr, proj, "/app", "BEFORE", "v"),
+ "the read grant replaces the member role's writes at /app")
+
+ // Action
+ setIdentityRoles(t, proj, pr, "admin")
+
+ // Assert
+ wait.Until(t, "the promoted admin to write at the granted folder", func() bool {
+ return createSecret(t, pr, proj, "/app", "AFTER", "v") == http.StatusOK
+ })
+ require.Equal(t, map[string]string{"AFTER": "v"}, secretsAt(t, proj, "/app"))
+ })
+}
+
+// folderIDAt finds a folder created implicitly as a parent, whose ID no create call
+// returned.
+func folderIDAt(t *testing.T, proj *fixture.Project, parent, name string) string {
+ t.Helper()
+ res, err := proj.Tenant().Admin.API.ListSecretFoldersWithResponse(t.Context(),
+ &api.ListSecretFoldersParams{ProjectId: proj.ID, Environment: "dev", Path: parent})
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "listing folders in %s returned %d: %s", parent, res.StatusCode(), apierr.Body(res.Body))
+ for _, f := range res.JSON200.Folders {
+ if f.Name == name {
+ return f.Id.String()
+ }
+ }
+ t.Fatalf("no folder %s under %s", name, parent)
+ return ""
+}
diff --git a/tests/suites/secretmanager/folderaccess/list_test.go b/tests/suites/secretmanager/folderaccess/list_test.go
new file mode 100644
index 0000000000..896c496248
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/list_test.go
@@ -0,0 +1,282 @@
+package folderaccess_test
+
+import (
+ "context"
+ "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 TestFolderAccess_List(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should split users by access, flag admins and annotate only the granted user", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := proj.NewUser(t, fixture.WithPrincipalName("member"))
+ noAccess := proj.NewUser(t, fixture.WithPrincipalName("noaccess"), fixture.WithRoles("no-access"))
+ groupOnly := tn.NewUser(t, harness.WithName("grouponly"))
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, groupOnly, member)
+ proj.GrantGroup(t, group, "member")
+ before := listUsersAs(t, tn.Admin, proj, at("/app"), "")
+
+ // Action
+ secretmanager.GrantFolderAccess(t, proj, noAccess, at("/app"), secretmanager.FolderRead)
+ after := listUsersAs(t, tn.Admin, proj, at("/app"), "")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, before.status, "listing: %s", before.body)
+ require.Equal(t, 4, before.total, "admin, member, no-access user and group-only user, each once")
+ require.True(t, before.with[tn.Admin.ID.String()].IsProjectAdmin)
+ require.NotContains(t, before.without, tn.Admin.ID.String())
+ require.Equal(t, holder{ID: member.ID.String(), Roles: []string{"member"}}, before.with[member.ID.String()])
+ require.Equal(t, holder{ID: groupOnly.ID.String(), Roles: []string{"member"}}, before.with[groupOnly.ID.String()])
+ require.Equal(t, holder{ID: noAccess.ID.String(), Roles: []string{"no-access"}}, before.without[noAccess.ID.String()])
+
+ require.Equal(t, before.total, after.total)
+ require.NotContains(t, after.without, noAccess.ID.String())
+ granted := after.with[noAccess.ID.String()]
+ require.Empty(t, granted.Roles)
+ require.NotNil(t, granted.Grant)
+ require.Equal(t, "read", granted.Grant.Permission)
+ require.Nil(t, after.with[member.ID.String()].Grant)
+ })
+
+ t.Run("should page users with a stable total and filter them by search", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := proj.NewUser(t, fixture.WithPrincipalName("member"))
+ proj.NewUser(t, fixture.WithPrincipalName("other"))
+ one := 1
+
+ // Action
+ seen := map[string]int{}
+ var totals []int
+ for offset := range 3 {
+ got := listAccess(t, tn.Admin, proj, harness.User, at("/app"), page{offset: &offset, limit: &one})
+ require.Equalf(t, http.StatusOK, got.status, "listing offset %d: %s", offset, got.body)
+ require.Equal(t, 1, len(got.with)+len(got.without))
+ for id := range got.with {
+ seen[id]++
+ }
+ for id := range got.without {
+ seen[id]++
+ }
+ totals = append(totals, got.total)
+ }
+ pastTheEnd := 13
+ past := listAccess(t, tn.Admin, proj, harness.User, at("/app"), page{offset: &pastTheEnd, limit: &one})
+ matching := listUsersAs(t, tn.Admin, proj, at("/app"), member.Email)
+ nonMatching := listUsersAs(t, tn.Admin, proj, at("/app"), "zzz-no-such-member")
+
+ // Assert
+ require.Equal(t, []int{3, 3, 3}, totals)
+ require.Len(t, seen, 3, "every user exactly once across the pages")
+ require.Empty(t, past.with)
+ require.Empty(t, past.without)
+ require.Equal(t, 3, past.total)
+ require.Contains(t, matching.with, member.ID.String())
+ require.Len(t, matching.with, 1)
+ require.Empty(t, nonMatching.with)
+ require.Equal(t, 0, nonMatching.total)
+ })
+
+ t.Run("should list identities once, flag admins and annotate only the granted one", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ admin := proj.NewMachineIdentity(t, fixture.WithRoles("admin"))
+ member := proj.NewMachineIdentity(t, fixture.WithRoles("member"))
+ noAccess := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ groupOnly := tn.NewMachineIdentity(t)
+ group := fixture.NewGroup(t, tn)
+ addIdentityToGroup(t, tn, group, groupOnly)
+ addIdentityToGroup(t, tn, group, member)
+ proj.GrantGroup(t, group, "member")
+ secretmanager.GrantFolderAccess(t, proj, member, at("/app"), secretmanager.FolderEdit)
+
+ // Action
+ got := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{})
+
+ // Assert
+ require.Equalf(t, http.StatusOK, got.status, "listing: %s", got.body)
+ require.Equal(t, 4, got.total)
+ require.True(t, got.with[admin.ID.String()].IsProjectAdmin)
+ require.NotContains(t, got.without, admin.ID.String())
+ require.NotNil(t, got.with[member.ID.String()].Grant)
+ require.Equal(t, "edit", got.with[member.ID.String()].Grant.Permission)
+ require.Equal(t, holder{ID: groupOnly.ID.String(), Roles: []string{"member"}}, got.with[groupOnly.ID.String()])
+ require.Equal(t, holder{ID: noAccess.ID.String(), Roles: []string{"no-access"}}, got.without[noAccess.ID.String()])
+ })
+
+ t.Run("should clear the annotation when the grant is revoked", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := proj.NewMachineIdentity(t, fixture.WithRoles("member"))
+ secretmanager.GrantFolderAccess(t, proj, member, at("/app"), secretmanager.FolderManage)
+ before := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{})
+
+ // Action
+ revoked := revokeGrant(t, tn.Admin, proj, member, at("/app"))
+ after := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{})
+
+ // Assert
+ require.Equalf(t, http.StatusOK, revoked.status, "revoking: %s", revoked.body)
+ require.NotNil(t, before.with[member.ID.String()].Grant)
+ require.Equal(t, "manage", before.with[member.ID.String()].Grant.Permission)
+ require.Contains(t, after.with, member.ID.String())
+ require.Nil(t, after.with[member.ID.String()].Grant)
+ require.Equal(t, before.total, after.total)
+ })
+
+ t.Run("should list, grant and find by search a user whose only project access is a group", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ groupOnly := tn.NewUser(t, harness.WithName("grouponly"))
+ group := fixture.NewGroup(t, tn)
+ group.AddUser(t, groupOnly)
+ proj.GrantGroup(t, group, "member")
+
+ // Action
+ granted := grantAs(t, tn.Admin, proj, groupOnly, at("/app"), secretmanager.FolderRead, nil)
+ listed := listUsersAs(t, tn.Admin, proj, at("/app"), "")
+ found := listUsersAs(t, tn.Admin, proj, at("/app"), "grouponly")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, granted.status, "granting: %s", granted.body)
+ require.NotNil(t, listed.with[groupOnly.ID.String()].Grant)
+ require.Equal(t, "read", listed.with[groupOnly.ID.String()].Grant.Permission)
+ require.Contains(t, found.with, groupOnly.ID.String())
+ require.Len(t, found.with, 1)
+ })
+
+ t.Run("should page and search identities with a stable total", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ named := proj.NewMachineIdentity(t, fixture.WithPrincipalName("findme-"+uuid.NewString()[:8]), fixture.WithRoles("member"))
+ proj.NewMachineIdentity(t, fixture.WithRoles("member"))
+ one, pastTheEnd := 1, 12
+
+ // Action
+ all := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{})
+ past := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{offset: &pastTheEnd, limit: &one})
+ found := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{search: &named.Name})
+ missing := "zzz-no-such-identity"
+ none := listAccess(t, tn.Admin, proj, harness.MachineIdentity, at("/app"), page{search: &missing})
+
+ // Assert
+ require.Equalf(t, http.StatusOK, all.status, "listing: %s", all.body)
+ require.Equal(t, 2, all.total)
+ require.Empty(t, past.with)
+ require.Equal(t, all.total, past.total)
+ require.Contains(t, found.with, named.ID.String())
+ require.Len(t, found.with, 1)
+ require.Empty(t, none.with)
+ require.Equal(t, 0, none.total)
+ })
+
+ t.Run("should refuse an access list for an unknown path, an unknown environment or an out-of-range limit", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ tooMany := 500
+
+ // Action
+ unknownPath := listUsersAs(t, tn.Admin, proj, at("/missing"), "")
+ unknownEnv := listUsersAs(t, tn.Admin, proj, secretmanager.Location{Env: "qa", Path: "/app"}, "")
+ outOfRange := listAccess(t, tn.Admin, proj, harness.User, at("/app"), page{limit: &tooMany})
+
+ // Assert
+ require.Equalf(t, http.StatusNotFound, unknownPath.status, "listing an unknown path: %s", unknownPath.body)
+ require.Equalf(t, http.StatusNotFound, unknownEnv.status, "listing an unknown environment: %s", unknownEnv.body)
+ require.Equalf(t, http.StatusUnprocessableEntity, outOfRange.status, "listing 500 at once: %s", outOfRange.body)
+ })
+
+ t.Run("should include a member's folder grants in their permission audit unless asked to leave them out", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ member := proj.NewUser(t, fixture.WithPrincipalName("member"))
+ granted := grantAs(t, tn.Admin, proj, member, at("/app"), secretmanager.FolderRead, nil)
+ require.Equalf(t, http.StatusOK, granted.status, "granting: %s", granted.body)
+ membershipID := membershipIDOf(t, proj, member)
+
+ // Action
+ withFolders := auditSources(t, proj, membershipID, nil)
+ withoutFolders := auditSources(t, proj, membershipID, map[string]string{"includeFolderPermissions": "false"})
+
+ // Assert
+ require.Contains(t, withFolders, granted.grant.ID)
+ require.NotContains(t, withoutFolders, granted.grant.ID)
+ require.NotEmpty(t, withoutFolders, "the member's role is still a source")
+ })
+
+}
+
+func membershipIDOf(t *testing.T, proj *fixture.Project, user *harness.Principal) string {
+ t.Helper()
+ res, err := proj.Tenant().Admin.API.GetProjectMembershipByUserIdWithResponse(t.Context(), uuid.MustParse(proj.ID), user.ID)
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "reading %s's membership returned %d: %s", user.Name, res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.Membership.Id.String()
+}
+
+// auditSources is the IDs of every source the permission audit names for a membership.
+func auditSources(t *testing.T, proj *fixture.Project, membershipID string, query map[string]string) []string {
+ t.Helper()
+ withQuery := func(_ context.Context, req *http.Request) error {
+ q := req.URL.Query()
+ for k, v := range query {
+ q.Set(k, v)
+ }
+ req.URL.RawQuery = q.Encode()
+ return nil
+ }
+ res, err := proj.Tenant().Admin.API.GetProjectMembershipPermissionAuditWithResponse(t.Context(), proj.ID, membershipID,
+ &api.GetProjectMembershipPermissionAuditParams{}, withQuery)
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "reading the permission audit returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ ids := []string{}
+ for _, source := range res.JSON200.Sources {
+ ids = append(ids, source.Id)
+ }
+ return ids
+}
diff --git a/tests/suites/secretmanager/folderaccess/main_test.go b/tests/suites/secretmanager/folderaccess/main_test.go
new file mode 100644
index 0000000000..8083eafa37
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/main_test.go
@@ -0,0 +1,9 @@
+package folderaccess_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/folderaccess/scope_test.go b/tests/suites/secretmanager/folderaccess/scope_test.go
new file mode 100644
index 0000000000..478a69d2f3
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/scope_test.go
@@ -0,0 +1,101 @@
+package folderaccess_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 TestFolderAccess_Scope(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should replace the base role at the granted path only", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/a/b")
+ secretmanager.CreateSecret(t, proj, "dev", "A_KEY", "a-value", secretmanager.WithPath("/a"))
+ secretmanager.CreateSecret(t, proj, "dev", "B_KEY", "b-value", secretmanager.WithPath("/a/b"))
+ member := proj.NewMachineIdentity(t, fixture.WithRoles("member"))
+ secretmanager.GrantFolderAccess(t, proj, member, at("/a"), secretmanager.FolderList)
+
+ // Action
+ granted := listSecrets(t, member, proj, "/a", false)
+ child := listSecrets(t, member, proj, "/a/b", false)
+
+ // Assert
+ require.Equalf(t, http.StatusForbidden, granted.status, "listing values at the granted path: %s", granted.body)
+ require.NotContains(t, string(granted.body), "a-value")
+ require.Equalf(t, http.StatusOK, child.status, "listing below the granted path: %s", child.body)
+ require.Equal(t, map[string]string{"B_KEY": "b-value"}, child.values)
+ })
+}
+
+func TestSecret_ListRecursive(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should list only the requested folder and its descendants when listing recursively from a subfolder", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/deep1/deep2")
+ secretmanager.CreateFolder(t, proj, "dev", "/other")
+ secretmanager.CreateSecret(t, proj, "dev", "ROOT", "root")
+ secretmanager.CreateSecret(t, proj, "dev", "DEEP1", "deep1", secretmanager.WithPath("/deep1"))
+ secretmanager.CreateSecret(t, proj, "dev", "DEEP2", "deep2", secretmanager.WithPath("/deep1/deep2"))
+ secretmanager.CreateSecret(t, proj, "dev", "OTHER", "other", secretmanager.WithPath("/other"))
+
+ // Action
+ got := listSecrets(t, tn.Admin, proj, "/deep1", true)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, got.status, "listing recursively: %s", got.body)
+ require.Equal(t, map[string]string{"DEEP1": "deep1", "DEEP2": "deep2"}, got.values)
+ })
+
+ t.Run("should list recursively only the granted subfolder for a grant-only user", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/a/b")
+ secretmanager.CreateSecret(t, proj, "dev", "IN_A", "secret-in-a", secretmanager.WithPath("/a"))
+ secretmanager.CreateSecret(t, proj, "dev", "IN_B", "secret-in-b", secretmanager.WithPath("/a/b"))
+ grantOnly := proj.NewUser(t, fixture.WithPrincipalName("granted"), fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, grantOnly, at("/a/b"), secretmanager.FolderRead)
+
+ // Action
+ got := listSecrets(t, grantOnly, proj, "/a", true)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, got.status, "listing recursively: %s", got.body)
+ require.Equal(t, map[string]string{"IN_B": "secret-in-b"}, got.values)
+ require.NotContains(t, string(got.body), "secret-in-a")
+ })
+
+ t.Run("should refuse a recursive list for a user with no access", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/a/b")
+ secretmanager.CreateSecret(t, proj, "dev", "IN_B", "secret-in-b", secretmanager.WithPath("/a/b"))
+ noAccess := proj.NewUser(t, fixture.WithPrincipalName("outsider"), fixture.WithRoles("no-access"))
+
+ // Action
+ got := listSecrets(t, noAccess, proj, "/a", true)
+
+ // Assert
+ require.Equalf(t, http.StatusForbidden, got.status, "listing recursively: %s", got.body)
+ require.NotContains(t, string(got.body), "secret-in-b")
+ })
+}
diff --git a/tests/suites/secretmanager/folderaccess/tier_test.go b/tests/suites/secretmanager/folderaccess/tier_test.go
new file mode 100644
index 0000000000..463ceea657
--- /dev/null
+++ b/tests/suites/secretmanager/folderaccess/tier_test.go
@@ -0,0 +1,191 @@
+package folderaccess_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "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/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+func TestFolderAccess_Tiers(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ // holder is a project identity with no base access and one tier on dev:/app, which
+ // holds API_KEY.
+ holder := func(t *testing.T, tier secretmanager.FolderTier) (*fixture.Project, *harness.Principal) {
+ t.Helper()
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "plaintext", secretmanager.WithPath("/app"))
+ pr := proj.NewMachineIdentity(t, fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, pr, at("/app"), tier)
+ return proj, pr
+ }
+
+ t.Run("should let a list holder see names but not values or write", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, pr := holder(t, secretmanager.FolderList)
+
+ // Action
+ withValues := listSecrets(t, pr, proj, "/app", false)
+ namesOnly, err := pr.API.ListSecretsV4WithResponse(t.Context(), &api.ListSecretsV4Params{
+ ProjectId: &proj.ID, Environment: new("dev"), SecretPath: new("/app"),
+ ViewSecretValue: new(api.ListSecretsV4ParamsViewSecretValueFalse),
+ })
+ created := createSecret(t, pr, proj, "/app", "NEW_KEY", "v")
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusForbidden, withValues.status, "listing with values: %s", withValues.body)
+ require.NotNilf(t, namesOnly.JSON200, "listing names returned %d: %s", namesOnly.StatusCode(), namesOnly.Body)
+ require.Len(t, namesOnly.JSON200.Secrets, 1)
+ require.Equal(t, "API_KEY", namesOnly.JSON200.Secrets[0].SecretKey)
+ require.True(t, namesOnly.JSON200.Secrets[0].SecretValueHidden)
+ require.NotContains(t, string(namesOnly.Body), "plaintext")
+ require.Equal(t, http.StatusForbidden, created)
+ require.Equal(t, map[string]string{"API_KEY": "plaintext"}, secretsAt(t, proj, "/app"))
+ })
+
+ t.Run("should let a read holder see values but not write", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, pr := holder(t, secretmanager.FolderRead)
+
+ // Action
+ got := listSecrets(t, pr, proj, "/app", false)
+ created := createSecret(t, pr, proj, "/app", "NEW_KEY", "v")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, got.status, "listing: %s", got.body)
+ require.Equal(t, map[string]string{"API_KEY": "plaintext"}, got.values)
+ require.Equal(t, http.StatusForbidden, created)
+ require.Equal(t, map[string]string{"API_KEY": "plaintext"}, secretsAt(t, proj, "/app"))
+ })
+
+ t.Run("should let an edit holder write secrets in the folder but not rotations", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj, pr := holder(t, secretmanager.FolderEdit)
+
+ // Action
+ inside := createSecret(t, pr, proj, "/app", "NEW_KEY", "v")
+ outside := createSecret(t, pr, proj, "/", "ROOT_KEY", "v")
+ rotation := createRotation(t, pr, proj, "/app")
+
+ // Assert
+ require.Equal(t, http.StatusOK, inside)
+ require.Equal(t, http.StatusForbidden, outside)
+ require.Equalf(t, http.StatusForbidden, rotation.StatusCode(), "creating a rotation: %s", rotation.Body)
+ require.Equal(t, map[string]string{"API_KEY": "plaintext", "NEW_KEY": "v"}, secretsAt(t, proj, "/app"))
+ require.Empty(t, secretsAt(t, proj, "/"))
+ })
+
+ t.Run("should let a manage holder write syncs and rotations in the folder where an edit holder cannot", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := newProject(t, tn)
+ secretmanager.CreateFolder(t, proj, "dev", "/app")
+ conn := fixture.NewAppConnection(t, tn, fixture.GitHubPATAppConnection)
+ manager, editor := tn.NewMachineIdentity(t), tn.NewMachineIdentity(t)
+ proj.Grant(t, manager, "member")
+ proj.Grant(t, editor, "member")
+ secretmanager.GrantFolderAccess(t, proj, manager, at("/app"), secretmanager.FolderManage)
+ secretmanager.GrantFolderAccess(t, proj, editor, at("/app"), secretmanager.FolderEdit)
+
+ // Action
+ byManager := createSync(t, manager, proj, conn, "/app")
+ byEditor := createSync(t, editor, proj, conn, "/app")
+ rotationByManager := createRotation(t, manager, proj, "/app")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, byManager.StatusCode(), "creating a sync as the manager: %s", byManager.Body)
+ require.Equalf(t, http.StatusForbidden, byEditor.StatusCode(), "creating a sync as the editor: %s", byEditor.Body)
+ require.NotEqualf(t, http.StatusForbidden, rotationByManager.StatusCode(),
+ "the manager passes the rotation permission check and fails only on the made-up connection: %s", rotationByManager.Body)
+ })
+
+ t.Run("should let a full-access holder grant others and delete folders inside the granted one but not the folder itself", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ proj := newProject(t, h.NewTenant(t))
+ secretmanager.CreateFolder(t, proj, "dev", "/app/child")
+ owner := proj.NewUser(t, fixture.WithPrincipalName("owner"), fixture.WithRoles("no-access"))
+ other := proj.NewUser(t, fixture.WithPrincipalName("other"), fixture.WithRoles("no-access"))
+ secretmanager.GrantFolderAccess(t, proj, owner, at("/app"), secretmanager.FolderFullAccess)
+ deleteAs := func(name, parent string) *api.DeleteSecretFolderResponse {
+ res, err := owner.API.DeleteSecretFolderWithResponse(t.Context(), name, api.DeleteSecretFolderJSONRequestBody{
+ ProjectId: proj.ID, Environment: "dev", Path: &parent,
+ })
+ require.NoError(t, err)
+ return res
+ }
+
+ // Action
+ granted := grantAs(t, owner, proj, other, at("/app"), secretmanager.FolderRead, nil)
+ child := deleteAs("child", "/app")
+ itself := deleteAs("app", "/")
+
+ // Assert
+ require.Equalf(t, http.StatusOK, granted.status, "granting as the full-access holder: %s", granted.body)
+ require.Len(t, grantsOf(t, proj, other), 1)
+ require.Equalf(t, http.StatusOK, child.StatusCode(), "deleting a folder inside the granted one: %s", child.Body)
+ require.Equalf(t, http.StatusForbidden, itself.StatusCode(),
+ "a folder delete is checked at its parent's path, which the grant does not cover: %s", itself.Body)
+ require.Equal(t, "/app", grantsOf(t, proj, owner)[0].SecretPath)
+ })
+}
+
+func createSync(t *testing.T, pr *harness.Principal, proj *fixture.Project, conn *fixture.AppConnection, secretPath string) *api.CreateGitHubSecretSyncResponse {
+ t.Helper()
+ var dest api.CreateGitHubSecretSyncJSONBody_DestinationConfig
+ require.NoError(t, dest.FromCreateGitHubSecretSyncJSONBodyDestinationConfig1(
+ api.CreateGitHubSecretSyncJSONBodyDestinationConfig1{Owner: "acme", Repo: "app", Scope: "repository"}))
+ body := api.CreateGitHubSecretSyncJSONRequestBody{
+ Name: "sync-" + uuid.NewString()[:8],
+ ProjectId: proj.ID,
+ ConnectionId: conn.ID,
+ Environment: "dev",
+ SecretPath: secretPath,
+ DestinationConfig: dest,
+ IsAutoSyncEnabled: new(false),
+ }
+ body.SyncOptions.InitialSyncBehavior = "overwrite-destination"
+ res, err := pr.API.CreateGitHubSecretSyncWithResponse(t.Context(), body)
+ require.NoError(t, err)
+ return res
+}
+
+// createRotation names a connection that does not exist, so it can only get as far as
+// the permission check and the lookups after it.
+func createRotation(t *testing.T, pr *harness.Principal, proj *fixture.Project, secretPath string) *api.CreatePostgreSQLCredentialsRotationResponse {
+ t.Helper()
+ raw, err := json.Marshal(map[string]any{
+ "name": "rotation-" + uuid.NewString()[:8],
+ "projectId": proj.ID,
+ "environment": "dev",
+ "secretPath": secretPath,
+ "connectionId": uuid.NewString(),
+ "rotationInterval": 30,
+ "parameters": map[string]any{"username1": "app_a", "username2": "app_b"},
+ "secretsMapping": map[string]any{"username": "DB_USER", "password": "DB_PASS"},
+ })
+ require.NoError(t, err)
+ res, err := pr.API.CreatePostgreSQLCredentialsRotationWithBodyWithResponse(t.Context(), "application/json", bytes.NewReader(raw))
+ require.NoError(t, err)
+ return res
+}