diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 09e62918..9518f080 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -130,6 +130,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `TaskChangedException::CODE` (`CONFLICT_001`): the conflict code a host answers with (409, `X-Conflict-Code`) when a host-port write finds the task changed (audit ZD-I5). + +### Fixed + +- Security (audit ZD-L1, Low): `TaskCommandsInterface` now checks its input with the same `Validation\TaskConstraints` as the page forms before anything is written: `addLink()` refuses URLs that are not http(s) (`javascript:`, `data:` …) and over-long labels / external ids, `createTask()` / `updateTask()` refuse a colour that is not `#rrggbb`, more than 20 tags and tags over 64 characters, `addComment()` a body over the comment limit, `logTime()` a note over 512 characters, `addHostObjectLink()` a label over 255 characters, and `addColumn()` a colour that is not hex. A refused value is an `InvalidArgumentException`, as the other invalid input of the port. Before, a host passing user input could store values the forms refuse (the bundle's own pages escaped or neutralised them; host templates, the Task API task output, the change history and events got them raw). Affected: 2.29.0 to 2.30.1. + ## [2.30.1] - 2026-11-22 ### Fixed diff --git a/docs/USAGE.md b/docs/USAGE.md index 7179172d..92d1bc68 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -839,12 +839,16 @@ copies of the user's detached time entries, in batches; idempotent). commits and dropped when it rolls back. - **Concurrency.** A task write locks the task's row first (after the column it enters, in the bundle's fixed lock order). Pass the `TaskView::$revision` you read as `$expectedRevision` to `updateTask` / `moveTask`: a task changed - meanwhile throws `TaskChangedException` (map it to **409 Conflict**, with `currentRevision`) and nothing is written. + meanwhile throws `TaskChangedException` (map it to **409 Conflict** with `X-Conflict-Code: TaskChangedException::CODE`, + i.e. `CONFLICT_001`, and `currentRevision`) and nothing is written. A lock conflict (deadlock, lock wait timeout) throws `Nowo\TransactionContract\TransientStorageFailure`: nothing was written, retry (an HTTP edge answers 503 with `Retry-After`). - The other errors are the pages' ones: `TaskReopenRefusedException` (your active-task limit), `ColumnTransitionRefusedException`, `UnassignableUserException`, `TaskLinkedToProviderException`, and - `InvalidArgumentException` for invalid input (checked before anything is written). + `InvalidArgumentException` for invalid input (checked before anything is written). Since 2.30.2 the input goes through + the same `Validation\TaskConstraints` as the page forms: link URLs http(s) only, task colour `#rrggbb`, column colour + hex, at most 20 tags of at most 64 characters, comment, time note, link label and external id lengths. Map it to + **422** at an HTTP edge, as the Task API does for its validation errors. **Access by id** (`TaskBoardAccessInterface`): `canAccess`, `canViewBoard`, `canEditBoard`, `canManageBoard`, `canViewTask`, `canEditTask`, `canTrackTime`, `filterBoardIds` (at most 500). An unknown user or id answers `false`. diff --git a/src/Exception/TaskChangedException.php b/src/Exception/TaskChangedException.php index 0eed1811..05f8987c 100644 --- a/src/Exception/TaskChangedException.php +++ b/src/Exception/TaskChangedException.php @@ -13,6 +13,12 @@ */ final class TaskChangedException extends RuntimeException { + /** + * Since 2.30.2 (audit ZD-I5): the house conflict code a host answers with (409, `X-Conflict-Code: CONFLICT_001`): + * nothing was written, a retry after reading the task again is safe. + */ + public const CODE = 'CONFLICT_001'; + public function __construct(public readonly int $currentRevision) { parent::__construct('TaskBoard: the task changed meanwhile; read it again.'); diff --git a/src/Resources/config/services.yaml b/src/Resources/config/services.yaml index b232355e..c3741e48 100644 --- a/src/Resources/config/services.yaml +++ b/src/Resources/config/services.yaml @@ -258,6 +258,7 @@ services: arguments: $managerRegistry: '@?doctrine' $rowLock: '@?Nowo\TaskBoardBundle\Service\OrderedRowLockInterface' + $validator: '@?validator' Nowo\TaskBoardBundle\Service\TaskCommandsInterface: alias: Nowo\TaskBoardBundle\Service\TaskCommands public: true diff --git a/src/Service/TaskCommands.php b/src/Service/TaskCommands.php index 4cc5659b..75f19dfe 100644 --- a/src/Service/TaskCommands.php +++ b/src/Service/TaskCommands.php @@ -39,6 +39,9 @@ use Nowo\TaskBoardBundle\View\TaskView; use Nowo\TaskBoardBundle\View\Views; use Nowo\TransactionContract\TransientStorageFailure; +use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Validation; +use Symfony\Component\Validator\Validator\ValidatorInterface; use Throwable; use function array_diff; @@ -47,6 +50,7 @@ use function array_values; use function count; use function is_scalar; +use function is_string; use function max; use function mb_strlen; use function min; @@ -59,12 +63,18 @@ * * Stateless (FrankenPHP worker mode with kernel reset off): every dependency is a stateless service or one the bundle * resets at each boundary; a failed unit resets a closed manager through the registry and reloads the task it touched. + * + * Since 2.30.2 (audit ZD-L1): the input goes through the same {@see TaskConstraints} as the page forms (http(s) link + * URLs, hex task and column colours, at most {@see TaskConstraints::TAGS_MAX} tags, comment / note / label / external id + * lengths) before anything is written; a value the forms refuse is an {@see InvalidArgumentException}. */ final readonly class TaskCommands implements TaskCommandsInterface { /** Rows per batch of {@see self::clearTimeEntrySnapshotsForUser()}. */ public const BATCH = 500; + private ValidatorInterface $validator; + public function __construct( private EntityManagerInterface $entityManager, private TaskBoardIdAccessChecker $access, @@ -85,7 +95,10 @@ public function __construct( private TaskBoardUsers $userReferences = new TaskBoardUsers(), // The fixed lock order of the bundle (columns, then tasks): a column a write enters is locked before the task. private ?OrderedRowLockInterface $rowLock = null, + // Since 2.30.2 (audit ZD-L1): checks the input against TaskConstraints; a standalone validator when none is given. + ?ValidatorInterface $validator = null, ) { + $this->validator = $validator ?? Validation::createValidator(); } public function createTask(UserRef $creator, string $boardId, TaskFormData $data, ?string $parentId = null, bool $completed = false): TaskView @@ -102,7 +115,7 @@ public function createTask(UserRef $creator, string $boardId, TaskFormData $data throw new InvalidArgumentException('TaskBoard: the parent task is on another board.'); } } - $this->assertTitle($data->title); + $this->assertTaskData($data); // The host's plan (QUOTA_CHECK), as the board page asks before a new task. $plan = $this->quota->refusal(TaskBoardQuotaCheckEvent::ACTION_TASK_CREATE, $board->getTenantKey(), $board, 1, $actor); if ($plan !== null) { @@ -127,7 +140,7 @@ public function updateTask(UserRef $actor, string $taskId, TaskFormData $data, ? { $user = $this->actor($actor); $task = $this->editableTask($user, $taskId); - $this->assertTitle($data->title); + $this->assertTaskData($data); return $this->unit(function () use ($task, $data, $user, $expectedRevision): TaskView { $this->lockColumn($data->columnId !== $task->getColumn()?->getId() ? $data->columnId : null); @@ -237,6 +250,7 @@ public function addComment(UserRef $author, string $taskId, string $body, array if (trim($body) === '') { throw new InvalidArgumentException('TaskBoard: a comment cannot be blank.'); } + $this->check($body, TaskConstraints::commentBody(), 'TaskBoard: a comment is too long.'); // @igor-ignore - Call on a stateless bundle service / a Doctrine entity loaded for this call; nothing is kept on the service. return $this->unit(fn (): string => $this->comments->add($task, $user, $body, array_values($mentionIds))->getId(), $task); @@ -249,6 +263,10 @@ public function addLink(UserRef $actor, string $taskId, TaskLinkFormData $data): if (trim($data->url) === '' || mb_strlen($data->url) > TaskConstraints::URL_MAX) { throw new InvalidArgumentException('TaskBoard: a link needs a URL of at most 2048 characters.'); } + // Audit ZD-L1: http(s) only, as the link form (no javascript:, data:, vbscript: … stored for a host template). + $this->check($data->url, TaskConstraints::linkUrl(), 'TaskBoard: a link URL must be an http or https URL.'); + $this->check($data->label, TaskConstraints::linkLabel(), 'TaskBoard: a link label has at most 255 characters.'); + $this->check($data->externalId, TaskConstraints::linkExternalId(), 'TaskBoard: a link external id has at most 128 characters.'); return $this->unit(fn (): string => $this->links->attach($task, $data, $user)->getId(), $task); } @@ -260,6 +278,7 @@ public function addHostObjectLink(UserRef $actor, string $taskId, string $object if (trim($objectType) === '' || trim($objectId) === '') { throw new InvalidArgumentException('TaskBoard: a host object link needs a type and an id.'); } + $this->check($label, TaskConstraints::linkLabel(), 'TaskBoard: a link label has at most 255 characters.'); return $this->unit(function () use ($task, $objectType, $objectId, $user, $label): string { // The task's row locked: two concurrent links of the same object never add two rows. @@ -309,6 +328,7 @@ public function logTime(UserRef $user, string $taskId, int $minutes, DateTimeImm if ($minutes < 1 || $minutes > TaskConstraints::MAX_MINUTES) { throw new InvalidArgumentException('TaskBoard: minutes must be between 1 and 10080.'); } + $this->check($note, TaskConstraints::timeNote(), 'TaskBoard: a time note has at most 512 characters.'); return $this->unit(fn (): string => $this->time->log($task, $actor, $minutes, $loggedAt, $note)->getId(), $task); } @@ -320,6 +340,7 @@ public function addColumn(UserRef $actor, string $boardId, BoardColumnFormData $ if (trim($data->name) === '' || mb_strlen($data->name) > TaskConstraints::COLUMN_NAME_MAX) { throw new InvalidArgumentException('TaskBoard: a column needs a name of 1 to 128 characters.'); } + $this->check($data->color, TaskConstraints::columnColor(), 'TaskBoard: a column colour is a hex colour (#rgb, #rgba, #rrggbb or #rrggbbaa).'); return $this->unit(function () use ($board, $data, $user, $position): string { // @igor-ignore - Call on a stateless bundle service / a Doctrine entity loaded for this call; nothing is kept on the service. @@ -479,13 +500,41 @@ private function lockColumn(?string $columnId): void } /** + * The task form's rules (audit ZD-L1): title, `#rrggbb` colour, at most {@see TaskConstraints::TAGS_MAX} tags of at + * most {@see TaskConstraints::TAG_MAX} characters. + * * @throws InvalidArgumentException */ - private function assertTitle(string $title): void + private function assertTaskData(TaskFormData $data): void { - if (trim($title) === '' || mb_strlen($title) > TaskConstraints::TITLE_MAX) { + if (trim($data->title) === '' || mb_strlen($data->title) > TaskConstraints::TITLE_MAX) { throw new InvalidArgumentException('TaskBoard: a task needs a title of 1 to 255 characters.'); } + $this->check($data->title, TaskConstraints::taskTitle(), 'TaskBoard: a task needs a title of 1 to 255 characters.'); + $this->check($data->color, TaskConstraints::taskColor(), 'TaskBoard: a task colour is #rrggbb.'); + if (count($data->tags) > TaskConstraints::TAGS_MAX) { + throw new InvalidArgumentException('TaskBoard: a task has at most 20 tags.'); + } + foreach ($data->tags as $tag) { + if (!is_string($tag)) { + throw new InvalidArgumentException('TaskBoard: a tag is a string of 1 to 64 characters.'); + } + $this->check($tag, TaskConstraints::tagName(), 'TaskBoard: a tag is a string of 1 to 64 characters.'); + } + } + + /** + * The value against the forms' constraints; any violation is the given refusal. + * + * @param list $constraints + * + * @throws InvalidArgumentException + */ + private function check(mixed $value, array $constraints, string $message): void + { + if ($this->validator->validate($value, $constraints)->count() > 0) { + throw new InvalidArgumentException($message); + } } /** diff --git a/tests/Functional/HostPorts/HostPortsTest.php b/tests/Functional/HostPorts/HostPortsTest.php index 58bfcbbb..a1418993 100644 --- a/tests/Functional/HostPorts/HostPortsTest.php +++ b/tests/Functional/HostPorts/HostPortsTest.php @@ -15,6 +15,7 @@ use Nowo\TaskBoardBundle\Dto\TaskMemberFormData; use Nowo\TaskBoardBundle\Entity\Task; use Nowo\TaskBoardBundle\Entity\TaskBoard; +use Nowo\TaskBoardBundle\Entity\TaskComment; use Nowo\TaskBoardBundle\Entity\TaskTimeEntry; use Nowo\TaskBoardBundle\Enum\TaskDependencyType; use Nowo\TaskBoardBundle\Enum\TaskMemberRole; @@ -43,6 +44,8 @@ use function array_slice; use function count; use function ksort; +use function range; +use function str_repeat; /** * Since 2.29.0 (DDD-host checklist B1 / B7 / B8): the id-based host ports on the functional kernel: a host passes ids and @@ -132,6 +135,7 @@ public function testAnExpectedRevisionThatChangedIsAConflictAndWritesNothing(): self::fail('A stale revision must be refused.'); } catch (TaskChangedException $changed) { self::assertSame($view->revision + 1, $changed->currentRevision); + self::assertSame('CONFLICT_001', $changed::CODE, 'audit ZD-I5: the house conflict code'); } try { $this->commands->moveTask($this->ownerRef, $view->id, null, 0, $view->revision); @@ -272,6 +276,58 @@ public function testInvalidInputIsRefusedBeforeAnyWrite(): void self::assertSame(1, $this->query->countTasks(TaskCriteria::forBoards([$board->getId()]))); } + /** + * Audit ZD-L1: the port applies the forms' TaskConstraints, so a host passing user input cannot store what the forms + * refuse (a `javascript:` link, a colour that leaves `style="…"`, more than 20 tags, over-long texts). + */ + public function testTheFormsConstraintsAreAppliedBeforeAnyWrite(): void + { + $board = $this->board(); + $task = $this->commands->createTask($this->ownerRef, $board->getId(), new TaskFormData('Work', color: '#AABBCC', tags: ['a', 'b'])); + $tags = array_map(static fn (int $i): string => 'tag' . $i, range(1, 21)); + $calls = [ + 'javascript: link' => fn (): string => $this->commands->addLink($this->ownerRef, $task->id, new TaskLinkFormData(url: 'javascript:alert(1)')), + 'data: link' => fn (): string => $this->commands->addLink($this->ownerRef, $task->id, new TaskLinkFormData(url: 'data:text/html,x')), + 'long link label' => fn (): string => $this->commands->addLink($this->ownerRef, $task->id, new TaskLinkFormData(url: 'https://example.com', label: str_repeat('l', 256))), + 'long external id' => fn (): string => $this->commands->addLink($this->ownerRef, $task->id, new TaskLinkFormData(url: 'https://example.com', externalId: str_repeat('e', 129))), + 'colour on create' => fn (): TaskView => $this->commands->createTask($this->ownerRef, $board->getId(), new TaskFormData('Red', color: 'red;')), + 'colour on update' => fn (): TaskView => $this->commands->updateTask($this->ownerRef, $task->id, new TaskFormData('Work', color: '#fff;background:url(x)')), + '21 tags' => fn (): TaskView => $this->commands->updateTask($this->ownerRef, $task->id, new TaskFormData('Work', tags: $tags)), + 'long tag' => fn (): TaskView => $this->commands->createTask($this->ownerRef, $board->getId(), new TaskFormData('Tagged', tags: [str_repeat('t', 65)])), + 'blank tag' => fn (): TaskView => $this->commands->createTask($this->ownerRef, $board->getId(), new TaskFormData('Tagged', tags: [''])), + 'non-string tag' => fn (): TaskView => $this->commands->createTask($this->ownerRef, $board->getId(), new TaskFormData('Tagged', tags: [42])), // @phpstan-ignore argument.type + 'long comment' => fn (): string => $this->commands->addComment($this->ownerRef, $task->id, str_repeat('c', 5001)), + 'long time note' => fn (): string => $this->commands->logTime($this->ownerRef, $task->id, 30, new DateTimeImmutable(), str_repeat('n', 513)), + 'long object label' => fn (): string => $this->commands->addHostObjectLink($this->ownerRef, $task->id, 'invoice', 'INV-9', str_repeat('l', 256)), + 'column colour' => fn (): string => $this->commands->addColumn($this->ownerRef, $board->getId(), new BoardColumnFormData('Doing', color: 'red;')), + ]; + foreach ($calls as $name => $call) { + try { + $call(); + self::fail('"' . $name . '" must be refused.'); + } catch (InvalidArgumentException) { + } + } + + $this->em->clear(); + $loaded = $this->em->find(Task::class, $task->id); + self::assertInstanceOf(Task::class, $loaded); + self::assertCount(0, $loaded->getLinks(), 'no link stored'); + self::assertSame(0, $this->em->getRepository(TaskComment::class)->count(['task' => $task->id]), 'no comment stored'); + self::assertSame('#aabbcc', $loaded->getColor(), 'stored lower-case, unchanged'); + self::assertSame(['a', 'b'], $loaded->getTags()); + self::assertSame(1, $this->query->countTasks(TaskCriteria::forBoards([$board->getId()]))); + + // What the forms accept still passes: 20 tags, an http link, the longest texts. + $this->commands->updateTask($this->ownerRef, $task->id, new TaskFormData('Work', color: '#00ff00', tags: array_slice($tags, 0, 20))); + $this->commands->addLink($this->ownerRef, $task->id, new TaskLinkFormData(url: 'http://intranet/spec', label: str_repeat('l', 255), externalId: str_repeat('e', 128))); + $this->commands->addComment($this->ownerRef, $task->id, str_repeat('c', 5000)); + $this->commands->logTime($this->ownerRef, $task->id, 30, new DateTimeImmutable(), str_repeat('n', 512)); + $this->commands->addColumn($this->ownerRef, $board->getId(), new BoardColumnFormData('Doing', color: '#123')); + $this->em->clear(); + self::assertCount(20, $this->em->find(Task::class, $task->id)?->getTags() ?? []); + } + public function testColumnsAreAddedAtAPositionAndReordered(): void { $board = $this->board('Flow', ['A', 'B']);