TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.
TypeScript graphviewkanban-boardnodejsproductivityproject-managementself-hostedtasktask-managementtask-managertodoapp
fix(security): enforce collaboration access permissions
Nikolai Gimanf79614ebc5f0
diff --git a/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.ts b/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.tsindex 4ddc288..46bdc99 100644--- a/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.ts+++ b/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.ts@@ -5,7 +5,8 @@ import { GoalPermissions } from '../../../types/auth.types';import { logError } from '../../../utils/api';export const CanFetchRolesPermissionsCollaborationRoles = async (req: Request, res: Response, next: NextFunction) => {- const goalId = req.body.goalId ? req.body.goalId : req.params.goalId;+ // the only route using this guard names the goal in the path+ const goalId = req.params.goalId;if (!goalId) {return res.status(400).end();diff --git a/api/src/tv-modules/collaboration/CollaborationRoutes.ts b/api/src/tv-modules/collaboration/CollaborationRoutes.tsindex b0391c2..c34fe9d 100644--- a/api/src/tv-modules/collaboration/CollaborationRoutes.ts+++ b/api/src/tv-modules/collaboration/CollaborationRoutes.ts@@ -5,7 +5,7 @@ import { IsOrgMemberIfProvided } from '../../middlewares/is-org-member';import { CollaborationController } from './CollaborationController';import { CanAddUserCollaboration } from './middlewares/CanAddUserCollaboration';import { CanDeleteUserCollaboration } from './middlewares/CanDeleteUserCollaboration';-// import { CanFetchUsersCollaboration } from './middlewares/CanFetchUsersCollaboration';+import { CanFetchUsersCollaboration } from './middlewares/CanFetchUsersCollaboration';import { CanToggleRolesCollaboration } from './middlewares/CanToggleRolesCollaboration';export default class CollaborationRoutes implements Routable {@@ -56,6 +56,10 @@ export default class CollaborationRoutes implements Routable {/*** Fetch users for goal for collaboration*/- this.router.get('/:goalId', [IsLoggedIn], this.collaborationController.fetchUsersForGoalNew);+ this.router.get(+ '/:goalId',+ [IsLoggedIn, CanFetchUsersCollaboration],+ this.collaborationController.fetchUsersForGoalNew+ );}}diff --git a/api/src/tv-modules/collaboration/middlewares/CanFetchUsersCollaboration.ts b/api/src/tv-modules/collaboration/middlewares/CanFetchUsersCollaboration.tsindex 9431823..7cd52c2 100644--- a/api/src/tv-modules/collaboration/middlewares/CanFetchUsersCollaboration.ts+++ b/api/src/tv-modules/collaboration/middlewares/CanFetchUsersCollaboration.ts@@ -21,7 +21,8 @@ export const CanFetchUsersCollaboration = async (req: Request, res: Response, neif (permissions.hasPermissions(GoalPermissions.TASKS_CAN_ASSIGN_USERS) ||- permissions.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS)+ permissions.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS) ||+ permissions.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS)) {return next();}diff --git a/api/src/tv-modules/graph/middlewares/resolveGoalId.ts b/api/src/tv-modules/graph/middlewares/resolveGoalId.tsindex e0f580b..40ad31f 100644--- a/api/src/tv-modules/graph/middlewares/resolveGoalId.ts+++ b/api/src/tv-modules/graph/middlewares/resolveGoalId.ts@@ -3,36 +3,32 @@ import { GraphRepository } from '../GraphRepository';import { TasksRepository } from '../../tasks/TasksRepository';/**- * Resolves goalId from graph request.- * - GET /:goalId → params.goalId- * - POST (addEdge) → resolve via fromTaskId (body.source)- * - DELETE /:id → resolve via edge id+ * Resolves the single goal a graph request belongs to.+ *+ * The source is chosen by what the route actually carries, not by probing every+ * field in turn: a route parameter always wins, and only a request with no+ * parameters at all (addEdge) is resolved from the body. Reading the body first+ * would let a caller point the guard at a task they own while the handler acts+ * on someone else's edge.+ *+ * A graph lives inside one project, so an edge whose endpoints sit in different+ * goals is not a permission question — it is an impossible object. It resolves+ * to null and the guards reject it before any permission is considered, the same+ * invariant the tasks.check_task_graph_relation_goal trigger enforces in the DB.*/export async function resolveGoalId(req: Request): Promise<number | null> {- // Direct goalId in params (fetchAllEdges)+ // fetchAllEdges: GET /:goalIdif (req.params.goalId) {- const id = Number(req.params.goalId);- return isNaN(id) ? null : id;+ const goalId = Number(req.params.goalId);+ return isNaN(goalId) ? null : goalId;}+ // fetchTaskEdges: GET /task/:taskIdif (req.params.taskId) {- const taskId = Number(req.params.taskId);- if (isNaN(taskId)) return null;- const tasksRepo = new TasksRepository();- const task = await tasksRepo.fetchTaskByIdNew(taskId);- return task?.goalId ?? null;+ return goalIdForTask(req.params.taskId);}- // addEdge: resolve goalId from task- if (req.body?.source) {- const taskId = Number(req.body.source);- if (isNaN(taskId)) return null;- const tasksRepo = new TasksRepository();- const task = await tasksRepo.fetchTaskByIdNew(taskId);- return task?.goalId ?? null;- }-- // deleteEdge: resolve goalId from edge+ // deleteEdge: DELETE /:idif (req.params.id) {const edgeId = Number(req.params.id);if (isNaN(edgeId)) return null;@@ -41,5 +37,25 @@ export async function resolveGoalId(req: Request): Promise<number | null> {return edge?.goalId ?? null;}+ // addEdge: POST with { source, target } — both endpoints must be in one goal+ if (req.body?.source) {+ const sourceGoalId = await goalIdForTask(req.body.source);+ if (sourceGoalId === null) return null;++ const targetGoalId = await goalIdForTask(req.body.target);+ if (targetGoalId !== sourceGoalId) return null;++ return sourceGoalId;+ }+return null;}++async function goalIdForTask(rawTaskId: unknown): Promise<number | null> {+ const taskId = Number(rawTaskId);+ if (!taskId || isNaN(taskId)) return null;++ const tasksRepo = new TasksRepository();+ const task = await tasksRepo.fetchTaskByIdNew(taskId);+ return task?.goalId ?? null;+}diff --git a/api/src/tv-modules/integrations/middlewares/resolveProjectId.ts b/api/src/tv-modules/integrations/middlewares/resolveProjectId.tsindex 5c939fb..4cd6a70 100644--- a/api/src/tv-modules/integrations/middlewares/resolveProjectId.ts+++ b/api/src/tv-modules/integrations/middlewares/resolveProjectId.ts@@ -2,22 +2,26 @@ import type { Request } from 'express';import { IntegrationsRepository } from '../IntegrationsRepository';/**- * Resolves projectId from request.- * Checks body (projectId, integrationId, id) and query (projectId, integrationId).+ * Resolves the project to authorize the request against.+ *+ * When the request names an integration, the project is derived from that+ * integration and a projectId supplied by the caller is ignored: every handler+ * that takes an integration id acts on the integration, so authorizing a+ * caller-supplied project would guard a different object than the one touched.+ *+ * Only create and fetch carry no integration id — there the project itself is+ * the object being acted on, so it is read from the request.*/export async function resolveProjectId(req: Request): Promise<number | null> {- // Direct projectId in body or query- const directId = req.body?.projectId ?? req.query?.projectId;- if (directId) {- const id = Number(directId);- return isNaN(id) ? null : id;+ const integrationId = Number(req.body?.integrationId || req.query?.integrationId || req.body?.id);+ if (integrationId && !isNaN(integrationId)) {+ const repo = new IntegrationsRepository();+ const integration = await repo.fetchById(integrationId);+ return integration?.projectId ?? null;}- // integrationId from body or query, or id from body- const integrationId = Number(req.body?.integrationId || req.query?.integrationId || req.body?.id);- if (!integrationId || isNaN(integrationId)) return null;+ const projectId = Number(req.body?.projectId || req.query?.projectId);+ if (!projectId || isNaN(projectId)) return null;- const repo = new IntegrationsRepository();- const integration = await repo.fetchById(integrationId);- return integration?.projectId ?? null;+ return projectId;}diff --git a/api/src/tv-modules/kanban/KanbanRoutes.ts b/api/src/tv-modules/kanban/KanbanRoutes.tsindex da17150..97133d1 100644--- a/api/src/tv-modules/kanban/KanbanRoutes.ts+++ b/api/src/tv-modules/kanban/KanbanRoutes.ts@@ -1,10 +1,11 @@import { Router } from 'express';import type { Routable } from '../../types/routable.type';+import { GoalPermissions } from '../../types/auth.types';import { IsLoggedIn } from '../auth/middlewares/is-logged-in';import { KanbanController } from './KanbanController';-import { CanManageKanban } from './middlewares/CanManageKanban';-import { CanViewKanban } from './middlewares/CanViewKanban';-import { CanFetchTasks } from './middlewares/CanFetchTasks';+import { goalIdFromBody, goalIdFromParam, goalIdFromStatusBody } from './middlewares/goal-id-resolvers';+import { requireKanbanPermission } from './middlewares/require-kanban-permission';+export default class KanbanRoutes implements Routable {private readonly router: ReturnType<typeof Router>;private readonly kanbanController: KanbanController;@@ -20,17 +21,89 @@ export default class KanbanRoutes implements Routable {}initRoutes() {- this.router.post('/fetch-statuses', [IsLoggedIn, CanViewKanban], this.kanbanController.fetchAllColumns);- this.router.post('/add-status', [IsLoggedIn, CanManageKanban], this.kanbanController.addStatus);- this.router.post('/delete-status', [IsLoggedIn, CanManageKanban], this.kanbanController.deleteStatus);- this.router.post('/update-status', [IsLoggedIn, CanManageKanban], this.kanbanController.updateStatus);+ this.router.post(+ '/fetch-statuses',+ [+ IsLoggedIn,+ requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_VIEW],+ resolveGoalId: goalIdFromBody,+ }),+ ],+ this.kanbanController.fetchAllColumns+ );++ this.router.post(+ '/add-status',+ [+ IsLoggedIn, requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],+ resolveGoalId: goalIdFromBody+ })+ ],+ this.kanbanController.addStatus+ );++ this.router.post(+ '/delete-status',+ [+ IsLoggedIn, requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],+ resolveGoalId: goalIdFromStatusBody+ })+ ],+ this.kanbanController.deleteStatus+ );++ this.router.post(+ '/update-status',+ [+ IsLoggedIn, requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],+ resolveGoalId: goalIdFromStatusBody+ })+ ],+ this.kanbanController.updateStatus+ );- // this.router.get('columns/:goalId', [IsLoggedIn], this.kanbanController.fetchAllColumns);- this.router.get('/tasks/:goalId/:columnId/:cursor', [IsLoggedIn, CanViewKanban, CanFetchTasks], this.kanbanController.fetchTasksForColumn);+ this.router.get(+ '/tasks/:goalId/:columnId/:cursor',+ [+ IsLoggedIn,+ requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_VIEW],+ resolveGoalId: goalIdFromParam,+ }),+ requireKanbanPermission({+ anyOf: [GoalPermissions.COMPONENT_CAN_WATCH_CONTENT],+ resolveGoalId: goalIdFromParam,+ }),+ ],+ this.kanbanController.fetchTasksForColumn+ );//we do not use this route in the client (no logic for this route on the client side)!!!- this.router.get('/tasks-order/:goalId/:columnId/:cursor', [IsLoggedIn, CanManageKanban], this.kanbanController.getTasksOrderForColumnAndCursor);+ this.router.get(+ '/tasks-order/:goalId/:columnId/:cursor',+ [+ IsLoggedIn, requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_VIEW],+ resolveGoalId: goalIdFromParam+ })+ ],+ this.kanbanController.getTasksOrderForColumnAndCursor+ );- this.router.patch('/update-tasks-order-and-column', [IsLoggedIn, CanManageKanban], this.kanbanController.updateTasksOrderAndColumn);+ this.router.patch(+ '/update-tasks-order-and-column',+ [+ IsLoggedIn,+ requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],+ resolveGoalId: goalIdFromBody+ })+ ],+ this.kanbanController.updateTasksOrderAndColumn+ );}}diff --git a/api/src/tv-modules/kanban/middlewares/CanFetchTasks.ts b/api/src/tv-modules/kanban/middlewares/CanFetchTasks.tsdeleted file mode 100644index f66d73a..0000000--- a/api/src/tv-modules/kanban/middlewares/CanFetchTasks.ts+++ /dev/null@@ -1,33 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';-import { KanbanArkTypeCanManageKanban } from '../types';-import { ArkErrors } from 'arktype';--export const CanFetchTasks = async (req: Request, res: Response, next: NextFunction) => {- const props = req.body.goalId ? req.body : req.params;-- const data = KanbanArkTypeCanManageKanban(props);-- if (data instanceof ArkErrors) {- return res.status(400).send(data.summary);- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(data.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)- .catch(logError);--- if (!permissions) {- $logger.error('Can not get permissions for CanAddTask middleware');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.COMPONENT_CAN_WATCH_CONTENT)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/kanban/middlewares/CanManageKanban.ts b/api/src/tv-modules/kanban/middlewares/CanManageKanban.tsdeleted file mode 100644index 4b78c2b..0000000--- a/api/src/tv-modules/kanban/middlewares/CanManageKanban.ts+++ /dev/null@@ -1,54 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { ALL_TASKS_LIST_ID, DEFAULT_ID } from '../../../types/tasks.types';-import { logError } from '../../../utils/api';-import { KanbanArkTypeCanManageKanban } from '../types';-import { ArkErrors } from 'arktype';--export const CanManageKanban = async (req: Request, res: Response, next: NextFunction) => {- let props = req.body.goalId ? req.body : req.params;-- switch (req.url) {- case '/update-status':- const result = await req.appUser.kanbanManager.repository.fetchStatus(req.body.id);- props = {- goalId: result?.goal_id,- };- break;- case '/delete-status':- const result2 = await req.appUser.kanbanManager.repository.fetchStatus(req.body.id);- props = {- goalId: result2?.goal_id,- };- break;- default:- break;- }-- const data = KanbanArkTypeCanManageKanban(props);-- if (data instanceof ArkErrors) {- return res.status(400).send(data.summary);- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(data.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)- .catch(logError);--- if (!permissions) {- $logger.error('Can not get permissions for CanAddTask middleware');- return res.status(500).end();- }-- if (- permissions.hasPermissions(GoalPermissions.COMPONENT_CAN_ADD_TASKS) ||- permissions.hasPermissions(GoalPermissions.TASKS_CAN_ADD_SUBTASKS)- ) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/kanban/middlewares/CanViewKanban.ts b/api/src/tv-modules/kanban/middlewares/CanViewKanban.tsdeleted file mode 100644index 4c93fef..0000000--- a/api/src/tv-modules/kanban/middlewares/CanViewKanban.ts+++ /dev/null@@ -1,33 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';-import { KanbanArkTypeCanManageKanban } from '../types';-import { ArkErrors } from 'arktype';--export const CanViewKanban = async (req: Request, res: Response, next: NextFunction) => {- const props = req.body.goalId ? req.body : req.params;-- const data = KanbanArkTypeCanManageKanban(props);-- if (data instanceof ArkErrors) {- return res.status(400).send(data.summary);- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(data.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)- .catch(logError);--- if (!permissions) {- $logger.error('Can not get permissions for CanAddTask middleware');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.KANBAN_CAN_VIEW)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/kanban/middlewares/goal-id-resolvers.ts b/api/src/tv-modules/kanban/middlewares/goal-id-resolvers.tsnew file mode 100644index 0000000..f527936--- /dev/null+++ b/api/src/tv-modules/kanban/middlewares/goal-id-resolvers.ts@@ -0,0 +1,19 @@+import type { Request } from 'express';++export function goalIdFromParam(req: Request): number | null {+ const goalId = Number(req.params.goalId);+ return goalId && !isNaN(goalId) ? goalId : null;+}++export function goalIdFromBody(req: Request): number | null {+ const goalId = Number(req.body?.goalId);+ return goalId && !isNaN(goalId) ? goalId : null;+}++export async function goalIdFromStatusBody(req: Request): Promise<number | null> {+ const statusId = Number(req.body?.id);+ if (!statusId || isNaN(statusId)) return null;++ const status = await req.appUser.kanbanManager.repository.fetchStatus(statusId);+ return status?.goal_id ?? null;+}diff --git a/api/src/tv-modules/kanban/middlewares/require-kanban-permission.ts b/api/src/tv-modules/kanban/middlewares/require-kanban-permission.tsnew file mode 100644index 0000000..0476538--- /dev/null+++ b/api/src/tv-modules/kanban/middlewares/require-kanban-permission.ts@@ -0,0 +1,24 @@+import type { NextFunction, Request, Response } from 'express';+import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';+import { $logger } from '../../../modules/logget';+import { logError } from '../../../utils/api';+import type { RequireKanbanPermissionArgs } from '../types';++export function requireKanbanPermission({ anyOf, resolveGoalId }: RequireKanbanPermissionArgs) {+ return async (req: Request, res: Response, next: NextFunction) => {+ const goalId = await resolveGoalId(req);+ if (!goalId) return res.status(400).end();++ const permissions = await req.appUser.permissionsFetcher+ .getPermissionsForType(goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)+ .catch(logError);++ if (!permissions) {+ $logger.error('Can not resolve kanban permissions');+ return res.status(500).end();+ }++ if (anyOf.some((permission) => permissions.hasPermissions(permission))) return next();+ return res.status(403).end();+ };+}diff --git a/api/src/tv-modules/kanban/types.ts b/api/src/tv-modules/kanban/types.tsindex e169f6a..cc9c324 100644--- a/api/src/tv-modules/kanban/types.ts+++ b/api/src/tv-modules/kanban/types.ts@@ -1,6 +1,8 @@import { type } from 'arktype';+import type { Request } from 'express';import { z } from 'zod';import { StringToNumber } from '../../types/app.types';+import type { GoalPermissionType } from '../../types/auth.types';// ============ Arktype schemas ============@@ -102,11 +104,13 @@ export const KanbanArkTypeUpdateTasksOrder = type({export type KanbanArgUpdateTasksOrder = typeof KanbanArkTypeUpdateTasksOrder.infer;-export const KanbanArkTypeCanManageKanban = type({- goalId: NumberFromString,-});+export type KanbanGoalIdResolver = (req: Request) => Promise<number | null> | number | null;-export type KanbanArgCanManageKanban = typeof KanbanArkTypeCanManageKanban.infer;+export type RequireKanbanPermissionArgs = {+ /** the caller must hold at least ONE of these */+ anyOf: GoalPermissionType[];+ resolveGoalId: KanbanGoalIdResolver;+};// ============ Deprecated Zod schemas ============diff --git a/api/src/tv-modules/tasks/TasksRoutes.ts b/api/src/tv-modules/tasks/TasksRoutes.tsindex c4edd8f..0f3cc3e 100644--- a/api/src/tv-modules/tasks/TasksRoutes.ts+++ b/api/src/tv-modules/tasks/TasksRoutes.ts@@ -2,25 +2,14 @@ import { Router } from 'express';import type { Routable } from '../../types/routable.type';import { IsLoggedIn } from '../auth/middlewares/is-logged-in';import { CanAddTaskNew } from './middlewares/CanAddTaskNew';-// import { CanAddTask } from './middlewares/CanAddTask';-// import { CanUpdateTaskStatus } from './middlewares/CanUpdateTaskStatus';import { CanDeleteTask } from './middlewares/CanDeleteTask';-// import { CanUpdateTaskAssignee } from './middlewares/CanUpdateTaskAssignee';import { CanFetchTask } from './middlewares/CanFetchTask';-// import { CanUpdateTaskDescription } from './middlewares/CanUpdateTaskDescription';-// import { CanUpdateTaskNote } from './middlewares/CanUpdateTaskNote';-// import { CanUpdateTaskDeadline } from './middlewares/CanUpdateTaskDeadline';-// import { CanFetchSubtasks } from './middlewares/CanFetchSubtasks';-// import { CanUpdateTaskPriority } from './middlewares/CanUpdateTaskPriority';-// import { CanMoveTask } from './middlewares/CanMoveTask';-// import { CanSeeTaskAssignedUsers } from './middlewares/CanSeeTaskAssignedUsers';import { CanFetchTaskHistory } from './middlewares/CanFetchTaskHistory';import { CanFetchTasks } from './middlewares/CanFetchTasks';import { CanRecoveryTaskHistory } from './middlewares/CanRecoveryTaskHistory';import { CanUpdateTask } from './middlewares/CanUpdateTask';import { CanUpdateTaskAssigneeNew } from './middlewares/CanUpdateTaskAssigneeNew';import { TasksController } from './TasksController';-// import { MainCanCreateTaskAction } from './middlewares/MainCanCreateTaskAction';export default class TasksRoutes implements Routable {private readonly router: ReturnType<typeof Router>;diff --git a/api/src/tv-modules/tasks/middlewares/CanAddTask.ts b/api/src/tv-modules/tasks/middlewares/CanAddTask.tsdeleted file mode 100644index 711d935..0000000--- a/api/src/tv-modules/tasks/middlewares/CanAddTask.ts+++ /dev/null@@ -1,39 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { ALL_TASKS_LIST_ID, DEFAULT_ID } from '../../../types/tasks.types';-import { logError } from '../../../utils/api';--export const CanAddTask = async (req: Request, res: Response, next: NextFunction) => {- const listId = req.body.componentId;-- if (!listId) {- return res.status(400).end();- }-- let permissions;- if (Number(listId) === ALL_TASKS_LIST_ID && req.body.goalId && req.body.goalId !== DEFAULT_ID) {- permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(req.body.goalId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)- .catch(logError);- } else {- permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(listId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASKLIST)- .catch(logError);- }-- if (!permissions) {- $logger.error('Can not get permissions for CanAddTask middleware');- return res.status(500).end();- }-- if (- permissions.hasPermissions(GoalPermissions.COMPONENT_CAN_ADD_TASKS) ||- permissions.hasPermissions(GoalPermissions.TASKS_CAN_ADD_SUBTASKS)- ) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanFetchSubtasks.ts b/api/src/tv-modules/tasks/middlewares/CanFetchSubtasks.tsdeleted file mode 100644index 5979819..0000000--- a/api/src/tv-modules/tasks/middlewares/CanFetchSubtasks.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanFetchSubtasks = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.query.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanFetchSubtasks');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_SUBTASKS)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanFetchTask.ts b/api/src/tv-modules/tasks/middlewares/CanFetchTask.tsindex 4e8a9ea..571f04e 100644--- a/api/src/tv-modules/tasks/middlewares/CanFetchTask.ts+++ b/api/src/tv-modules/tasks/middlewares/CanFetchTask.ts@@ -5,7 +5,7 @@ import { GoalPermissions } from '../../../types/auth.types';import { logError } from '../../../utils/api';export const CanFetchTask = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.query.taskId || req.params.taskId;+ const taskId = req.params.taskId;if (!taskId) {return res.status(400).end();diff --git a/api/src/tv-modules/tasks/middlewares/CanMoveTask.ts b/api/src/tv-modules/tasks/middlewares/CanMoveTask.tsdeleted file mode 100644index cd9d685..0000000--- a/api/src/tv-modules/tasks/middlewares/CanMoveTask.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanMoveTask = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanMoveTask');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_DELETE)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanSeeTaskAssignedUsers.ts b/api/src/tv-modules/tasks/middlewares/CanSeeTaskAssignedUsers.tsdeleted file mode 100644index f8f5a33..0000000--- a/api/src/tv-modules/tasks/middlewares/CanSeeTaskAssignedUsers.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanSeeTaskAssignedUsers = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanSeeTaskAssignedUsers');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskAssignee.ts b/api/src/tv-modules/tasks/middlewares/CanUpdateTaskAssignee.tsdeleted file mode 100644index 91673a9..0000000--- a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskAssignee.ts+++ /dev/null@@ -1,29 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--/** @deprecated */-export const CanUpdateTaskAssignee = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanUpdateTaskDescription');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_ASSIGN_USERS)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskDeadline.ts b/api/src/tv-modules/tasks/middlewares/CanUpdateTaskDeadline.tsdeleted file mode 100644index d1454f5..0000000--- a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskDeadline.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanUpdateTaskDeadline = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanUpdateTaskDeadline');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_DEADLINE)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskDescription.ts b/api/src/tv-modules/tasks/middlewares/CanUpdateTaskDescription.tsdeleted file mode 100644index ae96174..0000000--- a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskDescription.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanUpdateTaskDescription = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanUpdateTaskDescription');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_DESCRIPTION)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskNote.ts b/api/src/tv-modules/tasks/middlewares/CanUpdateTaskNote.tsdeleted file mode 100644index fb63e50..0000000--- a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskNote.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanUpdateTaskNote = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanUpdateTaskNote');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_NOTE)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskPriority.ts b/api/src/tv-modules/tasks/middlewares/CanUpdateTaskPriority.tsdeleted file mode 100644index 15941d5..0000000--- a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskPriority.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanUpdateTaskPriority = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanUpdateTaskPriority');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_PRIORITY)) {- return next();- }-- return res.status(403).end();-};diff --git a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskStatus.ts b/api/src/tv-modules/tasks/middlewares/CanUpdateTaskStatus.tsdeleted file mode 100644index 9d74d6a..0000000--- a/api/src/tv-modules/tasks/middlewares/CanUpdateTaskStatus.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { NextFunction, Request, Response } from 'express';-import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';-import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';-import { logError } from '../../../utils/api';--export const CanUpdateTaskStatus = async (req: Request, res: Response, next: NextFunction) => {- const taskId = req.body.taskId;-- if (!taskId) {- return res.status(400).end();- }-- const permissions = await req.appUser.permissionsFetcher- .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)- .catch(logError);-- if (!permissions) {- $logger.error('Can not get permissions for CanAddTask middleware');- return res.status(500).end();- }-- if (permissions.hasPermissions(GoalPermissions.TASKS_CAN_EDIT_STATUS)) {- return next();- }-- return res.status(403).end();-};diff --git a/taskview-packages/taskview-api/src/api/__tests__/collaboration-goal-access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/collaboration-goal-access.test.tsnew file mode 100644index 0000000..b6d6201--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/collaboration-goal-access.test.ts@@ -0,0 +1,300 @@+import { TvApi } from '@/tv'+import { TvPermissions } from '@/api/permissions'+import axios from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, initApi } from './init-api'++/**+ * GET /module/collaboration/:goalId must be an object-level protected route:+ * only a member of the goal holding task_can_assign_users or goal_can_manage_users+ * may read its collaborator list (emails, invitation dates, roles, goalOwner flag).+ */+describe('Collaboration goal member list access control', () => {+ let ownerApi: TvApi+ let outsiderApi: TvApi+ let outsiderEmail: string+ let deleteAllGoals: () => Promise<void>+ let manageUsersPermissionId: number+ const permissionIdByName = new Map<string, number>()++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ outsiderApi = init.$tvApiForSecondUser+ outsiderEmail = init.user2Email+ deleteAllGoals = init.deleteAllGoals++ const allPermissions = await ownerApi.collaboration.fetchAllPermissions()+ for (const permission of allPermissions) {+ permissionIdByName.set(permission.name, permission.id)+ }+ const found = permissionIdByName.get(TvPermissions.GOAL_CAN_MANAGE_USERS)+ if (!found) throw new Error('Permission "goal_can_manage_users" is not in DB')+ manageUsersPermissionId = found+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ async function expectHttpStatus<T>(promise: Promise<T>, status: number): Promise<void> {+ try {+ await promise+ throw new Error(`Expected HTTP ${status} but request succeeded`)+ } catch (e: any) {+ if (typeof e.message === 'string' && e.message.startsWith('Expected HTTP')) throw e+ expect(e.response?.status ?? e.status, `Expected ${status}, got ${e.response?.status ?? e.status}`).toBe(status)+ }+ }++ // A goal owned by user1 that user2 is NOT a member of, holding a third-party email+ async function createPrivateGoal(organizationId?: number) {+ const goal = await ownerApi.goals.createGoal({+ name: `Private goal ${Date.now()}`,+ ...(organizationId ? { organizationId } : {}),+ })+ if (!goal) throw new Error('Failed to create goal')++ const invitedEmail = `outside-party-${Date.now()}@test.com`+ const invited = await ownerApi.collaboration.inviteUserToGoal({ email: invitedEmail, goalId: goal.id })+ if (!invited) throw new Error('Failed to invite third-party email')++ return { goal, invitedEmail }+ }++ // Invite user2 into user1's goal and grant a role carrying goal_can_manage_users+ async function shareGoalWithOutsider() {+ const goal = await ownerApi.goals.createGoal({ name: `Shared goal ${Date.now()}` })+ if (!goal) throw new Error('Failed to create goal')++ const collab = await ownerApi.collaboration.inviteUserToGoal({ email: outsiderEmail, goalId: goal.id })+ if (!collab) throw new Error('Failed to invite user2')++ const role = await ownerApi.collaboration.createRoleForGoal({+ goalId: goal.id,+ roleName: `Manager ${Date.now()}`,+ })+ if (!role) throw new Error('Failed to create role')++ const toggled = await ownerApi.collaboration.toggleRolePermission({+ roleId: role.id,+ permissionId: manageUsersPermissionId,+ })+ if (!toggled || toggled.add !== true) {+ throw new Error(`Expected goal_can_manage_users to be added, got ${JSON.stringify(toggled)}`)+ }++ await ownerApi.collaboration.toggleUserRoles({+ goalId: goal.id,+ userId: collab.id,+ roles: [role.id],+ })++ return { goal, role, collab }+ }++ describe('JWT session of a non-member', () => {+ it('cannot read the collaborator list of someone else goal', async () => {+ const { goal } = await createPrivateGoal()++ await expectHttpStatus(outsiderApi.collaboration.fetchUsersForGoal(goal.id), 403)+ })++ it('cannot enumerate collaborator emails by walking goal ids', async () => {+ const { goal, invitedEmail } = await createPrivateGoal()++ let leaked: Awaited<ReturnType<typeof outsiderApi.collaboration.fetchUsersForGoal>> | null = null+ try {+ leaked = await outsiderApi.collaboration.fetchUsersForGoal(goal.id)+ } catch {+ return+ }++ expect(+ leaked ?? [],+ `Leaked collaborator list of goal ${goal.id}: ${JSON.stringify(leaked)}`,+ ).toEqual([])+ expect((leaked ?? []).some(u => u.email === invitedEmail)).toBe(false)+ expect((leaked ?? []).some(u => u.goalOwner)).toBe(false)+ })++ it('gets the same rejection for a goal id that does not exist', async () => {+ const nonExistentGoalId = 999999999++ await expectHttpStatus(outsiderApi.collaboration.fetchUsersForGoal(nonExistentGoalId), 403)+ })+ })++ describe('Organization boundary', () => {+ it('a member of the same organization who is not a member of the goal is still rejected', async () => {+ const org = await ownerApi.organizations.create({ name: `Access org ${Date.now()}` })+ if (!org) throw new Error('Failed to create organization')++ const added = await ownerApi.organizations.addMember({+ organizationId: org.id,+ email: outsiderEmail,+ role: 'member',+ })+ if (!added) throw new Error('Failed to add user2 to the organization')++ // The goal lives in the shared org, but user2 was never invited into the goal itself+ const { goal } = await createPrivateGoal(org.id)++ await expectHttpStatus(outsiderApi.collaboration.fetchUsersForGoal(goal.id), 403)+ })+ })++ describe('Unauthenticated access', () => {+ it('is rejected with 401 rather than served', async () => {+ const { goal } = await createPrivateGoal()++ const response = await axios.get(`${API_URL}/module/collaboration/${goal.id}`, {+ validateStatus: () => true,+ })++ expect(+ response.status,+ `Anonymous request returned ${response.status}: ${JSON.stringify(response.data)}`,+ ).toBe(401)+ })+ })++ describe('API token of a non-member', () => {+ it('cannot read the collaborator list of someone else goal', async () => {+ const created = await outsiderApi.apiTokens.create({ name: `Access probe ${Date.now()}` })+ if (!created) throw new Error('Failed to create API token for user2')++ const tokenApi = new TvApi(axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${created.token}` },+ }))++ const { goal } = await createPrivateGoal()++ try {+ await expectHttpStatus(tokenApi.collaboration.fetchUsersForGoal(goal.id), 403)+ } finally {+ await outsiderApi.apiTokens.delete(created.item.id)+ }+ })++ it('cannot read a goal that is outside the token allowedGoalIds scope', async () => {+ const ownGoal = await outsiderApi.goals.createGoal({ name: `User2 goal ${Date.now()}` })+ if (!ownGoal) throw new Error('Failed to create user2 goal')++ // Token is explicitly scoped to user2's own goal only+ const created = await outsiderApi.apiTokens.create({+ name: `Scoped probe ${Date.now()}`,+ allowedGoalIds: [ownGoal.id],+ })+ if (!created) throw new Error('Failed to create scoped API token for user2')++ const tokenApi = new TvApi(axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${created.token}` },+ }))++ const { goal } = await createPrivateGoal()++ try {+ await expectHttpStatus(tokenApi.collaboration.fetchUsersForGoal(goal.id), 403)+ } finally {+ await outsiderApi.apiTokens.delete(created.item.id)+ }+ })+ })++ describe('Legitimate access is preserved', () => {+ it('the goal owner can read the collaborator list', async () => {+ const { goal, invitedEmail } = await createPrivateGoal()++ const users = await ownerApi.collaboration.fetchUsersForGoal(goal.id)+ expect(users).toBeDefined()+ expect(users?.some(u => u.email === invitedEmail)).toBe(true)+ })++ it('a member with goal_can_manage_users can read the collaborator list', async () => {+ const { goal } = await shareGoalWithOutsider()++ const users = await outsiderApi.collaboration.fetchUsersForGoal(goal.id)+ expect(users).toBeDefined()+ expect(users?.some(u => u.email === outsiderEmail)).toBe(true)+ })++ /**+ * A rank-and-file member must still see the project roster, otherwise the UI+ * cannot render task assignees. Both default roles created by the goal trigger+ * (editor and executor, migration 1.6.1/5.default-roles-for-project.sql) carry+ * task_can_watch_assigned_users, so this is the common case, not an edge one.+ */+ it('a member with only task_can_watch_assigned_users can read the collaborator list', async () => {+ const goal = await ownerApi.goals.createGoal({ name: `Executor goal ${Date.now()}` })+ if (!goal) throw new Error('Failed to create goal')++ const collab = await ownerApi.collaboration.inviteUserToGoal({ email: outsiderEmail, goalId: goal.id })+ if (!collab) throw new Error('Failed to invite user2')++ const roles = await ownerApi.collaboration.fetchRolesForGoal(goal.id)+ const executor = roles?.find(r => r.name === 'executor')+ if (!executor) throw new Error('Default "executor" role is missing on a fresh goal')++ // the role grants the watch permission and neither of the two management ones,+ // so a pass here can only come from task_can_watch_assigned_users+ const matrix = await ownerApi.collaboration.fetchRoleToPermissionsForGoal(goal.id)+ const executorPermissionIds = (matrix ?? [])+ .filter(row => row.roleId === executor.id)+ .map(row => row.permissionId)+ expect(executorPermissionIds).toContain(permissionIdByName.get(TvPermissions.TASK_CAN_WATCH_ASSIGNED_USERS))+ expect(executorPermissionIds).not.toContain(permissionIdByName.get(TvPermissions.GOAL_CAN_MANAGE_USERS))+ expect(executorPermissionIds).not.toContain(permissionIdByName.get(TvPermissions.TASK_CAN_ASSIGN_USERS))++ await ownerApi.collaboration.toggleUserRoles({+ goalId: goal.id,+ userId: collab.id,+ roles: [executor.id],+ })++ const users = await outsiderApi.collaboration.fetchUsersForGoal(goal.id)+ expect(users).toBeDefined()+ expect(users?.some(u => u.email === outsiderEmail)).toBe(true)+ })++ it('a member whose role carries none of the three permissions is rejected', async () => {+ const goal = await ownerApi.goals.createGoal({ name: `Bare role goal ${Date.now()}` })+ if (!goal) throw new Error('Failed to create goal')++ const collab = await ownerApi.collaboration.inviteUserToGoal({ email: outsiderEmail, goalId: goal.id })+ if (!collab) throw new Error('Failed to invite user2')++ // a freshly created custom role carries no permissions at all+ const bareRole = await ownerApi.collaboration.createRoleForGoal({+ goalId: goal.id,+ roleName: `Bare ${Date.now()}`,+ })+ if (!bareRole) throw new Error('Failed to create role')++ await ownerApi.collaboration.toggleUserRoles({+ goalId: goal.id,+ userId: collab.id,+ roles: [bareRole.id],+ })++ await expectHttpStatus(outsiderApi.collaboration.fetchUsersForGoal(goal.id), 403)+ })+ })++ describe('Revoked access', () => {+ it('a removed collaborator loses access to the collaborator list', async () => {+ const { goal, collab } = await shareGoalWithOutsider()++ // sanity: access is real before removal+ const before = await outsiderApi.collaboration.fetchUsersForGoal(goal.id)+ expect(before?.some(u => u.email === outsiderEmail)).toBe(true)++ const removed = await ownerApi.collaboration.deleteUserFromGoal({ goalId: goal.id, id: collab.id })+ expect(removed).toBeTruthy()++ await expectHttpStatus(outsiderApi.collaboration.fetchUsersForGoal(goal.id), 403)+ })+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/graph-access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/graph-access.test.tsnew file mode 100644index 0000000..a4f48c7--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/graph-access.test.ts@@ -0,0 +1,161 @@+import { TvApi } from '@/tv'+import axios, { type AxiosInstance } from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, DEFAULT_PASSWORD, DEFAULT_USER_2, initApi } from './init-api'++/**+ * resolveGoalId() for the graph module inspects req.body.source before falling+ * back to req.params.id, while deleteEdge acts on req.params.id. A caller must+ * not be able to point the guard at a task they own while the handler operates+ * on an edge belonging to someone else.+ */+describe('Graph object-level access control', () => {+ let ownerApi: TvApi+ let outsiderApi: TvApi+ let deleteAllGoals: () => Promise<void>+ let attackerAxios: AxiosInstance+ let victimGoalId: number+ let attackerTaskId: number+ let victimTaskId: number++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ outsiderApi = init.$tvApiForSecondUser+ deleteAllGoals = init.deleteAllGoals++ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER_2,+ password: DEFAULT_PASSWORD,+ })+ attackerAxios = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })++ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim graph ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ victimGoalId = victimGoal.id++ const victimTask = await ownerApi.tasks.createTask({+ goalId: victimGoalId,+ description: `victim-task-${Date.now()}`,+ })+ if (!victimTask) throw new Error('Failed to create victim task')+ victimTaskId = victimTask.id++ const attackerGoal = await outsiderApi.goals.createGoal({ name: `Attacker graph ${Date.now()}` })+ if (!attackerGoal) throw new Error('Failed to create attacker goal')++ const attackerTask = await outsiderApi.tasks.createTask({+ goalId: attackerGoal.id,+ description: `attacker-task-${Date.now()}`,+ })+ if (!attackerTask) throw new Error('Failed to create attacker task')+ attackerTaskId = attackerTask.id+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ async function expectHttpStatus<T>(promise: Promise<T>, status: number): Promise<void> {+ try {+ await promise+ throw new Error(`Expected HTTP ${status} but request succeeded`)+ } catch (e: any) {+ if (typeof e.message === 'string' && e.message.startsWith('Expected HTTP')) throw e+ expect(e.response?.status ?? e.status, `Expected ${status}, got ${e.response?.status ?? e.status}`).toBe(status)+ }+ }++ async function createVictimEdge(): Promise<number> {+ const from = await ownerApi.tasks.createTask({+ goalId: victimGoalId,+ description: `victim-edge-from-${Date.now()}`,+ })+ const to = await ownerApi.tasks.createTask({+ goalId: victimGoalId,+ description: `victim-edge-to-${Date.now()}`,+ })+ if (!from || !to) throw new Error('Failed to create victim tasks')++ const edge = await ownerApi.graph.addEdge({ source: from.id, target: to.id })+ if (!edge) throw new Error('Failed to create victim edge')+ return edge.id+ }++ async function victimEdgeExists(edgeId: number): Promise<boolean> {+ const edges = await ownerApi.graph.fetchAllEdges(victimGoalId)+ return (edges ?? []).some(e => e.id === edgeId)+ }++ it('rejects deleting another user edge even when a self-owned source task is supplied', async () => {+ const edgeId = await createVictimEdge()++ const response = await attackerAxios.delete(`/module/graph/${edgeId}`, {+ data: { source: attackerTaskId },+ })++ expect(+ await victimEdgeExists(edgeId),+ `victim edge ${edgeId} was destroyed by a non-member`,+ ).toBe(true)+ expect(response.status).toBe(403)+ })++ // A graph lives inside one project, so an edge across two of them is not a+ // permission question but an impossible object: it is refused before any+ // permission is looked at. Driven through the SDK on purpose — this needs no+ // crafted request at all, an ordinary client using the public API reaches it.+ it('rejects creating an edge whose endpoints live in different projects', async () => {+ await expectHttpStatus(+ outsiderApi.graph.addEdge({ source: attackerTaskId, target: victimTaskId }),+ 400,+ )+ })++ // the mirror of the case above: a foreign source with an own target. This one+ // fails closed even without the endpoint comparison (the goal would resolve to+ // the victim project and the permission check would deny it), which is exactly+ // why it needs pinning — a regression here would be silent+ it('rejects creating an edge from a foreign task into a project the caller owns', async () => {+ await expectHttpStatus(+ outsiderApi.graph.addEdge({ source: victimTaskId, target: attackerTaskId }),+ 400,+ )+ })++ // both endpoints inside the victim project: the goal resolves cleanly, so this+ // is decided purely by the permission check on that goal+ it('rejects creating an edge between two tasks of a project the caller is not a member of', async () => {+ const second = await ownerApi.tasks.createTask({+ goalId: victimGoalId,+ description: `victim-second-${Date.now()}`,+ })+ if (!second) throw new Error('Failed to create second victim task')++ await expectHttpStatus(+ outsiderApi.graph.addEdge({ source: victimTaskId, target: second.id }),+ 403,+ )+ })++ it('control: without the injected source the guard already rejects the delete', async () => {+ const edgeId = await createVictimEdge()++ const response = await attackerAxios.delete(`/module/graph/${edgeId}`)++ expect(response.status).toBe(403)+ expect(await victimEdgeExists(edgeId)).toBe(true)+ })++ it('control: the owner can still delete their own edge', async () => {+ const edgeId = await createVictimEdge()++ const deleted = await ownerApi.graph.deleteEdge(edgeId)+ expect(deleted).toBeTruthy()+ expect(await victimEdgeExists(edgeId)).toBe(false)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/guard-param-confusion.test.ts b/taskview-packages/taskview-api/src/api/__tests__/guard-param-confusion.test.tsnew file mode 100644index 0000000..5babd32--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/guard-param-confusion.test.ts@@ -0,0 +1,113 @@+import { TvApi } from '@/tv'+import axios, { type AxiosInstance } from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, DEFAULT_PASSWORD, DEFAULT_USER_2, initApi } from './init-api'++/**+ * Several guards pick the goal to authorize with `req.body.goalId ? req.body : req.params`,+ * while their handlers read `req.params`. Supplying a body that names a goal the caller owns+ * must not authorize a request whose path points at someone else's goal.+ */+describe('Guard/handler parameter confusion', () => {+ let ownerApi: TvApi+ let deleteAllGoals: () => Promise<void>+ let attackerAxios: AxiosInstance+ let victimGoalId: number+ let attackerGoalId: number+ let victimColumnId: number++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ deleteAllGoals = init.deleteAllGoals++ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER_2,+ password: DEFAULT_PASSWORD,+ })+ attackerAxios = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })++ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim confusion ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ victimGoalId = victimGoal.id++ const attackerGoal = await axios.post(+ `${API_URL}/module/goals`,+ { name: `Attacker confusion ${Date.now()}` },+ { headers: { Authorization: `Bearer ${auth.data.access}` } },+ )+ attackerGoalId = attackerGoal.data.response.id++ await ownerApi.tasks.createTask({+ goalId: victimGoalId,+ description: `secret-task-${Date.now()}`,+ })++ const columns = await ownerApi.kanban.fetchAllColumns(victimGoalId)+ if (!columns?.length) throw new Error('Victim goal has no kanban columns')+ victimColumnId = columns[0].id+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ it('rejects reading another goal kanban tasks when a self-owned goalId is put in the body', async () => {+ const response = await attackerAxios.request({+ method: 'get',+ url: `/module/kanban/tasks/${victimGoalId}/${victimColumnId}/0`,+ data: { goalId: attackerGoalId, columnId: victimColumnId },+ })++ expect(+ response.status,+ `Leaked kanban tasks of goal ${victimGoalId}: ${JSON.stringify(response.data)}`,+ ).toBe(403)+ })++ it('rejects reading another goal task order when a self-owned goalId is put in the body', async () => {+ const response = await attackerAxios.request({+ method: 'get',+ url: `/module/kanban/tasks-order/${victimGoalId}/${victimColumnId}/0`,+ data: { goalId: attackerGoalId, columnId: victimColumnId },+ })++ expect(response.status).toBe(403)+ })++ it('rejects reading another goal role-to-permission matrix when a self-owned goalId is put in the body', async () => {+ const response = await attackerAxios.request({+ method: 'get',+ url: `/module/collaborationroles/role-to-permissions/${victimGoalId}`,+ data: { goalId: attackerGoalId },+ })++ expect(+ response.status,+ `Leaked role matrix of goal ${victimGoalId}: ${JSON.stringify(response.data)}`,+ ).toBe(403)+ })++ it('control: the same requests without a body are already rejected', async () => {+ const kanban = await attackerAxios.get(`/module/kanban/tasks/${victimGoalId}/${victimColumnId}/0`)+ expect(kanban.status).toBe(403)++ const roles = await attackerAxios.get(`/module/collaborationroles/role-to-permissions/${victimGoalId}`)+ expect(roles.status).toBe(403)+ })++ it('control: the owner still reads their own kanban tasks and role matrix', async () => {+ const tasks = await ownerApi.kanban+ .fetchTasksForColumn(victimGoalId, victimColumnId, 0)+ .catch((e: any) => { throw new Error(`kanban read failed: ${e.response?.status}`) })+ expect(tasks).toBeDefined()++ const matrix = await ownerApi.collaboration.fetchRoleToPermissionsForGoal(victimGoalId)+ .catch((e: any) => { throw new Error(`role matrix read failed: ${e.response?.status}`) })+ expect(matrix).toBeDefined()+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/integrations-access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/integrations-access.test.tsnew file mode 100644index 0000000..7faa003--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/integrations-access.test.ts@@ -0,0 +1,236 @@+import { TvApi } from '@/tv'+import { TvPermissions } from '@/api/permissions'+import axios, { type AxiosInstance } from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, DEFAULT_PASSWORD, DEFAULT_USER_2, initApi } from './init-api'++/**+ * The integrations guards resolve the project to authorize against via+ * resolveProjectId(), which prefers a projectId supplied by the caller over the+ * one derived from integrationId. The handlers, however, act on integrationId.+ * A caller must not be able to pass a project they own alongside someone else's+ * integration id and have the guard authorize the wrong object.+ */+describe('Integrations object-level access control', () => {+ let ownerApi: TvApi+ let outsiderApi: TvApi+ let deleteAllGoals: () => Promise<void>+ let outsiderEmail: string+ let attackerAxios: AxiosInstance+ let victimGoalId: number+ let attackerGoalId: number++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ outsiderApi = init.$tvApiForSecondUser+ deleteAllGoals = init.deleteAllGoals+ outsiderEmail = init.user2Email++ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER_2,+ password: DEFAULT_PASSWORD,+ })+ attackerAxios = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })++ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim project ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ victimGoalId = victimGoal.id++ const attackerGoal = await outsiderApi.goals.createGoal({ name: `Attacker project ${Date.now()}` })+ if (!attackerGoal) throw new Error('Failed to create attacker goal')+ attackerGoalId = attackerGoal.id+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ async function createVictimIntegration(): Promise<number> {+ const created = await ownerApi.integrations.createIntegration({+ provider: 'github',+ repoFullName: `victim-org/private-repo-${Date.now()}`,+ projectId: victimGoalId,+ })+ if (!created) throw new Error('Failed to create victim integration')+ return created.id+ }++ async function victimIntegrationExists(integrationId: number): Promise<boolean> {+ const list = await ownerApi.integrations.fetchIntegrations(victimGoalId)+ return (list ?? []).some(i => i.id === integrationId)+ }++ it('rejects deleting another user integration even when a self-owned projectId is supplied', async () => {+ const integrationId = await createVictimIntegration()++ const response = await attackerAxios.delete('/module/integrations', {+ data: { id: integrationId, projectId: attackerGoalId },+ })++ // impact first, mechanism second — so a failure reports whether data was actually destroyed+ expect(+ await victimIntegrationExists(integrationId),+ `victim integration ${integrationId} was destroyed by a non-member`,+ ).toBe(true)+ expect(+ response.status,+ `Guard authorized project ${attackerGoalId} while the handler acted on integration ${integrationId}`,+ ).toBe(403)+ })++ it('rejects toggling another user integration even when a self-owned projectId is supplied', async () => {+ const integrationId = await createVictimIntegration()++ const response = await attackerAxios.patch('/module/integrations/toggle', {+ id: integrationId,+ isActive: false,+ projectId: attackerGoalId,+ })++ expect(response.status).toBe(403)+ })++ it('rejects reading another user integration repos even when a self-owned projectId is supplied', async () => {+ const integrationId = await createVictimIntegration()++ const response = await attackerAxios.get('/module/integrations/repos', {+ params: { integrationId, projectId: attackerGoalId },+ })++ expect(response.status).toBe(403)+ })++ it('rejects syncing another user integration even when a self-owned projectId is supplied', async () => {+ const integrationId = await createVictimIntegration()++ const response = await attackerAxios.post('/module/integrations/sync', {+ integrationId,+ projectId: attackerGoalId,+ })++ expect(response.status).toBe(403)+ })++ it('control: without the injected projectId the guard already rejects the same request', async () => {+ const integrationId = await createVictimIntegration()++ const response = await attackerAxios.delete('/module/integrations', {+ data: { id: integrationId },+ })++ expect(response.status).toBe(403)+ expect(await victimIntegrationExists(integrationId)).toBe(true)+ })++ // select-repo is the most consequential handler of the four: besides writing to+ // the integration it kicks off syncIssues() and registerWebhook() against the repo+ it('rejects selecting a repo on another user integration even when a self-owned projectId is supplied', async () => {+ const integrationId = await createVictimIntegration()++ const response = await attackerAxios.patch('/module/integrations/select-repo', {+ integrationId,+ repoFullName: 'attacker-org/planted-repo',+ repoExternalId: '424242',+ projectId: attackerGoalId,+ })++ expect(response.status).toBe(403)+ })++ // resolveProjectId reads projectId from the query string too, so a fix that only+ // hardens the body would still leave this door open+ it('rejects the same bypass when projectId arrives via the query string', async () => {+ const integrationId = await createVictimIntegration()++ const response = await attackerAxios.delete('/module/integrations', {+ params: { projectId: attackerGoalId },+ data: { id: integrationId },+ })++ expect(+ await victimIntegrationExists(integrationId),+ `victim integration ${integrationId} was destroyed via a query-string projectId`,+ ).toBe(true)+ expect(response.status).toBe(403)+ })++ it('rejects listing the integrations of a project the caller is not a member of', async () => {+ await createVictimIntegration()++ const response = await attackerAxios.get('/module/integrations', {+ params: { projectId: victimGoalId },+ })++ expect(+ response.status,+ `Leaked integrations of project ${victimGoalId}: ${JSON.stringify(response.data)}`,+ ).toBe(403)+ })++ it('rejects planting a new integration into a project the caller is not a member of', async () => {+ const response = await attackerAxios.post('/module/integrations', {+ provider: 'github',+ repoFullName: 'attacker-org/planted-repo',+ projectId: victimGoalId,+ })++ expect(response.status).toBe(403)+ })++ it('control: the owner can still manage their own integration', async () => {+ const integrationId = await createVictimIntegration()++ const deleted = await ownerApi.integrations.deleteIntegration(integrationId)+ expect(deleted).toBeTruthy()+ expect(await victimIntegrationExists(integrationId)).toBe(false)+ })++ // guards against an over-strict fix: a project member holding integrations_can_manage+ // must keep working, not just the goal owner+ it('control: a project member with integrations_can_manage can delete the integration', async () => {+ const goal = await ownerApi.goals.createGoal({ name: `Shared integrations ${Date.now()}` })+ if (!goal) throw new Error('Failed to create goal')++ const collab = await ownerApi.collaboration.inviteUserToGoal({ email: outsiderEmail, goalId: goal.id })+ if (!collab) throw new Error('Failed to invite user2')++ const allPermissions = await ownerApi.collaboration.fetchAllPermissions()+ const managePermission = allPermissions.find(p => p.name === TvPermissions.INTEGRATIONS_CAN_MANAGE)+ if (!managePermission) throw new Error('Permission "integrations_can_manage" is not in DB')++ const role = await ownerApi.collaboration.createRoleForGoal({+ goalId: goal.id,+ roleName: `Integrator ${Date.now()}`,+ })+ if (!role) throw new Error('Failed to create role')++ const toggled = await ownerApi.collaboration.toggleRolePermission({+ roleId: role.id,+ permissionId: managePermission.id,+ })+ if (!toggled || toggled.add !== true) {+ throw new Error(`Expected integrations_can_manage to be added, got ${JSON.stringify(toggled)}`)+ }++ await ownerApi.collaboration.toggleUserRoles({+ goalId: goal.id,+ userId: collab.id,+ roles: [role.id],+ })++ const created = await ownerApi.integrations.createIntegration({+ provider: 'github',+ repoFullName: `shared-org/repo-${Date.now()}`,+ projectId: goal.id,+ })+ if (!created) throw new Error('Failed to create integration')++ const deleted = await outsiderApi.integrations.deleteIntegration(created.id)+ expect(deleted).toBeTruthy()+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/kanban.access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/kanban.access.test.tsnew file mode 100644index 0000000..44e4847--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/kanban.access.test.ts@@ -0,0 +1,220 @@+import { TvApi } from '@/tv'+import { TvPermissions } from '@/api/permissions'+import axios, { type AxiosInstance } from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, DEFAULT_PASSWORD, DEFAULT_USER_2, initApi } from './init-api'++/**+ * Board writes (columns and task placement) are gated by kanban_can_manage, the+ * permission the UI has always used. They used to accept component_can_add_tasks+ * or task_can_add_subtasks instead, which let a rank-and-file member delete other+ * people's board columns.+ */+describe('Kanban permission boundaries', () => {+ let ownerApi: TvApi+ let outsiderApi: TvApi+ let outsiderEmail: string+ let deleteAllGoals: () => Promise<void>+ let attackerAxios: AxiosInstance+ const permissionIdByName = new Map<string, number>()++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ outsiderApi = init.$tvApiForSecondUser+ outsiderEmail = init.user2Email+ deleteAllGoals = init.deleteAllGoals++ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER_2,+ password: DEFAULT_PASSWORD,+ })+ attackerAxios = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })++ for (const permission of await ownerApi.collaboration.fetchAllPermissions()) {+ permissionIdByName.set(permission.name, permission.id)+ }+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ async function expectHttpStatus<T>(promise: Promise<T>, status: number): Promise<void> {+ try {+ await promise+ throw new Error(`Expected HTTP ${status} but request succeeded`)+ } catch (e: any) {+ if (typeof e.message === 'string' && e.message.startsWith('Expected HTTP')) throw e+ expect(e.response?.status ?? e.status, `Expected ${status}, got ${e.response?.status ?? e.status}`).toBe(status)+ }+ }++ /** A goal of user1 that user2 joins through a role carrying exactly `permissionNames`. */+ async function shareGoalWith(permissionNames: string[]) {+ const goal = await ownerApi.goals.createGoal({ name: `Kanban access ${Date.now()}` })+ if (!goal) throw new Error('Failed to create goal')++ const collab = await ownerApi.collaboration.inviteUserToGoal({ email: outsiderEmail, goalId: goal.id })+ if (!collab) throw new Error('Failed to invite user2')++ const role = await ownerApi.collaboration.createRoleForGoal({+ goalId: goal.id,+ roleName: `Role ${Date.now()}`,+ })+ if (!role) throw new Error('Failed to create role')++ for (const name of permissionNames) {+ const permissionId = permissionIdByName.get(name)+ if (!permissionId) throw new Error(`Permission "${name}" is not in DB`)++ const toggled = await ownerApi.collaboration.toggleRolePermission({ roleId: role.id, permissionId })+ if (!toggled || toggled.add !== true) {+ throw new Error(`Expected "${name}" to be added, got ${JSON.stringify(toggled)}`)+ }+ }++ await ownerApi.collaboration.toggleUserRoles({ goalId: goal.id, userId: collab.id, roles: [role.id] })++ return goal+ }++ async function addColumn(goalId: number, name: string) {+ const column = await ownerApi.kanban.addColumn({ goalId, name })+ if (!column) throw new Error('Failed to create column')+ return column+ }++ describe('a member holding kanban_can_manage', () => {+ it('can create, rename and delete a board column', async () => {+ const goal = await shareGoalWith([TvPermissions.KANBAN_CAN_MANAGE])++ const created = await outsiderApi.kanban.addColumn({ goalId: goal.id, name: 'Created by member' })+ expect(created?.id).toBeGreaterThan(0)++ const renamed = await outsiderApi.kanban.updateColumn({ id: created!.id, name: 'Renamed by member' })+ expect(renamed).toBeTruthy()++ const deleted = await outsiderApi.kanban.deleteColumn({ id: created!.id })+ expect(deleted).toBeTruthy()+ })++ it('can move a task into another column', async () => {+ const goal = await shareGoalWith([TvPermissions.KANBAN_CAN_MANAGE])+ const from = await addColumn(goal.id, 'From')+ const to = await addColumn(goal.id, 'To')++ const task = await ownerApi.tasks.createTask({+ goalId: goal.id,+ description: `movable-${Date.now()}`,+ statusId: from.id,+ })+ if (!task) throw new Error('Failed to create task')++ const moved = await outsiderApi.kanban.updateTasksOrderAndColumn({+ goalId: goal.id,+ columnId: to.id,+ taskId: task.id,+ prevTaskId: null,+ nextTaskId: null,+ })+ expect(moved).toBeDefined()+ })+ })++ describe('a member holding only task-level permissions', () => {+ // exactly the pair the routes used to accept — the escalation that was closed+ const TASK_LEVEL = [TvPermissions.COMPONENT_CAN_ADD_TASKS, TvPermissions.TASK_CAN_ADD_SUBTASKS]++ it('cannot create a board column', async () => {+ const goal = await shareGoalWith(TASK_LEVEL)++ await expectHttpStatus(outsiderApi.kanban.addColumn({ goalId: goal.id, name: 'Nope' }), 403)+ })++ it('cannot rename or delete a board column', async () => {+ const goal = await shareGoalWith(TASK_LEVEL)+ const column = await addColumn(goal.id, 'Owned by user1')++ await expectHttpStatus(outsiderApi.kanban.updateColumn({ id: column.id, name: 'Nope' }), 403)+ await expectHttpStatus(outsiderApi.kanban.deleteColumn({ id: column.id }), 403)++ const survivors = await ownerApi.kanban.fetchAllColumns(goal.id)+ expect(survivors?.some(c => c.id === column.id), 'column was destroyed').toBe(true)+ })++ it('cannot move a task into another column', async () => {+ const goal = await shareGoalWith(TASK_LEVEL)+ const from = await addColumn(goal.id, 'From')+ const to = await addColumn(goal.id, 'To')++ const task = await ownerApi.tasks.createTask({+ goalId: goal.id,+ description: `pinned-${Date.now()}`,+ statusId: from.id,+ })+ if (!task) throw new Error('Failed to create task')++ await expectHttpStatus(+ outsiderApi.kanban.updateTasksOrderAndColumn({+ goalId: goal.id,+ columnId: to.id,+ taskId: task.id,+ prevTaskId: null,+ nextTaskId: null,+ }),+ 403,+ )+ })+ })++ describe('a member holding only kanban_can_view', () => {+ it('can read the task order of a column', async () => {+ const goal = await shareGoalWith([TvPermissions.KANBAN_CAN_VIEW])+ const column = await addColumn(goal.id, 'Readable')++ const order = await outsiderApi.kanban.getTaskOrdersForColumnAndCursor(goal.id, column.id, null)+ expect(order).toBeDefined()+ })++ it('cannot create a board column', async () => {+ const goal = await shareGoalWith([TvPermissions.KANBAN_CAN_VIEW])++ await expectHttpStatus(outsiderApi.kanban.addColumn({ goalId: goal.id, name: 'Nope' }), 403)+ })+ })++ describe('the goal a column belongs to is never taken from the request', () => {+ it('rejects deleting or renaming a foreign column even when a self-owned goalId is supplied', async () => {+ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim board ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ const victimColumn = await addColumn(victimGoal.id, 'Victim column')++ // a project user2 fully controls, offered to the guard as the authorization target+ const ownGoal = await outsiderApi.goals.createGoal({ name: `Attacker board ${Date.now()}` })+ if (!ownGoal) throw new Error('Failed to create attacker goal')++ const deleteResponse = await attackerAxios.post('/module/kanban/delete-status', {+ id: victimColumn.id,+ goalId: ownGoal.id,+ })+ const updateResponse = await attackerAxios.post('/module/kanban/update-status', {+ id: victimColumn.id,+ name: 'Renamed by an outsider',+ goalId: ownGoal.id,+ })++ const survivors = await ownerApi.kanban.fetchAllColumns(victimGoal.id)+ const survivor = (survivors ?? []).find(c => c.id === victimColumn.id)+ expect(survivor, `victim column ${victimColumn.id} was destroyed`).toBeDefined()+ expect(survivor?.name, 'victim column was renamed').toBe('Victim column')++ expect(deleteResponse.status).toBe(403)+ expect(updateResponse.status).toBe(403)+ })+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/tasks-access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/tasks-access.test.tsnew file mode 100644index 0000000..7090884--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/tasks-access.test.ts@@ -0,0 +1,80 @@+import { TvApi } from '@/tv'+import axios, { type AxiosInstance } from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, DEFAULT_PASSWORD, DEFAULT_USER_2, initApi } from './init-api'++/**+ * CanFetchTask authorizes `req.query.taskId || req.params.taskId`, while+ * fetchTaskByIdNew reads `req.params`. A caller must not be able to name a task+ * they own in the query string and have the guard authorize it while the handler+ * returns someone else's task.+ */+describe('Task object-level access control', () => {+ let ownerApi: TvApi+ let outsiderApi: TvApi+ let deleteAllGoals: () => Promise<void>+ let attackerAxios: AxiosInstance+ let victimTaskId: number+ let attackerTaskId: number++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ outsiderApi = init.$tvApiForSecondUser+ deleteAllGoals = init.deleteAllGoals++ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER_2,+ password: DEFAULT_PASSWORD,+ })+ attackerAxios = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })++ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim tasks ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ const victimTask = await ownerApi.tasks.createTask({+ goalId: victimGoal.id,+ description: `victim-secret-${Date.now()}`,+ })+ if (!victimTask) throw new Error('Failed to create victim task')+ victimTaskId = victimTask.id++ const attackerGoal = await outsiderApi.goals.createGoal({ name: `Attacker tasks ${Date.now()}` })+ if (!attackerGoal) throw new Error('Failed to create attacker goal')+ const attackerTask = await outsiderApi.tasks.createTask({+ goalId: attackerGoal.id,+ description: `attacker-own-${Date.now()}`,+ })+ if (!attackerTask) throw new Error('Failed to create attacker task')+ attackerTaskId = attackerTask.id+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ it('rejects reading another user task when a self-owned taskId is put in the query string', async () => {+ const response = await attackerAxios.get(`/module/tasks/${victimTaskId}`, {+ params: { taskId: attackerTaskId },+ })++ expect(+ response.status,+ `Leaked task ${victimTaskId}: ${JSON.stringify(response.data)}`,+ ).toBe(403)+ })++ it('control: without the query parameter the guard already rejects the same request', async () => {+ const response = await attackerAxios.get(`/module/tasks/${victimTaskId}`)++ expect(response.status).toBe(403)+ })++ it('control: the owner can still read their own task', async () => {+ const task = await ownerApi.tasks.fetchTaskById(victimTaskId)+ expect(task?.id).toBe(victimTaskId)+ })+})diff --git a/web/src/components/features/collaboration/CollaborationPanel.vue b/web/src/components/features/collaboration/CollaborationPanel.vueindex 52d5bf8..cf1b1ec 100644--- a/web/src/components/features/collaboration/CollaborationPanel.vue+++ b/web/src/components/features/collaboration/CollaborationPanel.vue@@ -18,6 +18,10 @@class="w-full":ui="{ list: 'rounded-2xl', trigger: 'rounded-xl', indicator: 'rounded-xl' }">+ <template #default="{ item }">+ <span :data-testid="`collab-tab-${item.value}`">{{ item.label }}</span>+ </template>+<template #members><MembersList:members="users"diff --git a/web/src/components/features/collaboration/parts/members/MemberAddInput.vue b/web/src/components/features/collaboration/parts/members/MemberAddInput.vueindex 360199b..ff8d4a9 100644--- a/web/src/components/features/collaboration/parts/members/MemberAddInput.vue+++ b/web/src/components/features/collaboration/parts/members/MemberAddInput.vue@@ -3,6 +3,7 @@v-model="email"type="email":placeholder="t('collaboration.members.emailPlaceholder')"+ data-testid="collab-member-email-input"size="xl"variant="soft"class="w-full"@@ -16,6 +17,7 @@v-if="isValid"icon="i-lucide-corner-down-left":label="t('collaboration.members.add')"+ data-testid="collab-member-add-button"color="primary"variant="ghost"size="xs"diff --git a/web/src/components/features/collaboration/parts/members/MemberEditModal.vue b/web/src/components/features/collaboration/parts/members/MemberEditModal.vueindex d23f0c3..379b1e6 100644--- a/web/src/components/features/collaboration/parts/members/MemberEditModal.vue+++ b/web/src/components/features/collaboration/parts/members/MemberEditModal.vue@@ -24,6 +24,7 @@<labelv-for="role in roles":key="role.id"+ :data-testid="`collab-member-role-${role.name}`"class="flex items-center gap-3 p-2 rounded hover:bg-elevated cursor-pointer"><UCheckbox@@ -51,6 +52,7 @@/><UButton:label="t('common.save')"+ data-testid="collab-member-roles-save"color="primary"variant="soft"@click="handleSave"diff --git a/web/src/components/features/collaboration/parts/members/MemberItem.vue b/web/src/components/features/collaboration/parts/members/MemberItem.vueindex 77bc7e3..83fb967 100644--- a/web/src/components/features/collaboration/parts/members/MemberItem.vue+++ b/web/src/components/features/collaboration/parts/members/MemberItem.vue@@ -1,5 +1,8 @@<template>- <div class="flex items-center justify-between p-3 rounded-2xl border border-default hover:bg-elevated transition-colors">+ <div+ :data-testid="`collab-member-${member.email}`"+ class="flex items-center justify-between p-3 rounded-2xl border border-default hover:bg-elevated transition-colors"+ ><div class="flex items-center gap-3"><UAvatar:alt="member.email"@@ -42,6 +45,7 @@color="neutral"variant="ghost"size="xs"+ data-testid="collab-member-menu-trigger"@click.stop="$emit('menu', $event)"/></div>diff --git a/web/src/components/features/collaboration/parts/members/MembersList.vue b/web/src/components/features/collaboration/parts/members/MembersList.vueindex 28de627..600c7ab 100644--- a/web/src/components/features/collaboration/parts/members/MembersList.vue+++ b/web/src/components/features/collaboration/parts/members/MembersList.vue@@ -47,6 +47,7 @@<div class="p-1 flex flex-col gap-1"><UButton:label="t('collaboration.members.assignRoles')"+ data-testid="collab-member-assign-roles"icon="i-lucide-user-cog"variant="ghost"color="neutral"@@ -56,6 +57,7 @@<USeparator class="my-1" /><UButton:label="t('collaboration.members.remove')"+ data-testid="collab-member-remove"icon="i-lucide-user-minus"variant="ghost"color="error"diff --git a/web/src/components/features/collaboration/parts/roles/PermissionsEditor.vue b/web/src/components/features/collaboration/parts/roles/PermissionsEditor.vueindex 9ff011d..2b856c2 100644--- a/web/src/components/features/collaboration/parts/roles/PermissionsEditor.vue+++ b/web/src/components/features/collaboration/parts/roles/PermissionsEditor.vue@@ -3,6 +3,7 @@<UInputv-model="searchQuery":placeholder="t('collaboration.permissions.searchPlaceholder')"+ data-testid="collab-permission-search"size="xl"variant="soft"class="w-full"@@ -39,6 +40,7 @@<labelv-for="permission in group.permissions":key="permission.id"+ :data-testid="`collab-permission-${permission.name}`"class="flex items-start gap-3 p-2 rounded hover:bg-elevated cursor-pointer"><UCheckboxdiff --git a/web/src/components/features/collaboration/parts/roles/RoleAddInput.vue b/web/src/components/features/collaboration/parts/roles/RoleAddInput.vueindex 36bedfc..74a6040 100644--- a/web/src/components/features/collaboration/parts/roles/RoleAddInput.vue+++ b/web/src/components/features/collaboration/parts/roles/RoleAddInput.vue@@ -2,6 +2,7 @@<UInputv-model="name":placeholder="t('collaboration.roles.namePlaceholder')"+ data-testid="collab-role-name-input"size="xl"variant="soft"class="w-full"@@ -18,6 +19,7 @@variant="ghost"size="xs":aria-label="t('collaboration.roles.create')"+ data-testid="collab-role-add-button"@click="addRole"/><UIcondiff --git a/web/src/components/features/collaboration/parts/roles/RoleDeleteDialog.vue b/web/src/components/features/collaboration/parts/roles/RoleDeleteDialog.vueindex 7b8f6ee..79cb6a2 100644--- a/web/src/components/features/collaboration/parts/roles/RoleDeleteDialog.vue+++ b/web/src/components/features/collaboration/parts/roles/RoleDeleteDialog.vue@@ -19,6 +19,7 @@/><UButton:label="t('contextMenu.delete')"+ data-testid="collab-role-delete-confirm"color="error"variant="soft"@click="handleDelete"diff --git a/web/src/components/features/collaboration/parts/roles/RoleItem.vue b/web/src/components/features/collaboration/parts/roles/RoleItem.vueindex 0314fa3..720a256 100644--- a/web/src/components/features/collaboration/parts/roles/RoleItem.vue+++ b/web/src/components/features/collaboration/parts/roles/RoleItem.vue@@ -1,5 +1,8 @@<template>- <div class="flex items-center justify-between p-3 rounded-2xl border border-default hover:bg-elevated transition-colors">+ <div+ :data-testid="`collab-role-${role.name}`"+ class="flex items-center justify-between p-3 rounded-2xl border border-default hover:bg-elevated transition-colors"+ ><div class="flex items-center gap-2"><UIconname="i-lucide-shield"@@ -18,6 +21,7 @@color="neutral"variant="ghost"size="xs"+ data-testid="collab-role-menu-trigger"@click.stop="$emit('menu', $event)"/></div>diff --git a/web/src/components/features/collaboration/parts/roles/RolesList.vue b/web/src/components/features/collaboration/parts/roles/RolesList.vueindex ccbf341..0cd3d86 100644--- a/web/src/components/features/collaboration/parts/roles/RolesList.vue+++ b/web/src/components/features/collaboration/parts/roles/RolesList.vue@@ -47,6 +47,7 @@<div class="p-1 flex flex-col gap-1"><UButton:label="t('collaboration.roles.assignPermissions')"+ data-testid="collab-role-assign-permissions"icon="i-lucide-shield-check"variant="ghost"color="neutral"@@ -56,6 +57,7 @@<USeparator class="my-1" /><UButton:label="t('contextMenu.delete')"+ data-testid="collab-role-delete"icon="i-lucide-trash-2"variant="ghost"color="error"diff --git a/web/src/components/features/kanban/KanbanBoard.vue b/web/src/components/features/kanban/KanbanBoard.vueindex 5769fd3..acb5e33 100644--- a/web/src/components/features/kanban/KanbanBoard.vue+++ b/web/src/components/features/kanban/KanbanBoard.vue@@ -11,6 +11,7 @@<divv-for="status in kanbanStore.statuses":key="status.id"+ :data-testid="`kanban-column-${t(status.name)}`"class="h-full max-w-[340px] min-w-[272px] shadow-lg gap-2 flex flex-col w-[91.666667%] rounded-lg"><div class="bg-elevated rounded-lg p-2 px-3 flex items-center text-base h-10 rounded-b-none">@@ -46,6 +47,7 @@<div:data-order="element.kanbanOrder":data-task-id="element.id"+ data-testid="kanban-task-card"><TaskItem:task="element"diff --git a/web/src/components/features/kanban/parts/KanbanAddStatus.vue b/web/src/components/features/kanban/parts/KanbanAddStatus.vueindex 4c70393..7f648df 100644--- a/web/src/components/features/kanban/parts/KanbanAddStatus.vue+++ b/web/src/components/features/kanban/parts/KanbanAddStatus.vue@@ -4,6 +4,7 @@<UInputv-model="statusName":placeholder="t('kanban.addColumn')"+ data-testid="kanban-add-column-input"icon="i-lucide-plus"size="xl"variant="soft"@@ -12,6 +13,7 @@<UButtonv-if="statusName.trim()"+ data-testid="kanban-add-column-submit"@click="addStatus">{{ t('kanban.addColumn') }}diff --git a/web/src/components/features/kanban/parts/KanbanDeleteModal.vue b/web/src/components/features/kanban/parts/KanbanDeleteModal.vueindex 3610c16..b72ecdd 100644--- a/web/src/components/features/kanban/parts/KanbanDeleteModal.vue+++ b/web/src/components/features/kanban/parts/KanbanDeleteModal.vue@@ -32,6 +32,7 @@<UButtoncolor="error"variant="soft"+ data-testid="kanban-delete-confirm"@click="confirmDelete">{{ t('common.delete') }}diff --git a/web/src/components/features/kanban/parts/KanbanEditModal.vue b/web/src/components/features/kanban/parts/KanbanEditModal.vueindex 1212675..255da83 100644--- a/web/src/components/features/kanban/parts/KanbanEditModal.vue+++ b/web/src/components/features/kanban/parts/KanbanEditModal.vue@@ -20,6 +20,7 @@<UInputv-model="name":placeholder="t('kanban.columnName')"+ data-testid="kanban-edit-name"class="w-full"/></UFormField>@@ -35,6 +36,7 @@</UButton><UButtonvariant="outline"+ data-testid="kanban-edit-save"@click="save">{{ t('common.save') }}diff --git a/web/src/components/features/kanban/parts/KanbanTitleMenu.vue b/web/src/components/features/kanban/parts/KanbanTitleMenu.vueindex 5b1670a..b99bf75 100644--- a/web/src/components/features/kanban/parts/KanbanTitleMenu.vue+++ b/web/src/components/features/kanban/parts/KanbanTitleMenu.vue@@ -9,6 +9,7 @@color="neutral"variant="ghost"size="sm"+ data-testid="kanban-column-menu-trigger"/></UDropdownMenu>@@ -48,6 +49,7 @@ const menuItems = computed<DropdownMenuItem[][]>(() => [label: t('kanban.edit'),icon: 'i-lucide-pencil',ui,+ 'data-testid': 'kanban-menu-edit',// size: 'lg',onSelect: () => {editOpen.value = true@@ -58,6 +60,7 @@ const menuItems = computed<DropdownMenuItem[][]>(() => [icon: 'i-lucide-trash-2',color: 'error' as const,ui,+ 'data-testid': 'kanban-menu-delete',onSelect: () => {deleteOpen.value = true},diff --git a/web/src/components/features/tasks/parts/TasksFilterDrawer.vue b/web/src/components/features/tasks/parts/TasksFilterDrawer.vueindex 3351dfb..d62ddeb 100644--- a/web/src/components/features/tasks/parts/TasksFilterDrawer.vue+++ b/web/src/components/features/tasks/parts/TasksFilterDrawer.vue@@ -11,7 +11,10 @@<USeparator /></template><template #body>- <div class="flex flex-col gap-4">+ <div+ class="flex flex-col gap-4"+ data-testid="tasks-filter-drawer"+ ><!-- User Filter --><UFormField:label="t('filters.assignee')"@@ -158,7 +161,7 @@ watch(isOpen, (open) => {// Fetch users for current projectconst projectId = route.params.projectIdif (projectId) {- collaborationStore.fetchCollaborationUsersForGoal(Number(projectId))+ collaborationStore.fetchCollaborationUsersForGoal(Number(projectId)).catch(() => null)}}})diff --git a/web/src/components/features/tasks/parts/TasksToolbar.vue b/web/src/components/features/tasks/parts/TasksToolbar.vueindex cdb6caa..97a9b64 100644--- a/web/src/components/features/tasks/parts/TasksToolbar.vue+++ b/web/src/components/features/tasks/parts/TasksToolbar.vue@@ -8,6 +8,7 @@:color="hasActiveFilters ? 'primary' : 'info'"variant="soft"size="sm"+ data-testid="tasks-filter-button"@click="isFilterDrawerOpen = true"/></UTooltip>diff --git a/web/src/composables/useProjectDataLoader.ts b/web/src/composables/useProjectDataLoader.tsindex c8faf56..0ac7f98 100644--- a/web/src/composables/useProjectDataLoader.ts+++ b/web/src/composables/useProjectDataLoader.ts@@ -17,7 +17,7 @@ export function useProjectDataLoader(projectId: Ref<number>) {if (id > 0) {Promise.all([kanbanStore.fetchStatuses(id),- collaborationStore.fetchCollaborationUsersForGoal(id),+ collaborationStore.fetchCollaborationUsersForGoal(id).catch(() => null),goalListsStore.fetchLists(id),])}