Skip to content

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

feat: define api design

adilson57aff33cb2d7
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 61e15a2f5d..46b362d059 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -210,7 +210,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` (any future grant/revoke API 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.
### Request-Scoped Memoization
diff --git a/backend/e2e-test/routes/v2/identity-folder-access.spec.ts b/backend/e2e-test/routes/v1/identity-folder-access.spec.ts
similarity index 80%
rename from backend/e2e-test/routes/v2/identity-folder-access.spec.ts
rename to backend/e2e-test/routes/v1/identity-folder-access.spec.ts
index be4f482f80..72a6fc36a6 100644
--- a/backend/e2e-test/routes/v2/identity-folder-access.spec.ts
+++ b/backend/e2e-test/routes/v1/identity-folder-access.spec.ts
@@ -19,13 +19,16 @@ const adminIdentityId = seedData1.machineIdentity.id;
let memberIdentityId: string;
let memberIdentityName: string;
-const folderAccessUrl = (folderId: string, targetIdentityId?: string) =>
- `/api/v2/identity-project-additional-privilege/projects/${projectId}/identities/${
- targetIdentityId ?? memberIdentityId
- }/folder-access/${folderId}`;
+const folderPath = "/identity-folder-access";
+const folderTarget = { environmentSlug: seedData1.environment.slug, secretPath: folderPath };
-const folderAccessIdentitiesUrl = (folderId: string, query = "") =>
- `/api/v2/identity-project-additional-privilege/projects/${projectId}/folder-access/${folderId}/identities${query}`;
+const folderAccessUrl = (targetIdentityId?: string) =>
+ `/api/v1/projects/${projectId}/memberships/identities/${targetIdentityId ?? memberIdentityId}/secret-folder-access`;
+
+const folderAccessIdentitiesUrl = (query = "") =>
+ `/api/v1/projects/${projectId}/memberships/secret-folder-access/identities?environmentSlug=${
+ seedData1.environment.slug
+ }&secretPath=${encodeURIComponent(folderPath)}${query}`;
const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });
@@ -111,9 +114,10 @@ describe("Identity folder access CRUD", () => {
const temporaryAccessStartTime = new Date().toISOString();
const createRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
body: {
+ ...folderTarget,
permission: SecretFolderRole.Manage,
type: {
isTemporary: true,
@@ -145,18 +149,18 @@ describe("Identity folder access CRUD", () => {
const conflictRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(conflictRes.statusCode).toBe(400);
expect(conflictRes.json().message).toContain("already has folder access");
const patchRes = await testServer.inject({
method: "PATCH",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.List, type: { isTemporary: false } }
+ body: { ...folderTarget, permission: SecretFolderRole.List, type: { isTemporary: false } }
});
expect(patchRes.statusCode).toBe(200);
const patched = patchRes.json().folderAccess;
@@ -166,8 +170,9 @@ describe("Identity folder access CRUD", () => {
const deleteRes = await testServer.inject({
method: "DELETE",
- url: folderAccessUrl(folder.id),
- headers: authHeaders()
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: folderTarget
});
expect(deleteRes.statusCode).toBe(200);
expect(deleteRes.json().folderAccess.id).toBe(created.id);
@@ -178,23 +183,53 @@ describe("Identity folder access CRUD", () => {
test("rejects granting to or updating a project admin identity", async () => {
const createRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id, adminIdentityId),
+ url: folderAccessUrl(adminIdentityId),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(createRes.statusCode).toBe(400);
expect(createRes.json().message).toContain("project admin role");
const patchRes = await testServer.inject({
method: "PATCH",
- url: folderAccessUrl(folder.id, adminIdentityId),
+ url: folderAccessUrl(adminIdentityId),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Edit }
+ body: { ...folderTarget, permission: SecretFolderRole.Edit }
});
expect(patchRes.statusCode).toBe(400);
expect(patchRes.json().message).toContain("project admin role");
});
+ test("rejects folder access at an unknown or malformed location", async () => {
+ const unknownPathRes = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: {
+ environmentSlug: seedData1.environment.slug,
+ secretPath: "/no-such-folder",
+ permission: SecretFolderRole.Read
+ }
+ });
+ expect(unknownPathRes.statusCode).toBe(404);
+
+ const unknownEnvRes = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { environmentSlug: "no-such-env", secretPath: folderPath, permission: SecretFolderRole.Read }
+ });
+ expect(unknownEnvRes.statusCode).toBe(404);
+
+ const malformedPathRes = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { environmentSlug: seedData1.environment.slug, secretPath: "/bad name!", permission: SecretFolderRole.Read }
+ });
+ expect(malformedPathRes.statusCode).toBe(400);
+ });
+
describe("roster", () => {
const listIdentities = async (
query = ""
@@ -204,7 +239,7 @@ describe("Identity folder access CRUD", () => {
}> => {
const res = await testServer.inject({
method: "GET",
- url: folderAccessIdentitiesUrl(folder.id, query),
+ url: folderAccessIdentitiesUrl(query),
headers: authHeaders()
});
expect(res.statusCode).toBe(200);
@@ -212,7 +247,7 @@ describe("Identity folder access CRUD", () => {
};
test("excludes project admin identities from the roster", async () => {
- const { identities } = await listIdentities("?limit=100");
+ const { identities } = await listIdentities("&limit=100");
expect(identities.map((identity) => identity.identityId)).not.toContain(adminIdentityId);
});
@@ -226,9 +261,9 @@ describe("Identity folder access CRUD", () => {
const createRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Edit }
+ body: { ...folderTarget, permission: SecretFolderRole.Edit }
});
expect(createRes.statusCode).toBe(200);
@@ -247,8 +282,9 @@ describe("Identity folder access CRUD", () => {
const deleteRes = await testServer.inject({
method: "DELETE",
- url: folderAccessUrl(folder.id),
- headers: authHeaders()
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: folderTarget
});
expect(deleteRes.statusCode).toBe(200);
@@ -259,16 +295,16 @@ describe("Identity folder access CRUD", () => {
});
test("filters by search and keeps totalCount stable past the end", async () => {
- const matching = await listIdentities(`?search=${encodeURIComponent(memberIdentityName)}`);
+ const matching = await listIdentities(`&search=${encodeURIComponent(memberIdentityName)}`);
expect(matching.identities.map((identity) => identity.identityId)).toContain(memberIdentityId);
const { totalCount } = await listIdentities();
- const pastTheEnd = await listIdentities(`?limit=1&offset=${totalCount + 10}`);
+ const pastTheEnd = await listIdentities(`&limit=1&offset=${totalCount + 10}`);
expect(pastTheEnd.identities).toEqual([]);
expect(pastTheEnd.totalCount).toBe(totalCount);
- const nonMatching = await listIdentities("?search=zzz-no-such-identity");
+ const nonMatching = await listIdentities("&search=zzz-no-such-identity");
expect(nonMatching.identities).toEqual([]);
expect(nonMatching.totalCount).toBe(0);
});
@@ -327,7 +363,7 @@ describe("Identity folder access CRUD", () => {
});
test("lists an identity whose only project access is a group, once", async () => {
- const { identities, totalCount } = await listIdentities("?limit=100");
+ const { identities, totalCount } = await listIdentities("&limit=100");
const groupIdentity = identities.find((identity) => identity.identityId === groupIdentityId);
expect(groupIdentity).toBeDefined();
@@ -340,23 +376,28 @@ describe("Identity folder access CRUD", () => {
});
test("grants folder access to a group-derived identity and shows it on the roster", async () => {
- const grantUrl = folderAccessUrl(folder.id, groupIdentityId);
+ const grantUrl = folderAccessUrl(groupIdentityId);
const createRes = await testServer.inject({
method: "POST",
url: grantUrl,
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(createRes.statusCode).toBe(200);
- const { identities } = await listIdentities("?limit=100");
+ const { identities } = await listIdentities("&limit=100");
const granted = identities.find((identity) => identity.identityId === groupIdentityId);
expect(granted!.folderRBACAccess).toEqual(
expect.objectContaining({ folderId: folder.id, permission: SecretFolderRole.Read })
);
- const deleteRes = await testServer.inject({ method: "DELETE", url: grantUrl, headers: authHeaders() });
+ const deleteRes = await testServer.inject({
+ method: "DELETE",
+ url: grantUrl,
+ headers: authHeaders(),
+ body: folderTarget
+ });
expect(deleteRes.statusCode).toBe(200);
});
@@ -388,16 +429,16 @@ describe("Identity folder access CRUD", () => {
});
test("excludes an identity whose admin role comes from a group", async () => {
- const { identities } = await listIdentities("?limit=100");
+ const { identities } = await listIdentities("&limit=100");
expect(identities.map((identity) => identity.identityId)).not.toContain(groupAdminIdentityId);
});
test("rejects granting to an identity whose admin role comes from a group", async () => {
const res = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id, groupAdminIdentityId),
+ url: folderAccessUrl(groupAdminIdentityId),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(res.statusCode).toBe(400);
expect(res.json().message).toContain("project admin role");
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 f80a248017..d21729c1c8 100644
--- a/backend/e2e-test/routes/v1/user-folder-access.spec.ts
+++ b/backend/e2e-test/routes/v1/user-folder-access.spec.ts
@@ -23,13 +23,18 @@ let memberUserId: string;
let memberEmail: string;
let memberProjectMembershipId: string;
-const folderAccessUrl = (folderId: string, targetUserId?: string) =>
- `/api/v1/user-project-additional-privilege/projects/${projectId}/users/${
- targetUserId ?? memberUserId
- }/folder-access/${folderId}`;
+const folderTarget = {
+ environmentSlug: seedData1.environment.slug,
+ secretPath: "/user-folder-access"
+};
+
+const folderAccessUrl = (targetUserId?: string) =>
+ `/api/v1/projects/${projectId}/users/${targetUserId ?? memberUserId}/secret-folder-access`;
-const folderAccessUsersUrl = (folderId: string, query = "") =>
- `/api/v1/user-project-additional-privilege/projects/${projectId}/folder-access/${folderId}/users${query}`;
+const folderAccessUsersUrl = (query = "", target: { environmentSlug: string; secretPath: string } = folderTarget) =>
+ `/api/v1/projects/${projectId}/secret-folder-access/users?environmentSlug=${encodeURIComponent(
+ target.environmentSlug
+ )}&secretPath=${encodeURIComponent(target.secretPath)}${query}`;
const authHeaders = () => ({ authorization: `Bearer ${jwtAuthToken}` });
@@ -132,9 +137,9 @@ describe("User folder access CRUD", () => {
const createRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(createRes.statusCode).toBe(200);
const created = createRes.json().folderAccess;
@@ -157,9 +162,9 @@ describe("User folder access CRUD", () => {
const conflictRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Edit }
+ body: { ...folderTarget, permission: SecretFolderRole.Edit }
});
expect(conflictRes.statusCode).toBe(400);
expect(conflictRes.json().message).toContain("already has folder access");
@@ -167,9 +172,10 @@ describe("User folder access CRUD", () => {
const temporaryAccessStartTime = new Date().toISOString();
const patchRes = await testServer.inject({
method: "PATCH",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
body: {
+ ...folderTarget,
permission: SecretFolderRole.Edit,
type: {
isTemporary: true,
@@ -192,9 +198,9 @@ describe("User folder access CRUD", () => {
const permanentRes = await testServer.inject({
method: "PATCH",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { type: { isTemporary: false } }
+ body: { ...folderTarget, type: { isTemporary: false } }
});
expect(permanentRes.statusCode).toBe(200);
const permanent = permanentRes.json().folderAccess;
@@ -205,9 +211,9 @@ describe("User folder access CRUD", () => {
const emptyPatchRes = await testServer.inject({
method: "PATCH",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: {}
+ body: { ...folderTarget }
});
expect(emptyPatchRes.statusCode).toBe(422);
@@ -221,8 +227,9 @@ describe("User folder access CRUD", () => {
const deleteRes = await testServer.inject({
method: "DELETE",
- url: folderAccessUrl(folder.id),
- headers: authHeaders()
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget }
});
expect(deleteRes.statusCode).toBe(200);
expect(deleteRes.json().folderAccess.id).toBe(created.id);
@@ -231,28 +238,49 @@ describe("User folder access CRUD", () => {
const deleteAgainRes = await testServer.inject({
method: "DELETE",
- url: folderAccessUrl(folder.id),
- headers: authHeaders()
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget }
});
expect(deleteAgainRes.statusCode).toBe(404);
});
- test("returns 404 for a folder outside the project", async () => {
+ test("returns 404 for an unknown secret path", async () => {
const res = await testServer.inject({
method: "POST",
- url: folderAccessUrl("00000000-0000-0000-0000-000000000000"),
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget, secretPath: "/no-such-folder", permission: SecretFolderRole.Read }
+ });
+ expect(res.statusCode).toBe(404);
+ });
+
+ test("returns 404 for an unknown environment", async () => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, environmentSlug: "no-such-env", permission: SecretFolderRole.Read }
});
expect(res.statusCode).toBe(404);
});
+ test("returns 400 for a malformed secret path", async () => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget, secretPath: "/bad name!", permission: SecretFolderRole.Read }
+ });
+ expect(res.statusCode).toBe(400);
+ });
+
test("returns 404 for a target that is not a project member", async () => {
const res = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id, "00000000-0000-0000-0000-000000000000"),
+ url: folderAccessUrl("00000000-0000-0000-0000-000000000000"),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(res.statusCode).toBe(404);
});
@@ -260,28 +288,69 @@ describe("User folder access CRUD", () => {
test("rejects an unknown role", async () => {
const res = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: "owner" }
+ body: { ...folderTarget, permission: "owner" }
});
expect(res.statusCode).toBe(422);
});
+ test("normalizes a trailing-slash secret path", async () => {
+ const createRes = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget, secretPath: `${folderTarget.secretPath}/`, permission: SecretFolderRole.Read }
+ });
+ expect(createRes.statusCode).toBe(200);
+ const created = createRes.json().folderAccess;
+ expect(created.folderId).toBe(folder.id);
+ expect(created.secretPath).toBe(folderTarget.secretPath);
+
+ const deleteRes = await testServer.inject({
+ method: "DELETE",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget, secretPath: `${folderTarget.secretPath}/` }
+ });
+ expect(deleteRes.statusCode).toBe(200);
+ expect(deleteRes.json().folderAccess.id).toBe(created.id);
+ });
+
+ test("grants and revokes access on the root folder", async () => {
+ const createRes = await testServer.inject({
+ method: "POST",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget, secretPath: "/", permission: SecretFolderRole.Read }
+ });
+ expect(createRes.statusCode).toBe(200);
+ expect(createRes.json().folderAccess.secretPath).toBe("/");
+
+ const deleteRes = await testServer.inject({
+ method: "DELETE",
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget, secretPath: "/" }
+ });
+ expect(deleteRes.statusCode).toBe(200);
+ });
+
test("rejects granting to or updating a project admin", async () => {
const createRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id, adminUserId),
+ url: folderAccessUrl(adminUserId),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(createRes.statusCode).toBe(400);
expect(createRes.json().message).toContain("project admin role");
const patchRes = await testServer.inject({
method: "PATCH",
- url: folderAccessUrl(folder.id, adminUserId),
+ url: folderAccessUrl(adminUserId),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Edit }
+ body: { ...folderTarget, permission: SecretFolderRole.Edit }
});
expect(patchRes.statusCode).toBe(400);
expect(patchRes.json().message).toContain("project admin role");
@@ -290,9 +359,9 @@ describe("User folder access CRUD", () => {
test("still allows revoking a grant whose holder became a project admin", async () => {
const createRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(createRes.statusCode).toBe(200);
@@ -303,16 +372,17 @@ describe("User folder access CRUD", () => {
try {
const patchRes = await testServer.inject({
method: "PATCH",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Edit }
+ body: { ...folderTarget, permission: SecretFolderRole.Edit }
});
expect(patchRes.statusCode).toBe(400);
const deleteRes = await testServer.inject({
method: "DELETE",
- url: folderAccessUrl(folder.id),
- headers: authHeaders()
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget }
});
expect(deleteRes.statusCode).toBe(200);
} finally {
@@ -336,7 +406,7 @@ describe("User folder access CRUD", () => {
}> => {
const res = await testServer.inject({
method: "GET",
- url: folderAccessUsersUrl(folder.id, query),
+ url: folderAccessUsersUrl(query),
headers: authHeaders()
});
expect(res.statusCode).toBe(200);
@@ -355,16 +425,16 @@ describe("User folder access CRUD", () => {
});
test("excludes project admins from the roster", async () => {
- const { users } = await listUsers("?limit=100");
+ const { users } = await listUsers("&limit=100");
expect(users.map((user) => user.userId)).not.toContain(adminUserId);
});
test("annotates the granted user and clears the annotation on revoke", async () => {
const createRes = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id),
+ url: folderAccessUrl(),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Manage }
+ body: { ...folderTarget, permission: SecretFolderRole.Manage }
});
expect(createRes.statusCode).toBe(200);
@@ -385,8 +455,9 @@ describe("User folder access CRUD", () => {
const deleteRes = await testServer.inject({
method: "DELETE",
- url: folderAccessUrl(folder.id),
- headers: authHeaders()
+ url: folderAccessUrl(),
+ headers: authHeaders(),
+ body: { ...folderTarget }
});
expect(deleteRes.statusCode).toBe(200);
@@ -399,42 +470,51 @@ describe("User folder access CRUD", () => {
test("keeps totalCount stable across pages and past the end", async () => {
const { totalCount } = await listUsers();
- const firstPage = await listUsers("?limit=1&offset=0");
+ const firstPage = await listUsers("&limit=1&offset=0");
expect(firstPage.users).toHaveLength(Math.min(1, totalCount));
expect(firstPage.totalCount).toBe(totalCount);
- const pastTheEnd = await listUsers(`?limit=1&offset=${totalCount + 10}`);
+ const pastTheEnd = await listUsers(`&limit=1&offset=${totalCount + 10}`);
expect(pastTheEnd.users).toEqual([]);
expect(pastTheEnd.totalCount).toBe(totalCount);
});
test("filters by search", async () => {
- const matching = await listUsers(`?search=${encodeURIComponent(memberEmail)}`);
+ 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)}`);
+ const adminSearch = await listUsers(`&search=${encodeURIComponent(seedData1.email)}`);
expect(adminSearch.users).toEqual([]);
expect(adminSearch.totalCount).toBe(0);
- const nonMatching = await listUsers("?search=zzz-no-such-member");
+ const nonMatching = await listUsers("&search=zzz-no-such-member");
expect(nonMatching.users).toEqual([]);
expect(nonMatching.totalCount).toBe(0);
});
- test("rejects a folder outside the project", async () => {
- const outsideRes = await testServer.inject({
+ test("rejects an unknown secret path", async () => {
+ const res = await testServer.inject({
method: "GET",
- url: folderAccessUsersUrl("00000000-0000-0000-0000-000000000000"),
+ url: folderAccessUsersUrl("", { ...folderTarget, secretPath: "/no-such-folder" }),
headers: authHeaders()
});
- expect(outsideRes.statusCode).toBe(404);
+ expect(res.statusCode).toBe(404);
+ });
+
+ test("rejects an unknown environment", async () => {
+ const res = await testServer.inject({
+ method: "GET",
+ url: folderAccessUsersUrl("", { ...folderTarget, environmentSlug: "no-such-env" }),
+ headers: authHeaders()
+ });
+ expect(res.statusCode).toBe(404);
});
test("rejects an out-of-range limit", async () => {
const res = await testServer.inject({
method: "GET",
- url: folderAccessUsersUrl(folder.id, "?limit=500"),
+ url: folderAccessUsersUrl("&limit=500"),
headers: authHeaders()
});
expect(res.statusCode).toBe(422);
@@ -530,7 +610,7 @@ describe("User folder access CRUD", () => {
});
test("counts an actor once however many memberships reach them", async () => {
- const { users, totalCount } = await listUsers("?limit=100");
+ const { users, totalCount } = await listUsers("&limit=100");
// groupUserId is in two groups, memberUserId is direct + in a group
expect(users.filter((user) => user.userId === groupUserId)).toHaveLength(1);
@@ -540,28 +620,33 @@ describe("User folder access CRUD", () => {
});
test("grants folder access to a group-derived user and shows it on the roster", async () => {
- const grantUrl = folderAccessUrl(folder.id, groupUserId);
+ const grantUrl = folderAccessUrl(groupUserId);
const createRes = await testServer.inject({
method: "POST",
url: grantUrl,
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(createRes.statusCode).toBe(200);
- const { users } = await listUsers("?limit=100");
+ const { users } = await listUsers("&limit=100");
const granted = users.find((user) => user.userId === groupUserId);
expect(granted!.folderRBACAccess).toEqual(
expect.objectContaining({ folderId: folder.id, permission: SecretFolderRole.Read })
);
- const deleteRes = await testServer.inject({ method: "DELETE", url: grantUrl, headers: authHeaders() });
+ const deleteRes = await testServer.inject({
+ method: "DELETE",
+ url: grantUrl,
+ headers: authHeaders(),
+ body: { ...folderTarget }
+ });
expect(deleteRes.statusCode).toBe(200);
});
test("finds a group-derived user by search", async () => {
- const { users } = await listUsers(`?search=group-only`);
+ const { users } = await listUsers(`&search=group-only`);
expect(users.map((user) => user.userId)).toContain(groupUserId);
});
@@ -586,16 +671,16 @@ describe("User folder access CRUD", () => {
});
test("excludes a user whose admin role comes from a group", async () => {
- const { users } = await listUsers("?limit=100");
+ const { users } = await listUsers("&limit=100");
expect(users.map((user) => user.userId)).not.toContain(groupAdminUserId);
});
test("rejects granting to a user whose admin role comes from a group", async () => {
const res = await testServer.inject({
method: "POST",
- url: folderAccessUrl(folder.id, groupAdminUserId),
+ url: folderAccessUrl(groupAdminUserId),
headers: authHeaders(),
- body: { permission: SecretFolderRole.Read }
+ body: { ...folderTarget, permission: SecretFolderRole.Read }
});
expect(res.statusCode).toBe(400);
expect(res.json().message).toContain("project admin role");
diff --git a/backend/src/ee/routes/v1/user-additional-privilege-router.ts b/backend/src/ee/routes/v1/user-additional-privilege-router.ts
index 6a4357f940..dac0891692 100644
--- a/backend/src/ee/routes/v1/user-additional-privilege-router.ts
+++ b/backend/src/ee/routes/v1/user-additional-privilege-router.ts
@@ -1,35 +1,18 @@
import slugify from "@sindresorhus/slugify";
import { z } from "zod";
-import { AccessScope, SecretFolderRole } from "@app/db/schemas";
+import { AccessScope } from "@app/db/schemas";
import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
-import { ApiDocsTags, FOLDER_ACCESS, PROJECT_USER_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
+import { PROJECT_USER_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema, temporaryPermissionTypeSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import {
- SanitizedFolderAccessSchema,
- SanitizedFolderAccessUserSchema
-} from "@app/server/routes/sanitizedSchema/folder-access";
import { SanitizedUserProjectAdditionalPrivilegeSchema } from "@app/server/routes/sanitizedSchema/user-additional-privilege";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
-const userFolderAccessParamsSchema = z.object({
- projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.CREATE.projectId),
- userId: z.string().uuid().describe(FOLDER_ACCESS.CREATE.userId),
- folderId: z.string().uuid().describe(FOLDER_ACCESS.CREATE.folderId)
-});
-
-const folderAccessCreateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.CREATE);
-const folderAccessUpdateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.UPDATE);
-
-const userFolderAccessResponseSchema = SanitizedFolderAccessSchema.extend({
- userId: z.string().uuid()
-});
-
export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
server.route({
url: "/",
@@ -315,173 +298,4 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
};
}
});
-
- server.route({
- method: "POST",
- url: "/projects/:projectId/users/:userId/folder-access/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- hide: false,
- operationId: "createUserFolderAccess",
- tags: [ApiDocsTags.FolderAccess],
- description: "Grant a user access to a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: userFolderAccessParamsSchema,
- body: z.object({
- permission: z.nativeEnum(SecretFolderRole).describe(FOLDER_ACCESS.CREATE.permission),
- type: folderAccessCreateTypeSchema.optional()
- }),
- response: {
- 200: z.object({
- folderAccess: userFolderAccessResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { folderAccess } = await server.services.folderPermission.createFolderGrant({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- target: { actorId: req.params.userId, actorType: ActorType.USER },
- role: req.body.permission,
- type: req.body.type
- });
-
- return { folderAccess: { ...folderAccess, userId: req.params.userId } };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/projects/:projectId/users/:userId/folder-access/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- hide: false,
- operationId: "updateUserFolderAccess",
- tags: [ApiDocsTags.FolderAccess],
- description: "Update a user's access to a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: userFolderAccessParamsSchema,
- body: z
- .object({
- permission: z.nativeEnum(SecretFolderRole).optional().describe(FOLDER_ACCESS.UPDATE.permission),
- type: folderAccessUpdateTypeSchema.optional()
- })
- .refine(
- (body) => body.permission !== undefined || body.type !== undefined,
- "Provide at least one of 'permission' or 'type' to update"
- ),
- response: {
- 200: z.object({
- folderAccess: userFolderAccessResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { folderAccess } = await server.services.folderPermission.updateFolderGrant({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- target: { actorId: req.params.userId, actorType: ActorType.USER },
- role: req.body.permission,
- type: req.body.type
- });
-
- return { folderAccess: { ...folderAccess, userId: req.params.userId } };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/projects/:projectId/users/:userId/folder-access/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- hide: false,
- operationId: "deleteUserFolderAccess",
- tags: [ApiDocsTags.FolderAccess],
- description: "Revoke a user's access to a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: userFolderAccessParamsSchema,
- response: {
- 200: z.object({
- folderAccess: userFolderAccessResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { folderAccess } = await server.services.folderPermission.deleteFolderGrant({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- target: { actorId: req.params.userId, actorType: ActorType.USER }
- });
-
- return { folderAccess: { ...folderAccess, userId: req.params.userId } };
- }
- });
-
- server.route({
- method: "GET",
- url: "/projects/:projectId/folder-access/:folderId/users",
- config: {
- rateLimit: readLimit
- },
- schema: {
- hide: false,
- operationId: "listFolderAccessUsers",
- tags: [ApiDocsTags.FolderAccess],
- description: "List every user in a project with the access they have on a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: z.object({
- projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.LIST_USERS.projectId),
- folderId: z.string().uuid().describe(FOLDER_ACCESS.LIST_USERS.folderId)
- }),
- querystring: z.object({
- offset: z.coerce.number().int().min(0).default(0).describe(FOLDER_ACCESS.LIST_USERS.offset),
- limit: z.coerce.number().int().min(1).max(100).default(50).describe(FOLDER_ACCESS.LIST_USERS.limit),
- search: z.string().trim().max(64).optional().describe(FOLDER_ACCESS.LIST_USERS.search)
- }),
- response: {
- 200: z.object({
- users: SanitizedFolderAccessUserSchema.array(),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) =>
- server.services.folderPermission.listFolderAccessUsers({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- limit: req.query.limit,
- offset: req.query.offset,
- search: req.query.search
- })
- });
};
diff --git a/backend/src/ee/routes/v2/identity-project-additional-privilege-router.ts b/backend/src/ee/routes/v2/identity-project-additional-privilege-router.ts
index caa9e888bb..fee5585b1b 100644
--- a/backend/src/ee/routes/v2/identity-project-additional-privilege-router.ts
+++ b/backend/src/ee/routes/v2/identity-project-additional-privilege-router.ts
@@ -1,35 +1,18 @@
import slugify from "@sindresorhus/slugify";
import { z } from "zod";
-import { AccessScope, SecretFolderRole } from "@app/db/schemas";
+import { AccessScope } from "@app/db/schemas";
import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
-import { ApiDocsTags, FOLDER_ACCESS, IDENTITY_ADDITIONAL_PRIVILEGE_V2 } from "@app/lib/api-docs";
+import { ApiDocsTags, IDENTITY_ADDITIONAL_PRIVILEGE_V2 } from "@app/lib/api-docs";
import { NotFoundError } from "@app/lib/errors";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema, temporaryPermissionTypeSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import {
- SanitizedFolderAccessIdentitySchema,
- SanitizedFolderAccessSchema
-} from "@app/server/routes/sanitizedSchema/folder-access";
import { SanitizedIdentityPrivilegeSchema } from "@app/server/routes/sanitizedSchema/identitiy-additional-privilege";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
-const identityFolderAccessParamsSchema = z.object({
- projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.CREATE.projectId),
- identityId: z.string().uuid().describe(FOLDER_ACCESS.CREATE.identityId),
- folderId: z.string().uuid().describe(FOLDER_ACCESS.CREATE.folderId)
-});
-
-const folderAccessCreateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.CREATE);
-const folderAccessUpdateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.UPDATE);
-
-const identityFolderAccessResponseSchema = SanitizedFolderAccessSchema.extend({
- identityId: z.string().uuid()
-});
-
export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
@@ -393,173 +376,4 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
};
}
});
-
- server.route({
- method: "POST",
- url: "/projects/:projectId/identities/:identityId/folder-access/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- hide: false,
- operationId: "createIdentityFolderAccess",
- tags: [ApiDocsTags.FolderAccess],
- description: "Grant a machine identity access to a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: identityFolderAccessParamsSchema,
- body: z.object({
- permission: z.nativeEnum(SecretFolderRole).describe(FOLDER_ACCESS.CREATE.permission),
- type: folderAccessCreateTypeSchema.optional()
- }),
- response: {
- 200: z.object({
- folderAccess: identityFolderAccessResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { folderAccess } = await server.services.folderPermission.createFolderGrant({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- target: { actorId: req.params.identityId, actorType: ActorType.IDENTITY },
- role: req.body.permission,
- type: req.body.type
- });
-
- return { folderAccess: { ...folderAccess, identityId: req.params.identityId } };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/projects/:projectId/identities/:identityId/folder-access/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- hide: false,
- operationId: "updateIdentityFolderAccess",
- tags: [ApiDocsTags.FolderAccess],
- description: "Update a machine identity's access to a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: identityFolderAccessParamsSchema,
- body: z
- .object({
- permission: z.nativeEnum(SecretFolderRole).optional().describe(FOLDER_ACCESS.UPDATE.permission),
- type: folderAccessUpdateTypeSchema.optional()
- })
- .refine(
- (body) => body.permission !== undefined || body.type !== undefined,
- "Provide at least one of 'permission' or 'type' to update"
- ),
- response: {
- 200: z.object({
- folderAccess: identityFolderAccessResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { folderAccess } = await server.services.folderPermission.updateFolderGrant({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- target: { actorId: req.params.identityId, actorType: ActorType.IDENTITY },
- role: req.body.permission,
- type: req.body.type
- });
-
- return { folderAccess: { ...folderAccess, identityId: req.params.identityId } };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/projects/:projectId/identities/:identityId/folder-access/:folderId",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- hide: false,
- operationId: "deleteIdentityFolderAccess",
- tags: [ApiDocsTags.FolderAccess],
- description: "Revoke a machine identity's access to a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: identityFolderAccessParamsSchema,
- response: {
- 200: z.object({
- folderAccess: identityFolderAccessResponseSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const { folderAccess } = await server.services.folderPermission.deleteFolderGrant({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- target: { actorId: req.params.identityId, actorType: ActorType.IDENTITY }
- });
-
- return { folderAccess: { ...folderAccess, identityId: req.params.identityId } };
- }
- });
-
- server.route({
- method: "GET",
- url: "/projects/:projectId/folder-access/:folderId/identities",
- config: {
- rateLimit: readLimit
- },
- schema: {
- hide: false,
- operationId: "listFolderAccessIdentities",
- tags: [ApiDocsTags.FolderAccess],
- description: "List every machine identity in a project with the access it has on a folder.",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: z.object({
- projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.LIST_IDENTITIES.projectId),
- folderId: z.string().uuid().describe(FOLDER_ACCESS.LIST_IDENTITIES.folderId)
- }),
- querystring: z.object({
- offset: z.coerce.number().int().min(0).default(0).describe(FOLDER_ACCESS.LIST_IDENTITIES.offset),
- limit: z.coerce.number().int().min(1).max(100).default(50).describe(FOLDER_ACCESS.LIST_IDENTITIES.limit),
- search: z.string().trim().max(64).optional().describe(FOLDER_ACCESS.LIST_IDENTITIES.search)
- }),
- response: {
- 200: z.object({
- identities: SanitizedFolderAccessIdentitySchema.array(),
- totalCount: z.number()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) =>
- server.services.folderPermission.listFolderAccessIdentities({
- permission: req.permission,
- projectId: req.params.projectId,
- folderId: req.params.folderId,
- limit: req.query.limit,
- offset: req.query.offset,
- search: req.query.search
- })
- });
};
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index fb0356ee36..1769496d27 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1737,7 +1737,8 @@ The permission object for the privilege.
export const FOLDER_ACCESS = {
CREATE: {
projectId: "The ID of the project the folder is in.",
- folderId: "The ID of the folder to grant access on.",
+ environmentSlug: "The slug of the environment the folder is in.",
+ secretPath: "The path of the folder to grant access on.",
userId: "The ID of the user to grant folder access to.",
identityId: "The ID of the machine identity to grant folder access to.",
permission: "The folder role to grant. One of: list, read, edit, manage, full-access.",
@@ -1748,7 +1749,8 @@ export const FOLDER_ACCESS = {
},
UPDATE: {
projectId: "The ID of the project the folder is in.",
- folderId: "The ID of the folder the access is on.",
+ environmentSlug: "The slug of the environment the folder is in.",
+ secretPath: "The path of the folder the access is on.",
userId: "The ID of the user whose folder access to update.",
identityId: "The ID of the machine identity whose folder access to update.",
permission: "The folder role to change the access to. One of: list, read, edit, manage, full-access.",
@@ -1760,20 +1762,23 @@ export const FOLDER_ACCESS = {
},
DELETE: {
projectId: "The ID of the project the folder is in.",
- folderId: "The ID of the folder the access is on.",
+ environmentSlug: "The slug of the environment the folder is in.",
+ secretPath: "The path of the folder the access is on.",
userId: "The ID of the user whose folder access to revoke.",
identityId: "The ID of the machine identity whose folder access to revoke."
},
LIST_USERS: {
projectId: "The ID of the project the folder is in.",
- folderId: "The ID of the folder to list access for.",
+ 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."
},
LIST_IDENTITIES: {
projectId: "The ID of the project the folder is in.",
- folderId: "The ID of the folder to list access for.",
+ 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."
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 32e9795d7d..78e051f3cd 100644
--- a/backend/src/server/routes/v1/identity-project-membership-router.ts
+++ b/backend/src/server/routes/v1/identity-project-membership-router.ts
@@ -5,18 +5,46 @@ import {
IdentitiesSchema,
IdentityProjectMembershipsSchema,
ProjectMembershipRole,
+ SecretFolderRole,
TemporaryPermissionMode
} from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, FOLDER_ACCESS, PROJECT_IDENTITIES, PROJECT_IDENTITY_MEMBERSHIP } from "@app/lib/api-docs";
import { BadRequestError } from "@app/lib/errors";
+import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";
import { ms } from "@app/lib/ms";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { temporaryPermissionTypeSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { ActorType, AuthMode } from "@app/services/auth/auth-type";
+import { SanitizedFolderAccessIdentitySchema, SanitizedFolderAccessSchema } from "../sanitizedSchema/folder-access";
import { booleanSchema } from "../sanitizedSchemas";
+const folderAccessFolderFields = (docs: { environmentSlug: string; secretPath: string }) => ({
+ environmentSlug: z.string().trim().min(1).max(64).describe(docs.environmentSlug),
+ secretPath: z
+ .string()
+ .trim()
+ .min(1)
+ .max(1024)
+ .transform(prefixWithSlash)
+ .transform(removeTrailingSlash)
+ .describe(docs.secretPath)
+});
+
+const identityFolderAccessParamsSchema = z.object({
+ projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.CREATE.projectId),
+ identityId: z.string().uuid().describe(FOLDER_ACCESS.CREATE.identityId)
+});
+
+const folderAccessCreateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.CREATE);
+const folderAccessUpdateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.UPDATE);
+
+const identityFolderAccessResponseSchema = SanitizedFolderAccessSchema.extend({
+ identityId: z.string().uuid()
+});
+
export const registerIdentityProjectMembershipRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
@@ -567,4 +595,182 @@ export const registerIdentityProjectMembershipRouter = async (server: FastifyZod
return { identities };
}
});
+
+ server.route({
+ method: "POST",
+ url: "/identities/:identityId/secret-folder-access",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "createIdentityFolderAccess",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "Grant a machine identity access to a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: identityFolderAccessParamsSchema,
+ body: z.object({
+ ...folderAccessFolderFields(FOLDER_ACCESS.CREATE),
+ permission: z.nativeEnum(SecretFolderRole).describe(FOLDER_ACCESS.CREATE.permission),
+ type: folderAccessCreateTypeSchema.optional()
+ }),
+ response: {
+ 200: z.object({
+ folderAccess: identityFolderAccessResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { folderAccess } = await server.services.folderPermission.createFolderGrant({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.body.environmentSlug,
+ secretPath: req.body.secretPath,
+ target: { actorId: req.params.identityId, actorType: ActorType.IDENTITY },
+ role: req.body.permission,
+ type: req.body.type
+ });
+
+ return { folderAccess: { ...folderAccess, identityId: req.params.identityId } };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/identities/:identityId/secret-folder-access",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "updateIdentityFolderAccess",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "Update a machine identity's access to a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: identityFolderAccessParamsSchema,
+ body: z
+ .object({
+ ...folderAccessFolderFields(FOLDER_ACCESS.UPDATE),
+ permission: z.nativeEnum(SecretFolderRole).optional().describe(FOLDER_ACCESS.UPDATE.permission),
+ type: folderAccessUpdateTypeSchema.optional()
+ })
+ .refine(
+ (body) => body.permission !== undefined || body.type !== undefined,
+ "Provide at least one of 'permission' or 'type' to update"
+ ),
+ response: {
+ 200: z.object({
+ folderAccess: identityFolderAccessResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { folderAccess } = await server.services.folderPermission.updateFolderGrant({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.body.environmentSlug,
+ secretPath: req.body.secretPath,
+ target: { actorId: req.params.identityId, actorType: ActorType.IDENTITY },
+ role: req.body.permission,
+ type: req.body.type
+ });
+
+ return { folderAccess: { ...folderAccess, identityId: req.params.identityId } };
+ }
+ });
+
+ // deliberate REST deviation: DELETE carries a body identifying the folder, consistent with the
+ // user folder-access routes and DELETE /:projectId/memberships
+ server.route({
+ method: "DELETE",
+ url: "/identities/:identityId/secret-folder-access",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "deleteIdentityFolderAccess",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "Revoke a machine identity's access to a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: identityFolderAccessParamsSchema,
+ body: z.object(folderAccessFolderFields(FOLDER_ACCESS.DELETE)),
+ response: {
+ 200: z.object({
+ folderAccess: identityFolderAccessResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { folderAccess } = await server.services.folderPermission.deleteFolderGrant({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.body.environmentSlug,
+ secretPath: req.body.secretPath,
+ target: { actorId: req.params.identityId, actorType: ActorType.IDENTITY }
+ });
+
+ return { folderAccess: { ...folderAccess, identityId: req.params.identityId } };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/secret-folder-access/identities",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "listFolderAccessIdentities",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "List every machine identity in a project with the access it has on a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.LIST_IDENTITIES.projectId)
+ }),
+ querystring: z.object({
+ ...folderAccessFolderFields(FOLDER_ACCESS.LIST_IDENTITIES),
+ offset: z.coerce.number().int().min(0).default(0).describe(FOLDER_ACCESS.LIST_IDENTITIES.offset),
+ limit: z.coerce.number().int().min(1).max(100).default(50).describe(FOLDER_ACCESS.LIST_IDENTITIES.limit),
+ search: z.string().trim().max(64).optional().describe(FOLDER_ACCESS.LIST_IDENTITIES.search)
+ }),
+ response: {
+ 200: z.object({
+ identities: SanitizedFolderAccessIdentitySchema.array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) =>
+ server.services.folderPermission.listFolderAccessIdentities({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.query.environmentSlug,
+ secretPath: req.query.secretPath,
+ limit: req.query.limit,
+ offset: req.query.offset,
+ search: req.query.search
+ })
+ });
};
diff --git a/backend/src/server/routes/v1/project-membership-router.ts b/backend/src/server/routes/v1/project-membership-router.ts
index 8e06eb50c5..966113a8b9 100644
--- a/backend/src/server/routes/v1/project-membership-router.ts
+++ b/backend/src/server/routes/v1/project-membership-router.ts
@@ -5,17 +5,21 @@ import {
ProjectMembershipRole,
ProjectMembershipsSchema,
ProjectUserMembershipRolesSchema,
+ SecretFolderRole,
TemporaryPermissionMode
} from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, FOLDER_ACCESS, PROJECT_USERS } from "@app/lib/api-docs";
+import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";
import { ms } from "@app/lib/ms";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { temporaryPermissionTypeSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+import { SanitizedFolderAccessSchema, SanitizedFolderAccessUserSchema } from "../sanitizedSchema/folder-access";
import { booleanSchema, SanitizedUserSchema } from "../sanitizedSchemas";
const projectUserMembershipRoleSchema = z.object({
@@ -36,6 +40,30 @@ const projectUserMembershipSchema = ProjectMembershipsSchema.extend({
roles: z.array(projectUserMembershipRoleSchema)
});
+const folderAccessFolderFields = (docs: { environmentSlug: string; secretPath: string }) => ({
+ environmentSlug: z.string().trim().min(1).max(64).describe(docs.environmentSlug),
+ secretPath: z
+ .string()
+ .trim()
+ .min(1)
+ .max(1024)
+ .transform(prefixWithSlash)
+ .transform(removeTrailingSlash)
+ .describe(docs.secretPath)
+});
+
+const userFolderAccessParamsSchema = z.object({
+ projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.CREATE.projectId),
+ userId: z.string().uuid().describe(FOLDER_ACCESS.CREATE.userId)
+});
+
+const folderAccessCreateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.CREATE);
+const folderAccessUpdateTypeSchema = temporaryPermissionTypeSchema(FOLDER_ACCESS.UPDATE);
+
+const userFolderAccessResponseSchema = SanitizedFolderAccessSchema.extend({
+ userId: z.string().uuid()
+});
+
export const registerProjectMembershipRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
@@ -694,4 +722,182 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
};
}
});
+
+ server.route({
+ method: "POST",
+ url: "/:projectId/users/:userId/secret-folder-access",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "createUserFolderAccess",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "Grant a user access to a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: userFolderAccessParamsSchema,
+ body: z.object({
+ ...folderAccessFolderFields(FOLDER_ACCESS.CREATE),
+ permission: z.nativeEnum(SecretFolderRole).describe(FOLDER_ACCESS.CREATE.permission),
+ type: folderAccessCreateTypeSchema.optional()
+ }),
+ response: {
+ 200: z.object({
+ folderAccess: userFolderAccessResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { folderAccess } = await server.services.folderPermission.createFolderGrant({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.body.environmentSlug,
+ secretPath: req.body.secretPath,
+ target: { actorId: req.params.userId, actorType: ActorType.USER },
+ role: req.body.permission,
+ type: req.body.type
+ });
+
+ return { folderAccess: { ...folderAccess, userId: req.params.userId } };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:projectId/users/:userId/secret-folder-access",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "updateUserFolderAccess",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "Update a user's access to a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: userFolderAccessParamsSchema,
+ body: z
+ .object({
+ ...folderAccessFolderFields(FOLDER_ACCESS.UPDATE),
+ permission: z.nativeEnum(SecretFolderRole).optional().describe(FOLDER_ACCESS.UPDATE.permission),
+ type: folderAccessUpdateTypeSchema.optional()
+ })
+ .refine(
+ (body) => body.permission !== undefined || body.type !== undefined,
+ "Provide at least one of 'permission' or 'type' to update"
+ ),
+ response: {
+ 200: z.object({
+ folderAccess: userFolderAccessResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { folderAccess } = await server.services.folderPermission.updateFolderGrant({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.body.environmentSlug,
+ secretPath: req.body.secretPath,
+ target: { actorId: req.params.userId, actorType: ActorType.USER },
+ role: req.body.permission,
+ type: req.body.type
+ });
+
+ return { folderAccess: { ...folderAccess, userId: req.params.userId } };
+ }
+ });
+
+ // deliberate REST deviation: DELETE carries a body identifying the folder, consistent with
+ // DELETE /:projectId/memberships in this router
+ server.route({
+ method: "DELETE",
+ url: "/:projectId/users/:userId/secret-folder-access",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "deleteUserFolderAccess",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "Revoke a user's access to a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: userFolderAccessParamsSchema,
+ body: z.object(folderAccessFolderFields(FOLDER_ACCESS.DELETE)),
+ response: {
+ 200: z.object({
+ folderAccess: userFolderAccessResponseSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { folderAccess } = await server.services.folderPermission.deleteFolderGrant({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.body.environmentSlug,
+ secretPath: req.body.secretPath,
+ target: { actorId: req.params.userId, actorType: ActorType.USER }
+ });
+
+ return { folderAccess: { ...folderAccess, userId: req.params.userId } };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/secret-folder-access/users",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "listFolderAccessUsers",
+ tags: [ApiDocsTags.FolderAccess],
+ description: "List every user in a project with the access they have on a folder.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().min(1).max(64).describe(FOLDER_ACCESS.LIST_USERS.projectId)
+ }),
+ querystring: z.object({
+ ...folderAccessFolderFields(FOLDER_ACCESS.LIST_USERS),
+ offset: z.coerce.number().int().min(0).default(0).describe(FOLDER_ACCESS.LIST_USERS.offset),
+ limit: z.coerce.number().int().min(1).max(100).default(50).describe(FOLDER_ACCESS.LIST_USERS.limit),
+ search: z.string().trim().max(64).optional().describe(FOLDER_ACCESS.LIST_USERS.search)
+ }),
+ response: {
+ 200: z.object({
+ users: SanitizedFolderAccessUserSchema.array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) =>
+ server.services.folderPermission.listFolderAccessUsers({
+ permission: req.permission,
+ projectId: req.params.projectId,
+ environmentSlug: req.query.environmentSlug,
+ secretPath: req.query.secretPath,
+ limit: req.query.limit,
+ offset: req.query.offset,
+ search: req.query.search
+ })
+ });
};
diff --git a/backend/src/services/folder-permission/folder-permission-fns.test.ts b/backend/src/services/folder-permission/folder-permission-fns.test.ts
index 253a5ba2a2..21258f8152 100644
--- a/backend/src/services/folder-permission/folder-permission-fns.test.ts
+++ b/backend/src/services/folder-permission/folder-permission-fns.test.ts
@@ -1,7 +1,9 @@
import { TemporaryPermissionMode } from "@app/db/schemas";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
-import { computeTemporaryFields } from "./folder-permission-fns";
+import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
+import { computeTemporaryFields, resolveFolder } from "./folder-permission-fns";
describe("computeTemporaryFields", () => {
test.each([undefined, { isTemporary: false as const }])("returns permanent fields for %o", (input) => {
@@ -30,3 +32,35 @@ describe("computeTemporaryFields", () => {
expect(result.temporaryAccessEndTime!.getTime() - result.temporaryAccessStartTime!.getTime()).toBe(ms("4h"));
});
});
+
+describe("resolveFolder", () => {
+ const stubSecretFolderDAL = (result: unknown) =>
+ ({
+ findBySecretPath: async () => result
+ }) as unknown as Pick<TSecretFolderDALFactory, "findBySecretPath">;
+
+ test("throws NotFoundError naming the environment and path when the folder does not exist", async () => {
+ await expect(resolveFolder("project-1", "dev", "/missing", stubSecretFolderDAL(undefined))).rejects.toThrow(
+ NotFoundError
+ );
+ await expect(resolveFolder("project-1", "dev", "/missing", stubSecretFolderDAL(undefined))).rejects.toThrow(
+ /'\/missing'.*'dev'/
+ );
+ });
+
+ test("throws BadRequestError for a reserved folder", async () => {
+ const folder = { id: "folder-1", path: "/reserved", isReserved: true, environment: { slug: "dev" } };
+ await expect(resolveFolder("project-1", "dev", "/reserved", stubSecretFolderDAL(folder))).rejects.toThrow(
+ BadRequestError
+ );
+ });
+
+ test("returns the folder id and canonical path and environment slug", async () => {
+ const folder = { id: "folder-1", path: "/app", isReserved: false, environment: { slug: "dev" } };
+ await expect(resolveFolder("project-1", "dev", "/app/", stubSecretFolderDAL(folder))).resolves.toEqual({
+ id: "folder-1",
+ path: "/app",
+ environmentSlug: "dev"
+ });
+ });
+});
diff --git a/backend/src/services/folder-permission/folder-permission-fns.ts b/backend/src/services/folder-permission/folder-permission-fns.ts
index 2efe59e925..7adc0567b6 100644
--- a/backend/src/services/folder-permission/folder-permission-fns.ts
+++ b/backend/src/services/folder-permission/folder-permission-fns.ts
@@ -38,19 +38,20 @@ export const computeTemporaryFields = (type: TFolderGrantTypeInput | undefined)
export const resolveFolder = async (
projectId: string,
- folderId: string,
- secretFolderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">
-) => {
- const [folder] = await secretFolderDAL.findSecretPathByFolderIds(projectId, [folderId]);
+ environmentSlug: string,
+ secretPath: string,
+ secretFolderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">
+): Promise<TResolvedFolder> => {
+ const folder = await secretFolderDAL.findBySecretPath(projectId, environmentSlug, secretPath);
if (!folder) {
throw new NotFoundError({
- message: `Folder with ID '${folderId}' not found in project with ID '${projectId}'`
+ message: `Folder at path '${secretPath}' not found in environment with slug '${environmentSlug}' in project with ID '${projectId}'`
});
}
if (folder.isReserved) {
throw new BadRequestError({ message: "Folder access cannot be granted on a reserved system folder." });
}
- return folder;
+ return { id: folder.id, path: folder.path, environmentSlug: folder.environment.slug };
};
export const assertManageFolderAccess = async (
@@ -154,12 +155,11 @@ export const toFolderGrant = (
| "updatedAt"
>,
projectId: string,
- folderId: string,
folder: TResolvedFolder
): TFolderGrant => ({
id: row.id,
projectId,
- folderId,
+ folderId: folder.id,
permission: row.role as SecretFolderRole,
environment: folder.environmentSlug,
secretPath: folder.path,
diff --git a/backend/src/services/folder-permission/folder-permission-service.ts b/backend/src/services/folder-permission/folder-permission-service.ts
index dbadb4ad6e..44fe531023 100644
--- a/backend/src/services/folder-permission/folder-permission-service.ts
+++ b/backend/src/services/folder-permission/folder-permission-service.ts
@@ -29,7 +29,7 @@ type TFolderPermissionServiceFactoryDep = {
TAdditionalPrivilegeDALFactory,
"findOne" | "create" | "updateById" | "deleteById" | "transaction"
>;
- secretFolderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;
+ secretFolderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "invalidateProjectFolderPermissionCache">;
folderPermissionDAL: Pick<
TFolderPermissionDALFactory,
@@ -46,8 +46,8 @@ export const folderPermissionServiceFactory = ({
folderPermissionDAL
}: TFolderPermissionServiceFactoryDep) => {
const createFolderGrant = async (dto: TCreateFolderGrantDTO) => {
- const { projectId, folderId, target } = dto;
- const folder = await resolveFolder(projectId, folderId, secretFolderDAL);
+ const { projectId, environmentSlug, secretPath, target } = dto;
+ const folder = await resolveFolder(projectId, environmentSlug, secretPath, secretFolderDAL);
await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);
await assertGrantTargetEligible(dto.permission.orgId, projectId, target, folderPermissionDAL);
@@ -60,7 +60,7 @@ export const folderPermissionServiceFactory = ({
try {
const grant = await additionalPrivilegeDAL.transaction(async (tx) => {
const existing = await additionalPrivilegeDAL.findOne(
- { projectId, folderId, [actorField]: target.actorId },
+ { projectId, folderId: folder.id, [actorField]: target.actorId },
tx
);
if (existing) throw alreadyExistsError();
@@ -69,7 +69,7 @@ export const folderPermissionServiceFactory = ({
{
name: slugify(alphaNumericNanoId(8)),
projectId,
- folderId,
+ folderId: folder.id,
role: dto.role,
[actorField]: target.actorId,
...computeTemporaryFields(dto.type)
@@ -80,7 +80,7 @@ export const folderPermissionServiceFactory = ({
return doc;
});
- return { folderAccess: toFolderGrant(grant, projectId, folderId, folder) };
+ return { folderAccess: toFolderGrant(grant, projectId, folder) };
} catch (error) {
const dbError = error instanceof DatabaseError ? (error.error as { code?: string }) : null;
if (dbError?.code === DatabaseErrorCode.UniqueViolation) throw alreadyExistsError();
@@ -89,17 +89,20 @@ export const folderPermissionServiceFactory = ({
};
const updateFolderGrant = async (dto: TUpdateFolderGrantDTO) => {
- const { projectId, folderId, target } = dto;
- const folder = await resolveFolder(projectId, folderId, secretFolderDAL);
+ const { projectId, environmentSlug, secretPath, target } = dto;
+ const folder = await resolveFolder(projectId, environmentSlug, secretPath, secretFolderDAL);
await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);
await assertGrantTargetEligible(dto.permission.orgId, projectId, target, folderPermissionDAL);
const actorField = targetActorField(target);
const grant = await additionalPrivilegeDAL.transaction(async (tx) => {
- const existing = await additionalPrivilegeDAL.findOne({ projectId, folderId, [actorField]: target.actorId }, tx);
+ const existing = await additionalPrivilegeDAL.findOne(
+ { projectId, folderId: folder.id, [actorField]: target.actorId },
+ tx
+ );
if (!existing) {
throw new NotFoundError({
- message: `No folder access found for ${targetLabel(target).toLowerCase()} with ID '${target.actorId}' on folder with ID '${folderId}'. Create one first.`
+ message: `No folder access found for ${targetLabel(target).toLowerCase()} with ID '${target.actorId}' on the folder at path '${folder.path}' in environment with slug '${folder.environmentSlug}'. Create one first.`
});
}
@@ -115,22 +118,25 @@ export const folderPermissionServiceFactory = ({
return doc;
});
- return { folderAccess: toFolderGrant(grant, projectId, folderId, folder) };
+ return { folderAccess: toFolderGrant(grant, projectId, folder) };
};
const deleteFolderGrant = async (dto: TDeleteFolderGrantDTO) => {
- const { projectId, folderId, target } = dto;
- const folder = await resolveFolder(projectId, folderId, secretFolderDAL);
+ const { projectId, environmentSlug, secretPath, target } = dto;
+ const folder = await resolveFolder(projectId, environmentSlug, secretPath, secretFolderDAL);
await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);
// no membership check on revoke: removing access from an actor that already left the project
// must keep working
const actorField = targetActorField(target);
const grant = await additionalPrivilegeDAL.transaction(async (tx) => {
- const existing = await additionalPrivilegeDAL.findOne({ projectId, folderId, [actorField]: target.actorId }, tx);
+ const existing = await additionalPrivilegeDAL.findOne(
+ { projectId, folderId: folder.id, [actorField]: target.actorId },
+ tx
+ );
if (!existing) {
throw new NotFoundError({
- message: `No folder access found for ${targetLabel(target).toLowerCase()} with ID '${target.actorId}' on folder with ID '${folderId}'`
+ message: `No folder access found for ${targetLabel(target).toLowerCase()} with ID '${target.actorId}' on the folder at path '${folder.path}' in environment with slug '${folder.environmentSlug}'`
});
}
@@ -139,18 +145,18 @@ export const folderPermissionServiceFactory = ({
return doc;
});
- return { folderAccess: toFolderGrant(grant, projectId, folderId, folder) };
+ return { folderAccess: toFolderGrant(grant, projectId, folder) };
};
const listFolderAccessUsers = async (dto: TListFolderAccessActorsDTO) => {
- const { projectId, folderId, limit, offset, search } = dto;
- const folder = await resolveFolder(projectId, folderId, secretFolderDAL);
+ const { projectId, environmentSlug, secretPath, limit, offset, search } = dto;
+ const folder = await resolveFolder(projectId, environmentSlug, secretPath, secretFolderDAL);
await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);
const { users, totalCount } = await folderPermissionDAL.findUsersWithFolderAccess({
projectId,
orgId: dto.permission.orgId,
- folderId,
+ folderId: folder.id,
search,
limit,
offset
@@ -159,21 +165,21 @@ export const folderPermissionServiceFactory = ({
return {
users: users.map(({ folderAccess, ...user }) => ({
...user,
- folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folderId, folder) : null
+ folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folder) : null
})),
totalCount
};
};
const listFolderAccessIdentities = async (dto: TListFolderAccessActorsDTO) => {
- const { projectId, folderId, limit, offset, search } = dto;
- const folder = await resolveFolder(projectId, folderId, secretFolderDAL);
+ const { projectId, environmentSlug, secretPath, limit, offset, search } = dto;
+ const folder = await resolveFolder(projectId, environmentSlug, secretPath, secretFolderDAL);
await assertManageFolderAccess(dto.permission, projectId, folder, permissionService);
const { identities, totalCount } = await folderPermissionDAL.findIdentitiesWithFolderAccess({
projectId,
orgId: dto.permission.orgId,
- folderId,
+ folderId: folder.id,
search,
limit,
offset
@@ -182,7 +188,7 @@ export const folderPermissionServiceFactory = ({
return {
identities: identities.map(({ folderAccess, ...identity }) => ({
...identity,
- folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folderId, folder) : null
+ folderRBACAccess: folderAccess ? toFolderGrant(folderAccess, projectId, folder) : null
})),
totalCount
};
diff --git a/backend/src/services/folder-permission/folder-permission-types.ts b/backend/src/services/folder-permission/folder-permission-types.ts
index 2ec6f3c569..bb20b3cad2 100644
--- a/backend/src/services/folder-permission/folder-permission-types.ts
+++ b/backend/src/services/folder-permission/folder-permission-types.ts
@@ -18,6 +18,7 @@ export type TFolderGrantTypeInput =
};
export type TResolvedFolder = {
+ id: string;
path: string;
environmentSlug: string;
};
@@ -25,7 +26,8 @@ export type TResolvedFolder = {
export type TCreateFolderGrantDTO = {
permission: OrgServiceActor;
projectId: string;
- folderId: string;
+ environmentSlug: string;
+ secretPath: string;
target: TFolderGrantActor;
role: SecretFolderRole;
// undefined means a permanent grant
@@ -35,7 +37,8 @@ export type TCreateFolderGrantDTO = {
export type TUpdateFolderGrantDTO = {
permission: OrgServiceActor;
projectId: string;
- folderId: string;
+ environmentSlug: string;
+ secretPath: string;
target: TFolderGrantActor;
role?: SecretFolderRole;
// undefined leaves the temporal state unchanged; { isTemporary: false } makes the grant
@@ -46,14 +49,16 @@ export type TUpdateFolderGrantDTO = {
export type TDeleteFolderGrantDTO = {
permission: OrgServiceActor;
projectId: string;
- folderId: string;
+ environmentSlug: string;
+ secretPath: string;
target: TFolderGrantActor;
};
export type TListFolderAccessActorsDTO = {
permission: OrgServiceActor;
projectId: string;
- folderId: string;
+ environmentSlug: string;
+ secretPath: string;
limit: number;
offset: number;
search?: string;
diff --git a/frontend/src/hooks/api/folderAccess/mutations.tsx b/frontend/src/hooks/api/folderAccess/mutations.tsx
index 40c7fdd01d..d069e3f21c 100644
--- a/frontend/src/hooks/api/folderAccess/mutations.tsx
+++ b/frontend/src/hooks/api/folderAccess/mutations.tsx
@@ -3,7 +3,6 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { roleQueryKeys } from "@app/hooks/api/roles/queries";
-import { IDENTITY_FOLDER_ACCESS_API, USER_FOLDER_ACCESS_API } from "./queries";
import {
TCreateIdentityFolderAccessDTO,
TCreateUserFolderAccessDTO,
@@ -14,20 +13,28 @@ import {
TUpdateUserFolderAccessDTO
} from "./types";
-type TFolderAccessScope = { projectId: string; folderId: string };
+type TFolderAccessScope = { projectId: string; environmentSlug: string; secretPath: string };
// a grant changes what the actor may read, so the roster and anything rendering the project's
// secrets both go stale. the roster is invalidated across every page/search variant.
const invalidateFolderAccess = (
queryClient: ReturnType<typeof useQueryClient>,
- { projectId, folderId }: TFolderAccessScope
+ { projectId, environmentSlug, secretPath }: TFolderAccessScope
) => {
queryClient.invalidateQueries({
predicate: (query) => {
const label = query.queryKey[1];
if (label !== "folder-access-users" && label !== "folder-access-identities") return false;
- const params = query.queryKey[0] as { projectId?: string; folderId?: string };
- return params?.projectId === projectId && params?.folderId === folderId;
+ const params = query.queryKey[0] as {
+ projectId?: string;
+ environmentSlug?: string;
+ secretPath?: string;
+ };
+ return (
+ params?.projectId === projectId &&
+ params?.environmentSlug === environmentSlug &&
+ params?.secretPath === secretPath
+ );
}
});
@@ -49,101 +56,156 @@ const invalidateFolderAccess = (
});
};
-const userFolderAccessUrl = ({ projectId, userId, folderId }: TDeleteUserFolderAccessDTO) =>
- `${USER_FOLDER_ACCESS_API}/projects/${projectId}/users/${userId}/folder-access/${folderId}`;
+const userFolderAccessUrl = ({ projectId, userId }: { projectId: string; userId: string }) =>
+ `/api/v1/projects/${projectId}/users/${userId}/secret-folder-access`;
const identityFolderAccessUrl = ({
projectId,
- identityId,
- folderId
-}: TDeleteIdentityFolderAccessDTO) =>
- `${IDENTITY_FOLDER_ACCESS_API}/projects/${projectId}/identities/${identityId}/folder-access/${folderId}`;
+ identityId
+}: {
+ projectId: string;
+ identityId: string;
+}) => `/api/v1/projects/${projectId}/memberships/identities/${identityId}/secret-folder-access`;
export const useCreateUserFolderAccess = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ permission, type, ...target }: TCreateUserFolderAccessDTO) => {
+ mutationFn: async ({
+ projectId,
+ userId,
+ environmentSlug,
+ secretPath,
+ permission,
+ type
+ }: TCreateUserFolderAccessDTO) => {
const { data } = await apiRequest.post<{ folderAccess: TFolderAccess & { userId: string } }>(
- userFolderAccessUrl(target),
- { permission, ...(type ? { type } : {}) }
+ userFolderAccessUrl({ projectId, userId }),
+ { environmentSlug, secretPath, permission, ...(type ? { type } : {}) }
);
return data.folderAccess;
},
- onSuccess: (_, { projectId, folderId }) =>
- invalidateFolderAccess(queryClient, { projectId, folderId })
+ onSuccess: (_, { projectId, environmentSlug, secretPath }) =>
+ invalidateFolderAccess(queryClient, { projectId, environmentSlug, secretPath })
});
};
export const useUpdateUserFolderAccess = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ permission, type, ...target }: TUpdateUserFolderAccessDTO) => {
+ mutationFn: async ({
+ projectId,
+ userId,
+ environmentSlug,
+ secretPath,
+ permission,
+ type
+ }: TUpdateUserFolderAccessDTO) => {
const { data } = await apiRequest.patch<{ folderAccess: TFolderAccess & { userId: string } }>(
- userFolderAccessUrl(target),
- { ...(permission ? { permission } : {}), ...(type ? { type } : {}) }
+ userFolderAccessUrl({ projectId, userId }),
+ {
+ environmentSlug,
+ secretPath,
+ ...(permission ? { permission } : {}),
+ ...(type ? { type } : {})
+ }
);
return data.folderAccess;
},
- onSuccess: (_, { projectId, folderId }) =>
- invalidateFolderAccess(queryClient, { projectId, folderId })
+ onSuccess: (_, { projectId, environmentSlug, secretPath }) =>
+ invalidateFolderAccess(queryClient, { projectId, environmentSlug, secretPath })
});
};
export const useDeleteUserFolderAccess = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async (target: TDeleteUserFolderAccessDTO) => {
+ mutationFn: async ({
+ projectId,
+ userId,
+ environmentSlug,
+ secretPath
+ }: TDeleteUserFolderAccessDTO) => {
const { data } = await apiRequest.delete<{
folderAccess: TFolderAccess & { userId: string };
- }>(userFolderAccessUrl(target));
+ }>(userFolderAccessUrl({ projectId, userId }), {
+ data: { environmentSlug, secretPath }
+ });
return data.folderAccess;
},
- onSuccess: (_, { projectId, folderId }) =>
- invalidateFolderAccess(queryClient, { projectId, folderId })
+ onSuccess: (_, { projectId, environmentSlug, secretPath }) =>
+ invalidateFolderAccess(queryClient, { projectId, environmentSlug, secretPath })
});
};
export const useCreateIdentityFolderAccess = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ permission, type, ...target }: TCreateIdentityFolderAccessDTO) => {
+ mutationFn: async ({
+ projectId,
+ identityId,
+ environmentSlug,
+ secretPath,
+ permission,
+ type
+ }: TCreateIdentityFolderAccessDTO) => {
const { data } = await apiRequest.post<{
folderAccess: TFolderAccess & { identityId: string };
- }>(identityFolderAccessUrl(target), { permission, ...(type ? { type } : {}) });
+ }>(identityFolderAccessUrl({ projectId, identityId }), {
+ environmentSlug,
+ secretPath,
+ permission,
+ ...(type ? { type } : {})
+ });
return data.folderAccess;
},
- onSuccess: (_, { projectId, folderId }) =>
- invalidateFolderAccess(queryClient, { projectId, folderId })
+ onSuccess: (_, { projectId, environmentSlug, secretPath }) =>
+ invalidateFolderAccess(queryClient, { projectId, environmentSlug, secretPath })
});
};
export const useUpdateIdentityFolderAccess = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ permission, type, ...target }: TUpdateIdentityFolderAccessDTO) => {
+ mutationFn: async ({
+ projectId,
+ identityId,
+ environmentSlug,
+ secretPath,
+ permission,
+ type
+ }: TUpdateIdentityFolderAccessDTO) => {
const { data } = await apiRequest.patch<{
folderAccess: TFolderAccess & { identityId: string };
- }>(identityFolderAccessUrl(target), {
+ }>(identityFolderAccessUrl({ projectId, identityId }), {
+ environmentSlug,
+ secretPath,
...(permission ? { permission } : {}),
...(type ? { type } : {})
});
return data.folderAccess;
},
- onSuccess: (_, { projectId, folderId }) =>
- invalidateFolderAccess(queryClient, { projectId, folderId })
+ onSuccess: (_, { projectId, environmentSlug, secretPath }) =>
+ invalidateFolderAccess(queryClient, { projectId, environmentSlug, secretPath })
});
};
export const useDeleteIdentityFolderAccess = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async (target: TDeleteIdentityFolderAccessDTO) => {
+ mutationFn: async ({
+ projectId,
+ identityId,
+ environmentSlug,
+ secretPath
+ }: TDeleteIdentityFolderAccessDTO) => {
const { data } = await apiRequest.delete<{
folderAccess: TFolderAccess & { identityId: string };
- }>(identityFolderAccessUrl(target));
+ }>(identityFolderAccessUrl({ projectId, identityId }), {
+ data: { environmentSlug, secretPath }
+ });
return data.folderAccess;
},
- onSuccess: (_, { projectId, folderId }) =>
- invalidateFolderAccess(queryClient, { projectId, folderId })
+ onSuccess: (_, { projectId, environmentSlug, secretPath }) =>
+ invalidateFolderAccess(queryClient, { projectId, environmentSlug, secretPath })
});
};
diff --git a/frontend/src/hooks/api/folderAccess/queries.tsx b/frontend/src/hooks/api/folderAccess/queries.tsx
index f1a4fb715f..60887c8c6e 100644
--- a/frontend/src/hooks/api/folderAccess/queries.tsx
+++ b/frontend/src/hooks/api/folderAccess/queries.tsx
@@ -4,57 +4,89 @@ import { apiRequest } from "@app/config/request";
import { TFolderAccessIdentity, TFolderAccessUser, TListFolderAccessActorsDTO } from "./types";
-export const USER_FOLDER_ACCESS_API = "/api/v1/user-project-additional-privilege";
-export const IDENTITY_FOLDER_ACCESS_API = "/api/v2/identity-project-additional-privilege";
-
const DEFAULT_LIMIT = 50;
export const folderAccessKeys = {
- listUsers: ({ projectId, folderId, offset, limit, search }: TListFolderAccessActorsDTO) =>
- [{ projectId, folderId, offset, limit, search }, "folder-access-users"] as const,
- listIdentities: ({ projectId, folderId, offset, limit, search }: TListFolderAccessActorsDTO) =>
- [{ projectId, folderId, offset, limit, search }, "folder-access-identities"] as const
+ listUsers: ({
+ projectId,
+ environmentSlug,
+ secretPath,
+ offset,
+ limit,
+ search
+ }: TListFolderAccessActorsDTO) =>
+ [
+ { projectId, environmentSlug, secretPath, offset, limit, search },
+ "folder-access-users"
+ ] as const,
+ listIdentities: ({
+ projectId,
+ environmentSlug,
+ secretPath,
+ offset,
+ limit,
+ search
+ }: TListFolderAccessActorsDTO) =>
+ [
+ { projectId, environmentSlug, secretPath, offset, limit, search },
+ "folder-access-identities"
+ ] as const
};
export const useListFolderAccessUsers = ({
projectId,
- folderId,
+ environmentSlug,
+ secretPath,
offset = 0,
limit = DEFAULT_LIMIT,
search
}: TListFolderAccessActorsDTO) =>
useQuery({
- queryKey: folderAccessKeys.listUsers({ projectId, folderId, offset, limit, search }),
+ queryKey: folderAccessKeys.listUsers({
+ projectId,
+ environmentSlug,
+ secretPath,
+ offset,
+ limit,
+ search
+ }),
queryFn: async () => {
const { data } = await apiRequest.get<{ users: TFolderAccessUser[]; totalCount: number }>(
- `${USER_FOLDER_ACCESS_API}/projects/${projectId}/folder-access/${folderId}/users`,
- { params: { offset, limit, ...(search ? { search } : {}) } }
+ `/api/v1/projects/${projectId}/secret-folder-access/users`,
+ {
+ params: { environmentSlug, secretPath, offset, limit, ...(search ? { search } : {}) }
+ }
);
return data;
},
- enabled: Boolean(projectId) && Boolean(folderId)
+ enabled: Boolean(projectId) && Boolean(environmentSlug) && Boolean(secretPath)
});
export const useListFolderAccessIdentities = ({
projectId,
- folderId,
+ environmentSlug,
+ secretPath,
offset = 0,
limit = DEFAULT_LIMIT,
search
}: TListFolderAccessActorsDTO) =>
useQuery({
- queryKey: folderAccessKeys.listIdentities({ projectId, folderId, offset, limit, search }),
+ queryKey: folderAccessKeys.listIdentities({
+ projectId,
+ environmentSlug,
+ secretPath,
+ offset,
+ limit,
+ search
+ }),
queryFn: async () => {
const { data } = await apiRequest.get<{
identities: TFolderAccessIdentity[];
totalCount: number;
- }>(
- `${IDENTITY_FOLDER_ACCESS_API}/projects/${projectId}/folder-access/${folderId}/identities`,
- {
- params: { offset, limit, ...(search ? { search } : {}) }
- }
- );
+ }>(`/api/v1/projects/${projectId}/memberships/secret-folder-access/identities`, {
+ params: { environmentSlug, secretPath, offset, limit, ...(search ? { search } : {}) }
+ });
return data;
},
- enabled: Boolean(projectId) && Boolean(folderId)
+ 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 7d06f36c2b..9b0cd4239c 100644
--- a/frontend/src/hooks/api/folderAccess/types.ts
+++ b/frontend/src/hooks/api/folderAccess/types.ts
@@ -49,7 +49,8 @@ export type TFolderAccessIdentity = {
export type TListFolderAccessActorsDTO = {
projectId: string;
- folderId: string;
+ environmentSlug: string;
+ secretPath: string;
offset?: number;
limit?: number;
search?: string;
@@ -57,7 +58,8 @@ export type TListFolderAccessActorsDTO = {
type TFolderAccessTargetDTO = {
projectId: string;
- folderId: string;
+ environmentSlug: string;
+ secretPath: string;
};
export type TCreateUserFolderAccessDTO = TFolderAccessTargetDTO & {
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index 211889f5bb..5f258ca4f4 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -172,10 +172,7 @@ import {
useGetSecretApprovalRequestCount,
useGetSecretApprovalRequests
} from "@app/hooks/api/secretApprovalRequest";
-import {
- useListProjectEnvironmentsFolders,
- useUpdateFolderBatch
-} from "@app/hooks/api/secretFolders/queries";
+import { useUpdateFolderBatch } from "@app/hooks/api/secretFolders/queries";
import { PendingAction, TUpdateFolderBatchDTO } from "@app/hooks/api/secretFolders/types";
import { TSecretImport } from "@app/hooks/api/secretImports/types";
import {
@@ -807,7 +804,6 @@ const OverviewPageContent = () => {
useFolderOverview(folders);
const [folderAccessTarget, setFolderAccessTarget] = useState<{
- folderId: string;
folderPath: string;
} | null>(null);
const [isCurrentFolderAccessOpen, setIsCurrentFolderAccessOpen] = useState(false);
@@ -834,21 +830,11 @@ const OverviewPageContent = () => {
const canManageCurrentFolderAccess =
isSingleEnvView && canManageFolderAccessAt(singleEnvSlug, secretPath);
- // the overview folder list only holds children of secretPath, so the folder you are *inside*
- // has to be resolved from the tree, which also covers the root at path "/"
- const { data: environmentsFolders } = useListProjectEnvironmentsFolders(projectId, {
- enabled: isCurrentFolderAccessOpen
- });
- const currentFolderId = environmentsFolders?.[singleEnvSlug]?.folders.find(
- (folder) => folder.path === secretPath
- )?.id;
-
const handleFolderAccessOpen = useCallback(
(folderName: string) => {
const folder = getFolderByNameAndEnv(folderName, singleEnvSlug);
if (!folder) return;
setFolderAccessTarget({
- folderId: folder.id,
folderPath: childFolderPath(folderName)
});
},
@@ -4073,17 +4059,17 @@ const OverviewPageContent = () => {
if (!isOpen) setFolderAccessTarget(null);
}}
projectId={projectId}
- folderId={folderAccessTarget.folderId}
+ environmentSlug={singleEnvSlug}
folderPath={folderAccessTarget.folderPath}
environmentName={singleEnvName}
/>
)}
- {isCurrentFolderAccessOpen && currentFolderId && (
+ {isCurrentFolderAccessOpen && (
<FolderAccessSheet
isOpen
onOpenChange={setIsCurrentFolderAccessOpen}
projectId={projectId}
- folderId={currentFolderId}
+ environmentSlug={singleEnvSlug}
folderPath={secretPath}
environmentName={singleEnvName}
/>
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 a6e37d59b8..0547d7c029 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/AddFolderAccessSheet.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/AddFolderAccessSheet.tsx
@@ -43,7 +43,7 @@ type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
projectId: string;
- folderId: string;
+ environmentSlug: string;
folderPath: string;
environmentName: string;
};
@@ -52,7 +52,7 @@ export const AddFolderAccessSheet = ({
isOpen,
onOpenChange,
projectId,
- folderId,
+ environmentSlug,
folderPath,
environmentName
}: Props) => {
@@ -65,7 +65,8 @@ export const AddFolderAccessSheet = ({
const listArgs = {
projectId,
- folderId,
+ environmentSlug,
+ secretPath: folderPath,
limit: CANDIDATE_LIMIT,
search: debouncedSearch.trim() || undefined
};
@@ -119,14 +120,16 @@ export const AddFolderAccessSheet = ({
actor.type === "user"
? createUserAccess.mutateAsync({
projectId,
- folderId,
+ environmentSlug,
+ secretPath: folderPath,
userId: actor.id,
permission: tier,
type
})
: createIdentityAccess.mutateAsync({
projectId,
- folderId,
+ environmentSlug,
+ secretPath: folderPath,
identityId: actor.id,
permission: tier,
type
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 c11f385c85..2a535eb085 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessRow.tsx
@@ -52,6 +52,7 @@ export const FolderAccessRow = ({
const { access } = actor;
const expiresAt = expiryOf(access);
+ const isExpired = Boolean(expiresAt && expiresAt.getTime() <= Date.now());
const firstName = actor.name.split(" ")[0];
const isRangeValid = isValidTemporaryRange(range);
@@ -73,12 +74,14 @@ export const FolderAccessRow = ({
{expiresAt && (
<Tooltip>
<TooltipTrigger>
- <Badge variant="outline" className="shrink-0">
+ <Badge variant={isExpired ? "danger" : "outline"} className="shrink-0">
<ClockIcon />
- Expires {formatExpiryShort(expiresAt)}
+ {isExpired ? "Expired" : "Expires"} {formatExpiryShort(expiresAt)}
</Badge>
</TooltipTrigger>
- <TooltipContent>Access expires {formatExpiryFull(expiresAt)}</TooltipContent>
+ <TooltipContent>
+ Access {isExpired ? "expired" : "expires"} {formatExpiryFull(expiresAt)}
+ </TooltipContent>
</Tooltip>
)}
@@ -128,7 +131,7 @@ export const FolderAccessRow = ({
}
temporaryLabel={
expiresAt
- ? `Edit temporary access · until ${formatExpiryShort(expiresAt)}`
+ ? `Edit temporary access · ${isExpired ? "expired" : "until"} ${formatExpiryShort(expiresAt)}`
: "Add temporary access"
}
onSelectTier={onSetTier}
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 5df41adc72..9576872202 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessSheet.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/FolderAccessSheet/FolderAccessSheet.tsx
@@ -49,7 +49,7 @@ type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
projectId: string;
- folderId: string;
+ environmentSlug: string;
folderPath: string;
environmentName: string;
};
@@ -58,7 +58,7 @@ export const FolderAccessSheet = ({
isOpen,
onOpenChange,
projectId,
- folderId,
+ environmentSlug,
folderPath,
environmentName
}: Props) => {
@@ -70,7 +70,8 @@ export const FolderAccessSheet = ({
const listArgs = {
projectId,
- folderId,
+ environmentSlug,
+ secretPath: folderPath,
limit: FETCH_LIMIT,
search: debouncedSearch.trim() || undefined
};
@@ -104,7 +105,7 @@ export const FolderAccessSheet = ({
const notifySuccess = (text: string) => createNotification({ text, type: "success" });
const setTier = (actor: TFolderAccessActor, permission: SecretFolderRole) => {
- const target = { projectId, folderId };
+ const target = { projectId, environmentSlug, secretPath: folderPath };
const tierLabel = FOLDER_ROLE_TIER_LABELS[permission];
const onSuccess = () =>
notifySuccess(
@@ -125,7 +126,7 @@ export const FolderAccessSheet = ({
};
const setAccessType = (actor: TFolderAccessActor, type: TFolderGrantType) => {
- const target = { projectId, folderId };
+ const target = { projectId, environmentSlug, secretPath: folderPath };
const onSuccess = () =>
notifySuccess(
type.isTemporary
@@ -139,7 +140,7 @@ export const FolderAccessSheet = ({
};
const removeAccess = (actor: TFolderAccessActor) => {
- const target = { projectId, folderId };
+ const target = { projectId, environmentSlug, secretPath: folderPath };
const onSuccess = () => {
notifySuccess(`Removed ${actor.name}'s folder access`);
setRemovalActor(null);
@@ -261,7 +262,7 @@ export const FolderAccessSheet = ({
isOpen={isAddOpen}
onOpenChange={setIsAddOpen}
projectId={projectId}
- folderId={folderId}
+ environmentSlug={environmentSlug}
folderPath={folderPath}
environmentName={environmentName}
/>