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.

feat(api): add workspace list and detail endpoints

Andrej9a6198e6754b
diff --git a/apps/api/src/workspace/controllers/get-workspace.ts b/apps/api/src/workspace/controllers/get-workspace.ts
new file mode 100644
index 000000000..c529169ec
--- /dev/null
+++ b/apps/api/src/workspace/controllers/get-workspace.ts
@@ -0,0 +1,46 @@
+import { and, eq, isNotNull, or } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import {
+ userTable,
+ workspaceTable,
+ workspaceUserTable,
+} from "../../database/schema";
+import { instanceAdminRoleSql } from "../../utils/instance-admin-role";
+import {
+ toWorkspaceResponse,
+ workspaceColumns,
+} from "../to-workspace-response";
+
+async function getWorkspace(workspaceId: string, userId: string) {
+ const [row] = await db
+ .select({ ...workspaceColumns, role: workspaceUserTable.role })
+ .from(workspaceTable)
+ .innerJoin(userTable, eq(userTable.id, userId))
+ .leftJoin(
+ workspaceUserTable,
+ and(
+ eq(workspaceUserTable.workspaceId, workspaceTable.id),
+ eq(workspaceUserTable.userId, userTable.id),
+ ),
+ )
+ .where(
+ and(
+ eq(workspaceTable.id, workspaceId),
+ or(
+ isNotNull(workspaceUserTable.id),
+ instanceAdminRoleSql(userTable.role),
+ ),
+ ),
+ )
+ .orderBy(workspaceUserTable.joinedAt, workspaceUserTable.id)
+ .limit(1);
+
+ if (!row) {
+ throw new HTTPException(404, { message: "Workspace not found" });
+ }
+
+ return toWorkspaceResponse(row);
+}
+
+export default getWorkspace;
diff --git a/apps/api/src/workspace/controllers/list-workspaces.ts b/apps/api/src/workspace/controllers/list-workspaces.ts
new file mode 100644
index 000000000..7c6e3b9a7
--- /dev/null
+++ b/apps/api/src/workspace/controllers/list-workspaces.ts
@@ -0,0 +1,35 @@
+import { and, eq, sql } from "drizzle-orm";
+import db from "../../database";
+import { workspaceTable, workspaceUserTable } from "../../database/schema";
+import {
+ toWorkspaceResponse,
+ workspaceColumns,
+} from "../to-workspace-response";
+
+async function listWorkspaces(userId: string) {
+ const sortName = sql`lower(${workspaceTable.name})`;
+
+ const rows = await db
+ .selectDistinctOn([sortName, workspaceTable.id], {
+ ...workspaceColumns,
+ role: workspaceUserTable.role,
+ })
+ .from(workspaceTable)
+ .innerJoin(
+ workspaceUserTable,
+ and(
+ eq(workspaceUserTable.workspaceId, workspaceTable.id),
+ eq(workspaceUserTable.userId, userId),
+ ),
+ )
+ .orderBy(
+ sortName,
+ workspaceTable.id,
+ workspaceUserTable.joinedAt,
+ workspaceUserTable.id,
+ );
+
+ return rows.map(toWorkspaceResponse);
+}
+
+export default listWorkspaces;
diff --git a/apps/api/src/workspace/index.ts b/apps/api/src/workspace/index.ts
index 185974b7f..b3888165a 100644
--- a/apps/api/src/workspace/index.ts
+++ b/apps/api/src/workspace/index.ts
@@ -9,12 +9,16 @@ import { listWorkspaceProjectAccess } from "../project-access/list-workspace-pro
import { 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";
import getWorkspaceMembersCtrl from "./controllers/get-workspace-members";
+import listWorkspacesCtrl from "./controllers/list-workspaces";
import updateMemberProjectAccessCtrl from "./controllers/update-member-project-access";
import {
memberProjectAccessListSchema,
memberProjectAccessSchema,
+ workspaceListSchema,
workspaceMemberListSchema,
+ workspaceSchema,
} from "./response";
import {
updateMemberProjectAccessBody,
@@ -23,6 +27,36 @@ import {
workspaceMembersQuery,
} from "./schema";
+const listWorkspacesRoute = createRoute({
+ method: "get",
+ operationId: "listWorkspaces",
+ path: "/",
+ 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.",
+ responses: {
+ 200: jsonResponse("The caller's workspaces", workspaceListSchema),
+ },
+});
+
+const getWorkspaceRoute = createRoute({
+ method: "get",
+ operationId: "getWorkspace",
+ path: "/{workspaceId}",
+ 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.",
+ request: { params: workspaceIdParam },
+ responses: {
+ 200: jsonResponse("The workspace", workspaceSchema),
+ 404: errorResponse(
+ "Workspace not found, or the caller is not a member of it",
+ ),
+ },
+});
+
const getWorkspaceMembersRoute = createRoute({
method: "get",
operationId: "getWorkspaceMembers",
@@ -117,6 +151,15 @@ const updateMemberProjectAccessRoute = createRoute({
});
const workspace = apiRouter<BaseVariables & { workspaceId: string }>()
+ .openapi(listWorkspacesRoute, async (c) =>
+ c.json(await listWorkspacesCtrl(c.get("userId")), 200),
+ )
+ .openapi(getWorkspaceRoute, async (c) =>
+ c.json(
+ await getWorkspaceCtrl(c.req.valid("param").workspaceId, c.get("userId")),
+ 200,
+ ),
+ )
.openapi(getWorkspaceMembersRoute, async (c) =>
c.json(
await getWorkspaceMembersCtrl({
diff --git a/apps/api/src/workspace/resolve-workspace-description.test.ts b/apps/api/src/workspace/resolve-workspace-description.test.ts
new file mode 100644
index 000000000..d088a8ac9
--- /dev/null
+++ b/apps/api/src/workspace/resolve-workspace-description.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vite-plus/test";
+import { resolveWorkspaceDescription } from "./resolve-workspace-description";
+
+describe("resolveWorkspaceDescription", () => {
+ it("prefers the description column", () => {
+ expect(
+ resolveWorkspaceDescription({
+ description: "From the column",
+ metadata: JSON.stringify({ description: "From metadata" }),
+ }),
+ ).toBe("From the column");
+ });
+
+ it("falls back to metadata.description when the column is empty", () => {
+ expect(
+ resolveWorkspaceDescription({
+ description: null,
+ metadata: JSON.stringify({ description: "From metadata" }),
+ }),
+ ).toBe("From metadata");
+ });
+
+ it("falls back to metadata.description when the column is blank", () => {
+ expect(
+ resolveWorkspaceDescription({
+ description: " ",
+ metadata: JSON.stringify({ description: "From metadata" }),
+ }),
+ ).toBe("From metadata");
+ });
+
+ it("returns null when neither source has a description", () => {
+ expect(
+ resolveWorkspaceDescription({ description: null, metadata: null }),
+ ).toBeNull();
+ expect(
+ resolveWorkspaceDescription({ description: "", metadata: "{}" }),
+ ).toBeNull();
+ });
+
+ it("ignores a blank metadata description", () => {
+ expect(
+ resolveWorkspaceDescription({
+ description: null,
+ metadata: JSON.stringify({ description: " \n " }),
+ }),
+ ).toBeNull();
+ });
+
+ it.each([
+ ["invalid JSON", "{not json"],
+ ["a JSON string", JSON.stringify("Just a string")],
+ ["a JSON number", "42"],
+ ["a JSON null", "null"],
+ ["a JSON array", JSON.stringify([{ description: "In an array" }])],
+ ["a non-string description", JSON.stringify({ description: 42 })],
+ ["a nested description", JSON.stringify({ description: { text: "x" } })],
+ ])("tolerates metadata that is %s", (_label, metadata) => {
+ expect(
+ resolveWorkspaceDescription({ description: null, metadata }),
+ ).toBeNull();
+ });
+});
diff --git a/apps/api/src/workspace/resolve-workspace-description.ts b/apps/api/src/workspace/resolve-workspace-description.ts
new file mode 100644
index 000000000..1707dedad
--- /dev/null
+++ b/apps/api/src/workspace/resolve-workspace-description.ts
@@ -0,0 +1,26 @@
+function nonBlank(value: unknown) {
+ return typeof value === "string" && value.trim() !== "" ? value : null;
+}
+
+function parseMetadata(metadata: string | null): unknown {
+ if (!metadata) return null;
+ try {
+ return JSON.parse(metadata);
+ } catch {
+ return null;
+ }
+}
+
+export function resolveWorkspaceDescription(workspace: {
+ description: string | null;
+ metadata: string | null;
+}) {
+ const description = nonBlank(workspace.description);
+ if (description !== null) return description;
+
+ const metadata = parseMetadata(workspace.metadata);
+ if (typeof metadata !== "object" || metadata === null) return null;
+ if (Array.isArray(metadata)) return null;
+
+ return nonBlank((metadata as { description?: unknown }).description);
+}
diff --git a/apps/api/src/workspace/response.ts b/apps/api/src/workspace/response.ts
index 561d1675c..4b25482ff 100644
--- a/apps/api/src/workspace/response.ts
+++ b/apps/api/src/workspace/response.ts
@@ -1,5 +1,22 @@
import { PROJECT_ACCESS_MODES } from "../project-access/project-access-mode";
-import { z } from "../openapi";
+import { responseTimestamp, z } from "../openapi";
+
+export const workspaceSchema = z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ slug: z.string(),
+ logo: z.string().nullable(),
+ description: z.string().nullable(),
+ 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.",
+ }),
+ })
+ .openapi("Workspace");
+
+export const workspaceListSchema = z.array(workspaceSchema);
export const workspaceMemberSchema = z
.object({
diff --git a/apps/api/src/workspace/to-workspace-response.ts b/apps/api/src/workspace/to-workspace-response.ts
new file mode 100644
index 000000000..4c012d78e
--- /dev/null
+++ b/apps/api/src/workspace/to-workspace-response.ts
@@ -0,0 +1,33 @@
+import { workspaceTable } from "../database/schema";
+import { resolveWorkspaceDescription } from "./resolve-workspace-description";
+
+export const workspaceColumns = {
+ id: workspaceTable.id,
+ name: workspaceTable.name,
+ slug: workspaceTable.slug,
+ logo: workspaceTable.logo,
+ description: workspaceTable.description,
+ metadata: workspaceTable.metadata,
+ createdAt: workspaceTable.createdAt,
+};
+
+export function toWorkspaceResponse(row: {
+ id: string;
+ name: string;
+ slug: string;
+ logo: string | null;
+ description: string | null;
+ metadata: string | null;
+ createdAt: Date;
+ role: string | null;
+}) {
+ return {
+ id: row.id,
+ name: row.name,
+ slug: row.slug,
+ logo: row.logo,
+ description: resolveWorkspaceDescription(row),
+ createdAt: row.createdAt,
+ role: row.role,
+ };
+}
diff --git a/apps/docs/api-reference/introduction.mdx b/apps/docs/api-reference/introduction.mdx
index e1bdc784d..c5def8c83 100644
--- a/apps/docs/api-reference/introduction.mdx
+++ b/apps/docs/api-reference/introduction.mdx
@@ -13,17 +13,24 @@ Keep keys in server-side scripts or secret storage. Do not put a personal API ke
## 2. Find your workspace and project IDs
-Open a project in the browser. Its URL includes both IDs:
+Set `KANEO_API_KEY` in your shell using your secret manager or a private environment file. Then list the workspaces you belong to with `GET /api/workspace`. Each item includes the workspace `id`, `name`, `slug`, and your `role`:
+
+```bash
+curl --fail-with-body 'https://kaneo.example.com/api/workspace' \
+ -H "Authorization: Bearer $KANEO_API_KEY"
+```
+
+You can also open a project in the browser. Its URL includes both IDs:
```text
/dashboard/workspace/WORKSPACE_ID/project/PROJECT_ID/board
```
-Use the IDs from the URL, not the workspace name or a task number such as `WEB-22`.
+Use the IDs, not the workspace name or a task number such as `WEB-22`.
## 3. List the workspace's projects
-Set `KANEO_API_KEY` in your shell using your secret manager or a private environment file. Then replace the example workspace ID:
+Replace the example workspace ID:
```bash
curl --fail-with-body --get 'https://kaneo.example.com/api/project' \
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index b43605a8b..d654be638 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -4294,6 +4294,52 @@
"valid"
]
},
+ "Workspace": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "slug": {
+ "type": "string"
+ },
+ "logo": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "role": {
+ "type": [
+ "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."
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "slug",
+ "logo",
+ "description",
+ "createdAt",
+ "role"
+ ]
+ },
"WorkspaceMember": {
"type": "object",
"properties": {
@@ -18967,6 +19013,79 @@
}
}
},
+ "/workspace": {
+ "get": {
+ "operationId": "listWorkspaces",
+ "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.",
+ "responses": {
+ "200": {
+ "description": "The caller's workspaces",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Workspace"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ }
+ }
+ }
+ },
+ "/workspace/{workspaceId}": {
+ "get": {
+ "operationId": "getWorkspace",
+ "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.",
+ "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"
+ },
+ "404": {
+ "description": "Workspace not found, or the caller is not a member of it",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/workspace/{workspaceId}/members": {
"get": {
"operationId": "getWorkspaceMembers",
diff --git a/tests/api-integration/openapi.test.ts b/tests/api-integration/openapi.test.ts
index c6d608691..c28ca44ba 100644
--- a/tests/api-integration/openapi.test.ts
+++ b/tests/api-integration/openapi.test.ts
@@ -72,6 +72,8 @@ describe("Kaneo API OpenAPI spec", () => {
"PATCH /task/bulk",
"GET /search",
"GET /notification",
+ "GET /workspace",
+ "GET /workspace/{workspaceId}",
"POST /auth/organization/create",
]) {
expect(keys.has(op), `missing operation ${op}`).toBe(true);
@@ -107,6 +109,7 @@ describe("Kaneo API OpenAPI spec", () => {
"Notification",
"Config",
"SearchResult",
+ "Workspace",
"WorkspaceMember",
"MattermostIntegration",
]),
diff --git a/tests/api-integration/workspace-endpoints.test.ts b/tests/api-integration/workspace-endpoints.test.ts
new file mode 100644
index 000000000..262b8e18c
--- /dev/null
+++ b/tests/api-integration/workspace-endpoints.test.ts
@@ -0,0 +1,362 @@
+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 { 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 });
+}
+
+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,
+ };
+}
+
+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, "guest");
+ 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, "guest"),
+ ]);
+ });
+
+ 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("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");
+ });
+});
+
+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);
+ });
+
+ 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");
+ });
+
+ 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");
+ });
+});
+
+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("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");
+ });
+});