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): close five workspace-scoping gaps

Andrej Acevski6de9ea05f1eb
diff --git a/apps/api/src/activity/index.ts b/apps/api/src/activity/index.ts
index 38fe79d2d..09b0e20c2 100644
--- a/apps/api/src/activity/index.ts
+++ b/apps/api/src/activity/index.ts
@@ -58,7 +58,6 @@ const activity = new Hono<{
"json",
v.object({
taskId: v.string(),
- userId: v.string(),
message: v.nullable(v.string()),
type: v.string(),
eventData: v.optional(v.nullable(v.record(v.string(), v.unknown()))),
@@ -67,7 +66,8 @@ const activity = new Hono<{
workspaceAccess.fromTaskId(),
requireWorkspacePermission({ task: ["update"] }),
async (c) => {
- const { taskId, userId, message, type, eventData } = c.req.valid("json");
+ const { taskId, message, type, eventData } = c.req.valid("json");
+ const userId = c.get("userId");
const activity = await createActivity(
taskId,
type,
diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.ts
index d72e69b2f..6b2bf7318 100644
--- a/apps/api/src/github-integration/index.ts
+++ b/apps/api/src/github-integration/index.ts
@@ -89,7 +89,7 @@ const githubIntegration = new Hono<{
},
)
.get(
- "/repositories",
+ "/repositories/:projectId",
describeRoute({
operationId: "listGitHubRepositories",
tags: ["GitHub"],
@@ -105,6 +105,9 @@ const githubIntegration = new Hono<{
},
},
}),
+ validator("param", v.object({ projectId: v.string() })),
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ workspace: ["manage_settings"] }),
async (c) => {
const repositories = await listUserRepositories();
return c.json(repositories);
@@ -128,10 +131,13 @@ const githubIntegration = new Hono<{
validator(
"json",
v.object({
+ projectId: v.pipe(v.string(), v.minLength(1)),
repositoryOwner: v.pipe(v.string(), v.minLength(1)),
repositoryName: v.pipe(v.string(), v.minLength(1)),
}),
),
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ workspace: ["manage_settings"] }),
async (c) => {
const { repositoryOwner, repositoryName } = c.req.valid("json");
diff --git a/apps/api/src/plugins/generic-webhook/client.ts b/apps/api/src/plugins/generic-webhook/client.ts
index b39e93ea7..109192aeb 100644
--- a/apps/api/src/plugins/generic-webhook/client.ts
+++ b/apps/api/src/plugins/generic-webhook/client.ts
@@ -4,6 +4,8 @@ import { assertPublicWebhookDestination } from "./config";
type GenericWebhookPayload = Record<string, unknown>;
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+
const GENERIC_WEBHOOK_TIMEOUT_MS = 10_000;
export async function postToGenericWebhook(
@@ -41,8 +43,16 @@ export async function postToGenericWebhook(
headers,
body,
signal: controller.signal,
+ redirect: "manual",
});
+ if (REDIRECT_STATUSES.has(response.status)) {
+ await response.body?.cancel();
+ throw new Error(
+ `Generic webhook request was redirected (${response.status}); redirects are not followed`,
+ );
+ }
+
if (!response.ok) {
const errorText = await response.text();
throw new Error(
diff --git a/apps/api/src/project/controllers/get-public-project.ts b/apps/api/src/project/controllers/get-public-project.ts
index 6813a2922..d7a9dafd5 100644
--- a/apps/api/src/project/controllers/get-public-project.ts
+++ b/apps/api/src/project/controllers/get-public-project.ts
@@ -1,7 +1,28 @@
+import { eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { projectTable } from "../../database/schema";
import getTasks from "../../task/controllers/get-tasks";
export async function getPublicProject(id: string) {
+ const [project] = await db
+ .select({ isPublic: projectTable.isPublic })
+ .from(projectTable)
+ .where(eq(projectTable.id, id))
+ .limit(1);
+
+ if (!project) {
+ throw new HTTPException(404, {
+ message: "Project not found",
+ });
+ }
+
+ if (!project.isPublic) {
+ throw new HTTPException(403, {
+ message: "Project is not public",
+ });
+ }
+
const result = await getTasks(id);
if (!result.data) {
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
index 2ed839c78..aa1b6b229 100644
--- a/apps/api/src/task/controllers/bulk-update-tasks.ts
+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts
@@ -12,6 +12,7 @@ import {
import { publishEvent } from "../../events";
import { removeLabelFromGitea } from "../../plugins/gitea/utils/sync-label-to-gitea";
import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";
+import { assertAssignableUser } from "../../utils/assert-assignable-user";
import {
assertValidPriority,
assertValidTaskStatus,
@@ -164,34 +165,45 @@ async function bulkUpdateTasks({
}
case "updateAssignee": {
- const newAssigneeName = value
+ // Normalised like the other assignment paths: a blank value unassigns,
+ // and a padded id resolves to the user it names rather than being
+ // rejected as unassignable.
+ const assigneeId = value?.trim() || null;
+
+ if (assigneeId) {
+ await assertAssignableUser(assigneeId, workspaceId);
+ }
+
+ const newAssigneeName = assigneeId
? (
await db
.select({ name: userTable.name })
.from(userTable)
- .where(eq(userTable.id, value))
+ .where(eq(userTable.id, assigneeId))
.limit(1)
)[0]?.name
: undefined;
const result = await db
.update(taskTable)
- .set({ userId: value || null })
+ .set({ userId: assigneeId })
.where(inArray(taskTable.id, foundIds));
updatedCount = result.rowCount ?? foundIds.length;
for (const task of tasks) {
- const eventType = value ? "task.assignee_changed" : "task.unassigned";
+ const eventType = assigneeId
+ ? "task.assignee_changed"
+ : "task.unassigned";
await publishEvent(eventType, {
taskId: task.id,
projectId: task.projectId,
userId,
oldAssignee: task.userId,
newAssignee: newAssigneeName,
- newAssigneeId: value || null,
+ newAssigneeId: assigneeId,
title: task.title,
- type: value ? "assignee_changed" : "unassigned",
+ type: assigneeId ? "assignee_changed" : "unassigned",
});
}
break;
diff --git a/apps/api/src/task/controllers/create-task.ts b/apps/api/src/task/controllers/create-task.ts
index 7f742afd8..e6e0da418 100644
--- a/apps/api/src/task/controllers/create-task.ts
+++ b/apps/api/src/task/controllers/create-task.ts
@@ -3,6 +3,10 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { columnTable, taskTable, userTable } from "../../database/schema";
import { publishEvent } from "../../events";
+import {
+ assertAssignableUser,
+ getProjectWorkspaceId,
+} from "../../utils/assert-assignable-user";
import { assertValidTaskStatus } from "../validate-task-fields";
import { claimTaskNumber } from "./claim-task-numbers";
@@ -34,15 +38,18 @@ async function createTask({
await assertValidTaskStatus(resolvedStatus, projectId);
- const [assignee] = await db
- .select({ name: userTable.name })
- .from(userTable)
- .where(eq(userTable.id, normalizedUserId ?? ""));
+ let assignee: { name: string } | undefined;
- if (normalizedUserId && !assignee) {
- throw new HTTPException(404, {
- message: "Assignee not found",
- });
+ if (normalizedUserId) {
+ await assertAssignableUser(
+ normalizedUserId,
+ await getProjectWorkspaceId(projectId),
+ );
+
+ [assignee] = await db
+ .select({ name: userTable.name })
+ .from(userTable)
+ .where(eq(userTable.id, normalizedUserId));
}
const column = await db.query.columnTable.findFirst({
diff --git a/apps/api/src/task/controllers/import-tasks.ts b/apps/api/src/task/controllers/import-tasks.ts
index 5906009b2..7a7ee1a3f 100644
--- a/apps/api/src/task/controllers/import-tasks.ts
+++ b/apps/api/src/task/controllers/import-tasks.ts
@@ -3,6 +3,7 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { columnTable, projectTable, taskTable } from "../../database/schema";
import { publishEvent } from "../../events";
+import { filterAssignableUsers } from "../../utils/assert-assignable-user";
import {
coercePriority,
coerceStatus,
@@ -35,11 +36,37 @@ async function importTasks(
});
}
+ const assigneeIds = [
+ ...new Set(
+ tasksToImport
+ .map((task) => task.userId?.trim())
+ .filter((id): id is string => Boolean(id)),
+ ),
+ ];
+
+ // Resolved in one query, then applied per task: this endpoint reports mixed
+ // successful/failed outcomes, so one bad assignee must not sink the batch.
+ const assignableIds = await filterAssignableUsers(
+ assigneeIds,
+ project.workspaceId,
+ );
+
const validStatuses = await getValidTaskStatuses(projectId);
const results = [];
for (const taskData of tasksToImport) {
+ const assigneeId = taskData.userId?.trim() || null;
+
+ if (assigneeId && !assignableIds.has(assigneeId)) {
+ results.push({
+ success: false,
+ error: "Assignee is not a member of this workspace",
+ task: taskData,
+ });
+ continue;
+ }
+
try {
const { status, warning: statusWarning } = coerceStatus(
taskData.status,
@@ -64,7 +91,7 @@ async function importTasks(
.insert(taskTable)
.values({
projectId,
- userId: taskData.userId || null,
+ userId: assigneeId,
title: taskData.title,
status,
columnId: column?.id ?? null,
diff --git a/apps/api/src/task/controllers/update-task-assignee.ts b/apps/api/src/task/controllers/update-task-assignee.ts
index 32df12b46..11de30d59 100644
--- a/apps/api/src/task/controllers/update-task-assignee.ts
+++ b/apps/api/src/task/controllers/update-task-assignee.ts
@@ -3,6 +3,10 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { taskTable, userTable } from "../../database/schema";
import { publishEvent } from "../../events";
+import {
+ assertAssignableUser,
+ getProjectWorkspaceId,
+} from "../../utils/assert-assignable-user";
async function updateTaskAssignee({
id,
@@ -23,14 +27,21 @@ async function updateTaskAssignee({
});
}
- const nextAssigneeId = userId || null;
+ const nextAssigneeId = userId?.trim() || null;
if (existingTask.userId === nextAssigneeId) {
return existingTask;
}
+ if (nextAssigneeId) {
+ await assertAssignableUser(
+ nextAssigneeId,
+ await getProjectWorkspaceId(existingTask.projectId),
+ );
+ }
+
const [updatedTask] = await db
.update(taskTable)
- .set({ userId: nextAssigneeId || null })
+ .set({ userId: nextAssigneeId })
.where(eq(taskTable.id, id))
.returning();
@@ -40,17 +51,17 @@ async function updateTaskAssignee({
});
}
- const newAssigneeName = userId
+ const newAssigneeName = nextAssigneeId
? (
await db
.select({ name: userTable.name })
.from(userTable)
- .where(eq(userTable.id, userId))
+ .where(eq(userTable.id, nextAssigneeId))
.limit(1)
)[0]?.name
: undefined;
- if (!userId) {
+ if (!nextAssigneeId) {
await publishEvent("task.unassigned", {
taskId: updatedTask.id,
projectId: updatedTask.projectId,
@@ -68,7 +79,7 @@ async function updateTaskAssignee({
userId: currentUserId,
oldAssignee: existingTask.userId,
newAssignee: newAssigneeName,
- newAssigneeId: userId,
+ newAssigneeId: nextAssigneeId,
title: updatedTask.title,
type: "assignee_changed",
});
diff --git a/apps/api/src/task/controllers/update-task.ts b/apps/api/src/task/controllers/update-task.ts
index 069e35570..c6b81cbb3 100644
--- a/apps/api/src/task/controllers/update-task.ts
+++ b/apps/api/src/task/controllers/update-task.ts
@@ -4,6 +4,10 @@ import db from "../../database";
import { columnTable, taskTable } from "../../database/schema";
import { publishEvent } from "../../events";
import { deleteOrphanedAssets } from "../../storage/cleanup-assets";
+import {
+ assertAssignableUser,
+ getProjectWorkspaceId,
+} from "../../utils/assert-assignable-user";
import { assertValidTaskStatus } from "../validate-task-fields";
async function updateTask(
@@ -44,6 +48,15 @@ async function updateTask(
await assertValidTaskStatus(status, projectId);
+ const normalizedUserId = userId?.trim() || undefined;
+
+ if (normalizedUserId) {
+ await assertAssignableUser(
+ normalizedUserId,
+ await getProjectWorkspaceId(projectId),
+ );
+ }
+
const column = await db.query.columnTable.findFirst({
where: and(
eq(columnTable.projectId, projectId),
@@ -63,7 +76,7 @@ async function updateTask(
description,
priority,
position,
- userId: userId || null,
+ userId: normalizedUserId ?? null,
})
.where(eq(taskTable.id, id))
.returning();
diff --git a/apps/api/src/utils/assert-assignable-user.ts b/apps/api/src/utils/assert-assignable-user.ts
new file mode 100644
index 000000000..8531d5368
--- /dev/null
+++ b/apps/api/src/utils/assert-assignable-user.ts
@@ -0,0 +1,82 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db, { schema } from "../database";
+
+const NOT_ASSIGNABLE = "Assignee is not a member of this workspace";
+
+/**
+ * Resolves which of the given users may be assigned work in a workspace.
+ *
+ * Membership is checked first because it is the common case; instance admins
+ * reach every workspace without holding a membership row, mirroring
+ * validateWorkspaceAccess. A user that does not exist is simply absent from the
+ * result, so callers cannot tell "no such user" from "not a member".
+ */
+export async function filterAssignableUsers(
+ userIds: string[],
+ workspaceId: string,
+): Promise<Set<string>> {
+ if (userIds.length === 0) {
+ return new Set();
+ }
+
+ const memberships = await db
+ .select({ userId: schema.workspaceUserTable.userId })
+ .from(schema.workspaceUserTable)
+ .where(
+ and(
+ inArray(schema.workspaceUserTable.userId, userIds),
+ eq(schema.workspaceUserTable.workspaceId, workspaceId),
+ ),
+ );
+
+ const assignable = new Set(memberships.map((row) => row.userId));
+ const remaining = userIds.filter((id) => !assignable.has(id));
+
+ if (remaining.length === 0) {
+ return assignable;
+ }
+
+ const admins = await db
+ .select({ id: schema.userTable.id })
+ .from(schema.userTable)
+ .where(
+ and(
+ inArray(schema.userTable.id, remaining),
+ eq(schema.userTable.role, "admin"),
+ ),
+ );
+
+ for (const admin of admins) {
+ assignable.add(admin.id);
+ }
+
+ return assignable;
+}
+
+export async function assertAssignableUser(
+ userId: string,
+ workspaceId: string,
+): Promise<void> {
+ const assignable = await filterAssignableUsers([userId], workspaceId);
+
+ if (!assignable.has(userId)) {
+ throw new HTTPException(403, { message: NOT_ASSIGNABLE });
+ }
+}
+
+export async function getProjectWorkspaceId(
+ projectId: string,
+): Promise<string> {
+ const [project] = await db
+ .select({ workspaceId: schema.projectTable.workspaceId })
+ .from(schema.projectTable)
+ .where(eq(schema.projectTable.id, projectId))
+ .limit(1);
+
+ if (!project) {
+ throw new HTTPException(404, { message: "Project not found" });
+ }
+
+ return project.workspaceId;
+}
diff --git a/apps/web/src/components/project/github-integration-settings.tsx b/apps/web/src/components/project/github-integration-settings.tsx
index 1c932a2d0..62704d9b8 100644
--- a/apps/web/src/components/project/github-integration-settings.tsx
+++ b/apps/web/src/components/project/github-integration-settings.tsx
@@ -113,7 +113,7 @@ export function GitHubIntegrationSettings({
const handleVerifyInstallation = React.useCallback(
async (data: GithubIntegrationFormValues, showToast = true) => {
try {
- const result = await verifyInstallation(data);
+ const result = await verifyInstallation({ ...data, projectId });
setVerificationResult(result);
if (showToast) {
@@ -142,7 +142,7 @@ export function GitHubIntegrationSettings({
setVerificationResult(null);
}
},
- [verifyInstallation, t],
+ [verifyInstallation, projectId, t],
);
React.useEffect(() => {
@@ -177,7 +177,7 @@ export function GitHubIntegrationSettings({
const onSubmit = async (data: GithubIntegrationFormValues) => {
try {
- const verification = await verifyInstallation(data);
+ const verification = await verifyInstallation({ ...data, projectId });
if (!verification.isInstalled) {
toast.error(t("settings:githubIntegration.toast.installAppFirst"));
@@ -681,6 +681,7 @@ export function GitHubIntegrationSettings({
)}
<RepositoryBrowserModal
+ projectId={projectId}
open={showRepositoryBrowser}
onOpenChange={setShowRepositoryBrowser}
onSelectRepository={handleRepositorySelect}
diff --git a/apps/web/src/components/project/repository-browser-modal.tsx b/apps/web/src/components/project/repository-browser-modal.tsx
index e3501ac90..c83b143b3 100644
--- a/apps/web/src/components/project/repository-browser-modal.tsx
+++ b/apps/web/src/components/project/repository-browser-modal.tsx
@@ -31,6 +31,7 @@ import { cn } from "@/lib/cn";
import { getInitials } from "@/lib/get-initials";
type RepositoryBrowserModalProps = {
+ projectId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onSelectRepository: (repository: { owner: string; name: string }) => void;
@@ -38,6 +39,7 @@ type RepositoryBrowserModalProps = {
};
export function RepositoryBrowserModal({
+ projectId,
open,
onOpenChange,
onSelectRepository,
@@ -47,8 +49,8 @@ export function RepositoryBrowserModal({
const [searchTerm, setSearchTerm] = React.useState("");
const { data, isLoading, error, refetch } = useQuery({
- queryKey: ["github-repositories"],
- queryFn: listRepositories,
+ queryKey: ["github-repositories", projectId],
+ queryFn: () => listRepositories(projectId),
enabled: open,
});
diff --git a/apps/web/src/fetchers/github-integration/list-repositories.ts b/apps/web/src/fetchers/github-integration/list-repositories.ts
index cfd6cbc56..f4eb25dc1 100644
--- a/apps/web/src/fetchers/github-integration/list-repositories.ts
+++ b/apps/web/src/fetchers/github-integration/list-repositories.ts
@@ -2,11 +2,17 @@ import { client } from "@kaneo/libs";
import type { InferResponseType } from "hono";
export type ListRepositoriesResponse = InferResponseType<
- (typeof client)["github-integration"]["repositories"]["$get"]
+ (typeof client)["github-integration"]["repositories"][":projectId"]["$get"]
>;
-async function listRepositories(): Promise<ListRepositoriesResponse> {
- const response = await client["github-integration"].repositories.$get();
+async function listRepositories(
+ projectId: string,
+): Promise<ListRepositoriesResponse> {
+ const response = await client["github-integration"].repositories[
+ ":projectId"
+ ].$get({
+ param: { projectId },
+ });
if (!response.ok) {
const error = await response.text();
diff --git a/tests/api-integration/authorization-boundaries.test.ts b/tests/api-integration/authorization-boundaries.test.ts
new file mode 100644
index 000000000..1cc7da5b3
--- /dev/null
+++ b/tests/api-integration/authorization-boundaries.test.ts
@@ -0,0 +1,454 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+beforeEach(async () => {
+ await resetTestDatabase();
+});
+
+describe("github integration routes are workspace scoped", () => {
+ it("refuses to list repositories for a member without manage_settings", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "member" });
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(
+ `/api/github-integration/repositories/${project.id}`,
+ );
+
+ expect(response.status).toBe(403);
+ });
+
+ it("refuses to verify an installation for a member without manage_settings", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "member" });
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/github-integration/verify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ projectId: project.id,
+ repositoryOwner: "usekaneo",
+ repositoryName: "kaneo",
+ }),
+ });
+
+ expect(response.status).toBe(403);
+ });
+
+ it("refuses to list repositories for a project in another workspace", async () => {
+ const outsider = await createWorkspaceMember({ role: "owner" });
+ const other = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({
+ workspaceId: other.workspace.id,
+ });
+
+ mockAuthenticatedSession(outsider.user);
+ const { app } = createApp();
+
+ const response = await app.request(
+ `/api/github-integration/repositories/${project.id}`,
+ );
+
+ expect(response.status).toBe(403);
+ });
+});
+
+describe("public project route", () => {
+ it("refuses a project that is not public", async () => {
+ const { workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ const { app } = createApp();
+ const response = await app.request(`/api/public-project/${project.id}`);
+
+ expect(response.status).toBe(403);
+ expect(await response.text()).not.toContain(project.name);
+ });
+});
+
+describe("task assignees stay inside the workspace", () => {
+ it("refuses to create a task assigned to a non-member", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/${project.id}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ title: "Cross-workspace assignment",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ userId: outsider.user.id,
+ }),
+ });
+
+ expect(response.status).toBe(403);
+ });
+
+ it("refuses to reassign an existing task to a non-member", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createWorkspaceMember({ role: "owner" });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Seeded",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ columnId: columns.todo?.id ?? null,
+ number: 1,
+ position: 1,
+ })
+ .returning();
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/assignee/${task.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ userId: outsider.user.id }),
+ });
+
+ expect(response.status).toBe(403);
+ });
+});
+
+describe("activity attribution", () => {
+ it("credits the session user, not a userId supplied in the body", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const impersonated = await createWorkspaceMember({ role: "owner" });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Seeded",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ columnId: columns.todo?.id ?? null,
+ number: 1,
+ position: 1,
+ })
+ .returning();
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/activity/create", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskId: task.id,
+ userId: impersonated.user.id,
+ message: `note-${randomUUID()}`,
+ type: "created",
+ }),
+ });
+
+ expect(response.status).toBe(200);
+ const activity = await response.json();
+ expect(activity.userId).toBe(user.id);
+ expect(activity.userId).not.toBe(impersonated.user.id);
+ });
+});
+
+describe("every assignee write path is workspace scoped", () => {
+ it("refuses a non-member through the task update endpoint", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createWorkspaceMember({ role: "owner" });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Seeded",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ columnId: columns.todo?.id ?? null,
+ number: 1,
+ position: 1,
+ })
+ .returning();
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/${task.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ title: "Seeded",
+ status: "to-do",
+ projectId: project.id,
+ description: "",
+ priority: "low",
+ position: 1,
+ userId: outsider.user.id,
+ }),
+ });
+
+ expect(response.status).toBe(403);
+ });
+
+ it("imports the valid tasks and fails only the one with a bad assignee", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/import/${project.id}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ tasks: [
+ { title: "Good", status: "to-do", priority: "low" },
+ {
+ title: "Bad",
+ status: "to-do",
+ priority: "low",
+ userId: outsider.user.id,
+ },
+ ],
+ }),
+ });
+
+ expect(response.status).toBe(200);
+
+ const stored = await db
+ .select({ title: schema.taskTable.title })
+ .from(schema.taskTable)
+ .where(eq(schema.taskTable.projectId, project.id));
+
+ expect(stored.map((t) => t.title)).toEqual(["Good"]);
+ });
+
+ it("refuses a non-member through task import", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/import/${project.id}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ tasks: [
+ {
+ title: "Imported",
+ status: "to-do",
+ priority: "low",
+ userId: outsider.user.id,
+ },
+ ],
+ }),
+ });
+
+ expect(response.status).toBe(200);
+
+ const stored = await db
+ .select({ id: schema.taskTable.id })
+ .from(schema.taskTable)
+ .where(eq(schema.taskTable.projectId, project.id));
+
+ expect(stored).toHaveLength(0);
+ });
+
+ it("stores a padded assignee id in its normalised form", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/import/${project.id}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ tasks: [
+ {
+ title: "Imported",
+ status: "to-do",
+ priority: "low",
+ userId: ` ${user.id} `,
+ },
+ ],
+ }),
+ });
+
+ expect(response.status).toBe(200);
+
+ const [stored] = await db
+ .select({ userId: schema.taskTable.userId })
+ .from(schema.taskTable)
+ .where(eq(schema.taskTable.projectId, project.id));
+
+ expect(stored.userId).toBe(user.id);
+ });
+
+ it("treats a whitespace-only assignee as an unassignment", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Seeded",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ columnId: columns.todo?.id ?? null,
+ number: 1,
+ position: 1,
+ userId: user.id,
+ })
+ .returning();
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/assignee/${task.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ userId: " " }),
+ });
+
+ expect(response.status).toBe(200);
+
+ const [after] = await db
+ .select({ userId: schema.taskTable.userId })
+ .from(schema.taskTable)
+ .where(eq(schema.taskTable.id, task.id));
+
+ expect(after.userId).toBeNull();
+ });
+
+ it("assigns a padded but valid member id", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Seeded",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ columnId: columns.todo?.id ?? null,
+ number: 1,
+ position: 1,
+ })
+ .returning();
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/task/assignee/${task.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ userId: ` ${user.id} ` }),
+ });
+
+ expect(response.status).toBe(200);
+
+ const [after] = await db
+ .select({ userId: schema.taskTable.userId })
+ .from(schema.taskTable)
+ .where(eq(schema.taskTable.id, task.id));
+
+ expect(after.userId).toBe(user.id);
+ });
+
+ it("refuses a non-member through the bulk assignee operation", async () => {
+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
+ const outsider = await createWorkspaceMember({ role: "owner" });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: "Seeded",
+ description: "",
+ priority: "low",
+ status: "to-do",
+ columnId: columns.todo?.id ?? null,
+ number: 1,
+ position: 1,
+ })
+ .returning();
+
+ mockAuthenticatedSession(user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/task/bulk", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ taskIds: [task.id],
+ operation: "updateAssignee",
+ value: outsider.user.id,
+ }),
+ });
+
+ expect(response.status).toBe(403);
+ });
+});
diff --git a/tests/api-integration/task.test.ts b/tests/api-integration/task.test.ts
index fe4239a68..1917c1ac0 100644
--- a/tests/api-integration/task.test.ts
+++ b/tests/api-integration/task.test.ts
@@ -281,7 +281,7 @@ describe("API integration: task creation", () => {
});
});
- it("rejects task creation when the assignee userId does not exist", async () => {
+ it("rejects task creation for an assignee that cannot be assigned, without revealing whether the user exists", async () => {
const member = await createWorkspaceMember();
const { project } = await createProjectFixture({
workspaceId: member.workspace.id,
@@ -305,8 +305,12 @@ describe("API integration: task creation", () => {
}),
});
- expect(response.status).toBe(404);
- await expect(response.text()).resolves.toContain("Assignee not found");
+ // A missing user and a non-member both answer 403 with the same message, so
+ // the endpoint cannot be used to probe which user ids exist.
+ expect(response.status).toBe(403);
+ await expect(response.text()).resolves.toContain(
+ "Assignee is not a member of this workspace",
+ );
const persistedTask = await db.query.taskTable.findFirst({
where: and(