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.

Merge remote-tracking branch 'origin/main' into merge-1960

Andrej19ce80688b93
diff --cc apps/api/src/utils/require-workspace-permission.ts
index d75a0c5a3,601dd8397..5387e008e
--- a/apps/api/src/utils/require-workspace-permission.ts
+++ b/apps/api/src/utils/require-workspace-permission.ts
@@@ -2,46 -3,88 +2,54 @@@ import { and, eq, inArray } from "drizz
import type { Context, Next } from "hono";
import { HTTPException } from "hono/http-exception";
import db, { schema } from "../database";
+ import { ApiError } from "../errors/api-error";
import { isInstanceAdmin } from "./is-instance-admin";
+ import { missingPermissions } from "./missing-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(
+import {
+ type PermissionMap,
+ rolesAllow,
++ rolesMissingPermissions,
+ type StoredRolePermission,
+ satisfies,
+} from "./role-permissions";
+import { splitRoles } from "./split-roles";
+
+async function storedRolePermissions(
workspaceId: string,
- role: string,
- database: Pick<typeof db, "select"> = db,
-): Promise<Record<string, readonly string[]> | null> {
- const [row] = await database
- .select({ permission: schema.workspaceRoleTable.permission })
+ roles: string[],
+ database: Pick<typeof db, "select">,
+): Promise<StoredRolePermission[]> {
+ if (roles.length === 0) return [];
+ return database
+ .select({
+ role: schema.workspaceRoleTable.role,
+ permission: schema.workspaceRoleTable.permission,
+ })
.from(schema.workspaceRoleTable)
.where(
and(
eq(schema.workspaceRoleTable.workspaceId, workspaceId),
- eq(schema.workspaceRoleTable.role, role),
+ inArray(schema.workspaceRoleTable.role, roles),
),
- )
- .limit(1);
-
- if (!row?.permission) return null;
+ );
+}
- function apiKeyAllows(c: Context, permissions: PermissionMap) {
- return parsePermissionStatements(row.permission);
++function apiKeyPermissions(c: Context) {
+ const apiKey = c.get("apiKey") as
+ | { permissions?: Record<string, string[]> | null }
+ | undefined;
- return !apiKey?.permissions || satisfies(apiKey.permissions, permissions);
++ return apiKey?.permissions ?? null;
}
-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" });
++ const scope = apiKeyPermissions(c);
++ if (scope && !satisfies(scope, permissions)) {
++ throw new ApiError(403, {
++ message: "Insufficient API key scope",
++ code: "API_KEY_SCOPE",
++ missingPermissions: missingPermissions(scope, permissions),
++ });
}
- return true;
}
export async function roleHasWorkspacePermission(
@@@ -69,7 -110,10 +77,8 @@@ export async function hasWorkspacePermi
const workspaceId = workspaceIdOverride ?? c.get("workspaceId");
if (!workspaceId) return false;
- if (!apiKeyAllows(c, permissions)) {
- const apiKey = c.get("apiKey") as
- | { permissions?: Record<string, string[]> | null }
- | undefined;
- if (apiKey?.permissions && !satisfies(apiKey.permissions, permissions)) {
++ const scope = apiKeyPermissions(c);
++ if (scope && !satisfies(scope, permissions)) {
return false;
}
@@@ -77,8 -121,16 +86,16 @@@
return true;
}
- const statements = await memberStatements(c, workspaceId);
- return Boolean(statements && satisfies(statements, permissions));
++ const { roles, stored } = await memberRoles(c, workspaceId);
++ return rolesAllow(roles, stored, permissions);
+ }
+
-async function memberStatements(
++async function memberRoles(
+ c: Context,
+ workspaceId: string,
-): Promise<Record<string, readonly string[]> | null> {
++): Promise<{ roles: string[]; stored: StoredRolePermission[] }> {
const userId = c.get("userId");
- if (!userId) return false;
- if (!userId) return null;
++ if (!userId) return { roles: [], stored: [] };
const [member] = await db
.select({ role: schema.workspaceUserTable.role })
@@@ -91,22 -143,18 +108,24 @@@
)
.limit(1);
- if (!member?.role) return false;
- if (!member?.role) return null;
--
// Prefer the DB row when present so admin-edited defaults
// (viewer/member/admin) take effect immediately. Falls back to the
// compiled-in static definitions only when no row exists, which protects
// 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).
- return roleHasWorkspacePermission(workspaceId, member.role, permissions);
- return (
- (await customRoleStatements(workspaceId, member.role)) ??
- builtInRoleStatements(member.role)
- );
++ const roles = splitRoles(member?.role);
++ return {
++ roles,
++ stored: await storedRolePermissions(workspaceId, roles, db),
++ };
+}
+
+export function requireApiKeyScope(permissions: PermissionMap) {
+ return async (c: Context, next: Next) => {
+ assertApiKeyScope(c, permissions);
+ return next();
+ };
}
export function requireWorkspacePermission(permissions: PermissionMap) {
@@@ -117,13 -166,32 +137,23 @@@
});
}
- const apiKey = c.get("apiKey") as
- | { permissions?: Record<string, string[]> | null }
- | undefined;
- if (apiKey?.permissions && !satisfies(apiKey.permissions, permissions)) {
- throw new ApiError(403, {
- message: "Insufficient API key scope",
- code: "API_KEY_SCOPE",
- missingPermissions: missingPermissions(apiKey.permissions, permissions),
- });
- }
+ assertApiKeyScope(c, permissions);
- if (!(await hasWorkspacePermission(c, permissions))) {
- if (!c.get("userId")) {
- throw new HTTPException(401, { message: "Unauthorized" });
- }
- throw new HTTPException(403, { message: "Insufficient permissions" });
+ if (await isInstanceAdmin(c)) {
+ return next();
+ }
+
+ if (!c.get("userId")) {
+ throw new HTTPException(401, { message: "Unauthorized" });
+ }
+
- const statements = await memberStatements(c, workspaceId);
- if (!statements || !satisfies(statements, permissions)) {
++ const { roles, stored } = await memberRoles(c, workspaceId);
++ if (!rolesAllow(roles, stored, permissions)) {
+ throw new ApiError(403, {
+ message: "Insufficient permissions",
+ code: "MISSING_PERMISSION",
- missingPermissions: missingPermissions(statements, permissions),
++ missingPermissions: rolesMissingPermissions(roles, stored, permissions),
+ });
}
return next();
diff --cc apps/api/src/utils/role-permissions.test.ts
index c391931cf,000000000..27038ab9a
mode 100644,000000..100644
--- a/apps/api/src/utils/role-permissions.test.ts
+++ b/apps/api/src/utils/role-permissions.test.ts
@@@ -1,117 -1,0 +1,192 @@@
+import { describe, expect, it } from "vite-plus/test";
- import { roleAllows, rolesAllow, satisfies } from "./role-permissions";
++import {
++ roleAllows,
++ rolesAllow,
++ rolesMissingPermissions,
++ 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("rolesAllow", () => {
+ const noRead = JSON.stringify({ task: ["read"] });
+ const read = JSON.stringify(workspaceRead);
+
+ it("allows when any role grants the permission", () => {
+ expect(
+ rolesAllow(
+ ["limited", "reader"],
+ [
+ { role: "limited", permission: noRead },
+ { role: "reader", permission: read },
+ ],
+ workspaceRead,
+ ),
+ ).toBe(true);
+ expect(
+ rolesAllow(
+ ["limited", "viewer"],
+ [{ role: "limited", permission: noRead }],
+ workspaceRead,
+ ),
+ ).toBe(true);
+ });
+
+ it("denies when no role grants the permission", () => {
+ expect(
+ rolesAllow(
+ ["limited", "viewer"],
+ [
+ { role: "limited", permission: noRead },
+ { role: "viewer", permission: noRead },
+ ],
+ workspaceRead,
+ ),
+ ).toBe(false);
+ expect(rolesAllow([], [], workspaceRead)).toBe(false);
+ });
+
+ it("allows when any duplicate row for a role grants the permission", () => {
+ for (const stored of [
+ [
+ { role: "custom", permission: noRead },
+ { role: "custom", permission: read },
+ ],
+ [
+ { role: "custom", permission: read },
+ { role: "custom", permission: noRead },
+ ],
+ ]) {
+ expect(rolesAllow(["custom"], stored, workspaceRead)).toBe(true);
+ }
+ });
+
+ it("ignores stored rows for roles the member does not have", () => {
+ expect(
+ rolesAllow(
+ ["limited"],
+ [
+ { role: "limited", permission: noRead },
+ { role: "reader", permission: read },
+ ],
+ workspaceRead,
+ ),
+ ).toBe(false);
+ });
+});
+
++describe("rolesMissingPermissions", () => {
++ const required = { task: ["create", "update"], project: ["read"] };
++
++ it("lists what a single role lacks", () => {
++ expect(
++ rolesMissingPermissions(
++ ["custom"],
++ [{ role: "custom", permission: JSON.stringify({ task: ["create"] }) }],
++ required,
++ ),
++ ).toEqual(["task:update", "project:read"]);
++ });
++
++ it("reports the role that lacks the fewest permissions", () => {
++ expect(
++ rolesMissingPermissions(
++ ["far", "near"],
++ [
++ { role: "far", permission: JSON.stringify({ label: ["read"] }) },
++ {
++ role: "near",
++ permission: JSON.stringify({
++ task: ["create", "update"],
++ }),
++ },
++ ],
++ required,
++ ),
++ ).toEqual(["project:read"]);
++ });
++
++ it("compares every duplicate row and the built-in fallback", () => {
++ expect(
++ rolesMissingPermissions(
++ ["custom", "viewer"],
++ [
++ { role: "custom", permission: JSON.stringify({ task: ["read"] }) },
++ {
++ role: "custom",
++ permission: JSON.stringify({ task: ["create", "update"] }),
++ },
++ ],
++ required,
++ ),
++ ).toEqual(["project:read"]);
++ expect(rolesMissingPermissions(["viewer"], [], required)).toEqual([
++ "task:create",
++ "task:update",
++ ]);
++ });
++
++ it("lists every required permission when the member has no roles", () => {
++ expect(rolesMissingPermissions([], [], required)).toEqual([
++ "task:create",
++ "task:update",
++ "project:read",
++ ]);
++ });
++
++ it("returns nothing when a role grants every permission", () => {
++ expect(
++ rolesMissingPermissions(
++ ["limited", "admin"],
++ [{ role: "limited", permission: JSON.stringify({ task: ["read"] }) }],
++ required,
++ ),
++ ).toEqual([]);
++ });
++});
++
+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 --cc apps/api/src/utils/role-permissions.ts
index 982fe5b13,000000000..485fa5618
mode 100644,000000..100644
--- a/apps/api/src/utils/role-permissions.ts
+++ b/apps/api/src/utils/role-permissions.ts
@@@ -1,84 -1,0 +1,115 @@@
+import { type BuiltInRoleName, builtInRoles } from "@kaneo/permissions";
++import { missingPermissions } from "./missing-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;
+}
+
++function roleStatements(
++ role: string,
++ storedPermission: string | null | undefined,
++): PermissionStatements | null {
++ return (
++ (storedPermission ? parsePermissionStatements(storedPermission) : null) ??
++ builtInRoleStatements(role)
++ );
++}
++
+export function roleAllows(
+ role: string,
+ storedPermission: string | null | undefined,
+ permissions: PermissionMap,
+) {
- const statements =
- (storedPermission ? parsePermissionStatements(storedPermission) : null) ??
- builtInRoleStatements(role);
++ const statements = roleStatements(role, storedPermission);
+ return Boolean(statements && satisfies(statements, permissions));
+}
+
+export type StoredRolePermission = {
+ role: string;
+ permission: string | null;
+};
+
- export function rolesAllow(
++function candidateStatements(
+ roles: readonly string[],
+ stored: readonly StoredRolePermission[],
- permissions: PermissionMap,
+) {
- return roles.some((role) => {
++ return roles.flatMap((role) => {
+ const rows = stored.filter((row) => row.role === role);
- if (rows.length === 0) return roleAllows(role, null, permissions);
- return rows.some((row) => roleAllows(role, row.permission, permissions));
++ if (rows.length === 0) return [roleStatements(role, null)];
++ return rows.map((row) => roleStatements(role, row.permission));
+ });
+}
++
++export function rolesAllow(
++ roles: readonly string[],
++ stored: readonly StoredRolePermission[],
++ permissions: PermissionMap,
++) {
++ return candidateStatements(roles, stored).some((statements) =>
++ Boolean(statements && satisfies(statements, permissions)),
++ );
++}
++
++export function rolesMissingPermissions(
++ roles: readonly string[],
++ stored: readonly StoredRolePermission[],
++ permissions: PermissionMap,
++): string[] {
++ let closest = missingPermissions(null, permissions);
++ for (const statements of candidateStatements(roles, stored)) {
++ const missing = missingPermissions(statements, permissions);
++ if (missing.length < closest.length) closest = missing;
++ }
++ return closest;
++}
diff --cc apps/docs/openapi.json
index fdf36f8f4,37e0e8212..981ab7e00
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@@ -19013,99 -20127,6 +20173,113 @@@
}
}
},
+ "/workspace": {
+ "get": {
+ "operationId": "listWorkspaces",
+ "tags": [
+ "Workspaces"
+ ],
+ "summary": "List workspaces",
+ "description": "List the workspaces where one of the caller's roles 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",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Workspace"
+ }
+ }
+ }
+ }
+ },
+ "401": {
- "description": "Missing or invalid credentials"
++ "description": "Missing or invalid credentials",
++ "content": {
++ "application/json": {
++ "schema": {
++ "$ref": "#/components/schemas/ApiError"
++ }
++ }
++ }
+ },
+ "403": {
+ "description": "The API key lacks workspace:read",
+ "content": {
- "text/plain": {
++ "application/json": {
+ "schema": {
- "type": "string"
++ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/workspace/{workspaceId}": {
+ "get": {
+ "operationId": "getWorkspace",
+ "tags": [
+ "Workspaces"
+ ],
+ "summary": "Get workspace",
+ "description": "Get a workspace where one of the caller's roles 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": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "workspaceId",
+ "in": "path"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The workspace",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/Workspace"
+ }
+ }
+ }
+ },
+ "401": {
- "description": "Missing or invalid credentials"
++ "description": "Missing or invalid credentials",
++ "content": {
++ "application/json": {
++ "schema": {
++ "$ref": "#/components/schemas/ApiError"
++ }
++ }
++ }
+ },
+ "403": {
+ "description": "The API key lacks workspace:read",
+ "content": {
- "text/plain": {
++ "application/json": {
+ "schema": {
- "type": "string"
++ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Workspace not found, the caller is not a member of it, or none of their roles grants workspace:read",
+ "content": {
- "text/plain": {
++ "application/json": {
+ "schema": {
- "type": "string"
++ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/workspace/{workspaceId}/members": {
"get": {
"operationId": "getWorkspaceMembers",
diff --cc tests/api-integration/api-key-mixed-credentials.test.ts
index 000000000,b689f96a8..c26d9438e
mode 000000,100644..100644
--- a/tests/api-integration/api-key-mixed-credentials.test.ts
+++ b/tests/api-integration/api-key-mixed-credentials.test.ts
@@@ -1,0 -1,157 +1,162 @@@
+ import { createHash, randomUUID } from "node:crypto";
+ import { eq } from "drizzle-orm";
+ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+ import { auth } from "../../apps/api/src/auth";
+ import db, { schema } from "../../apps/api/src/database";
+ import { createApp } from "../../apps/api/src/index";
+ import {
+ createAuthorizationRequest,
+ registerClient,
+ } from "../../apps/api/src/mcp/oauth";
+ import { resetTestDatabase } from "./helpers/database";
++import { readErrorBody } from "./helpers/error-body";
+ import {
+ createProjectFixture,
+ createWorkspaceMember,
+ } from "./helpers/fixtures";
+
+ vi.mock("../../apps/api/src/storage/s3", async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getPrivateObject: async () => ({
+ body: new Uint8Array([1, 2, 3]),
+ contentType: "image/png",
+ contentLength: 3,
+ }),
+ }));
+
+ const invalidBearer = { Authorization: "Bearer not-a-real-token" };
+
+ async function createKey(
+ userId: string,
+ permissions?: Record<string, string[]>,
+ ) {
+ const { key } = await auth.api.createApiKey({
+ body: { userId, name: "Mixed credentials test", permissions },
+ });
+ return key;
+ }
+
+ describe("API integration: API key sent with an invalid bearer token", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("does not turn an administrator API key into a session", async () => {
+ const { user } = await createWorkspaceMember();
+ await db
+ .update(schema.userTable)
+ .set({ role: "admin" })
+ .where(eq(schema.userTable.id, user.id));
+ const key = await createKey(user.id);
+ const { app } = createApp();
+
+ const keyOnly = await app.request("/api/admin/users", {
+ headers: { "x-api-key": key },
+ });
+ expect(keyOnly.status).toBe(403);
+
+ const mixed = await app.request("/api/admin/users", {
+ headers: { "x-api-key": key, ...invalidBearer },
+ });
+ expect(mixed.status).toBe(401);
+ });
+
+ it("keeps the API key scope", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const key = await createKey(user.id, { project: ["read"] });
+ const { app } = createApp();
+ const createProject = (headers: Record<string, string>) =>
+ app.request("/api/project", {
+ method: "POST",
+ headers: { "content-type": "application/json", ...headers },
+ body: JSON.stringify({
+ name: "Scoped",
+ workspaceId: workspace.id,
+ icon: "Layout",
+ slug: "SCP",
+ }),
+ });
+
+ const keyOnly = await createProject({ "x-api-key": key });
+ expect(keyOnly.status).toBe(403);
- expect(await keyOnly.text()).toBe("Insufficient API key scope");
++ expect(await readErrorBody(keyOnly)).toEqual({
++ message: "Insufficient API key scope",
++ code: "API_KEY_SCOPE",
++ missingPermissions: ["project:create"],
++ });
+
+ const mixed = await createProject({ "x-api-key": key, ...invalidBearer });
+ expect(mixed.status).toBe(401);
+ expect(
+ await db
+ .select()
+ .from(schema.projectTable)
+ .where(eq(schema.projectTable.workspaceId, workspace.id)),
+ ).toHaveLength(0);
+ });
+
+ it("rejects private asset downloads", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const [asset] = await db
+ .insert(schema.assetTable)
+ .values({
+ workspaceId: workspace.id,
+ projectId: project.id,
+ objectKey: randomUUID(),
+ filename: "image.png",
+ mimeType: "image/png",
+ size: 3,
+ surface: "comment",
+ createdBy: user.id,
+ })
+ .returning();
+ const key = await createKey(user.id);
+ const { app } = createApp();
+
+ const keyOnly = await app.request(`/api/asset/${asset.id}`, {
+ headers: { "x-api-key": key },
+ });
+ expect(keyOnly.status).toBe(200);
+
+ const mixed = await app.request(`/api/asset/${asset.id}`, {
+ headers: { "x-api-key": key, ...invalidBearer },
+ });
+ expect(mixed.status).toBe(401);
+ });
+ });
+
+ describe("API integration: MCP consent with an API key", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("requires a user session to approve an authorization request", async () => {
+ const { user } = await createWorkspaceMember();
+ const key = await createKey(user.id, { project: ["read"] });
+ const redirectUri = "https://client.example/callback";
+ const client = await registerClient({ redirectUris: [redirectUri] });
+ const id = await createAuthorizationRequest({
+ clientId: client.clientId,
+ codeChallenge: createHash("sha256")
+ .update("test-verifier")
+ .digest("base64url"),
+ redirectUri,
+ });
+ const { app } = createApp();
+
+ const response = await app.request(`/api/mcp/authorize/request/${id}`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ origin: "http://localhost:5173",
+ "x-api-key": key,
+ },
+ body: JSON.stringify({ approved: true }),
+ });
+
+ expect(response.status).toBe(401);
+ });
+ });
diff --cc tests/api-integration/workspace-endpoints.test.ts
index 628d20fe7,000000000..0300132f3
mode 100644,000000..100644
--- a/tests/api-integration/workspace-endpoints.test.ts
+++ b/tests/api-integration/workspace-endpoints.test.ts
@@@ -1,554 -1,0 +1,566 @@@
+import { randomUUID } from "node:crypto";
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+import { auth } from "../../apps/api/src/auth";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { createInstanceAdmin } from "./helpers/admin/create-instance-admin";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { signUpWithSession } from "./helpers/auth-session";
+import { resetTestDatabase } from "./helpers/database";
++import { readErrorBody } from "./helpers/error-body";
+import { createWorkspaceMember } from "./helpers/fixtures";
+
+type WorkspaceRow = typeof schema.workspaceTable.$inferSelect;
+
+async function createWorkspace(
+ values: Partial<Omit<WorkspaceRow, "id" | "slug">> & { id?: string } = {},
+) {
+ const [workspace] = await db
+ .insert(schema.workspaceTable)
+ .values({
+ id: values.id ?? `workspace-${randomUUID()}`,
+ name: values.name ?? "Workspace",
+ slug: `workspace-${randomUUID()}`,
+ logo: values.logo ?? null,
+ description: values.description ?? null,
+ metadata: values.metadata ?? null,
+ createdAt: values.createdAt ?? new Date(),
+ })
+ .returning();
+ return workspace;
+}
+
+async function addMembership(
+ workspaceId: string,
+ userId: string,
+ role: string,
+ joinedAt = new Date(),
+) {
+ await db
+ .insert(schema.workspaceUserTable)
+ .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,
+ name: workspace.name,
+ slug: workspace.slug,
+ logo: workspace.logo,
+ description: workspace.description,
+ createdAt: workspace.createdAt.toISOString(),
+ role,
+ };
+}
+
++const workspaceNotFound = {
++ message: "Workspace not found",
++ code: "NOT_FOUND",
++};
++
++const unauthorized = { message: "Unauthorized", code: "UNAUTHORIZED" };
++
+async function readJson(response: Response) {
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as unknown;
+ const items = Array.isArray(body) ? body : [body];
+ for (const item of items) {
+ expect(item).not.toHaveProperty("metadata");
+ }
+ return body;
+}
+
+describe("GET /api/workspace", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("lists only the caller's workspaces with their role, sorted by name", async () => {
+ const { app } = createApp();
+ const caller = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Caller",
+ });
+ const beta = await createWorkspace({ name: "beta" });
+ const alpha = await createWorkspace({ name: "Alpha" });
+ const charlie = await createWorkspace({ name: "Charlie" });
+ const twinB = await createWorkspace({ id: "workspace-b", name: "Twin" });
+ const twinA = await createWorkspace({ id: "workspace-a", name: "twin" });
+ 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, "viewer");
+ await addMembership(twinA.id, caller.userId, "member");
+ await createWorkspaceMember({ workspaceName: "Aardvark" });
+
+ const response = await app.request("/api/workspace", {
+ headers: { cookie: caller.cookies },
+ });
+
+ expect(await readJson(response)).toEqual([
+ expected(alpha, "member"),
+ expected(beta, "owner"),
+ expected(charlie, "admin"),
+ expected(twinA, "member"),
+ expected(twinB, "viewer"),
+ ]);
+ });
+
+ it("lists a workspace once when the caller has a duplicate membership row", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ await addMembership(
+ workspace.id,
+ user.id,
+ "member",
+ new Date(Date.now() + 60_000),
+ );
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/workspace");
+
+ expect(await readJson(response)).toEqual([expected(workspace, "owner")]);
+ });
+
+ it("only lists an instance admin's own memberships", async () => {
+ await createWorkspaceMember({ workspaceName: "Someone else's" });
+ const admin = await createInstanceAdmin();
+ const joined = await createWorkspace({ name: "Joined" });
+ await addMembership(joined.id, admin.id, "member");
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ const response = await app.request("/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 and reads a workspace when any of the caller's roles grants workspace:read", async () => {
+ const { user, workspace: custom } = await createWorkspaceMember({
+ role: "limited,reader",
+ workspaceName: "Custom",
+ });
+ await addRole(custom.id, "limited", { task: ["read"] });
+ await addRole(custom.id, "reader", { workspace: ["read"] });
+ const builtIn = await createWorkspace({ name: "Built-in" });
+ await addMembership(builtIn.id, user.id, "limited, viewer");
+ await addRole(builtIn.id, "limited", { task: ["read"] });
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const list = await app.request("/api/workspace");
+ const customSingle = await app.request(`/api/workspace/${custom.id}`);
+ const builtInSingle = await app.request(`/api/workspace/${builtIn.id}`);
+
+ expect(await readJson(list)).toEqual([
+ expected(builtIn, "limited, viewer"),
+ expected(custom, "limited,reader"),
+ ]);
+ expect(await readJson(customSingle)).toEqual(
+ expected(custom, "limited,reader"),
+ );
+ expect(await readJson(builtInSingle)).toEqual(
+ expected(builtIn, "limited, viewer"),
+ );
+ });
+
+ it("hides a workspace when none of the caller's roles grants workspace:read", async () => {
+ const { user, workspace } = await createWorkspaceMember({
+ role: "limited,other",
+ });
+ await addRole(workspace.id, "limited", { task: ["read"] });
+ await addRole(workspace.id, "other", { project: ["read"] });
+ await addRole(workspace.id, "reader", { workspace: ["read"] });
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const list = await app.request("/api/workspace");
+ const single = await app.request(`/api/workspace/${workspace.id}`);
+
+ expect(await readJson(list)).toEqual([]);
+ expect(single.status).toBe(404);
- expect(await single.text()).toContain("Workspace not found");
++ expect(await readErrorBody(single)).toEqual(workspaceNotFound);
+ });
+
+ it("grants access when any duplicate role row grants workspace:read", async () => {
+ const { user, workspace: readFirst } = await createWorkspaceMember({
+ role: "custom",
+ workspaceName: "Read first",
+ });
+ await addRole(readFirst.id, "custom", { workspace: ["read"] });
+ await addRole(readFirst.id, "custom", { task: ["read"] });
+ const readLast = await createWorkspace({ name: "Read last" });
+ await addMembership(readLast.id, user.id, "custom");
+ await addRole(readLast.id, "custom", { task: ["read"] });
+ await addRole(readLast.id, "custom", { workspace: ["read"] });
+ const noRead = await createWorkspace({ name: "No read" });
+ await addMembership(noRead.id, user.id, "custom");
+ await addRole(noRead.id, "custom", { task: ["read"] });
+ await addRole(noRead.id, "custom", { project: ["read"] });
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const list = await app.request("/api/workspace");
+ const first = await app.request(`/api/workspace/${readFirst.id}`);
+ const last = await app.request(`/api/workspace/${readLast.id}`);
+ const denied = await app.request(`/api/workspace/${noRead.id}`);
+
+ expect(await readJson(list)).toEqual([
+ expected(readFirst, "custom"),
+ expected(readLast, "custom"),
+ ]);
+ expect(await readJson(first)).toEqual(expected(readFirst, "custom"));
+ expect(await readJson(last)).toEqual(expected(readLast, "custom"));
+ expect(denied.status).toBe(404);
+ });
+
+ 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();
+ const caller = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Lonely",
+ });
+
+ const response = await app.request("/api/workspace", {
+ headers: { cookie: caller.cookies },
+ });
+
+ expect(await readJson(response)).toEqual([]);
+ });
+
+ it("rejects missing credentials", async () => {
+ const { app } = createApp();
+
+ const response = await app.request("/api/workspace");
+
+ expect(response.status).toBe(401);
- expect(await response.text()).toContain("Unauthorized");
++ expect(await readErrorBody(response)).toEqual(unauthorized);
+ });
+});
+
+describe("GET /api/workspace/{workspaceId}", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("returns the workspace with exactly the documented fields", async () => {
+ const { app } = createApp();
+ const caller = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Member",
+ });
+ const workspace = await createWorkspace({
+ name: "Product",
+ logo: "https://example.com/logo.png",
+ description: "Where the roadmap lives",
+ metadata: JSON.stringify({ description: "Older text", secret: "x" }),
+ });
+ await addMembership(workspace.id, caller.userId, "admin");
+
+ const response = await app.request(`/api/workspace/${workspace.id}`, {
+ headers: { cookie: caller.cookies },
+ });
+
+ expect(await readJson(response)).toEqual(expected(workspace, "admin"));
+ });
+
+ it("falls back to the description stored in metadata", async () => {
+ const { user } = await createWorkspaceMember();
+ const workspace = await createWorkspace({
+ metadata: JSON.stringify({ description: "From metadata" }),
+ });
+ await addMembership(workspace.id, user.id, "member");
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/workspace/${workspace.id}`);
+
+ expect(await readJson(response)).toEqual({
+ ...expected(workspace, "member"),
+ description: "From metadata",
+ });
+ });
+
+ it("returns null for a missing or unreadable description", async () => {
+ const { user } = await createWorkspaceMember();
+ const workspace = await createWorkspace({
+ description: " ",
+ metadata: "{not json",
+ });
+ await addMembership(workspace.id, user.id, "member");
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/workspace/${workspace.id}`);
+
+ expect(await readJson(response)).toEqual({
+ ...expected(workspace, "member"),
+ description: null,
+ });
+ });
+
+ it("returns the earliest membership role when the caller has duplicate rows", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ await addMembership(
+ workspace.id,
+ user.id,
+ "member",
+ new Date(Date.now() + 60_000),
+ );
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/workspace/${workspace.id}`);
+
+ expect(await readJson(response)).toEqual(expected(workspace, "owner"));
+ });
+
+ it("returns the same 404 for a non-member and a nonexistent workspace", async () => {
+ const { workspace } = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createWorkspaceMember();
+ mockAuthenticatedSession(outsider.user);
+ const { app } = createApp();
+
+ const notMember = await app.request(`/api/workspace/${workspace.id}`);
+ const missing = await app.request("/api/workspace/workspace-missing");
+
+ expect(notMember.status).toBe(404);
+ expect(missing.status).toBe(404);
- const notMemberBody = await notMember.text();
- expect(notMemberBody).toContain("Workspace not found");
- expect(await missing.text()).toBe(notMemberBody);
++ expect(await readErrorBody(notMember)).toEqual(workspaceNotFound);
++ expect(await readErrorBody(missing)).toEqual(workspaceNotFound);
+ });
+
+ 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);
++ expect(missing.status).toBe(404);
++ expect(await readErrorBody(denied)).toEqual(workspaceNotFound);
++ expect(await readErrorBody(missing)).toEqual(workspaceNotFound);
+ });
+
+ 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();
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/workspace/${workspace.id}`);
+
+ expect(await readJson(response)).toEqual(expected(workspace, null));
+ });
+
+ it("returns 404 to an instance admin for a nonexistent workspace", async () => {
+ const admin = await createInstanceAdmin();
+ mockAuthenticatedSession(admin);
+ const { app } = createApp();
+
+ const response = await app.request("/api/workspace/workspace-missing");
+
+ expect(response.status).toBe(404);
- expect(await response.text()).toContain("Workspace not found");
++ expect(await readErrorBody(response)).toEqual(workspaceNotFound);
+ });
+
+ it("rejects missing credentials", async () => {
+ const { workspace } = await createWorkspaceMember();
+ const { app } = createApp();
+
+ const response = await app.request(`/api/workspace/${workspace.id}`);
+
+ expect(response.status).toBe(401);
- expect(await response.text()).toContain("Unauthorized");
++ expect(await readErrorBody(response)).toEqual(unauthorized);
+ });
+});
+
+describe("workspace endpoints with bearer credentials", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it.each(["Authorization", "x-api-key"])(
+ "accepts an API key in %s",
+ async (header) => {
+ await createWorkspaceMember({ workspaceName: "Not mine" });
+ const { user, workspace } = await createWorkspaceMember({
+ role: "owner",
+ });
+ const { key } = await auth.api.createApiKey({
+ body: { userId: user.id, name: "Workspace endpoints test" },
+ });
+ const headers = {
+ [header]: header === "Authorization" ? `Bearer ${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("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,
+ });
+
++ const scopeError = {
++ message: "Insufficient API key scope",
++ code: "API_KEY_SCOPE",
++ missingPermissions: ["workspace:read"],
++ };
+ expect(list.status).toBe(403);
- expect(await list.text()).toContain("Insufficient API key scope");
++ expect(await readErrorBody(list)).toEqual(scopeError);
+ expect(single.status).toBe(403);
- expect(await single.text()).toContain("Insufficient API key scope");
++ expect(await readErrorBody(single)).toEqual(scopeError);
+ });
+
+ 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();
+ const { key } = await auth.api.createApiKey({
+ body: { userId: admin.id, name: "Admin key" },
+ });
+ const { app } = createApp();
+
+ const response = await app.request(`/api/workspace/${workspace.id}`, {
+ headers: { Authorization: `Bearer ${key}` },
+ });
+
+ expect(await readJson(response)).toEqual(expected(workspace, null));
+ });
+
+ it("accepts a session token as a bearer token", async () => {
+ const { app } = createApp();
+ const caller = await signUpWithSession(app, {
+ email: "[email protected]",
+ name: "Bearer",
+ });
+ const workspace = await createWorkspace({ name: "Bearer workspace" });
+ await addMembership(workspace.id, caller.userId, "member");
+ const signIn = await app.request("/api/auth/sign-in/email", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ email: "[email protected]",
+ password: "correct horse battery staple",
+ }),
+ });
+ const token = signIn.headers.get("set-auth-token");
+ expect(token).toBeTruthy();
+
+ const response = await app.request("/api/workspace", {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ expect(await readJson(response)).toEqual([expected(workspace, "member")]);
+ });
+
+ it("rejects an invalid API key", async () => {
+ const { app } = createApp();
+
+ const response = await app.request("/api/workspace", {
+ headers: { "x-api-key": "invalid-key" },
+ });
+
+ expect(response.status).toBe(401);
- expect(await response.text()).toContain("Unauthorized");
++ expect(await readErrorBody(response)).toEqual(unauthorized);
+ });
+});
diff --cc tests/api-integration/workspace-rbac.test.ts
index 57c5fa4f7,fe0ad494f..cee861d58
--- a/tests/api-integration/workspace-rbac.test.ts
+++ b/tests/api-integration/workspace-rbac.test.ts
@@@ -576,59 -581,6 +581,64 @@@ describe("API integration: workspace RB
mockAuthenticatedSession(member.user);
const { app } = createApp();
+ const response = await postCreateTask(app, project.id);
+ expect(response.status).toBe(200);
+ });
+
+ it("allows a member with several roles when any role grants the permission", async () => {
+ const member = await createWorkspaceMember({ role: "readonly,member" });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ await createWorkspaceRoleRow(member.workspace.id, "readonly", {
+ task: ["read"],
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await postCreateTask(app, project.id);
+ expect(response.status).toBe(200);
+ });
+
+ it("blocks a member with several roles when no role grants the permission", async () => {
+ const member = await createWorkspaceMember({ role: "readonly,viewer" });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ await createWorkspaceRoleRow(member.workspace.id, "readonly", {
+ task: ["read"],
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await postCreateTask(app, project.id);
+ expect(response.status).toBe(403);
++ expect(await readErrorBody(response)).toEqual({
++ message: "Insufficient permissions",
++ code: "MISSING_PERMISSION",
++ missingPermissions: ["task:create"],
++ });
+ });
+
+ it("allows a role when any duplicate workspace_role row grants the permission", async () => {
+ const member = await createWorkspaceMember({ role: "creator" });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ await createWorkspaceRoleRow(member.workspace.id, "creator", {
+ task: ["read"],
+ project: ["read"],
+ });
+ await createWorkspaceRoleRow(member.workspace.id, "creator", {
+ task: ["create", "read"],
+ project: ["read"],
+ });
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
const response = await postCreateTask(app, project.id);
expect(response.status).toBe(200);
});