Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(api): enforce workspace:read on workspace endpoints

Andrej3a7faecef146
diff --git a/apps/api/src/utils/require-workspace-permission.ts b/apps/api/src/utils/require-workspace-permission.ts
index 96edd576d..4dead6cbe 100644
--- a/apps/api/src/utils/require-workspace-permission.ts
+++ b/apps/api/src/utils/require-workspace-permission.ts
@@ -1,60 +1,15 @@
-import { type BuiltInRoleName, builtInRoles } from "@kaneo/permissions";
import { and, eq } from "drizzle-orm";
import type { Context, Next } from "hono";
import { HTTPException } from "hono/http-exception";
import db, { schema } from "../database";
import { isInstanceAdmin } from "./is-instance-admin";
+import { type PermissionMap, roleAllows, satisfies } from "./role-permissions";
-type PermissionMap = Record<string, string[]>;
-
-function builtInRoleStatements(
- role: string,
-): Record<string, readonly string[]> | null {
- if (role in builtInRoles) {
- return builtInRoles[role as BuiltInRoleName].statements as Record<
- string,
- readonly string[]
- >;
- }
- return null;
-}
-
-function parsePermissionStatements(
- raw: string,
-): Record<string, readonly string[]> | null {
- let value: unknown;
- try {
- value = JSON.parse(raw);
- } catch {
- return null;
- }
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- return null;
- }
-
- // Only keep entries shaped like { [resource: string]: string[] }.
- // Anything malformed is dropped so `satisfies()` never calls
- // `.includes()` on a non-array.
- const result: Record<string, string[]> = {};
- for (const [resource, actions] of Object.entries(
- value as Record<string, unknown>,
- )) {
- if (!Array.isArray(actions)) continue;
- const filtered = actions.filter(
- (action): action is string => typeof action === "string",
- );
- if (filtered.length > 0) {
- result[resource] = filtered;
- }
- }
- return result;
-}
-
-async function customRoleStatements(
+async function storedRolePermission(
workspaceId: string,
role: string,
database: Pick<typeof db, "select"> = db,
-): Promise<Record<string, readonly string[]> | null> {
+): Promise<string | null> {
const [row] = await database
.select({ permission: schema.workspaceRoleTable.permission })
.from(schema.workspaceRoleTable)
@@ -66,23 +21,20 @@ async function customRoleStatements(
)
.limit(1);
- if (!row?.permission) return null;
+ return row?.permission ?? null;
+}
- return parsePermissionStatements(row.permission);
+function apiKeyAllows(c: Context, permissions: PermissionMap) {
+ const apiKey = c.get("apiKey") as
+ | { permissions?: Record<string, string[]> | null }
+ | undefined;
+ return !apiKey?.permissions || satisfies(apiKey.permissions, permissions);
}
-function satisfies(
- statements: Record<string, readonly string[]>,
- required: PermissionMap,
-): boolean {
- for (const [resource, actions] of Object.entries(required)) {
- const granted = statements[resource];
- if (!granted) return false;
- for (const action of actions) {
- if (!granted.includes(action)) return false;
- }
+function assertApiKeyScope(c: Context, permissions: PermissionMap) {
+ if (!apiKeyAllows(c, permissions)) {
+ throw new HTTPException(403, { message: "Insufficient API key scope" });
}
- return true;
}
export async function roleHasWorkspacePermission(
@@ -91,10 +43,11 @@ export async function roleHasWorkspacePermission(
permissions: PermissionMap,
database: Pick<typeof db, "select"> = db,
) {
- const statements =
- (await customRoleStatements(workspaceId, role, database)) ??
- builtInRoleStatements(role);
- return Boolean(statements && satisfies(statements, permissions));
+ return roleAllows(
+ role,
+ await storedRolePermission(workspaceId, role, database),
+ permissions,
+ );
}
export async function hasWorkspacePermission(
@@ -108,10 +61,7 @@ export async function hasWorkspacePermission(
const workspaceId = workspaceIdOverride ?? c.get("workspaceId");
if (!workspaceId) return false;
- const apiKey = c.get("apiKey") as
- | { permissions?: Record<string, string[]> | null }
- | undefined;
- if (apiKey?.permissions && !satisfies(apiKey.permissions, permissions)) {
+ if (!apiKeyAllows(c, permissions)) {
return false;
}
@@ -141,11 +91,14 @@ export async function hasWorkspacePermission(
// viewer/member/admin users from a 403 if their workspace somehow
// missed the seed (e.g., seed failed during workspace creation and
// the boot-time backfill hasn't run yet).
- const statements =
- (await customRoleStatements(workspaceId, member.role)) ??
- builtInRoleStatements(member.role);
+ return roleHasWorkspacePermission(workspaceId, member.role, permissions);
+}
- return Boolean(statements && satisfies(statements, permissions));
+export function requireApiKeyScope(permissions: PermissionMap) {
+ return async (c: Context, next: Next) => {
+ assertApiKeyScope(c, permissions);
+ return next();
+ };
}
export function requireWorkspacePermission(permissions: PermissionMap) {
@@ -156,12 +109,7 @@ export function requireWorkspacePermission(permissions: PermissionMap) {
});
}
- const apiKey = c.get("apiKey") as
- | { permissions?: Record<string, string[]> | null }
- | undefined;
- if (apiKey?.permissions && !satisfies(apiKey.permissions, permissions)) {
- throw new HTTPException(403, { message: "Insufficient API key scope" });
- }
+ assertApiKeyScope(c, permissions);
if (!(await hasWorkspacePermission(c, permissions))) {
if (!c.get("userId")) {
diff --git a/apps/api/src/utils/role-permissions.test.ts b/apps/api/src/utils/role-permissions.test.ts
new file mode 100644
index 000000000..e55b1079d
--- /dev/null
+++ b/apps/api/src/utils/role-permissions.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vite-plus/test";
+import { roleAllows, satisfies } from "./role-permissions";
+
+const workspaceRead = { workspace: ["read"] };
+
+describe("roleAllows", () => {
+ it("uses the built-in statements when no permission is stored", () => {
+ expect(roleAllows("viewer", null, workspaceRead)).toBe(true);
+ expect(roleAllows("viewer", undefined, { task: ["create"] })).toBe(false);
+ });
+
+ it("prefers the stored permission over the built-in statements", () => {
+ const stored = JSON.stringify({ task: ["read"] });
+
+ expect(roleAllows("member", stored, workspaceRead)).toBe(false);
+ expect(roleAllows("member", stored, { task: ["read"] })).toBe(true);
+ });
+
+ it("reads a custom role from its stored permission only", () => {
+ expect(roleAllows("custom", null, workspaceRead)).toBe(false);
+ expect(
+ roleAllows("custom", JSON.stringify(workspaceRead), workspaceRead),
+ ).toBe(true);
+ });
+
+ it("falls back to the built-in statements when the stored JSON is malformed", () => {
+ expect(roleAllows("viewer", "{not json", workspaceRead)).toBe(true);
+ expect(roleAllows("custom", "{not json", workspaceRead)).toBe(false);
+ });
+
+ it("ignores malformed entries in the stored permission", () => {
+ const stored = JSON.stringify({
+ workspace: "read",
+ task: ["read", 1],
+ });
+
+ expect(roleAllows("custom", stored, workspaceRead)).toBe(false);
+ expect(roleAllows("custom", stored, { task: ["read"] })).toBe(true);
+ });
+});
+
+describe("satisfies", () => {
+ it("requires every action of every resource", () => {
+ const statements = { task: ["read", "update"], label: ["read"] };
+
+ expect(satisfies(statements, { task: ["read", "update"] })).toBe(true);
+ expect(satisfies(statements, { task: ["delete"] })).toBe(false);
+ expect(satisfies(statements, { workspace: ["read"] })).toBe(false);
+ });
+});
diff --git a/apps/api/src/utils/role-permissions.ts b/apps/api/src/utils/role-permissions.ts
new file mode 100644
index 000000000..f6d04d2f7
--- /dev/null
+++ b/apps/api/src/utils/role-permissions.ts
@@ -0,0 +1,67 @@
+import { type BuiltInRoleName, builtInRoles } from "@kaneo/permissions";
+
+export type PermissionMap = Record<string, string[]>;
+
+type PermissionStatements = Record<string, readonly string[]>;
+
+function builtInRoleStatements(role: string): PermissionStatements | null {
+ if (role in builtInRoles) {
+ return builtInRoles[role as BuiltInRoleName]
+ .statements as PermissionStatements;
+ }
+ return null;
+}
+
+function parsePermissionStatements(raw: string): PermissionStatements | null {
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return null;
+ }
+
+ // Only keep entries shaped like { [resource: string]: string[] }.
+ // Anything malformed is dropped so `satisfies()` never calls
+ // `.includes()` on a non-array.
+ const result: Record<string, string[]> = {};
+ for (const [resource, actions] of Object.entries(
+ value as Record<string, unknown>,
+ )) {
+ if (!Array.isArray(actions)) continue;
+ const filtered = actions.filter(
+ (action): action is string => typeof action === "string",
+ );
+ if (filtered.length > 0) {
+ result[resource] = filtered;
+ }
+ }
+ return result;
+}
+
+export function satisfies(
+ statements: PermissionStatements,
+ required: PermissionMap,
+): boolean {
+ for (const [resource, actions] of Object.entries(required)) {
+ const granted = statements[resource];
+ if (!granted) return false;
+ for (const action of actions) {
+ if (!granted.includes(action)) return false;
+ }
+ }
+ return true;
+}
+
+export function roleAllows(
+ role: string,
+ storedPermission: string | null | undefined,
+ permissions: PermissionMap,
+) {
+ const statements =
+ (storedPermission ? parsePermissionStatements(storedPermission) : null) ??
+ builtInRoleStatements(role);
+ return Boolean(statements && satisfies(statements, permissions));
+}
diff --git a/apps/api/src/workspace/can-read-workspace.test.ts b/apps/api/src/workspace/can-read-workspace.test.ts
new file mode 100644
index 000000000..fd0d1d56d
--- /dev/null
+++ b/apps/api/src/workspace/can-read-workspace.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vite-plus/test";
+import { canReadWorkspace } from "./can-read-workspace";
+
+const noRead = JSON.stringify({ task: ["read"] });
+
+describe("canReadWorkspace", () => {
+ it("allows built-in roles", () => {
+ for (const role of ["viewer", "member", "admin", "owner"]) {
+ expect(
+ canReadWorkspace({ role, rolePermission: null, instanceAdmin: false }),
+ ).toBe(true);
+ }
+ });
+
+ it("denies a role whose permission lacks workspace:read", () => {
+ expect(
+ canReadWorkspace({
+ role: "custom",
+ rolePermission: noRead,
+ instanceAdmin: false,
+ }),
+ ).toBe(false);
+ });
+
+ it("denies a non-member who is not an instance admin", () => {
+ expect(
+ canReadWorkspace({
+ role: null,
+ rolePermission: null,
+ instanceAdmin: false,
+ }),
+ ).toBe(false);
+ });
+
+ it("lets instance admins read regardless of their role", () => {
+ expect(
+ canReadWorkspace({
+ role: "custom",
+ rolePermission: noRead,
+ instanceAdmin: true,
+ }),
+ ).toBe(true);
+ expect(
+ canReadWorkspace({
+ role: null,
+ rolePermission: null,
+ instanceAdmin: true,
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/apps/api/src/workspace/can-read-workspace.ts b/apps/api/src/workspace/can-read-workspace.ts
new file mode 100644
index 000000000..f037c60c7
--- /dev/null
+++ b/apps/api/src/workspace/can-read-workspace.ts
@@ -0,0 +1,26 @@
+import { sql } from "drizzle-orm";
+import {
+ userTable,
+ workspaceRoleTable,
+ workspaceUserTable,
+} from "../database/schema";
+import { instanceAdminRoleSql } from "../utils/instance-admin-role";
+import { roleAllows } from "../utils/role-permissions";
+
+export const workspaceAccessColumns = {
+ role: workspaceUserTable.role,
+ rolePermission: workspaceRoleTable.permission,
+ instanceAdmin: sql<boolean>`coalesce(${instanceAdminRoleSql(userTable.role)}, false)`,
+};
+
+export function canReadWorkspace(row: {
+ role: string | null;
+ rolePermission: string | null;
+ instanceAdmin: boolean;
+}) {
+ if (row.instanceAdmin) return true;
+ return (
+ row.role !== null &&
+ roleAllows(row.role, row.rolePermission, { workspace: ["read"] })
+ );
+}
diff --git a/apps/api/src/workspace/controllers/get-workspace.ts b/apps/api/src/workspace/controllers/get-workspace.ts
index c529169ec..8fdbe8f2c 100644
--- a/apps/api/src/workspace/controllers/get-workspace.ts
+++ b/apps/api/src/workspace/controllers/get-workspace.ts
@@ -3,10 +3,15 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
userTable,
+ workspaceRoleTable,
workspaceTable,
workspaceUserTable,
} from "../../database/schema";
import { instanceAdminRoleSql } from "../../utils/instance-admin-role";
+import {
+ canReadWorkspace,
+ workspaceAccessColumns,
+} from "../can-read-workspace";
import {
toWorkspaceResponse,
workspaceColumns,
@@ -14,7 +19,7 @@ import {
async function getWorkspace(workspaceId: string, userId: string) {
const [row] = await db
- .select({ ...workspaceColumns, role: workspaceUserTable.role })
+ .select({ ...workspaceColumns, ...workspaceAccessColumns })
.from(workspaceTable)
.innerJoin(userTable, eq(userTable.id, userId))
.leftJoin(
@@ -24,6 +29,13 @@ async function getWorkspace(workspaceId: string, userId: string) {
eq(workspaceUserTable.userId, userTable.id),
),
)
+ .leftJoin(
+ workspaceRoleTable,
+ and(
+ eq(workspaceRoleTable.workspaceId, workspaceTable.id),
+ eq(workspaceRoleTable.role, workspaceUserTable.role),
+ ),
+ )
.where(
and(
eq(workspaceTable.id, workspaceId),
@@ -36,7 +48,7 @@ async function getWorkspace(workspaceId: string, userId: string) {
.orderBy(workspaceUserTable.joinedAt, workspaceUserTable.id)
.limit(1);
- if (!row) {
+ if (!row || !canReadWorkspace(row)) {
throw new HTTPException(404, { message: "Workspace not found" });
}
diff --git a/apps/api/src/workspace/controllers/list-workspaces.ts b/apps/api/src/workspace/controllers/list-workspaces.ts
index 7c6e3b9a7..2ea5a9480 100644
--- a/apps/api/src/workspace/controllers/list-workspaces.ts
+++ b/apps/api/src/workspace/controllers/list-workspaces.ts
@@ -1,6 +1,15 @@
import { and, eq, sql } from "drizzle-orm";
import db from "../../database";
-import { workspaceTable, workspaceUserTable } from "../../database/schema";
+import {
+ userTable,
+ workspaceRoleTable,
+ workspaceTable,
+ workspaceUserTable,
+} from "../../database/schema";
+import {
+ canReadWorkspace,
+ workspaceAccessColumns,
+} from "../can-read-workspace";
import {
toWorkspaceResponse,
workspaceColumns,
@@ -12,7 +21,7 @@ async function listWorkspaces(userId: string) {
const rows = await db
.selectDistinctOn([sortName, workspaceTable.id], {
...workspaceColumns,
- role: workspaceUserTable.role,
+ ...workspaceAccessColumns,
})
.from(workspaceTable)
.innerJoin(
@@ -22,6 +31,14 @@ async function listWorkspaces(userId: string) {
eq(workspaceUserTable.userId, userId),
),
)
+ .innerJoin(userTable, eq(userTable.id, workspaceUserTable.userId))
+ .leftJoin(
+ workspaceRoleTable,
+ and(
+ eq(workspaceRoleTable.workspaceId, workspaceTable.id),
+ eq(workspaceRoleTable.role, workspaceUserTable.role),
+ ),
+ )
.orderBy(
sortName,
workspaceTable.id,
@@ -29,7 +46,7 @@ async function listWorkspaces(userId: string) {
workspaceUserTable.id,
);
- return rows.map(toWorkspaceResponse);
+ return rows.filter(canReadWorkspace).map(toWorkspaceResponse);
}
export default listWorkspaces;
diff --git a/apps/api/src/workspace/index.ts b/apps/api/src/workspace/index.ts
index b3888165a..8e82f6c78 100644
--- a/apps/api/src/workspace/index.ts
+++ b/apps/api/src/workspace/index.ts
@@ -6,7 +6,10 @@ import {
jsonResponse,
} from "../openapi";
import { listWorkspaceProjectAccess } from "../project-access/list-workspace-project-access";
-import { requireWorkspacePermission } from "../utils/require-workspace-permission";
+import {
+ requireApiKeyScope,
+ requireWorkspacePermission,
+} from "../utils/require-workspace-permission";
import { workspaceAccess } from "../utils/workspace-access-middleware";
import getMyProjectAccessCtrl from "./controllers/get-my-project-access";
import getWorkspaceCtrl from "./controllers/get-workspace";
@@ -34,9 +37,11 @@ const listWorkspacesRoute = createRoute({
tags: ["Workspaces"],
summary: "List workspaces",
description:
- "List the workspaces the caller is a member of, with the caller's role, sorted by name. Instance admins also only get the workspaces they are a member of.",
+ "List the workspaces where the caller is a member with a role that grants workspace:read, with the caller's role, sorted by name. Instance admins get every workspace they are a member of, and only those.",
+ middleware: [requireApiKeyScope({ workspace: ["read"] })] as const,
responses: {
200: jsonResponse("The caller's workspaces", workspaceListSchema),
+ 403: errorResponse("The API key lacks workspace:read"),
},
});
@@ -47,12 +52,14 @@ const getWorkspaceRoute = createRoute({
tags: ["Workspaces"],
summary: "Get workspace",
description:
- "Get a workspace the caller is a member of, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member.",
+ "Get a workspace the caller is a member of with a role that grants workspace:read, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member.",
+ middleware: [requireApiKeyScope({ workspace: ["read"] })] as const,
request: { params: workspaceIdParam },
responses: {
200: jsonResponse("The workspace", workspaceSchema),
+ 403: errorResponse("The API key lacks workspace:read"),
404: errorResponse(
- "Workspace not found, or the caller is not a member of it",
+ "Workspace not found, the caller is not a member of it, or their role lacks workspace:read",
),
},
});
diff --git a/apps/api/src/workspace/response.ts b/apps/api/src/workspace/response.ts
index 4b25482ff..618909819 100644
--- a/apps/api/src/workspace/response.ts
+++ b/apps/api/src/workspace/response.ts
@@ -11,7 +11,7 @@ export const workspaceSchema = z
createdAt: responseTimestamp,
role: z.string().nullable().openapi({
description:
- "The caller's workspace role: a built-in role (owner, admin, member, guest) or a custom role name. Null when an instance admin views a workspace they are not a member of.",
+ "The caller's workspace role: a built-in role (owner, admin, member, viewer) or the name of a custom role defined in the workspace. Null when an instance admin views a workspace they are not a member of.",
}),
})
.openapi("Workspace");
@@ -26,7 +26,7 @@ export const workspaceMemberSchema = z
image: z.string().nullable(),
role: z.string().openapi({
description:
- "The member's workspace role: a built-in role (owner, admin, member, guest) or a custom role name.",
+ "The member's workspace role: a built-in role (owner, admin, member, viewer) or the name of a custom role defined in the workspace.",
}),
})
.openapi("WorkspaceMember");
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index d654be638..3b0caf2eb 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -4327,7 +4327,7 @@
"string",
"null"
],
- "description": "The caller's workspace role: a built-in role (owner, admin, member, guest) or a custom role name. Null when an instance admin views a workspace they are not a member of."
+ "description": "The caller's workspace role: a built-in role (owner, admin, member, viewer) or the name of a custom role defined in the workspace. Null when an instance admin views a workspace they are not a member of."
}
},
"required": [
@@ -4360,7 +4360,7 @@
},
"role": {
"type": "string",
- "description": "The member's workspace role: a built-in role (owner, admin, member, guest) or a custom role name."
+ "description": "The member's workspace role: a built-in role (owner, admin, member, viewer) or the name of a custom role defined in the workspace."
}
},
"required": [
@@ -19020,7 +19020,7 @@
"Workspaces"
],
"summary": "List workspaces",
- "description": "List the workspaces the caller is a member of, with the caller's role, sorted by name. Instance admins also only get the workspaces they are a member of.",
+ "description": "List the workspaces where the caller is a member with a role that grants workspace:read, with the caller's role, sorted by name. Instance admins get every workspace they are a member of, and only those.",
"responses": {
"200": {
"description": "The caller's workspaces",
@@ -19037,6 +19037,16 @@
},
"401": {
"description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "The API key lacks workspace:read",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
}
}
@@ -19048,7 +19058,7 @@
"Workspaces"
],
"summary": "Get workspace",
- "description": "Get a workspace the caller is a member of, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member.",
+ "description": "Get a workspace the caller is a member of with a role that grants workspace:read, with the caller's role. Instance admins can get any workspace, with a null role when they are not a member.",
"parameters": [
{
"schema": {
@@ -19073,8 +19083,18 @@
"401": {
"description": "Missing or invalid credentials"
},
+ "403": {
+ "description": "The API key lacks workspace:read",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"404": {
- "description": "Workspace not found, or the caller is not a member of it",
+ "description": "Workspace not found, the caller is not a member of it, or their role lacks workspace:read",
"content": {
"text/plain": {
"schema": {
diff --git a/tests/api-integration/workspace-endpoints.test.ts b/tests/api-integration/workspace-endpoints.test.ts
index 262b8e18c..43f7183d7 100644
--- a/tests/api-integration/workspace-endpoints.test.ts
+++ b/tests/api-integration/workspace-endpoints.test.ts
@@ -40,6 +40,18 @@ async function addMembership(
.values({ workspaceId, userId, role, joinedAt });
}
+async function addRole(
+ workspaceId: string,
+ role: string,
+ permission: Record<string, string[]>,
+) {
+ await db.insert(schema.workspaceRoleTable).values({
+ workspaceId,
+ role,
+ permission: JSON.stringify(permission),
+ });
+}
+
function expected(workspace: WorkspaceRow, role: string | null) {
return {
id: workspace.id,
@@ -81,7 +93,7 @@ describe("GET /api/workspace", () => {
await addMembership(beta.id, caller.userId, "owner");
await addMembership(alpha.id, caller.userId, "member");
await addMembership(charlie.id, caller.userId, "admin");
- await addMembership(twinB.id, caller.userId, "guest");
+ await addMembership(twinB.id, caller.userId, "viewer");
await addMembership(twinA.id, caller.userId, "member");
await createWorkspaceMember({ workspaceName: "Aardvark" });
@@ -94,7 +106,7 @@ describe("GET /api/workspace", () => {
expected(beta, "owner"),
expected(charlie, "admin"),
expected(twinA, "member"),
- expected(twinB, "guest"),
+ expected(twinB, "viewer"),
]);
});
@@ -127,6 +139,46 @@ describe("GET /api/workspace", () => {
expect(await readJson(response)).toEqual([expected(joined, "member")]);
});
+ it("leaves out workspaces where the caller's role lacks workspace:read", async () => {
+ const { user, workspace: hidden } = await createWorkspaceMember({
+ role: "limited",
+ workspaceName: "Hidden",
+ });
+ await addRole(hidden.id, "limited", { task: ["read"] });
+ const edited = await createWorkspace({ name: "Edited viewer" });
+ await addMembership(edited.id, user.id, "viewer");
+ await addRole(edited.id, "viewer", { project: ["read"] });
+ const custom = await createWorkspace({ name: "Custom" });
+ await addMembership(custom.id, user.id, "reader");
+ await addRole(custom.id, "reader", { workspace: ["read"] });
+ const visible = await createWorkspace({ name: "Visible" });
+ await addMembership(visible.id, user.id, "member");
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/workspace");
+
+ expect(await readJson(response)).toEqual([
+ expected(custom, "reader"),
+ expected(visible, "member"),
+ ]);
+ });
+
+ it("lists an instance admin's membership even when the role lacks workspace:read", async () => {
+ const admin = await createInstanceAdmin();
+ const workspace = await createWorkspace({ name: "Limited" });
+ await addMembership(workspace.id, admin.id, "limited");
+ await addRole(workspace.id, "limited", { task: ["read"] });
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ const list = await app.request("/api/workspace");
+ const single = await app.request(`/api/workspace/${workspace.id}`);
+
+ expect(await readJson(list)).toEqual([expected(workspace, "limited")]);
+ expect(await readJson(single)).toEqual(expected(workspace, "limited"));
+ });
+
it("returns an empty list when the caller has no workspaces", async () => {
await createWorkspaceMember();
const { app } = createApp();
@@ -245,6 +297,23 @@ describe("GET /api/workspace/{workspaceId}", () => {
expect(await missing.text()).toBe(notMemberBody);
});
+ it("returns the same 404 when the caller's role lacks workspace:read", async () => {
+ const { user, workspace } = await createWorkspaceMember({
+ role: "limited",
+ });
+ await addRole(workspace.id, "limited", { task: ["read"] });
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const denied = await app.request(`/api/workspace/${workspace.id}`);
+ const missing = await app.request("/api/workspace/workspace-missing");
+
+ expect(denied.status).toBe(404);
+ const deniedBody = await denied.text();
+ expect(deniedBody).toContain("Workspace not found");
+ expect(await missing.text()).toBe(deniedBody);
+ });
+
it("lets an instance admin read a workspace they are not a member of", async () => {
const { workspace } = await createWorkspaceMember({ role: "owner" });
const admin = await createInstanceAdmin();
@@ -308,6 +377,50 @@ describe("workspace endpoints with bearer credentials", () => {
},
);
+ it("rejects an API key without workspace:read on both routes", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const { key } = await auth.api.createApiKey({
+ body: {
+ userId: user.id,
+ name: "Task reader",
+ permissions: { task: ["read"], project: ["read"] },
+ },
+ });
+ const headers = { Authorization: `Bearer ${key}` };
+ const { app } = createApp();
+
+ const list = await app.request("/api/workspace", { headers });
+ const single = await app.request(`/api/workspace/${workspace.id}`, {
+ headers,
+ });
+
+ expect(list.status).toBe(403);
+ expect(await list.text()).toContain("Insufficient API key scope");
+ expect(single.status).toBe(403);
+ expect(await single.text()).toContain("Insufficient API key scope");
+ });
+
+ it("accepts an API key scoped to workspace:read", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const { key } = await auth.api.createApiKey({
+ body: {
+ userId: user.id,
+ name: "Workspace reader",
+ permissions: { workspace: ["read"] },
+ },
+ });
+ const headers = { "x-api-key": key };
+ const { app } = createApp();
+
+ const list = await app.request("/api/workspace", { headers });
+ const single = await app.request(`/api/workspace/${workspace.id}`, {
+ headers,
+ });
+
+ expect(await readJson(list)).toEqual([expected(workspace, "owner")]);
+ expect(await readJson(single)).toEqual(expected(workspace, "owner"));
+ });
+
it("reads the instance admin role from the database for API keys", async () => {
const { workspace } = await createWorkspaceMember({ role: "owner" });
const admin = await createInstanceAdmin();