Skip to content

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

feat: evaluate role before sending to the UI

adilson5b08f9bd6c52
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 3849be614e..043a5cd1db 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -202,7 +202,7 @@ Built-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. Custom roles use unpack
- **No explicit cache invalidation calls exist.** The fingerprint self-corrects within the marker TTL (10s eventual consistency for access granting). The old `invalidateProjectPermissionCache` / DAL version counter pattern has been removed.
- Cache helpers (`cacheGet`, `cacheSet`, `applyReviver`) in `src/lib/cache/with-cache.ts` are shared between the simple `withCache` and the fingerprint-based `withCacheFingerprint`.
-**Folder RBAC (folder-scoped privileges)**: `additional_privileges` rows with a `folderId` + `role` (`SecretFolderRole` tiers in `folder-roles.ts`) are fetched in `getProjectPermission` through a second, longer-lived fingerprint cache (15m data / 15s marker) whose fingerprint is a Postgres version counter bumped by `permissionService.invalidateProjectFolderPermissionCache` (the folder-access grant/revoke endpoints on the project membership routers and every folder rename/move/delete path MUST call it). When an actor holds folder grants, `buildProjectPermissionRules` appends per-grant CASL rules built by `buildFolderScopedPrivilegeRules` (`permission-fns.ts`): a deny of every secretPath-capable subject conditioned on `{ environment, secretPath }` (exact path, folder-only, subfolders fall back to base roles), followed by the folder role's allows with the same conditions. CASL gives the last matching rule precedence, so the folder role fully replaces base permissions at the granted path and nowhere else. The deny list `FOLDER_SCOPED_DENY_RULES` (`folder-roles.ts`) is deliberately literal: `folder-scoped-privilege-rules.test.ts` enumerates `ProjectPermissionV2Schema` and fails when a new secretPath-scoped subject or action is added, forcing a human to extend the deny list and reconsider the role tiers. Only `getProjectPermission` evaluates folder grants; audits and `getProjectPermissions` do not yet.
+**Folder RBAC (folder-scoped privileges)**: `additional_privileges` rows with a `folderId` + `role` (`SecretFolderRole` tiers in `folder-roles.ts`) are fetched in `getProjectPermission` through a second, longer-lived fingerprint cache (15m data / 15s marker) whose fingerprint is a Postgres version counter bumped by `permissionService.invalidateProjectFolderPermissionCache` (the folder-access grant/revoke endpoints on the project membership routers and every folder rename/move/delete path MUST call it). When an actor holds folder grants, `buildProjectPermissionRules` appends per-grant CASL rules built by `buildFolderScopedPrivilegeRules` (`permission-fns.ts`): a deny of every secretPath-capable subject conditioned on `{ environment, secretPath }` (exact path, folder-only, subfolders fall back to base roles), followed by the folder role's allows with the same conditions. CASL gives the last matching rule precedence, so the folder role fully replaces base permissions at the granted path and nowhere else. The deny list `FOLDER_SCOPED_DENY_RULES` (`folder-roles.ts`) is deliberately literal: `folder-scoped-privilege-rules.test.ts` enumerates `ProjectPermissionV2Schema` and fails when a new secretPath-scoped subject or action is added, forcing a human to extend the deny list and reconsider the role tiers. Only `getProjectPermission` evaluates folder grants; audits and `getProjectPermissions` do not yet. The folder access sheet endpoints (`folderPermissionService.listFolderAccessUsers` / `listFolderAccessIdentities`) answer "who has access on this folder" without building an ability per actor: `folder-access-roles-fns.ts` builds one ability per distinct project role, probes it with every `(action, subject)` pair from `FOLDER_SCOPED_DENY_RULES` plus `SecretFolders.Read`, and caches the evaluated roster per `(projectId, folderId, actorType)` with `withCacheFingerprint` (10m data / 20s marker, fingerprint = membership counts and max timestamps plus the folder's env and path). Folder grants are merged live so a grant or revoke shows on the next request.
### Request-Scoped Memoization
diff --git a/backend/e2e-test/routes/v1/identity-folder-access.spec.ts b/backend/e2e-test/routes/v1/identity-folder-access.spec.ts
index d74e390a66..6c2ac876e4 100644
--- a/backend/e2e-test/routes/v1/identity-folder-access.spec.ts
+++ b/backend/e2e-test/routes/v1/identity-folder-access.spec.ts
@@ -7,8 +7,10 @@ import {
TemporaryPermissionMode
} from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
+import { KeyStorePrefixes } from "@app/keystore/keystore";
import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
+import { ActorType } from "@app/services/auth/auth-type";
const projectId = seedData1.project.id;
const orgId = seedData1.organization.id;
@@ -307,12 +309,31 @@ describe("Identity folder access CRUD", () => {
});
describe("roster", () => {
+ type TRosterIdentity = {
+ identityId: string;
+ name: string;
+ membership: {
+ id: string | null;
+ isProjectAdmin: boolean;
+ roles: { id: string | null; slug: string; name: string }[];
+ };
+ folderRBACAccess: Record<string, unknown> | null;
+ };
+ const memberRole = { id: null, slug: ProjectMembershipRole.Member, name: "Member" };
+
const listIdentities = async (
query = ""
): Promise<{
- identities: { identityId: string; name: string; folderRBACAccess: Record<string, unknown> | null }[];
+ identities: TRosterIdentity[];
+ identitiesWithoutAccess: TRosterIdentity[];
totalCount: number;
+ totalCountWithoutAccess: number;
}> => {
+ // the roster is cached behind a 20s marker; tests mutate memberships and list right away
+ await testRedis.del(
+ KeyStorePrefixes.ProjectFolderAccessRosterMarker(projectId, folder.id, ActorType.IDENTITY),
+ KeyStorePrefixes.ProjectFolderAccessRosterData(projectId, folder.id, ActorType.IDENTITY)
+ );
const res = await testServer.inject({
method: "GET",
url: folderAccessIdentitiesUrl(query),
@@ -322,9 +343,48 @@ describe("Identity folder access CRUD", () => {
return res.json();
};
- test("excludes project admin identities from the roster", async () => {
- const { identities } = await listIdentities("&limit=100");
- expect(identities.map((identity) => identity.identityId)).not.toContain(adminIdentityId);
+ test("lists project admin identities as flagged, non-grantable entries", async () => {
+ const { identities, identitiesWithoutAccess } = await listIdentities("&limit=100");
+ const admin = identities.find((identity) => identity.identityId === adminIdentityId);
+ expect(admin).toBeDefined();
+ expect(admin!.membership.isProjectAdmin).toBe(true);
+ // never a candidate: that list is what the grant picker offers, and granting to an admin 400s
+ expect(identitiesWithoutAccess.map((identity) => identity.identityId)).not.toContain(adminIdentityId);
+ });
+
+ test("lists identities without a granting role separately until they receive a grant", async () => {
+ const noAccess = await createProjectIdentity(ProjectMembershipRole.NoAccess);
+ try {
+ const before = await listIdentities("&limit=100");
+ expect(before.identities.map((identity) => identity.identityId)).not.toContain(noAccess.identityId);
+ const excluded = before.identitiesWithoutAccess.find((identity) => identity.identityId === noAccess.identityId);
+ expect(excluded).toBeDefined();
+ expect(excluded!.folderRBACAccess).toBeNull();
+ expect(excluded!.membership.id).toEqual(expect.any(String));
+ expect(excluded!.membership.roles).toEqual([
+ { id: null, slug: ProjectMembershipRole.NoAccess, name: "No Access" }
+ ]);
+ expect(before.totalCountWithoutAccess).toBeGreaterThan(0);
+
+ const createRes = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(noAccess.identityId),
+ headers: authHeaders(),
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
+ });
+ expect(createRes.statusCode).toBe(200);
+
+ const after = await listIdentities("&limit=100");
+ const granted = after.identities.find((identity) => identity.identityId === noAccess.identityId);
+ expect(granted).toBeDefined();
+ expect(granted!.membership.roles).toEqual([]);
+ expect(granted!.folderRBACAccess).toEqual(expect.objectContaining({ permission: SecretFolderRole.Read }));
+ expect(after.identitiesWithoutAccess.map((identity) => identity.identityId)).not.toContain(
+ noAccess.identityId
+ );
+ } finally {
+ await deleteProjectIdentity(noAccess.identityId);
+ }
});
test("lists project identities and annotates only the granted one", async () => {
@@ -334,6 +394,8 @@ describe("Identity folder access CRUD", () => {
expect(memberBefore).toBeDefined();
expect(memberBefore!.folderRBACAccess).toBeNull();
expect(memberBefore).not.toHaveProperty("roles");
+ expect(memberBefore!.membership.id).toEqual(expect.any(String));
+ expect(memberBefore!.membership.roles).toEqual([memberRole]);
const createRes = await testServer.inject({
method: "POST",
@@ -504,9 +566,14 @@ describe("Identity folder access CRUD", () => {
await testDb(TableName.Identity).where({ id: groupAdminIdentityId }).del();
});
- test("excludes an identity whose admin role comes from a group", async () => {
- const { identities } = await listIdentities("&limit=100");
- expect(identities.map((identity) => identity.identityId)).not.toContain(groupAdminIdentityId);
+ test("flags an identity whose admin role comes from a group", async () => {
+ const { identities, identitiesWithoutAccess } = await listIdentities("&limit=100");
+ const groupAdmin = identities.find((identity) => identity.identityId === groupAdminIdentityId);
+ expect(groupAdmin).toBeDefined();
+ expect(groupAdmin!.membership.isProjectAdmin).toBe(true);
+ expect(identitiesWithoutAccess.map((identity) => identity.identityId)).not.toContain(
+ groupAdminIdentityId
+ );
});
test("rejects granting to an identity whose admin role comes from a group", async () => {
diff --git a/backend/e2e-test/routes/v1/user-folder-access.spec.ts b/backend/e2e-test/routes/v1/user-folder-access.spec.ts
index 335546a994..3618b6a27e 100644
--- a/backend/e2e-test/routes/v1/user-folder-access.spec.ts
+++ b/backend/e2e-test/routes/v1/user-folder-access.spec.ts
@@ -25,7 +25,7 @@ import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { alertChannelRecipientDALFactory } from "@app/services/alert/alert-channel-recipient-dal";
-import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";
+import { ActorType, AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";
import { identityDALFactory } from "@app/services/identity/identity-dal";
import { membershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
import { projectDALFactory } from "@app/services/project/project-dal";
@@ -491,17 +491,31 @@ describe("User folder access CRUD", () => {
});
describe("roster", () => {
+ type TRosterUser = {
+ userId: string;
+ username: string;
+ membership: {
+ id: string | null;
+ isProjectAdmin: boolean;
+ roles: { id: string | null; slug: string; name: string }[];
+ };
+ folderRBACAccess: Record<string, unknown> | null;
+ };
+ const memberRole = { id: null, slug: ProjectMembershipRole.Member, name: "Member" };
+
const listUsers = async (
query = ""
): Promise<{
- users: {
- userId: string;
- username: string;
- membershipId: string | null;
- folderRBACAccess: Record<string, unknown> | null;
- }[];
+ users: TRosterUser[];
+ usersWithoutAccess: TRosterUser[];
totalCount: number;
+ totalCountWithoutAccess: number;
}> => {
+ // the roster is cached behind a 20s marker; tests mutate memberships and list right away
+ await testRedis.del(
+ KeyStorePrefixes.ProjectFolderAccessRosterMarker(projectId, folder.id, ActorType.USER),
+ KeyStorePrefixes.ProjectFolderAccessRosterData(projectId, folder.id, ActorType.USER)
+ );
const res = await testServer.inject({
method: "GET",
url: folderAccessUsersUrl(query),
@@ -519,12 +533,54 @@ describe("User folder access CRUD", () => {
expect(member).toBeDefined();
expect(member!.folderRBACAccess).toBeNull();
expect(member).not.toHaveProperty("roles");
- expect(member!.membershipId).toBe(memberProjectMembershipId);
+ expect(member!.membership).toEqual({
+ id: memberProjectMembershipId,
+ isProjectAdmin: false,
+ roles: [memberRole]
+ });
});
- test("excludes project admins from the roster", async () => {
- const { users } = await listUsers("&limit=100");
- expect(users.map((user) => user.userId)).not.toContain(adminUserId);
+ test("lists project admins as flagged, non-grantable entries", async () => {
+ const { users, usersWithoutAccess } = await listUsers("&limit=100");
+ const admin = users.find((user) => user.userId === adminUserId);
+ expect(admin).toBeDefined();
+ expect(admin!.membership.isProjectAdmin).toBe(true);
+ // never a candidate: that list is what the grant picker offers, and granting to an admin 400s
+ expect(usersWithoutAccess.map((user) => user.userId)).not.toContain(adminUserId);
+ });
+
+ test("lists users without a granting role separately until they receive a grant", async () => {
+ const noAccess = await createProjectUser(ProjectMembershipRole.NoAccess);
+ try {
+ const before = await listUsers("&limit=100");
+ expect(before.users.map((user) => user.userId)).not.toContain(noAccess.userId);
+ const excluded = before.usersWithoutAccess.find((user) => user.userId === noAccess.userId);
+ expect(excluded).toBeDefined();
+ expect(excluded!.folderRBACAccess).toBeNull();
+ expect(excluded!.membership).toEqual({
+ id: noAccess.projectMembershipId,
+ isProjectAdmin: false,
+ roles: [{ id: null, slug: ProjectMembershipRole.NoAccess, name: "No Access" }]
+ });
+ expect(before.totalCountWithoutAccess).toBeGreaterThan(0);
+
+ const createRes = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(noAccess.userId),
+ headers: authHeaders(),
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
+ });
+ expect(createRes.statusCode).toBe(200);
+
+ const after = await listUsers("&limit=100");
+ const granted = after.users.find((user) => user.userId === noAccess.userId);
+ expect(granted).toBeDefined();
+ expect(granted!.membership.roles).toEqual([]);
+ expect(granted!.folderRBACAccess).toEqual(expect.objectContaining({ permission: SecretFolderRole.Read }));
+ expect(after.usersWithoutAccess.map((user) => user.userId)).not.toContain(noAccess.userId);
+ } finally {
+ await deleteProjectUser(noAccess.userId);
+ }
});
test("annotates the granted user and clears the annotation on revoke", async () => {
@@ -581,10 +637,8 @@ describe("User folder access CRUD", () => {
const matching = await listUsers(`&search=${encodeURIComponent(memberEmail)}`);
expect(matching.users.map((user) => user.userId)).toContain(memberUserId);
- // the seed admin cannot be reached even by an exact search
const adminSearch = await listUsers(`&search=${encodeURIComponent(seedData1.email)}`);
- expect(adminSearch.users).toEqual([]);
- expect(adminSearch.totalCount).toBe(0);
+ expect(adminSearch.users.map((user) => user.userId)).toContain(adminUserId);
const nonMatching = await listUsers("&search=zzz-no-such-member");
expect(nonMatching.users).toEqual([]);
@@ -704,7 +758,8 @@ describe("User folder access CRUD", () => {
expect(groupUser).toBeDefined();
expect(groupUser!.folderRBACAccess).toBeNull();
- expect(groupUser!.membershipId).toBeNull();
+ // both groups carry the member role, so it is reported once
+ expect(groupUser!.membership).toEqual({ id: null, roles: [memberRole] });
});
test("counts an actor once however many memberships reach them", async () => {
@@ -768,9 +823,12 @@ describe("User folder access CRUD", () => {
await deleteProjectUser(groupAdminUserId);
});
- test("excludes a user whose admin role comes from a group", async () => {
- const { users } = await listUsers("&limit=100");
- expect(users.map((user) => user.userId)).not.toContain(groupAdminUserId);
+ test("flags a user whose admin role comes from a group", async () => {
+ const { users, usersWithoutAccess } = await listUsers("&limit=100");
+ const groupAdmin = users.find((user) => user.userId === groupAdminUserId);
+ expect(groupAdmin).toBeDefined();
+ expect(groupAdmin!.membership.isProjectAdmin).toBe(true);
+ expect(usersWithoutAccess.map((user) => user.userId)).not.toContain(groupAdminUserId);
});
test("rejects granting to a user whose admin role comes from a group", async () => {
diff --git a/backend/src/ee/services/license/__mocks__/license-fns.ts b/backend/src/ee/services/license/__mocks__/license-fns.ts
index cc15fc2fae..0e32ee3ae1 100644
--- a/backend/src/ee/services/license/__mocks__/license-fns.ts
+++ b/backend/src/ee/services/license/__mocks__/license-fns.ts
@@ -45,7 +45,8 @@ export const getDefaultOnPremFeatures = () => {
honeyTokens: false,
honeyTokenLimit: 0,
gatewayPool: false,
- fips: true
+ fips: true,
+ secretsFolderRbac: true
};
};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 9b1d722d47..6075083181 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -103,6 +103,11 @@ export const KeyStorePrefixes = {
// Postgres key_value_store key (pgIncrementBy/pgGetIntItem), not a Redis key
ProjectFolderPermissionVersion: (projectId: string) => `project-folder-permission-version:${projectId}` as const,
+ ProjectFolderAccessRosterMarker: (projectId: string, folderId: string, actorType: string) =>
+ `project-folder-access-roster-marker:${projectId}:${folderId}:${actorType}` as const,
+ ProjectFolderAccessRosterData: (projectId: string, folderId: string, actorType: string) =>
+ `project-folder-access-roster-data:${projectId}:${folderId}:${actorType}` as const,
+
KmsProjectSecretManagerMaterial: (projectId: string) => `kms-project-sm-material:${projectId}` as const,
PkiAcmeNonce: (nonce: string) => `pki-acme-nonce:${nonce}` as const,
@@ -200,6 +205,8 @@ export const KeyStoreTtls = {
// Folder-scoped privilege cache must outlive the project permission cache above
ProjectFolderPermissionMarkerTtlSeconds: 15,
ProjectFolderPermissionDataTtlSeconds: 900, // 15 minutes
+ ProjectFolderAccessRosterMarkerTtlSeconds: 20,
+ ProjectFolderAccessRosterDataTtlSeconds: 600, // 10 minutes
MfaSessionInSeconds: 300, // 5 minutes
RecentMfaAuthInSeconds: 600, // 10 minutes
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 67c55556a1..13e3e15545 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1832,17 +1832,32 @@ export const FOLDER_ACCESS = {
projectId: "The ID of the project the folder is in.",
environmentSlug: "The slug of the environment the folder is in.",
secretPath: "The path of the folder to list access for.",
- offset: "The offset to start from. If you enter 10, it will start from the 10th user.",
- limit: "The number of users to return.",
- search: "The text string that user names and email addresses will be filtered by."
+ offset:
+ "The offset to start from, applied to the users with access and the users without access independently. If you enter 10, each list starts from its 10th user.",
+ limit: "The number of users to return in each of the two lists.",
+ search:
+ "The text string that user names and email addresses will be filtered by, applied to both lists.",
+ users:
+ "The users whose project roles or folder access give them access on the folder. membership.roles lists only the roles that grant that access, so it is empty when the access comes from the folder access alone.",
+ usersWithoutAccess:
+ "The users of the project with no access on the folder. membership.roles lists all of their active project roles and folderRBACAccess is always null.",
+ totalCount: "The number of users with access on the folder that match the search.",
+ totalCountWithoutAccess: "The number of users without access on the folder that match the search."
},
LIST_IDENTITIES: {
projectId: "The ID of the project the folder is in.",
environmentSlug: "The slug of the environment the folder is in.",
secretPath: "The path of the folder to list access for.",
- offset: "The offset to start from. If you enter 10, it will start from the 10th machine identity.",
- limit: "The number of machine identities to return.",
- search: "The text string that machine identity names will be filtered by."
+ offset:
+ "The offset to start from, applied to the machine identities with access and the ones without access independently. If you enter 10, each list starts from its 10th machine identity.",
+ limit: "The number of machine identities to return in each of the two lists.",
+ search: "The text string that machine identity names will be filtered by, applied to both lists.",
+ identities:
+ "The machine identities whose project roles or folder access give them access on the folder. membership.roles lists only the roles that grant that access, so it is empty when the access comes from the folder access alone.",
+ identitiesWithoutAccess:
+ "The machine identities of the project with no access on the folder. membership.roles lists all of their active project roles and folderRBACAccess is always null.",
+ totalCount: "The number of machine identities with access on the folder that match the search.",
+ totalCountWithoutAccess: "The number of machine identities without access on the folder that match the search."
},
LIST_USER_GRANTS: {
projectId: "The ID of the project to list the user's folder access grants in.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index d30e032f75..7df31866d4 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -943,7 +943,8 @@ export const registerRoutes = async (
secretFolderDAL: folderDAL,
permissionService,
folderPermissionDAL,
- licenseService
+ licenseService,
+ keyStore
});
const kmsService = kmsServiceFactory({
diff --git a/backend/src/server/routes/sanitizedSchema/folder-access.ts b/backend/src/server/routes/sanitizedSchema/folder-access.ts
index 74e5406e36..5102fdcbe6 100644
--- a/backend/src/server/routes/sanitizedSchema/folder-access.ts
+++ b/backend/src/server/routes/sanitizedSchema/folder-access.ts
@@ -18,18 +18,31 @@ export const SanitizedFolderAccessSchema = z.object({
updatedAt: z.date()
});
+export const SanitizedFolderAccessRoleSchema = z.object({
+ id: z.string().uuid().nullable(),
+ slug: z.string(),
+ name: z.string()
+});
+
+export const SanitizedFolderAccessMembershipSchema = z.object({
+ id: z.string().uuid().nullable(),
+ isProjectAdmin: z.boolean(),
+ roles: SanitizedFolderAccessRoleSchema.array()
+});
+
export const SanitizedFolderAccessUserSchema = z.object({
userId: z.string().uuid(),
- membershipId: z.string().uuid().nullable(),
username: z.string(),
email: z.string().nullable(),
firstName: z.string().nullable(),
lastName: z.string().nullable(),
+ membership: SanitizedFolderAccessMembershipSchema,
folderRBACAccess: SanitizedFolderAccessSchema.nullable()
});
export const SanitizedFolderAccessIdentitySchema = z.object({
identityId: z.string().uuid(),
name: z.string(),
+ membership: SanitizedFolderAccessMembershipSchema,
folderRBACAccess: SanitizedFolderAccessSchema.nullable()
});
diff --git a/backend/src/server/routes/v1/identity-project-membership-router.ts b/backend/src/server/routes/v1/identity-project-membership-router.ts
index 070003e91a..fc75996f89 100644
--- a/backend/src/server/routes/v1/identity-project-membership-router.ts
+++ b/backend/src/server/routes/v1/identity-project-membership-router.ts
@@ -777,7 +777,8 @@ export const registerIdentityProjectMembershipRouter = async (server: FastifyZod
hide: true,
operationId: "listFolderAccessIdentities",
tags: [ApiDocsTags.FolderAccess],
- description: "List every machine identity in a project with the access it has on a folder.",
+ description:
+ "List the machine identities of a project split by whether they have access on a folder, with the project roles that grant it.",
security: [
{
bearerAuth: []
@@ -794,8 +795,12 @@ export const registerIdentityProjectMembershipRouter = async (server: FastifyZod
}),
response: {
200: z.object({
- identities: SanitizedFolderAccessIdentitySchema.array(),
- totalCount: z.number()
+ identities: SanitizedFolderAccessIdentitySchema.array().describe(FOLDER_ACCESS.LIST_IDENTITIES.identities),
+ identitiesWithoutAccess: SanitizedFolderAccessIdentitySchema.array().describe(
+ FOLDER_ACCESS.LIST_IDENTITIES.identitiesWithoutAccess
+ ),
+ totalCount: z.number().describe(FOLDER_ACCESS.LIST_IDENTITIES.totalCount),
+ totalCountWithoutAccess: z.number().describe(FOLDER_ACCESS.LIST_IDENTITIES.totalCountWithoutAccess)
})
}
},
diff --git a/backend/src/server/routes/v1/project-membership-router.ts b/backend/src/server/routes/v1/project-membership-router.ts
index c0b7a9b6d1..094f39f097 100644
--- a/backend/src/server/routes/v1/project-membership-router.ts
+++ b/backend/src/server/routes/v1/project-membership-router.ts
@@ -904,7 +904,8 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
hide: true,
operationId: "listFolderAccessUsers",
tags: [ApiDocsTags.FolderAccess],
- description: "List every user in a project with the access they have on a folder.",
+ description:
+ "List the users of a project split by whether they have access on a folder, with the project roles that grant it.",
security: [
{
bearerAuth: []
@@ -921,8 +922,12 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
}),
response: {
200: z.object({
- users: SanitizedFolderAccessUserSchema.array(),
- totalCount: z.number()
+ users: SanitizedFolderAccessUserSchema.array().describe(FOLDER_ACCESS.LIST_USERS.users),
+ usersWithoutAccess: SanitizedFolderAccessUserSchema.array().describe(
+ FOLDER_ACCESS.LIST_USERS.usersWithoutAccess
+ ),
+ totalCount: z.number().describe(FOLDER_ACCESS.LIST_USERS.totalCount),
+ totalCountWithoutAccess: z.number().describe(FOLDER_ACCESS.LIST_USERS.totalCountWithoutAccess)
})
}
},
diff --git a/backend/src/services/folder-permission/folder-access-roles-fns.test.ts b/backend/src/services/folder-permission/folder-access-roles-fns.test.ts
new file mode 100644
index 0000000000..8bcf413835
--- /dev/null
+++ b/backend/src/services/folder-permission/folder-access-roles-fns.test.ts
@@ -0,0 +1,424 @@
+import { MongoAbility, RawRuleOf } from "@casl/ability";
+import { packRules } from "@casl/ability/extra";
+
+import { ProjectMembershipRole, ProjectType, TAdditionalPrivileges } from "@app/db/schemas";
+import { FOLDER_SCOPED_DENY_RULES } from "@app/ee/services/permission/folder-roles";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionSecretActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { getPredefinedRoles } from "@app/services/project-role/project-role-fns";
+
+import {
+ BUILT_IN_PROJECT_ROLE_NAMES,
+ buildFolderAccessRoster,
+ collectDistinctRoles,
+ FOLDER_ACCESS_PROBES,
+ matchesSearch,
+ paginateRoster,
+ reviveFolderAccessRoster,
+ roleGrantsFolderAccess,
+ sortRosterEntries,
+ splitFolderAccessRoster,
+ TDistinctProjectRole,
+ toCachedRosterRole
+} from "./folder-access-roles-fns";
+import { TCachedFolderAccessRoster, TCachedRosterRole, TRosterRoleRow, TRosterUser } from "./folder-permission-types";
+
+const folder = { environmentSlug: "dev", path: "/team/app" };
+const now = new Date("2026-08-25T12:00:00.000Z");
+const past = new Date("2026-08-25T11:00:00.000Z");
+const future = new Date("2026-08-25T13:00:00.000Z");
+
+const pack = (rules: RawRuleOf<MongoAbility>[]) => packRules(rules);
+
+const builtIn = (slug: string): TDistinctProjectRole => ({ key: slug, slug, isCustom: false });
+const custom = (permissions: unknown): TDistinctProjectRole => ({
+ key: "custom-role-id",
+ slug: "custom-role",
+ isCustom: true,
+ permissions
+});
+
+const roleRow = (overrides: Partial<TRosterRoleRow> = {}): TRosterRoleRow => ({
+ membershipRoleId: "membership-role-id",
+ role: ProjectMembershipRole.Member,
+ customRoleId: null,
+ customRoleSlug: null,
+ customRoleName: null,
+ customRolePermissions: null,
+ isTemporary: false,
+ temporaryAccessEndTime: null,
+ ...overrides
+});
+
+const customRoleRow = (overrides: Partial<TRosterRoleRow> = {}): TRosterRoleRow =>
+ roleRow({
+ membershipRoleId: "custom-membership-role-id",
+ role: ProjectMembershipRole.Custom,
+ customRoleId: "custom-role-id",
+ customRoleSlug: "custom-role",
+ customRoleName: "Custom Role",
+ customRolePermissions: [],
+ ...overrides
+ });
+
+const cachedRole = (overrides: Partial<TCachedRosterRole> = {}): TCachedRosterRole => ({
+ id: null,
+ slug: ProjectMembershipRole.Member,
+ name: "Member",
+ isTemporary: false,
+ temporaryAccessEndTime: null,
+ ...overrides
+});
+
+const user = (userId: string, membershipId: string | null = `${userId}-membership`): TRosterUser => ({
+ userId,
+ username: `${userId}@example.com`,
+ email: `${userId}@example.com`,
+ firstName: null,
+ lastName: null,
+ membershipId
+});
+
+const grant = { id: "grant-id" } as TAdditionalPrivileges;
+
+describe("FOLDER_ACCESS_PROBES", () => {
+ test("covers every deny-list pair", () => {
+ const denied = FOLDER_SCOPED_DENY_RULES.flatMap((rule) => {
+ const subjects = Array.isArray(rule.subject) ? rule.subject : [rule.subject];
+ const actions = Array.isArray(rule.action) ? rule.action : [rule.action];
+ return subjects.flatMap((sub) => actions.map((action) => ({ action, subject: sub })));
+ });
+
+ expect(FOLDER_ACCESS_PROBES).toEqual(denied);
+ expect(new Set(FOLDER_ACCESS_PROBES.map((probe) => probe.subject))).toEqual(
+ new Set([
+ ProjectPermissionSub.Secrets,
+ ProjectPermissionSub.SecretFolders,
+ ProjectPermissionSub.SecretImports,
+ ProjectPermissionSub.DynamicSecrets,
+ ProjectPermissionSub.SecretSyncs,
+ ProjectPermissionSub.SecretRotation,
+ ProjectPermissionSub.SecretEventSubscriptions,
+ ProjectPermissionSub.HoneyTokens,
+ ProjectPermissionSub.Commits
+ ])
+ );
+ });
+});
+
+describe("roleGrantsFolderAccess", () => {
+ test.each([ProjectMembershipRole.Admin, ProjectMembershipRole.Member, ProjectMembershipRole.Viewer])(
+ "built-in %s grants access",
+ (slug) => {
+ expect(roleGrantsFolderAccess(builtIn(slug), folder)).toBe(true);
+ }
+ );
+
+ test("no-access grants nothing", () => {
+ expect(roleGrantsFolderAccess(builtIn(ProjectMembershipRole.NoAccess), folder)).toBe(false);
+ });
+
+ test("custom role scoped by environment and secretPath glob grants access only under that path", () => {
+ const role = custom(
+ pack([
+ {
+ action: ProjectPermissionSecretActions.ReadValue,
+ subject: ProjectPermissionSub.Secrets,
+ conditions: { environment: "dev", secretPath: { $glob: "/team/**" } }
+ }
+ ])
+ );
+
+ expect(roleGrantsFolderAccess(role, folder)).toBe(true);
+ expect(roleGrantsFolderAccess(role, { environmentSlug: "dev", path: "/other" })).toBe(false);
+ expect(roleGrantsFolderAccess(role, { environmentSlug: "prod", path: "/team/app" })).toBe(false);
+ });
+
+ test("custom role granting only non-folder subjects grants nothing", () => {
+ const role = custom(pack([{ action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.Member }]));
+ expect(roleGrantsFolderAccess(role, folder)).toBe(false);
+ });
+
+ test("custom role with only SecretFolders.Read grants nothing", () => {
+ const role = custom(pack([{ action: ProjectPermissionActions.Read, subject: ProjectPermissionSub.SecretFolders }]));
+ expect(roleGrantsFolderAccess(role, folder)).toBe(false);
+ });
+
+ test("inverted rules grant nothing", () => {
+ const role = custom(
+ pack([
+ { action: ProjectPermissionSecretActions.ReadValue, subject: ProjectPermissionSub.Secrets, inverted: true }
+ ])
+ );
+ expect(roleGrantsFolderAccess(role, folder)).toBe(false);
+ });
+});
+
+describe("BUILT_IN_PROJECT_ROLE_NAMES", () => {
+ test("matches the predefined role names", () => {
+ [ProjectType.SecretManager, ProjectType.KMS].forEach((projectType) => {
+ getPredefinedRoles({ projectId: "project-id", projectType }).forEach(({ slug, name }) => {
+ expect(BUILT_IN_PROJECT_ROLE_NAMES[slug]).toBe(name);
+ });
+ });
+ });
+});
+
+describe("collectDistinctRoles", () => {
+ test("keys built-ins by slug and custom roles by id, once each", () => {
+ const roles = collectDistinctRoles([
+ { roles: [roleRow(), customRoleRow({ customRolePermissions: ["packed"] })] },
+ { roles: [roleRow({ membershipRoleId: "other" }), customRoleRow({ membershipRoleId: "other-custom" })] }
+ ]);
+
+ expect(roles).toEqual([
+ { key: ProjectMembershipRole.Member, slug: ProjectMembershipRole.Member, isCustom: false },
+ { key: "custom-role-id", slug: "custom-role", isCustom: true, permissions: ["packed"] }
+ ]);
+ });
+
+ test("skips custom rows whose role row is missing", () => {
+ expect(collectDistinctRoles([{ roles: [customRoleRow({ customRoleId: null, customRoleSlug: null })] }])).toEqual(
+ []
+ );
+ });
+});
+
+describe("toCachedRosterRole", () => {
+ test("maps a built-in role to a null id and its display name", () => {
+ expect(toCachedRosterRole(roleRow({ role: ProjectMembershipRole.NoAccess }))).toEqual({
+ id: null,
+ slug: ProjectMembershipRole.NoAccess,
+ name: "No Access",
+ isTemporary: false,
+ temporaryAccessEndTime: null
+ });
+ });
+
+ test("maps a custom role to its row id, slug and name", () => {
+ expect(toCachedRosterRole(customRoleRow({ isTemporary: true, temporaryAccessEndTime: future }))).toEqual({
+ id: "custom-role-id",
+ slug: "custom-role",
+ name: "Custom Role",
+ isTemporary: true,
+ temporaryAccessEndTime: future
+ });
+ });
+
+ test("drops a custom role whose row no longer exists", () => {
+ expect(toCachedRosterRole(customRoleRow({ customRoleName: null }))).toBeNull();
+ });
+});
+
+describe("buildFolderAccessRoster", () => {
+ test("records the granting role keys and the display roles without permissions", () => {
+ const roster = buildFolderAccessRoster(
+ [
+ { actor: user("member"), roles: [roleRow()] },
+ { actor: user("locked"), roles: [roleRow({ role: ProjectMembershipRole.NoAccess })] }
+ ],
+ folder
+ );
+
+ expect(roster.grantingRoleKeys).toEqual([ProjectMembershipRole.Member]);
+ expect(roster.actors).toEqual([
+ { actor: user("member"), roles: [cachedRole()] },
+ { actor: user("locked"), roles: [cachedRole({ slug: ProjectMembershipRole.NoAccess, name: "No Access" })] }
+ ]);
+ expect(JSON.stringify(roster)).not.toContain("permissions");
+ });
+});
+
+describe("reviveFolderAccessRoster", () => {
+ test("restores temporaryAccessEndTime dates after a JSON round trip", () => {
+ const roster: TCachedFolderAccessRoster<TRosterUser> = {
+ grantingRoleKeys: [],
+ actors: [{ actor: user("u"), roles: [cachedRole({ isTemporary: true, temporaryAccessEndTime: future })] }]
+ };
+
+ const revived = reviveFolderAccessRoster(JSON.parse(JSON.stringify(roster)) as typeof roster);
+ expect(revived.actors[0].roles[0].temporaryAccessEndTime).toEqual(future);
+ });
+});
+
+describe("splitFolderAccessRoster", () => {
+ const split = (roster: TCachedFolderAccessRoster<TRosterUser>, grants: [string, TAdditionalPrivileges][] = []) =>
+ splitFolderAccessRoster({
+ roster,
+ grantByActorId: new Map(grants),
+ actorIdOf: (actor) => actor.userId,
+ now
+ });
+
+ test("puts actors with a granting role in the with-access list with only those roles", () => {
+ const roles = [cachedRole(), cachedRole({ slug: ProjectMembershipRole.NoAccess, name: "No Access" })];
+ const { withAccess, withoutAccess } = split({
+ grantingRoleKeys: [ProjectMembershipRole.Member],
+ actors: [{ actor: user("u"), roles }]
+ });
+
+ expect(withoutAccess).toEqual([]);
+ expect(withAccess).toEqual([
+ {
+ actor: user("u"),
+ membership: {
+ id: "u-membership",
+ isProjectAdmin: false,
+ roles: [{ id: null, slug: ProjectMembershipRole.Member, name: "Member" }]
+ },
+ grant: null
+ }
+ ]);
+ });
+
+ test("lists every active role for actors without access", () => {
+ const { withAccess, withoutAccess } = split({
+ grantingRoleKeys: [],
+ actors: [
+ {
+ actor: user("u", null),
+ roles: [
+ cachedRole({ slug: ProjectMembershipRole.NoAccess, name: "No Access" }),
+ cachedRole({ id: "custom-role-id", slug: "custom-role", name: "Custom Role" })
+ ]
+ }
+ ]
+ });
+
+ expect(withAccess).toEqual([]);
+ expect(withoutAccess).toEqual([
+ {
+ actor: user("u", null),
+ membership: {
+ id: null,
+ isProjectAdmin: false,
+ roles: [
+ { id: null, slug: ProjectMembershipRole.NoAccess, name: "No Access" },
+ { id: "custom-role-id", slug: "custom-role", name: "Custom Role" }
+ ]
+ },
+ grant: null
+ }
+ ]);
+ });
+
+ test("keeps an actor with a folder grant but no granting role in the with-access list", () => {
+ const { withAccess, withoutAccess } = split(
+ {
+ grantingRoleKeys: [],
+ actors: [{ actor: user("u"), roles: [cachedRole({ slug: ProjectMembershipRole.NoAccess, name: "No Access" })] }]
+ },
+ [["u", grant]]
+ );
+
+ expect(withoutAccess).toEqual([]);
+ expect(withAccess).toEqual([
+ { actor: user("u"), membership: { id: "u-membership", isProjectAdmin: false, roles: [] }, grant }
+ ]);
+ });
+
+ test("ignores expired temporary roles", () => {
+ const { withAccess, withoutAccess } = split({
+ grantingRoleKeys: [ProjectMembershipRole.Member],
+ actors: [
+ {
+ actor: user("u"),
+ roles: [
+ cachedRole({ isTemporary: true, temporaryAccessEndTime: past }),
+ cachedRole({ slug: ProjectMembershipRole.NoAccess, name: "No Access" })
+ ]
+ }
+ ]
+ });
+
+ expect(withAccess).toEqual([]);
+ expect(withoutAccess[0].membership.roles).toEqual([
+ { id: null, slug: ProjectMembershipRole.NoAccess, name: "No Access" }
+ ]);
+ });
+
+ test("flags actors holding an active built-in admin role and keeps them in the with-access list", () => {
+ const { withAccess, withoutAccess } = split({
+ grantingRoleKeys: [ProjectMembershipRole.Admin, ProjectMembershipRole.Member, "custom-role-id"],
+ actors: [
+ { actor: user("admin"), roles: [cachedRole({ slug: ProjectMembershipRole.Admin, name: "Admin" })] },
+ {
+ actor: user("former-admin"),
+ roles: [
+ cachedRole({
+ slug: ProjectMembershipRole.Admin,
+ name: "Admin",
+ isTemporary: true,
+ temporaryAccessEndTime: past
+ }),
+ cachedRole()
+ ]
+ },
+ {
+ actor: user("custom-admin"),
+ roles: [cachedRole({ id: "custom-role-id", slug: ProjectMembershipRole.Admin, name: "Admin" })]
+ }
+ ]
+ });
+
+ expect(withoutAccess).toEqual([]);
+ expect(withAccess.map((entry) => entry.actor.userId)).toEqual(["admin", "former-admin", "custom-admin"]);
+ // only a currently active built-in admin is one: an expired temporary admin and a custom role
+ // slugged "admin" are ordinary grantees
+ expect(withAccess.map((entry) => entry.membership.isProjectAdmin)).toEqual([true, false, false]);
+ });
+
+ test("keeps an admin out of the without-access list even when no role grants folder access", () => {
+ const { withAccess, withoutAccess } = split({
+ grantingRoleKeys: [],
+ actors: [{ actor: user("admin"), roles: [cachedRole({ slug: ProjectMembershipRole.Admin, name: "Admin" })] }]
+ });
+
+ expect(withoutAccess).toEqual([]);
+ expect(withAccess).toEqual([
+ { actor: user("admin"), membership: { id: "admin-membership", isProjectAdmin: true, roles: [] }, grant: null }
+ ]);
+ });
+
+ test("dedupes the same role reached directly and through a group", () => {
+ const { withAccess } = split({
+ grantingRoleKeys: [ProjectMembershipRole.Member],
+ actors: [{ actor: user("u"), roles: [cachedRole(), cachedRole()] }]
+ });
+
+ expect(withAccess[0].membership.roles).toHaveLength(1);
+ });
+});
+
+describe("matchesSearch", () => {
+ test("matches case-insensitively across any field and skips empty fields", () => {
+ expect(matchesSearch("ALICE", [null, "[email protected]"])).toBe(true);
+ expect(matchesSearch("bob", ["alice", null, undefined])).toBe(false);
+ expect(matchesSearch(undefined, [])).toBe(true);
+ });
+});
+
+describe("sortRosterEntries", () => {
+ test("orders by the lower-cased name and then by the tie-break", () => {
+ const sorted = sortRosterEntries(
+ [
+ { name: "bob", id: "2" },
+ { name: "Alice", id: "9" },
+ { name: "alice", id: "1" }
+ ],
+ (entry) => [entry.name, entry.id]
+ );
+
+ expect(sorted.map((entry) => entry.id)).toEqual(["1", "9", "2"]);
+ });
+});
+
+describe("paginateRoster", () => {
+ test("slices the page and reports the full count", () => {
+ expect(paginateRoster([1, 2, 3, 4, 5], 1, 2)).toEqual({ items: [2, 3], totalCount: 5 });
+ expect(paginateRoster([1, 2, 3], 10, 2)).toEqual({ items: [], totalCount: 3 });
+ });
+});
diff --git a/backend/src/services/folder-permission/folder-access-roles-fns.ts b/backend/src/services/folder-permission/folder-access-roles-fns.ts
new file mode 100644
index 0000000000..a772fdb300
--- /dev/null
+++ b/backend/src/services/folder-permission/folder-access-roles-fns.ts
@@ -0,0 +1,200 @@
+import { createMongoAbility, MongoAbility, RawRuleOf, subject } from "@casl/ability";
+
+import { ProjectMembershipRole, ProjectType, TAdditionalPrivileges } from "@app/db/schemas";
+import { FOLDER_SCOPED_DENY_RULES } from "@app/ee/services/permission/folder-roles";
+import { buildProjectPermissionRules } from "@app/ee/services/permission/permission-service";
+import { ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { conditionsMatcher } from "@app/lib/casl";
+
+import {
+ TCachedFolderAccessRoster,
+ TCachedRosterRole,
+ TFolderAccessRole,
+ TFolderAccessRosterEntry,
+ TResolvedFolder,
+ TRosterActor,
+ TRosterEntry,
+ TRosterRoleRow
+} from "./folder-permission-types";
+
+type TFolderAccessProbe = { action: string; subject: ProjectPermissionSub };
+
+type TFolderLocation = Pick<TResolvedFolder, "environmentSlug" | "path">;
+
+export type TDistinctProjectRole =
+ | { key: string; slug: string; isCustom: false }
+ | { key: string; slug: string; isCustom: true; permissions: unknown };
+
+const toArray = <T>(value: T | T[]): T[] => (Array.isArray(value) ? value : [value]);
+
+// The deny list is what defines "secretPath-scoped subject" for folder RBAC, so deriving the probes
+// from it keeps them under the same guard test.
+export const FOLDER_ACCESS_PROBES: TFolderAccessProbe[] = FOLDER_SCOPED_DENY_RULES.flatMap((rule) =>
+ toArray(rule.subject as ProjectPermissionSub | ProjectPermissionSub[]).flatMap((sub) =>
+ toArray(rule.action as string | string[]).map((action) => ({ action, subject: sub }))
+ )
+);
+
+export const BUILT_IN_PROJECT_ROLE_NAMES: Record<string, string> = {
+ [ProjectMembershipRole.Admin]: "Admin",
+ [ProjectMembershipRole.Member]: "Member",
+ [ProjectMembershipRole.Viewer]: "Viewer",
+ [ProjectMembershipRole.NoAccess]: "No Access",
+ [ProjectMembershipRole.KmsCryptographicOperator]: "Cryptographic Operator"
+};
+
+// A built-in role has no row of its own, so it is keyed by slug while a custom role is keyed by id.
+// The two never collide: a custom role slugged like a built-in still stores role = 'custom'.
+export const folderAccessRoleKey = (role: Pick<TFolderAccessRole, "id" | "slug">) => role.id ?? role.slug;
+
+export const collectDistinctRoles = (entries: { roles: TRosterRoleRow[] }[]): TDistinctProjectRole[] => {
+ const byKey = new Map<string, TDistinctProjectRole>();
+ entries.forEach(({ roles }) =>
+ roles.forEach((row) => {
+ if (row.role === ProjectMembershipRole.Custom) {
+ if (row.customRoleId && row.customRoleSlug && !byKey.has(row.customRoleId)) {
+ byKey.set(row.customRoleId, {
+ key: row.customRoleId,
+ slug: row.customRoleSlug,
+ isCustom: true,
+ permissions: row.customRolePermissions ?? []
+ });
+ }
+ } else if (!byKey.has(row.role)) {
+ byKey.set(row.role, { key: row.role, slug: row.role, isCustom: false });
+ }
+ })
+ );
+ return [...byKey.values()];
+};
+
+// Evaluated once per role rather than per actor: the folder subject is the same for everyone, so
+// the verdict depends only on the role. Handlebars conditions are therefore never interpolated and
+// a templated condition compares literally, which does not match.
+export const roleGrantsFolderAccess = (role: TDistinctProjectRole, folder: TFolderLocation) => {
+ const rules = buildProjectPermissionRules(
+ [
+ role.isCustom
+ ? { role: ProjectMembershipRole.Custom, permissions: role.permissions }
+ : { role: role.slug, permissions: [] }
+ ],
+ ProjectType.SecretManager
+ ) as RawRuleOf<MongoAbility>[];
+ const ability = createMongoAbility(rules, { conditionsMatcher });
+ // subject() tags the object it receives with the subject type and refuses to retag it, so each probe
+ // gets its own copy of the folder fields
+ return FOLDER_ACCESS_PROBES.some(({ action, subject: sub }) =>
+ ability.can(action, subject(sub, { environment: folder.environmentSlug, secretPath: folder.path }))
+ );
+};
+
+export const toCachedRosterRole = (row: TRosterRoleRow): TCachedRosterRole | null => {
+ const temporal = { isTemporary: row.isTemporary, temporaryAccessEndTime: row.temporaryAccessEndTime };
+ if (row.role === ProjectMembershipRole.Custom) {
+ if (!row.customRoleId || !row.customRoleSlug || !row.customRoleName) return null;
+ return { id: row.customRoleId, slug: row.customRoleSlug, name: row.customRoleName, ...temporal };
+ }
+ return { id: null, slug: row.role, name: BUILT_IN_PROJECT_ROLE_NAMES[row.role] ?? row.role, ...temporal };
+};
+
+export const buildFolderAccessRoster = <TActor extends TRosterActor>(
+ entries: TRosterEntry<TActor>[],
+ folder: TFolderLocation
+): TCachedFolderAccessRoster<TActor> => ({
+ grantingRoleKeys: collectDistinctRoles(entries)
+ .filter((role) => roleGrantsFolderAccess(role, folder))
+ .map((role) => role.key),
+ actors: entries.map(({ actor, roles }) => ({
+ actor,
+ roles: roles.map(toCachedRosterRole).filter((role): role is TCachedRosterRole => role !== null)
+ }))
+});
+
+export const reviveFolderAccessRoster = <TActor extends TRosterActor>(
+ parsed: TCachedFolderAccessRoster<TActor>
+): TCachedFolderAccessRoster<TActor> => ({
+ ...parsed,
+ actors: parsed.actors.map((entry) => ({
+ ...entry,
+ roles: entry.roles.map((role) => ({
+ ...role,
+ temporaryAccessEndTime: role.temporaryAccessEndTime ? new Date(role.temporaryAccessEndTime) : null
+ }))
+ }))
+});
+
+const isRoleActiveAt = (role: Pick<TCachedRosterRole, "isTemporary" | "temporaryAccessEndTime">, now: Date) =>
+ !role.isTemporary || Boolean(role.temporaryAccessEndTime && now < role.temporaryAccessEndTime);
+
+const isBuiltInAdmin = (role: TFolderAccessRole) => role.id === null && role.slug === ProjectMembershipRole.Admin;
+
+const uniqueByKey = (roles: TCachedRosterRole[]) => {
+ const seen = new Set<string>();
+ return roles.filter((role) => {
+ const key = folderAccessRoleKey(role);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+};
+
+const toPublicRole = ({ id, slug, name }: TCachedRosterRole): TFolderAccessRole => ({ id, slug, name });
+
+export const splitFolderAccessRoster = <TActor extends TRosterActor>({
+ roster,
+ grantByActorId,
+ actorIdOf,
+ now
+}: {
+ roster: TCachedFolderAccessRoster<TActor>;
+ grantByActorId: Map<string, TAdditionalPrivileges>;
+ actorIdOf: (actor: TActor) => string;
+ now: Date;
+}) => {
+ const granting = new Set(roster.grantingRoleKeys);
+ const withAccess: TFolderAccessRosterEntry<TActor>[] = [];
+ const withoutAccess: TFolderAccessRosterEntry<TActor>[] = [];
+
+ roster.actors.forEach(({ actor, roles }) => {
+ const activeRoles = uniqueByKey(roles.filter((role) => isRoleActiveAt(role, now)));
+ const isProjectAdmin = activeRoles.some(isBuiltInAdmin);
+
+ const grantingRoles = activeRoles.filter((role) => granting.has(folderAccessRoleKey(role)));
+ const grant = grantByActorId.get(actorIdOf(actor)) ?? null;
+ // an admin is kept out of withoutAccess even if no probe matched: that list is what the grant
+ // picker offers, and a folder grant could only remove privileges from an admin
+ if (isProjectAdmin || grantingRoles.length || grant) {
+ withAccess.push({
+ actor,
+ membership: { id: actor.membershipId, isProjectAdmin, roles: grantingRoles.map(toPublicRole) },
+ grant
+ });
+ } else {
+ withoutAccess.push({
+ actor,
+ membership: { id: actor.membershipId, isProjectAdmin, roles: activeRoles.map(toPublicRole) },
+ grant: null
+ });
+ }
+ });
+
+ return { withAccess, withoutAccess };
+};
+
+export const matchesSearch = (search: string | undefined, fields: (string | null | undefined)[]) => {
+ if (!search) return true;
+ const term = search.toLowerCase();
+ return fields.some((field) => Boolean(field && field.toLowerCase().includes(term)));
+};
+
+export const sortRosterEntries = <T>(entries: T[], sortKey: (entry: T) => [name: string, tieBreak: string]) =>
+ [...entries].sort((a, b) => {
+ const [aName, aTieBreak] = sortKey(a);
+ const [bName, bTieBreak] = sortKey(b);
+ return aName.toLowerCase().localeCompare(bName.toLowerCase()) || aTieBreak.localeCompare(bTieBreak);
+ });
+
+export const paginateRoster = <T>(entries: T[], offset: number, limit: number) => ({
+ items: entries.slice(offset, offset + limit),
+ totalCount: entries.length
+});
diff --git a/backend/src/services/folder-permission/folder-permission-dal.ts b/backend/src/services/folder-permission/folder-permission-dal.ts
index 0917d3074e..7ffd0b5ac9 100644
--- a/backend/src/services/folder-permission/folder-permission-dal.ts
+++ b/backend/src/services/folder-permission/folder-permission-dal.ts
@@ -1,69 +1,35 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { AccessScope, ProjectMembershipRole, TableName, TAdditionalPrivileges } from "@app/db/schemas";
+import { AccessScope, ProjectMembershipRole, TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
-import { sanitizeSqlLikeString } from "@app/lib/fn";
+import { sqlNestRelationships } from "@app/lib/knex";
import { ActorType } from "../auth/auth-type";
+import { TRosterIdentity, TRosterRoleRow, TRosterUser } from "./folder-permission-types";
export type TFolderPermissionDALFactory = ReturnType<typeof folderPermissionDALFactory>;
-// UNION (not UNION ALL): a single actor can be reached both directly and through several groups.
-type TFindFolderAccessActorsDAL = {
- projectId: string;
- orgId: string;
- folderId: string;
- search?: string;
- limit: number;
- offset: number;
-};
+type TFolderActorType = ActorType.USER | ActorType.IDENTITY;
+
+type TProjectScope = { projectId: string; orgId: string };
// Nullable columns come back from knex as `T | null | undefined` because the generated table types
// mark them optional, so every field here has to tolerate undefined and be normalized below.
type TMaybe<T> = T | null | undefined;
-const $folderAccessSelect = (db: Knex) => [
- db.ref("id").withSchema(TableName.AdditionalPrivilege).as("folderAccessId"),
- db.ref("role").withSchema(TableName.AdditionalPrivilege).as("folderAccessRole"),
- db.ref("isTemporary").withSchema(TableName.AdditionalPrivilege).as("folderAccessIsTemporary"),
- db.ref("temporaryMode").withSchema(TableName.AdditionalPrivilege).as("folderAccessTemporaryMode"),
- db.ref("temporaryRange").withSchema(TableName.AdditionalPrivilege).as("folderAccessTemporaryRange"),
- db
- .ref("temporaryAccessStartTime")
- .withSchema(TableName.AdditionalPrivilege)
- .as("folderAccessTemporaryAccessStartTime"),
- db.ref("temporaryAccessEndTime").withSchema(TableName.AdditionalPrivilege).as("folderAccessTemporaryAccessEndTime"),
- db.ref("createdAt").withSchema(TableName.AdditionalPrivilege).as("folderAccessCreatedAt"),
- db.ref("updatedAt").withSchema(TableName.AdditionalPrivilege).as("folderAccessUpdatedAt")
-];
-
-type TFolderAccessRow = {
- folderAccessId: TMaybe<string>;
- folderAccessRole: TMaybe<string>;
- folderAccessIsTemporary: TMaybe<boolean>;
- folderAccessTemporaryMode: TMaybe<string>;
- folderAccessTemporaryRange: TMaybe<string>;
- folderAccessTemporaryAccessStartTime: TMaybe<Date>;
- folderAccessTemporaryAccessEndTime: TMaybe<Date>;
- folderAccessCreatedAt: TMaybe<Date>;
- folderAccessUpdatedAt: TMaybe<Date>;
+type TRosterRoleQueryRow = {
+ membershipRoleId: TMaybe<string>;
+ role: TMaybe<string>;
+ customRoleId: TMaybe<string>;
+ customRoleSlug: TMaybe<string>;
+ customRoleName: TMaybe<string>;
+ customRolePermissions: unknown;
+ isTemporary: TMaybe<boolean>;
+ temporaryAccessEndTime: TMaybe<Date>;
};
-type TFolderAccessGrantRow = Pick<
- TAdditionalPrivileges,
- | "id"
- | "role"
- | "isTemporary"
- | "temporaryMode"
- | "temporaryRange"
- | "temporaryAccessStartTime"
- | "temporaryAccessEndTime"
- | "createdAt"
- | "updatedAt"
->;
-
-type TUserFolderAccessQueryRow = TFolderAccessRow & {
+type TUserRosterQueryRow = TRosterRoleQueryRow & {
userId: string;
username: string;
email: TMaybe<string>;
@@ -72,23 +38,29 @@ type TUserFolderAccessQueryRow = TFolderAccessRow & {
membershipId: TMaybe<string>;
};
-type TIdentityFolderAccessQueryRow = TFolderAccessRow & {
+type TIdentityRosterQueryRow = TRosterRoleQueryRow & {
identityId: string;
name: string;
+ membershipId: TMaybe<string>;
};
-const $mapFolderAccess = (el: TFolderAccessRow): TFolderAccessGrantRow | null => {
- if (!el.folderAccessId || !el.folderAccessCreatedAt || !el.folderAccessUpdatedAt) return null;
+const ROSTER_ROLE_COLUMNS = [
+ "membershipRoleId",
+ "role",
+ "customRoleId",
+ "isTemporary",
+ "temporaryAccessEndTime",
+ "customRoleSlug",
+ "customRoleName",
+ "customRolePermissions"
+] as const;
+
+const $actorColumns = (actorType: TFolderActorType) => {
+ const isIdentity = actorType === ActorType.IDENTITY;
return {
- id: el.folderAccessId,
- role: el.folderAccessRole ?? null,
- isTemporary: Boolean(el.folderAccessIsTemporary),
- temporaryMode: el.folderAccessTemporaryMode ?? null,
- temporaryRange: el.folderAccessTemporaryRange ?? null,
- temporaryAccessStartTime: el.folderAccessTemporaryAccessStartTime ?? null,
- temporaryAccessEndTime: el.folderAccessTemporaryAccessEndTime ?? null,
- createdAt: el.folderAccessCreatedAt,
- updatedAt: el.folderAccessUpdatedAt
+ membershipActorColumn: isIdentity ? "actorIdentityId" : "actorUserId",
+ groupTable: isIdentity ? TableName.IdentityGroupMembership : TableName.UserGroupMembership,
+ groupActorColumn: isIdentity ? "identityId" : "userId"
};
};
@@ -117,17 +89,9 @@ const $activeAdminRole = (qb: Knex.QueryBuilder) => {
// privileges; admins are therefore neither listed as candidates nor accepted as grant targets.
const $projectAdminActorIds = (
conn: Knex,
- {
- projectId,
- orgId,
- actorType,
- actorId
- }: { projectId: string; orgId: string; actorType: ActorType.USER | ActorType.IDENTITY; actorId?: string }
+ { projectId, orgId, actorType, actorId }: TProjectScope & { actorType: TFolderActorType; actorId?: string }
) => {
- const isIdentity = actorType === ActorType.IDENTITY;
- const membershipActorColumn = isIdentity ? "actorIdentityId" : "actorUserId";
- const groupTable = isIdentity ? TableName.IdentityGroupMembership : TableName.UserGroupMembership;
- const groupActorColumn = isIdentity ? "identityId" : "userId";
+ const { membershipActorColumn, groupTable, groupActorColumn } = $actorColumns(actorType);
const direct = conn(TableName.Membership)
.modify($projectScoped(projectId, orgId))
@@ -151,109 +115,94 @@ const $projectAdminActorIds = (
return direct.union([viaGroup]);
};
-const $excludeProjectAdmins =
- (
- conn: Knex,
- {
- projectId,
- orgId,
- actorType
- }: { projectId: string; orgId: string; actorType: ActorType.USER | ActorType.IDENTITY }
- ) =>
- (qb: Knex.QueryBuilder) => {
- const actorTable = actorType === ActorType.IDENTITY ? TableName.Identity : TableName.Users;
- void qb.whereNotIn(`${actorTable}.id`, $projectAdminActorIds(conn, { projectId, orgId, actorType }));
- };
+const $rosterRoleSelect = (conn: Knex, actorIdColumn: string) => [
+ conn.ref(actorIdColumn).as("actorId"),
+ conn.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),
+ conn.ref("role").withSchema(TableName.MembershipRole).as("role"),
+ conn.ref("customRoleId").withSchema(TableName.MembershipRole).as("customRoleId"),
+ conn.ref("isTemporary").withSchema(TableName.MembershipRole).as("isTemporary"),
+ conn.ref("temporaryAccessEndTime").withSchema(TableName.MembershipRole).as("temporaryAccessEndTime"),
+ conn.ref("slug").withSchema(TableName.Role).as("customRoleSlug"),
+ conn.ref("name").withSchema(TableName.Role).as("customRoleName"),
+ conn.ref("permissions").withSchema(TableName.Role).as("customRolePermissions")
+];
-export const folderPermissionDALFactory = (db: TDbClient) => {
- // Bound to the user/identity id, not Membership.actor*Id, which is NULL on a group membership row.
- // permission-dal.ts documents the same bug: the column-to-column form silently dropped privileges
- // for every actor whose only project access came through a group.
- const $joinFolderGrant = (actorTable: TableName.Users | TableName.Identity, folderId: string) => {
- const privilegeActorColumn = actorTable === TableName.Users ? "actorUserId" : "actorIdentityId";
-
- return (qb: Knex.QueryBuilder) => {
- void qb.leftJoin(TableName.AdditionalPrivilege, (bd) => {
- void bd
- .on(`${TableName.AdditionalPrivilege}.${privilegeActorColumn}`, `${actorTable}.id`)
- .andOn(`${TableName.AdditionalPrivilege}.folderId`, "=", db.raw("?", [folderId]));
- });
- };
+// Every membership_roles row an actor holds in the project, whether the membership is their own or
+// one of their groups', keyed by the actor id so it can be joined onto the actor roster.
+const $rosterRolesUnion = (conn: Knex, { projectId, orgId }: TProjectScope, actorType: TFolderActorType) => {
+ const { membershipActorColumn, groupTable, groupActorColumn } = $actorColumns(actorType);
+ const $withRoles = (qb: Knex.QueryBuilder) => {
+ void qb
+ .join(TableName.MembershipRole, `${TableName.Membership}.id`, `${TableName.MembershipRole}.membershipId`)
+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`);
};
+ const direct = conn(TableName.Membership)
+ .modify($projectScoped(projectId, orgId))
+ .whereNotNull(`${TableName.Membership}.${membershipActorColumn}`)
+ .modify($withRoles)
+ .select($rosterRoleSelect(conn, `${TableName.Membership}.${membershipActorColumn}`));
+
+ const viaGroup = conn(groupTable)
+ .join(TableName.Membership, `${groupTable}.groupId`, `${TableName.Membership}.actorGroupId`)
+ .modify($projectScoped(projectId, orgId))
+ .whereNotNull(`${TableName.Membership}.actorGroupId`)
+ .modify($withRoles)
+ .select($rosterRoleSelect(conn, `${groupTable}.${groupActorColumn}`));
+
+ return direct.unionAll([viaGroup], true);
+};
+
+const $toRosterRole = (el: TRosterRoleQueryRow): TRosterRoleRow => ({
+ membershipRoleId: el.membershipRoleId as string,
+ role: el.role ?? "",
+ customRoleId: el.customRoleId ?? null,
+ customRoleSlug: el.customRoleSlug ?? null,
+ customRoleName: el.customRoleName ?? null,
+ customRolePermissions: el.customRolePermissions ?? null,
+ isTemporary: Boolean(el.isTemporary),
+ temporaryAccessEndTime: el.temporaryAccessEndTime ?? null
+});
+
+export const folderPermissionDALFactory = (db: TDbClient) => {
// The direct-membership id is resolved with the same correlated subquery in both union branches
- // so a user reachable directly and through a group still dedupes; NULL for group-only users,
- // whose membership rows have actorUserId = NULL.
- const $userSelect = (projectId: string, orgId: string) => [
+ // so an actor reachable directly and through a group still dedupes; NULL for group-only actors,
+ // whose membership rows have actor*Id = NULL.
+ const $directMembershipId = (
+ { projectId, orgId }: TProjectScope,
+ actorType: TFolderActorType,
+ actorTable: TableName.Users | TableName.Identity
+ ) =>
+ db(TableName.Membership)
+ .modify($projectScoped(projectId, orgId))
+ .where(`${TableName.Membership}.${$actorColumns(actorType).membershipActorColumn}`, db.ref(`${actorTable}.id`))
+ .select(`${TableName.Membership}.id`)
+ .limit(1)
+ .as("membershipId");
+
+ const $userSelect = (scope: TProjectScope) => [
db.ref("id").withSchema(TableName.Users).as("userId"),
db.ref("username").withSchema(TableName.Users).as("username"),
db.ref("email").withSchema(TableName.Users).as("email"),
db.ref("firstName").withSchema(TableName.Users).as("firstName"),
db.ref("lastName").withSchema(TableName.Users).as("lastName"),
- db(TableName.Membership)
- .modify($projectScoped(projectId, orgId))
- .where(`${TableName.Membership}.actorUserId`, db.ref(`${TableName.Users}.id`))
- .select(`${TableName.Membership}.id`)
- .limit(1)
- .as("membershipId"),
- ...$folderAccessSelect(db)
+ $directMembershipId(scope, ActorType.USER, TableName.Users)
];
- const $searchUsers = (search?: string) => (qb: Knex.QueryBuilder) => {
- if (!search) return;
- const term = `%${sanitizeSqlLikeString(search)}%`;
- // grouped so the ORs cannot escape the project scope predicates
- void qb.where((bd) => {
- void bd
- .whereILike(`${TableName.Users}.username`, term)
- .orWhereILike(`${TableName.Users}.email`, term)
- .orWhereILike(`${TableName.Users}.firstName`, term)
- .orWhereILike(`${TableName.Users}.lastName`, term);
- });
- };
-
- const $identitySelect = () => [
+ const $identitySelect = (scope: TProjectScope) => [
db.ref("id").withSchema(TableName.Identity).as("identityId"),
db.ref("name").withSchema(TableName.Identity).as("name"),
- ...$folderAccessSelect(db)
+ $directMembershipId(scope, ActorType.IDENTITY, TableName.Identity)
];
- const $searchIdentities = (search?: string) => (qb: Knex.QueryBuilder) => {
- if (!search) return;
- void qb.whereILike(`${TableName.Identity}.name`, `%${sanitizeSqlLikeString(search)}%`);
- };
-
- const $toUserRow = (el: TUserFolderAccessQueryRow) => ({
- userId: el.userId,
- username: el.username,
- email: el.email ?? null,
- firstName: el.firstName ?? null,
- lastName: el.lastName ?? null,
- membershipId: el.membershipId ?? null,
- folderAccess: $mapFolderAccess(el)
- });
-
- const $toIdentityRow = (el: TIdentityFolderAccessQueryRow) => ({
- identityId: el.identityId,
- name: el.name,
- folderAccess: $mapFolderAccess(el)
- });
-
- const $usersUnion = (
- conn: Knex,
- { projectId, orgId, folderId, search }: Omit<TFindFolderAccessActorsDAL, "limit" | "offset">
- ) => {
- const $excludeAdmins = $excludeProjectAdmins(conn, { projectId, orgId, actorType: ActorType.USER });
-
+ // UNION (not UNION ALL): a single actor can be reached both directly and through several groups.
+ const $usersUnion = (conn: Knex, scope: TProjectScope) => {
const direct = conn(TableName.Membership)
.join(TableName.Users, `${TableName.Users}.id`, `${TableName.Membership}.actorUserId`)
- .modify($projectScoped(projectId, orgId))
+ .modify($projectScoped(scope.projectId, scope.orgId))
.whereNotNull(`${TableName.Membership}.actorUserId`)
.where(`${TableName.Users}.isGhost`, false)
- .modify($excludeAdmins)
- .modify($joinFolderGrant(TableName.Users, folderId))
- .modify($searchUsers(search))
- .select($userSelect(projectId, orgId));
+ .select($userSelect(scope));
// isPending is deliberately not filtered: permission-dal.getPermission grants access on group
// membership alone and the flag is no longer cleared when a user is accepted, so filtering it
@@ -262,31 +211,20 @@ export const folderPermissionDALFactory = (db: TDbClient) => {
const viaGroup = conn(TableName.UserGroupMembership)
.join(TableName.Membership, `${TableName.UserGroupMembership}.groupId`, `${TableName.Membership}.actorGroupId`)
.join(TableName.Users, `${TableName.Users}.id`, `${TableName.UserGroupMembership}.userId`)
- .modify($projectScoped(projectId, orgId))
+ .modify($projectScoped(scope.projectId, scope.orgId))
.whereNotNull(`${TableName.Membership}.actorGroupId`)
.where(`${TableName.Users}.isGhost`, false)
- .modify($excludeAdmins)
- .modify($joinFolderGrant(TableName.Users, folderId))
- .modify($searchUsers(search))
- .select($userSelect(projectId, orgId));
+ .select($userSelect(scope));
return direct.union([viaGroup], true);
};
- const $identitiesUnion = (
- conn: Knex,
- { projectId, orgId, folderId, search }: Omit<TFindFolderAccessActorsDAL, "limit" | "offset">
- ) => {
- const $excludeAdmins = $excludeProjectAdmins(conn, { projectId, orgId, actorType: ActorType.IDENTITY });
-
+ const $identitiesUnion = (conn: Knex, scope: TProjectScope) => {
const direct = conn(TableName.Membership)
.join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)
- .modify($projectScoped(projectId, orgId))
+ .modify($projectScoped(scope.projectId, scope.orgId))
.whereNotNull(`${TableName.Membership}.actorIdentityId`)
- .modify($excludeAdmins)
- .modify($joinFolderGrant(TableName.Identity, folderId))
- .modify($searchIdentities(search))
- .select($identitySelect());
+ .select($identitySelect(scope));
const viaGroup = conn(TableName.IdentityGroupMembership)
.join(
@@ -295,90 +233,138 @@ export const folderPermissionDALFactory = (db: TDbClient) => {
`${TableName.Membership}.actorGroupId`
)
.join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.IdentityGroupMembership}.identityId`)
- .modify($projectScoped(projectId, orgId))
+ .modify($projectScoped(scope.projectId, scope.orgId))
.whereNotNull(`${TableName.Membership}.actorGroupId`)
- .modify($excludeAdmins)
- .modify($joinFolderGrant(TableName.Identity, folderId))
- .modify($searchIdentities(search))
- .select($identitySelect());
+ .select($identitySelect(scope));
return direct.union([viaGroup], true);
};
- const findUsersWithFolderAccess = async (
- { projectId, orgId, folderId, search, limit, offset }: TFindFolderAccessActorsDAL,
- tx?: Knex
- ) => {
+ const $selectRoster = (
+ conn: Knex,
+ actors: Knex.QueryBuilder,
+ actorIdColumn: string,
+ scope: TProjectScope,
+ actorType: TFolderActorType
+ ) =>
+ conn
+ .from(actors.as("roster"))
+ .leftJoin(
+ $rosterRolesUnion(conn, scope, actorType).as("roster_roles"),
+ "roster_roles.actorId",
+ `roster.${actorIdColumn}`
+ )
+ .select("roster.*", ...ROSTER_ROLE_COLUMNS.map((column) => `roster_roles.${column}`));
+
+ const findProjectUserRoster = async (scope: TProjectScope, tx?: Knex) => {
try {
const conn = tx || db.replicaNode();
- const selector = { projectId, orgId, folderId, search };
-
- const [docs, countRow] = (await Promise.all([
- conn
- .from($usersUnion(conn, selector).as("folder_access_users"))
- .orderByRaw("lower(coalesce(??, ''))", ["username"])
- .orderBy("userId")
- .limit(limit)
- .offset(offset),
- conn.from($usersUnion(conn, selector).as("folder_access_users")).count("* as count").first()
- ])) as [TUserFolderAccessQueryRow[], { count?: string | number } | undefined];
-
- return {
- users: docs.map($toUserRow),
- totalCount: Number(countRow?.count ?? 0)
- };
+ const docs = (await $selectRoster(
+ conn,
+ $usersUnion(conn, scope),
+ "userId",
+ scope,
+ ActorType.USER
+ )) as TUserRosterQueryRow[];
+
+ return sqlNestRelationships({
+ data: docs,
+ key: "userId",
+ parentMapper: (el) => ({
+ actor: {
+ userId: el.userId,
+ username: el.username,
+ email: el.email ?? null,
+ firstName: el.firstName ?? null,
+ lastName: el.lastName ?? null,
+ membershipId: el.membershipId ?? null
+ } as TRosterUser
+ }),
+ childrenMapper: [{ key: "membershipRoleId", label: "roles" as const, mapper: $toRosterRole }]
+ });
} catch (error) {
- throw new DatabaseError({ error, name: "FindUsersWithFolderAccess" });
+ throw new DatabaseError({ error, name: "FindProjectUserRoster" });
}
};
- const findIdentitiesWithFolderAccess = async (
- { projectId, orgId, folderId, search, limit, offset }: TFindFolderAccessActorsDAL,
+ const findProjectIdentityRoster = async (scope: TProjectScope, tx?: Knex) => {
+ try {
+ const conn = tx || db.replicaNode();
+ const docs = (await $selectRoster(
+ conn,
+ $identitiesUnion(conn, scope),
+ "identityId",
+ scope,
+ ActorType.IDENTITY
+ )) as TIdentityRosterQueryRow[];
+
+ return sqlNestRelationships({
+ data: docs,
+ key: "identityId",
+ parentMapper: (el) => ({
+ actor: { identityId: el.identityId, name: el.name, membershipId: el.membershipId ?? null } as TRosterIdentity
+ }),
+ childrenMapper: [{ key: "membershipRoleId", label: "roles" as const, mapper: $toRosterRole }]
+ });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindProjectIdentityRoster" });
+ }
+ };
+
+ // Memberships are tracked by createdAt, not updatedAt: every login bumps Membership.updatedAt
+ // (lastLoginTime), which would bust the roster on any member's sign-in.
+ const getFolderAccessRosterFingerprint = async (
+ { projectId, orgId, actorType }: TProjectScope & { actorType: TFolderActorType },
tx?: Knex
) => {
try {
const conn = tx || db.replicaNode();
- const selector = { projectId, orgId, folderId, search };
-
- const [docs, countRow] = (await Promise.all([
- conn
- .from($identitiesUnion(conn, selector).as("folder_access_identities"))
- .orderByRaw("lower(coalesce(??, ''))", ["name"])
- .orderBy("identityId")
- .limit(limit)
- .offset(offset),
- conn.from($identitiesUnion(conn, selector).as("folder_access_identities")).count("* as count").first()
- ])) as [TIdentityFolderAccessQueryRow[], { count?: string | number } | undefined];
-
- return {
- identities: docs.map($toIdentityRow),
- totalCount: Number(countRow?.count ?? 0)
- };
+ const { groupTable } = $actorColumns(actorType);
+ const countAndMax = (column: string) => conn.raw(`count(*) || ':' || coalesce(max(??)::text, '')`, [column]);
+
+ const row = await conn
+ .select(
+ conn(TableName.Membership)
+ .modify($projectScoped(projectId, orgId))
+ .select(countAndMax(`${TableName.Membership}.createdAt`))
+ .as("memberships"),
+ conn(TableName.MembershipRole)
+ .join(TableName.Membership, `${TableName.Membership}.id`, `${TableName.MembershipRole}.membershipId`)
+ .modify($projectScoped(projectId, orgId))
+ .select(countAndMax(`${TableName.MembershipRole}.updatedAt`))
+ .as("membershipRoles"),
+ conn(TableName.Role)
+ .where(`${TableName.Role}.projectId`, projectId)
+ .select(conn.raw(`coalesce(max(??)::text, '')`, [`${TableName.Role}.updatedAt`]))
+ .as("roles"),
+ conn(groupTable)
+ .join(TableName.Membership, `${groupTable}.groupId`, `${TableName.Membership}.actorGroupId`)
+ .modify($projectScoped(projectId, orgId))
+ .whereNotNull(`${TableName.Membership}.actorGroupId`)
+ .select(countAndMax(`${groupTable}.createdAt`))
+ .as("groupMemberships")
+ )
+ .first<{ memberships: string; membershipRoles: string; roles: string; groupMemberships: string }>();
+
+ return [row?.memberships, row?.membershipRoles, row?.roles, row?.groupMemberships].join("|");
} catch (error) {
- throw new DatabaseError({ error, name: "FindIdentitiesWithFolderAccess" });
+ throw new DatabaseError({ error, name: "FolderAccessRosterFingerprint" });
}
};
// Access can be inherited from a group, so this is two lookups rather than one membership read.
// The direct check runs first because it is the common case and short-circuits.
const hasProjectAccess = async (
- {
- projectId,
- orgId,
- actorId,
- actorType
- }: { projectId: string; orgId: string; actorId: string; actorType: ActorType.USER | ActorType.IDENTITY },
+ { projectId, orgId, actorId, actorType }: TProjectScope & { actorId: string; actorType: TFolderActorType },
tx?: Knex
) => {
try {
const conn = tx || db.replicaNode();
- const isIdentity = actorType === ActorType.IDENTITY;
- const groupTable = isIdentity ? TableName.IdentityGroupMembership : TableName.UserGroupMembership;
- const groupActorColumn = isIdentity ? "identityId" : "userId";
+ const { membershipActorColumn, groupTable, groupActorColumn } = $actorColumns(actorType);
const direct = (await conn(TableName.Membership)
.modify($projectScoped(projectId, orgId))
- .where(`${TableName.Membership}.${isIdentity ? "actorIdentityId" : "actorUserId"}`, actorId)
+ .where(`${TableName.Membership}.${membershipActorColumn}`, actorId)
.first(`${TableName.Membership}.id`)) as unknown as { id: string } | undefined;
if (direct) return true;
@@ -395,12 +381,7 @@ export const folderPermissionDALFactory = (db: TDbClient) => {
};
const isProjectAdmin = async (
- {
- projectId,
- orgId,
- actorId,
- actorType
- }: { projectId: string; orgId: string; actorId: string; actorType: ActorType.USER | ActorType.IDENTITY },
+ { projectId, orgId, actorId, actorType }: TProjectScope & { actorId: string; actorType: TFolderActorType },
tx?: Knex
) => {
try {
@@ -415,8 +396,9 @@ export const folderPermissionDALFactory = (db: TDbClient) => {
};
return {
- findUsersWithFolderAccess,
- findIdentitiesWithFolderAccess,
+ findProjectUserRoster,
+ findProjectIdentityRoster,
+ getFolderAccessRosterFingerprint,
hasProjectAccess,
isProjectAdmin
};
diff --git a/backend/src/services/folder-permission/folder-permission-service.ts b/backend/src/services/folder-permission/folder-permission-service.ts
index 86e7c7f239..8861bf869e 100644
--- a/backend/src/services/folder-permission/folder-permission-service.ts
+++ b/backend/src/services/folder-permission/folder-permission-service.ts
@@ -3,12 +3,23 @@ import slugify from "@sindresorhus/slugify";
import { SecretFolderRole } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { withCacheFingerprint } from "@app/lib/cache/with-cache";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
+import { ActorType } from "../auth/auth-type";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
+import {
+ buildFolderAccessRoster,
+ matchesSearch,
+ paginateRoster,
+ reviveFolderAccessRoster,
+ sortRosterEntries,
+ splitFolderAccessRoster
+} from "./folder-access-roles-fns";
import { TFolderPermissionDALFactory } from "./folder-permission-dal";
import {
assertFullAccessIsPermanent,
@@ -23,10 +34,19 @@ import {
toFolderGrant
} from "./folder-permission-fns";
import {
+ TCachedFolderAccessRoster,
TCreateFolderGrantDTO,
TDeleteFolderGrantDTO,
+ TFolderAccessMembership,
+ TFolderAccessRosterEntry,
+ TFolderGrant,
TListActorFolderGrantsDTO,
TListFolderAccessActorsDTO,
+ TResolvedFolder,
+ TRosterActor,
+ TRosterEntry,
+ TRosterIdentity,
+ TRosterUser,
TUpdateFolderGrantDTO
} from "./folder-permission-types";
@@ -39,9 +59,24 @@ type TFolderPermissionServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "invalidateProjectFolderPermissionCache">;
folderPermissionDAL: Pick<
TFolderPermissionDALFactory,
- "findUsersWithFolderAccess" | "findIdentitiesWithFolderAccess" | "hasProjectAccess" | "isProjectAdmin"
+ | "findProjectUserRoster"
+ | "findProjectIdentityRoster"
+ | "getFolderAccessRosterFingerprint"
+ | "hasProjectAccess"
+ | "isProjectAdmin"
>;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
+};
+
+type TFolderActorType = ActorType.USER | ActorType.IDENTITY;
+
+type TProjectScope = { projectId: string; orgId: string };
+
+type TFolderAccessItem<TActor extends TRosterActor> = {
+ actor: TActor;
+ membership: TFolderAccessMembership;
+ folderRBACAccess: TFolderGrant | null;
};
export type TFolderPermissionServiceFactory = ReturnType<typeof folderPermissionServiceFactory>;
@@ -51,7 +86,8 @@ export const folderPermissionServiceFactory = ({
secretFolderDAL,
permissionService,
folderPermissionDAL,
- licenseService
+ licenseService,
+ keyStore
}: TFolderPermissionServiceFactoryDep) => {
const assertFolderRbacLicensed = async (orgId: string) => {
const plan = await licenseService.getPlan(orgId);
@@ -178,53 +214,139 @@ export const folderPermissionServiceFactory = ({
return { folderAccess: toFolderGrant(grant, projectId, folder) };
};
- const listFolderAccessUsers = async (dto: TListFolderAccessActorsDTO) => {
+ const $getFolderAccessRoster = <TActor extends TRosterActor>(
+ { projectId, orgId, folder, actorType }: TProjectScope & { folder: TResolvedFolder; actorType: TFolderActorType },
+ fetchRoster: () => Promise<TRosterEntry<TActor>[]>
+ ) =>
+ withCacheFingerprint<TCachedFolderAccessRoster<TActor>>({
+ keyStore,
+ dataKey: KeyStorePrefixes.ProjectFolderAccessRosterData(projectId, folder.id, actorType),
+ markerKey: KeyStorePrefixes.ProjectFolderAccessRosterMarker(projectId, folder.id, actorType),
+ markerTtlSeconds: KeyStoreTtls.ProjectFolderAccessRosterMarkerTtlSeconds,
+ dataTtlSeconds: KeyStoreTtls.ProjectFolderAccessRosterDataTtlSeconds,
+ // the key is by folder id but the granting roles are evaluated against the folder's path, and a
+ // rename or move changes neither the id nor anything the DB fingerprint tracks
+ fingerprintFetcher: async () => {
+ const fingerprint = await folderPermissionDAL.getFolderAccessRosterFingerprint({ projectId, orgId, actorType });
+ return `${fingerprint}|${folder.environmentSlug}|${folder.path}`;
+ },
+ dataFetcher: async () => buildFolderAccessRoster(await fetchRoster(), folder),
+ reviver: reviveFolderAccessRoster
+ });
+
+ const $listFolderAccessActors = async <TActor extends TRosterActor>(
+ dto: TListFolderAccessActorsDTO,
+ {
+ actorType,
+ fetchRoster,
+ actorIdOf,
+ searchFields,
+ sortKey
+ }: {
+ actorType: TFolderActorType;
+ fetchRoster: (scope: TProjectScope) => Promise<TRosterEntry<TActor>[]>;
+ actorIdOf: (actor: TActor) => string;
+ searchFields: (actor: TActor) => (string | null)[];
+ sortKey: (actor: TActor) => [name: string, tieBreak: string];
+ }
+ ) => {
const { projectId, environmentSlug, secretPath, limit, offset, search } = dto;
- await assertFolderRbacLicensed(dto.permission.orgId);
+ const { orgId } = dto.permission;
+ await assertFolderRbacLicensed(orgId);
const callerPermission = await getFolderAccessPermission(dto.permission, projectId, permissionService);
const folder = await resolveFolder(projectId, environmentSlug, secretPath, secretFolderDAL);
assertManageFolderAccess(callerPermission, folder);
- const { users, totalCount } = await folderPermissionDAL.findUsersWithFolderAccess({
- projectId,
- orgId: dto.permission.orgId,
- folderId: folder.id,
- search,
- limit,
- offset
+ const actorField = actorType === ActorType.USER ? "actorUserId" : "actorIdentityId";
+ // grants stay out of the cached roster so a grant or revoke is visible on the very next request
+ const [roster, grants] = await Promise.all([
+ $getFolderAccessRoster<TActor>({ projectId, orgId, folder, actorType }, () => fetchRoster({ projectId, orgId })),
+ additionalPrivilegeDAL.find({ projectId, folderId: folder.id, $notNull: [actorField] })
+ ]);
+ const grantByActorId = new Map(
+ grants.filter((grant) => grant.role).map((grant) => [grant[actorField] as string, grant])
+ );
+
+ const { withAccess, withoutAccess } = splitFolderAccessRoster({
+ roster,
+ grantByActorId,
+ actorIdOf,
+ now: new Date()
+ });
+
+ const page = (entries: TFolderAccessRosterEntry<TActor>[]) =>
+ paginateRoster(
+ sortRosterEntries(
+ entries.filter((entry) => matchesSearch(search, searchFields(entry.actor))),
+ (entry) => sortKey(entry.actor)
+ ),
+ offset,
+ limit
+ );
+ const toItem = ({ actor, membership, grant }: TFolderAccessRosterEntry<TActor>): TFolderAccessItem<TActor> => ({
+ actor,
+ membership,
+ folderRBACAccess: grant ? toFolderGrant(grant, projectId, folder) : null
});
+ const withAccessPage = page(withAccess);
+ const withoutAccessPage = page(withoutAccess);
return {
- users: users.map(({ folderAccess, ...user }) => ({
- ...user,
- folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folder) : null
- })),
- totalCount
+ withAccess: withAccessPage.items.map(toItem),
+ totalCount: withAccessPage.totalCount,
+ withoutAccess: withoutAccessPage.items.map(toItem),
+ totalCountWithoutAccess: withoutAccessPage.totalCount
+ };
+ };
+
+ const listFolderAccessUsers = async (dto: TListFolderAccessActorsDTO) => {
+ const toUser = ({ actor, membership, folderRBACAccess }: TFolderAccessItem<TRosterUser>) => ({
+ userId: actor.userId,
+ username: actor.username,
+ email: actor.email,
+ firstName: actor.firstName,
+ lastName: actor.lastName,
+ membership,
+ folderRBACAccess
+ });
+
+ const result = await $listFolderAccessActors<TRosterUser>(dto, {
+ actorType: ActorType.USER,
+ fetchRoster: (scope) => folderPermissionDAL.findProjectUserRoster(scope),
+ actorIdOf: (user) => user.userId,
+ searchFields: (user) => [user.username, user.email, user.firstName, user.lastName],
+ sortKey: (user) => [user.username, user.userId]
+ });
+
+ return {
+ users: result.withAccess.map(toUser),
+ usersWithoutAccess: result.withoutAccess.map(toUser),
+ totalCount: result.totalCount,
+ totalCountWithoutAccess: result.totalCountWithoutAccess
};
};
const listFolderAccessIdentities = async (dto: TListFolderAccessActorsDTO) => {
- const { projectId, environmentSlug, secretPath, limit, offset, search } = dto;
- await assertFolderRbacLicensed(dto.permission.orgId);
- const callerPermission = await getFolderAccessPermission(dto.permission, projectId, permissionService);
- const folder = await resolveFolder(projectId, environmentSlug, secretPath, secretFolderDAL);
- assertManageFolderAccess(callerPermission, folder);
+ const toIdentity = ({ actor, membership, folderRBACAccess }: TFolderAccessItem<TRosterIdentity>) => ({
+ identityId: actor.identityId,
+ name: actor.name,
+ membership,
+ folderRBACAccess
+ });
- const { identities, totalCount } = await folderPermissionDAL.findIdentitiesWithFolderAccess({
- projectId,
- orgId: dto.permission.orgId,
- folderId: folder.id,
- search,
- limit,
- offset
+ const result = await $listFolderAccessActors<TRosterIdentity>(dto, {
+ actorType: ActorType.IDENTITY,
+ fetchRoster: (scope) => folderPermissionDAL.findProjectIdentityRoster(scope),
+ actorIdOf: (identity) => identity.identityId,
+ searchFields: (identity) => [identity.name],
+ sortKey: (identity) => [identity.name, identity.identityId]
});
return {
- identities: identities.map(({ folderAccess, ...identity }) => ({
- ...identity,
- folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folder) : null
- })),
- totalCount
+ identities: result.withAccess.map(toIdentity),
+ identitiesWithoutAccess: result.withoutAccess.map(toIdentity),
+ totalCount: result.totalCount,
+ totalCountWithoutAccess: result.totalCountWithoutAccess
};
};
diff --git a/backend/src/services/folder-permission/folder-permission-types.ts b/backend/src/services/folder-permission/folder-permission-types.ts
index 7d7ae71ccc..2396c0dc07 100644
--- a/backend/src/services/folder-permission/folder-permission-types.ts
+++ b/backend/src/services/folder-permission/folder-permission-types.ts
@@ -1,4 +1,4 @@
-import { SecretFolderRole, TemporaryPermissionMode } from "@app/db/schemas";
+import { SecretFolderRole, TAdditionalPrivileges, TemporaryPermissionMode } from "@app/db/schemas";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "../auth/auth-type";
@@ -85,3 +85,62 @@ export type TFolderGrant = {
createdAt: Date;
updatedAt: Date;
};
+
+export type TFolderAccessRole = {
+ id: string | null;
+ slug: string;
+ name: string;
+};
+
+export type TFolderAccessMembership = {
+ id: string | null;
+ isProjectAdmin: boolean;
+ roles: TFolderAccessRole[];
+};
+
+export type TRosterRoleRow = {
+ membershipRoleId: string;
+ role: string;
+ customRoleId: string | null;
+ customRoleSlug: string | null;
+ customRoleName: string | null;
+ customRolePermissions: unknown;
+ isTemporary: boolean;
+ temporaryAccessEndTime: Date | null;
+};
+
+export type TCachedRosterRole = TFolderAccessRole & {
+ isTemporary: boolean;
+ temporaryAccessEndTime: Date | null;
+};
+
+export type TRosterActor = { membershipId: string | null };
+
+export type TRosterUser = TRosterActor & {
+ userId: string;
+ username: string;
+ email: string | null;
+ firstName: string | null;
+ lastName: string | null;
+};
+
+export type TRosterIdentity = TRosterActor & {
+ identityId: string;
+ name: string;
+};
+
+export type TRosterEntry<TActor extends TRosterActor> = {
+ actor: TActor;
+ roles: TRosterRoleRow[];
+};
+
+export type TCachedFolderAccessRoster<TActor extends TRosterActor> = {
+ actors: { actor: TActor; roles: TCachedRosterRole[] }[];
+ grantingRoleKeys: string[];
+};
+
+export type TFolderAccessRosterEntry<TActor extends TRosterActor> = {
+ actor: TActor;
+ membership: TFolderAccessMembership;
+ grant: TAdditionalPrivileges | null;
+};
diff --git a/frontend/src/hooks/api/folderAccess/index.ts b/frontend/src/hooks/api/folderAccess/index.ts
index 2bd8ea0a43..853ac3e461 100644
--- a/frontend/src/hooks/api/folderAccess/index.ts
+++ b/frontend/src/hooks/api/folderAccess/index.ts
@@ -20,10 +20,14 @@ export type {
TDeleteUserFolderAccessDTO,
TFolderAccess,
TFolderAccessIdentity,
+ TFolderAccessMembership,
+ TFolderAccessRole,
TFolderAccessUser,
TFolderGrantType,
TIdentityFolderAccess,
TListFolderAccessActorsDTO,
+ TListFolderAccessIdentitiesResponse,
+ TListFolderAccessUsersResponse,
TListIdentityFolderAccessDTO,
TListUserFolderAccessDTO,
TUpdateIdentityFolderAccessDTO,
diff --git a/frontend/src/hooks/api/folderAccess/queries.tsx b/frontend/src/hooks/api/folderAccess/queries.tsx
index df352c2c25..fe048ebeb2 100644
--- a/frontend/src/hooks/api/folderAccess/queries.tsx
+++ b/frontend/src/hooks/api/folderAccess/queries.tsx
@@ -3,10 +3,10 @@ import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import {
- TFolderAccessIdentity,
- TFolderAccessUser,
TIdentityFolderAccess,
TListFolderAccessActorsDTO,
+ TListFolderAccessIdentitiesResponse,
+ TListFolderAccessUsersResponse,
TListIdentityFolderAccessDTO,
TListUserFolderAccessDTO,
TUserFolderAccess
@@ -63,7 +63,7 @@ export const useListFolderAccessUsers = ({
search
}),
queryFn: async () => {
- const { data } = await apiRequest.get<{ users: TFolderAccessUser[]; totalCount: number }>(
+ const { data } = await apiRequest.get<TListFolderAccessUsersResponse>(
`/api/v1/projects/${projectId}/secret-folder-access/users`,
{
params: { environmentSlug, secretPath, offset, limit, ...(search ? { search } : {}) }
@@ -119,12 +119,12 @@ export const useListFolderAccessIdentities = ({
search
}),
queryFn: async () => {
- const { data } = await apiRequest.get<{
- identities: TFolderAccessIdentity[];
- totalCount: number;
- }>(`/api/v1/projects/${projectId}/memberships/secret-folder-access/identities`, {
- params: { environmentSlug, secretPath, offset, limit, ...(search ? { search } : {}) }
- });
+ const { data } = await apiRequest.get<TListFolderAccessIdentitiesResponse>(
+ `/api/v1/projects/${projectId}/memberships/secret-folder-access/identities`,
+ {
+ params: { environmentSlug, secretPath, offset, limit, ...(search ? { search } : {}) }
+ }
+ );
return data;
},
enabled: Boolean(projectId) && Boolean(environmentSlug) && Boolean(secretPath)
diff --git a/frontend/src/hooks/api/folderAccess/types.ts b/frontend/src/hooks/api/folderAccess/types.ts
index 7d75f963bb..7526dc933d 100644
--- a/frontend/src/hooks/api/folderAccess/types.ts
+++ b/frontend/src/hooks/api/folderAccess/types.ts
@@ -31,22 +31,54 @@ export type TFolderAccess = {
updatedAt: string;
};
+export type TFolderAccessRole = {
+ id: string | null;
+ slug: string;
+ name: string;
+};
+
+// id is null when the actor reaches the project only through a group
+export type TFolderAccessMembership = {
+ id: string | null;
+ isProjectAdmin: boolean;
+ roles: TFolderAccessRole[];
+};
+
export type TFolderAccessUser = {
userId: string;
- membershipId: string | null;
username: string;
email: string | null;
firstName: string | null;
lastName: string | null;
+ membership: TFolderAccessMembership;
folderRBACAccess: TFolderAccess | null;
};
export type TFolderAccessIdentity = {
identityId: string;
name: string;
+ membership: TFolderAccessMembership;
folderRBACAccess: TFolderAccess | null;
};
+// `users` have access on the folder and membership.roles holds only the roles granting it (empty
+// when the access comes from the folder grant alone). `usersWithoutAccess` have none, their
+// membership.roles holds every role, and folderRBACAccess is always null. search/offset/limit
+// apply to each group independently.
+export type TListFolderAccessUsersResponse = {
+ users: TFolderAccessUser[];
+ usersWithoutAccess: TFolderAccessUser[];
+ totalCount: number;
+ totalCountWithoutAccess: number;
+};
+
+export type TListFolderAccessIdentitiesResponse = {
+ identities: TFolderAccessIdentity[];
+ identitiesWithoutAccess: TFolderAccessIdentity[];
+ totalCount: number;
+ totalCountWithoutAccess: number;
+};
+
export type TUserFolderAccess = TFolderAccess & { userId: string };
export type TIdentityFolderAccess = TFolderAccess & { identityId: string };
diff --git a/frontend/src/pages/project/components/FolderAccessSection/FolderAccessSection.tsx b/frontend/src/pages/project/components/FolderAccessSection/FolderAccessSection.tsx
index 3640989b9c..033d855d7f 100644
--- a/frontend/src/pages/project/components/FolderAccessSection/FolderAccessSection.tsx
+++ b/frontend/src/pages/project/components/FolderAccessSection/FolderAccessSection.tsx
@@ -111,17 +111,18 @@ export const FolderAccessSection = ({ actor, hideActions = false }: Props) => {
if (actor.type === "user") {
return toUserActor({
userId: actor.id,
- membershipId: actor.membershipId,
username: actor.username,
email: actor.email,
firstName: actor.firstName,
lastName: actor.lastName,
+ membership: { id: actor.membershipId, isProjectAdmin: false, roles: [] },
folderRBACAccess: deleteTarget
});
}
return toIdentityActor({
identityId: actor.id,
name: actor.name,
+ membership: { id: null, isProjectAdmin: false, roles: [] },
folderRBACAccess: deleteTarget
});
})();
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/AddFolderAccessSheet.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/AddFolderAccessSheet.tsx
index f08c7302ff..1097c461ae 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/AddFolderAccessSheet.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/AddFolderAccessSheet.tsx
@@ -26,6 +26,7 @@ import {
import { DEFAULT_TEMPORARY_RANGE, TEMPORARY_RANGE_PRESETS } from "./folder-access.const";
import {
+ byName,
isValidTemporaryRange,
TFolderAccessActor,
toIdentityActor,
@@ -80,11 +81,9 @@ export const AddFolderAccessSheet = ({
const candidates = useMemo(
() =>
[
- ...(users?.users ?? []).map(toUserActor),
- ...(identities?.identities ?? []).map(toIdentityActor)
- ]
- .filter((actor) => !actor.access)
- .sort((a, b) => a.name.localeCompare(b.name)),
+ ...(users?.usersWithoutAccess ?? []).map(toUserActor),
+ ...(identities?.identitiesWithoutAccess ?? []).map(toIdentityActor)
+ ].sort(byName),
[users, identities]
);
@@ -183,7 +182,11 @@ export const AddFolderAccessSheet = ({
// client filter would drop matches found by email or identity metadata
filterOption={null}
placeholder="Search users & machine identities"
- noOptionsMessage={() => "No matches found"}
+ noOptionsMessage={({ inputValue }) =>
+ inputValue
+ ? "No matches found"
+ : "Every project member already has access to this folder."
+ }
/>
</div>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessRow.tsx
index 5a60df2dab..d2e631e97e 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessRow.tsx
@@ -1,5 +1,5 @@
import { useState } from "react";
-import { BotIcon, ChevronDownIcon, ClockIcon, TriangleAlertIcon } from "lucide-react";
+import { BotIcon, ChevronDownIcon, ClockIcon, ShieldIcon, TriangleAlertIcon } from "lucide-react";
import {
Badge,
@@ -30,6 +30,26 @@ import {
} from "./folder-access.utils";
import { TierDropdown } from "./TierDropdown";
+const ActorIdentity = ({ actor }: { actor: TFolderAccessActor }) => (
+ <>
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-border bg-neutral/10 text-xs font-semibold text-accent">
+ {actor.type === "identity" ? <BotIcon className="size-4" /> : actor.initials}
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <p className="truncate text-sm font-medium text-foreground">{actor.name}</p>
+ {actor.isProjectAdmin && (
+ <Badge variant="neutral" className="shrink-0">
+ <ShieldIcon />
+ Admin
+ </Badge>
+ )}
+ </div>
+ <p className="truncate text-xs text-muted">{actor.subtitle}</p>
+ </div>
+ </>
+);
+
type Props = {
actor: TFolderAccessActor;
isDisabled?: boolean;
@@ -55,21 +75,27 @@ export const FolderAccessRow = ({
const isExpired = Boolean(expiresAt && expiresAt.getTime() <= Date.now());
const firstName = actor.name.split(" ")[0];
const isRangeValid = isValidTemporaryRange(range);
+ const roleNames = actor.roles.map((role) => role.name).join(", ");
const openTemporary = () => {
setRange(access?.temporaryRange || DEFAULT_TEMPORARY_RANGE);
setIsTemporaryOpen(true);
};
+ // admins already have full access everywhere and cannot be granted folder access, so the row is
+ // shown for completeness with no controls at all
+ if (actor.isProjectAdmin) {
+ return (
+ <div className="flex items-center gap-3 border-b border-border py-3">
+ <ActorIdentity actor={actor} />
+ <p className="shrink-0 text-sm text-muted">Full access on all folders</p>
+ </div>
+ );
+ }
+
return (
<div className="flex items-center gap-3 border-b border-border py-3">
- <div className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-border bg-neutral/10 text-xs font-semibold text-accent">
- {actor.type === "identity" ? <BotIcon className="size-4" /> : actor.initials}
- </div>
- <div className="min-w-0 flex-1">
- <p className="truncate text-sm font-medium text-foreground">{actor.name}</p>
- <p className="truncate text-xs text-muted">{actor.subtitle}</p>
- </div>
+ <ActorIdentity actor={actor} />
{expiresAt && (
<Tooltip>
@@ -85,7 +111,7 @@ export const FolderAccessRow = ({
</Tooltip>
)}
- {access && (
+ {access && actor.roles.length > 0 && (
<Tooltip>
<TooltipTrigger>
<Badge variant="warning" className="shrink-0">
@@ -103,8 +129,8 @@ export const FolderAccessRow = ({
<PopoverAnchor asChild>
<div className="shrink-0">
<DropdownMenu>
- <DropdownMenuTrigger asChild>
- {access ? (
+ {access ? (
+ <DropdownMenuTrigger asChild>
<Button
variant="outline"
size="sm"
@@ -114,14 +140,26 @@ export const FolderAccessRow = ({
{FOLDER_ROLE_TIER_LABELS[access.permission]}
<ChevronDownIcon />
</Button>
- ) : (
- <Button variant="outline" size="sm" isDisabled={isDisabled}>
- <TriangleAlertIcon className="text-warning" />
- Access via project role
- <ChevronDownIcon />
- </Button>
- )}
- </DropdownMenuTrigger>
+ </DropdownMenuTrigger>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" size="sm" isDisabled={isDisabled}>
+ <TriangleAlertIcon className="text-warning" />
+ Access via project role
+ <ChevronDownIcon />
+ </Button>
+ </DropdownMenuTrigger>
+ </TooltipTrigger>
+ <TooltipContent side="left" className="flex max-w-64 flex-col gap-0.5">
+ <span className="font-medium">Project roles</span>
+ <span className="opacity-70">
+ {roleNames || "No project role found for this folder."}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ )}
<TierDropdown
activeTier={access?.permission ?? null}
headerNote={
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessSheet.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessSheet.tsx
index 1703aae1f2..91a42e7662 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessSheet.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessSheet.tsx
@@ -39,7 +39,12 @@ import {
import { AddFolderAccessSheet } from "./AddFolderAccessSheet";
import { FOLDER_ROLE_TIER_LABELS } from "./folder-access.const";
-import { byName, TFolderAccessActor, toIdentityActor, toUserActor } from "./folder-access.utils";
+import {
+ byAdminThenName,
+ TFolderAccessActor,
+ toIdentityActor,
+ toUserActor
+} from "./folder-access.utils";
import { FolderAccessRow } from "./FolderAccessRow";
import { RemoveFolderAccessDialog } from "./RemoveFolderAccessDialog";
@@ -94,7 +99,7 @@ export const FolderAccessSheet = ({
[
...(users?.users ?? []).map(toUserActor),
...(identities?.identities ?? []).map(toIdentityActor)
- ].sort(byName),
+ ].sort(byAdminThenName),
[users, identities]
);
@@ -224,7 +229,7 @@ export const FolderAccessSheet = ({
<EmptyDescription>
{debouncedSearch.trim()
? "No users or machine identities match your search."
- : "This project has no users or machine identities yet."}
+ : "No users or machine identities have access to this folder."}
</EmptyDescription>
</EmptyHeader>
</Empty>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.const.ts b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.const.ts
index 93f5f69f16..875f744fa7 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.const.ts
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.const.ts
@@ -25,8 +25,8 @@ export const FOLDER_ROLE_TIERS: TFolderRoleTier[] = [
},
{
value: SecretFolderRole.Manage,
- label: "Configure",
- description: "Can configure rotations, dynamic secrets, and honey tokens."
+ label: "Manage",
+ description: "Can manage rotations, dynamic secrets, and honey tokens."
},
{
value: SecretFolderRole.FullAccess,
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.utils.ts b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.utils.ts
index c9d16de8ee..f520d98013 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.utils.ts
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/folder-access.utils.ts
@@ -3,6 +3,7 @@ import { format } from "date-fns";
import {
TFolderAccess,
TFolderAccessIdentity,
+ TFolderAccessRole,
TFolderAccessUser
} from "@app/hooks/api/folderAccess";
import { ms } from "@app/lib/fn/time";
@@ -14,9 +15,15 @@ export type TFolderAccessActor = {
name: string;
subtitle: string;
initials: string;
+ isProjectAdmin: boolean;
+ // with access: only the roles granting access on this folder; without access: every role
+ roles: TFolderAccessRole[];
access: TFolderAccess | null;
};
+const sortRoles = (roles: TFolderAccessRole[]) =>
+ [...roles].sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
+
const initialsOf = (value: string) =>
value
.split(/[\s@._-]+/)
@@ -31,10 +38,12 @@ export const toUserActor = (user: TFolderAccessUser): TFolderAccessActor => {
return {
type: "user",
id: user.userId,
- membershipId: user.membershipId,
+ membershipId: user.membership.id,
name,
subtitle: user.email ?? user.username,
initials: initialsOf(name),
+ isProjectAdmin: user.membership.isProjectAdmin,
+ roles: sortRoles(user.membership.roles),
access: user.folderRBACAccess
};
};
@@ -42,16 +51,21 @@ export const toUserActor = (user: TFolderAccessUser): TFolderAccessActor => {
export const toIdentityActor = (identity: TFolderAccessIdentity): TFolderAccessActor => ({
type: "identity",
id: identity.identityId,
- membershipId: null,
+ membershipId: identity.membership.id,
name: identity.name,
subtitle: "Machine identity",
initials: initialsOf(identity.name),
+ isProjectAdmin: identity.membership.isProjectAdmin,
+ roles: sortRoles(identity.membership.roles),
access: identity.folderRBACAccess
});
export const byName = (a: TFolderAccessActor, b: TFolderAccessActor) =>
a.name.localeCompare(b.name);
+export const byAdminThenName = (a: TFolderAccessActor, b: TFolderAccessActor) =>
+ Number(b.isProjectAdmin) - Number(a.isProjectAdmin) || byName(a, b);
+
export const isValidTemporaryRange = (value: string) => {
if (!value.trim()) return false;
try {