From 55539ff5dd519e46a2964156f1abc61d7619e08d Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 00:58:54 +0000 Subject: [PATCH 1/2] test(e2e): REST posts and votes journeys (API-R-001..043, 103, 104) Product-suite specs for /api/v1/posts and the vote routes: list paging and filters, reads behind read:feedback and post.view_private, create with its side effects (auto-vote, author subscription, activity, post.created), admin overrides and import mode, PATCH per-field gates, delete, merge, the scope and Contributor matrices, the vote toggle and proxy votes. Six quarantined tests pin product bugs (QUARANTINE.md, API REST posts and votes). --- apps/web/e2e/QUARANTINE.md | 48 + apps/web/e2e/product/api-rest.ts | 179 ++ .../web/e2e/tests/platform/rest-posts.spec.ts | 1703 +++++++++++++++++ .../web/e2e/tests/platform/rest-votes.spec.ts | 427 +++++ 4 files changed, 2357 insertions(+) create mode 100644 apps/web/e2e/product/api-rest.ts create mode 100644 apps/web/e2e/tests/platform/rest-posts.spec.ts create mode 100644 apps/web/e2e/tests/platform/rest-votes.spec.ts diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 015c373943..301208ba9b 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -257,3 +257,51 @@ owner: unassigned, review by: 2026-12-03 for every entry. when that article has no published French translation. Fix: load related articles for the locale (translated only), or link untranslated ones to the default-language URL. +### Product suite: API REST (posts and votes) +- `platform/rest-posts.spec.ts` › API-R-026 a PATCH with no recognised field + is refused to a key that cannot read posts. Product bug: `PATCH +/api/v1/posts/:id` authenticates with a bare `withApiKeyAuth(request)` and + gates only the fields present (`permissionsForPostPatch`, + `apps/web/src/routes/api/v1/posts/$postId.ts:31-38`, `:117`), so `{}` (or a + body of unknown fields such as `boardId`, which zod strips) checks no + permission and no scope, and `updatePost` returns the whole post. A + `read:chat` key that `GET /posts/:id` refuses reads any post this way. Fix: + refuse a body with no updatable field (400), or require + `post.view_private` (with its scope) on every PATCH. owner: unassigned, + review by: 2026-12-03. +- `platform/rest-posts.spec.ts` › API-R-027 PATCH tags with an unknown tag id + is refused and keeps the post's tags. Product bug: `updatePost` deletes every + tag assignment, then inserts the new set outside a transaction + (`apps/web/src/lib/server/domains/posts/post.service.ts:480-486`); an + unknown tag id (foreign key) or a repeated one (primary key) fails the + insert, the route answers 500 and the post is left with no tags. Fix: check + the tag ids exist (404) and de-duplicate before deleting, and run the + delete and insert in one transaction. owner: unassigned, review by: +- `platform/rest-posts.spec.ts` › API-R-012 an unknown or repeated tag id on + create is refused without leaving a post. Product bug: `createPost` inserts + the tag assignments without looking the tags up + (`apps/web/src/lib/server/domains/posts/post.service.ts:271-276`), so an + unknown tag id or the same id twice answers 500 (no post row is left, the + insert is in the transaction). Fix: load the tags (non-deleted) and + de-duplicate first; answer 404 "Tag not found" for a missing one. owner: + unassigned, review by: 2026-12-03. +- `platform/rest-posts.spec.ts` › API-R-013 a soft-deleted status is not found + on create or update. Product bug: the status lookups in `createPost` and + `updatePost` have no `deletedAt` filter + (`apps/web/src/lib/server/domains/posts/post.service.ts:148`, `:393-394`), + so a post can be put in a deleted status no list shows. Fix: add + `isNull(postStatuses.deletedAt)` to both lookups. owner: unassigned, review + by: 2026-12-03. +- `platform/rest-posts.spec.ts` › API-R-028 a deleted post cannot be edited. + Product bug: `updatePost` never checks `deletedAt` + (`apps/web/src/lib/server/domains/posts/post.service.ts:379-383`), so + `PATCH /api/v1/posts/:id` edits a soft-deleted post and a status change + emails its subscribers. Fix: treat a deleted post as not found, as votes + and comments do. owner: unassigned, review by: 2026-12-03. +- `platform/rest-votes.spec.ts` › API-R-041 a proxy vote for an unknown voter + is a not-found refusal, not a server error. Product bug: `POST +/api/v1/posts/:id/vote/proxy` never looks the voter up + (`apps/web/src/routes/api/v1/posts/$postId.vote.proxy.ts:43-63`); the vote + insert hits the principal foreign key and the route answers 500. Fix: look + the principal up first and answer 404 "User not found". owner: unassigned, + review by: 2026-12-03. diff --git a/apps/web/e2e/product/api-rest.ts b/apps/web/e2e/product/api-rest.ts new file mode 100644 index 0000000000..5f59778647 --- /dev/null +++ b/apps/web/e2e/product/api-rest.ts @@ -0,0 +1,179 @@ +/** + * Helpers for the REST v1 feedback specs (tests/platform/rest-posts.spec.ts, + * rest-votes.spec.ts). + * + * const admin = await keyApi(playwright, baseURL, { creatorEmail, kind: 'workspace' }) + * const board = await newBoard(admin.api, marker) + * const post = await newPost(admin.api, board.id, `${marker} title`) + * + * Every key is made through the app's own service (support/api-client.ts + * createKey) and every request context carries its own client address, so the + * 100-a-minute per-address limit never couples tests. Boards, tags and posts + * are made over REST with an admin key (preconditions); assertions read the + * response, the database rows the product promises, or the webhook sink. + */ +import { expect, type APIRequestContext, type PlaywrightWorkerArgs } from '@playwright/test' +import { fromUuid, toUuid } from '@quackback/ids' +import { apiFor, createKey, expectJson, type KeyOptions, type Wire } from '../support/api-client' +import { pollFor, supportDb } from '../support/db' + +export interface KeyedApi { + api: APIRequestContext + key: string + /** The key's own service principal (TypeID). */ + principalId: string +} + +/** A fresh key and a request context authenticated with it. */ +export async function keyApi( + playwright: PlaywrightWorkerArgs['playwright'], + baseURL: string | undefined, + opts: KeyOptions, + extraHeaders: Record = {} +): Promise { + const { key, principalId } = createKey(opts) + return { api: await apiFor(playwright, baseURL, key, extraHeaders), key, principalId } +} + +/** The error envelope a refusal answers with. */ +export async function expectError( + res: Awaited>, + status: number, + code: string, + message?: string | RegExp +): Promise { + const body = await expectJson(res, status) + expect(body.error.code, JSON.stringify(body)).toBe(code) + if (message !== undefined) { + if (typeof message === 'string') expect(body.error.message).toBe(message) + else expect(body.error.message).toMatch(message) + } + return body +} + +export interface Board { + id: string + slug: string + name: string +} + +/** A public board only this test uses. */ +export async function newBoard(api: APIRequestContext, marker: string): Promise { + const body = await expectJson( + await api.post('/api/v1/boards', { data: { name: `Board ${marker}`.slice(0, 100) } }), + 201 + ) + return body.data as Board +} + +/** A tag only this test uses. */ +export async function newTag( + api: APIRequestContext, + name: string +): Promise<{ id: string; name: string }> { + const body = await expectJson( + await api.post('/api/v1/tags', { data: { name: name.slice(0, 50) } }), + 201 + ) + return body.data +} + +/** Create a post over REST and return its response body's data. */ +export async function newPost( + api: APIRequestContext, + boardId: string, + title: string, + extra: Record = {} +): Promise { + const body = await expectJson( + await api.post('/api/v1/posts', { data: { boardId, title, content: 'Body', ...extra } }), + 201 + ) + return body.data +} + +/** A post status TypeID by slug (seeded statuses: open, under_review, planned, in_progress, complete, closed). */ +export async function statusIdBySlug(slug: string): Promise { + const [row] = + await supportDb()`SELECT id FROM post_statuses WHERE slug = ${slug} AND deleted_at IS NULL LIMIT 1` + if (!row) throw new Error(`No status ${slug}`) + return fromUuid('post_status', row.id as string) +} + +export function uuid(typeId: string): string { + return toUuid(typeId as `post_${string}`) +} + +/** The post row (snake_case columns). */ +export async function postRow(postId: string): Promise { + const [row] = await supportDb()`SELECT * FROM posts WHERE id = ${uuid(postId)}` + return row ?? null +} + +/** Tag ids on a post (TypeIDs). */ +export async function postTagIds(postId: string): Promise { + const rows = + await supportDb()`SELECT tag_id FROM post_tag_assignments WHERE post_id = ${uuid(postId)}` + return rows.map((r) => fromUuid('post_tag', r.tag_id as string)).sort() +} + +export interface ActivityRow { + type: string + principal_id: string | null + metadata: Wire +} + +/** Activity rows of a post, oldest first. */ +export async function activityOf(postId: string, type?: string): Promise { + const rows = (await supportDb()` + SELECT type, principal_id, metadata FROM post_activity + WHERE post_id = ${uuid(postId)} ORDER BY created_at, id`) as unknown as ActivityRow[] + return type ? rows.filter((r) => r.type === type) : rows +} + +/** Wait for an activity row of `type` (createActivity is fire-and-forget). */ +export function waitForActivity(postId: string, type: string): Promise { + return pollFor(`${type} activity on ${postId}`, async () => { + const rows = await activityOf(postId, type) + return rows.length > 0 ? rows : null + }) +} + +/** Votes on a post: principal TypeID, source and who added it. */ +export async function votesOf(postId: string): Promise< + Array<{ + principalId: string + sourceType: string | null + addedBy: string | null + createdAt: Date + }> +> { + const rows = await supportDb()` + SELECT principal_id, source_type, added_by_principal_id, created_at FROM post_votes + WHERE post_id = ${uuid(postId)}` + return rows.map((r) => ({ + principalId: fromUuid('principal', r.principal_id as string), + sourceType: (r.source_type as string | null) ?? null, + addedBy: r.added_by_principal_id + ? fromUuid('principal', r.added_by_principal_id as string) + : null, + createdAt: r.created_at as Date, + })) +} + +/** Subscriptions on a post: principal TypeID to reason. */ +export async function subscriptionsOf(postId: string): Promise> { + const rows = await supportDb()` + SELECT principal_id, reason FROM post_subscriptions WHERE post_id = ${uuid(postId)}` + return Object.fromEntries( + rows.map((r) => [fromUuid('principal', r.principal_id as string), r.reason as string]) + ) +} + +/** A post's in-app notifications (bells) for a principal, by type. */ +export async function bellsFor(principalId: string, postId: string): Promise { + const rows = await supportDb()` + SELECT type FROM in_app_notifications + WHERE principal_id = ${uuid(principalId)} AND post_id = ${uuid(postId)}` + return rows.map((r) => r.type as string) +} diff --git a/apps/web/e2e/tests/platform/rest-posts.spec.ts b/apps/web/e2e/tests/platform/rest-posts.spec.ts new file mode 100644 index 0000000000..031146e9a9 --- /dev/null +++ b/apps/web/e2e/tests/platform/rest-posts.spec.ts @@ -0,0 +1,1703 @@ +/** + * REST v1 posts: list, read, create, edit, delete, merge, and the scope and + * permission matrices on the feedback routes. + * + * Journeys: API-R-001..API-R-014, API-R-016, API-R-018, API-R-020..API-R-029, + * API-R-031..API-R-034, API-R-103, API-R-104. Not pinned (owner questions): + * API-R-015 (author override follows role admin, not post.set_author), + * API-R-019 (plan-cap 402 body), and the default-status half of API-R-010. + * API-R-017 (a required custom field blocks every REST post) is listed for the + * owner, and API-R-030 (post move) waits for #791. + * + * Every test makes its own board (so lists are filtered to rows it owns), its + * own keys and its own customers. Webhooks are deleted in `finally` (the + * 25-webhook cap is workspace-wide). + */ +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { expectJson, newTeammate, seedCustomer } from '../../support/api-client' +import { deliveriesOf, bodyOf, subscribe, unsubscribe, type Hook } from '../../support/webhooks' +import { sink } from '../../support/webhook-sink-client' +import { waitForMail } from '../../support/mailpit' +import { pollFor, supportDb } from '../../support/db' +import { + activityOf, + bellsFor, + expectError, + keyApi, + newBoard, + newPost, + newTag, + postRow, + postTagIds, + statusIdBySlug, + subscriptionsOf, + uuid, + votesOf, + waitForActivity, +} from '../../product/api-rest' + +// Key and teammate scripts start the app's modules (about a second each). +test.describe.configure({ timeout: 60_000 }) + +const LIST_ITEM_KEYS = [ + 'authorName', + 'boardId', + 'boardName', + 'boardSlug', + 'canonicalPostId', + 'commentCount', + 'content', + 'createdAt', + 'deletedAt', + 'id', + 'isCommentsLocked', + 'mergedAt', + 'ownerId', + 'statusId', + 'summaryJson', + 'tags', + 'title', + 'updatedAt', + 'voteCount', +] + +test.describe('REST posts: list and read', () => { + test( + 'API-R-001 list posts answers the documented shape, newest first, with cursor paging', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const first = await newPost(admin.api, board.id, `${marker} first`) + const second = await newPost(admin.api, board.id, `${marker} second`) + const third = await newPost(admin.api, board.id, `${marker} third`) + + const page1 = await expectJson( + await admin.api.get(`/api/v1/posts?boardId=${board.id}&limit=2`), + 200 + ) + expect(page1.data.map((p: { id: string }) => p.id)).toEqual([third.id, second.id]) + expect(page1.meta.pagination).toEqual({ cursor: expect.any(String), hasMore: true }) + expect(Object.keys(page1.data[0]).sort()).toEqual(LIST_ITEM_KEYS) + expect(page1.data[0]).toMatchObject({ + title: `${marker} third`, + content: 'Body', + voteCount: 1, + commentCount: 0, + boardId: board.id, + boardSlug: board.slug, + boardName: board.name, + tags: [], + canonicalPostId: null, + mergedAt: null, + isCommentsLocked: false, + deletedAt: null, + }) + + const page2 = await expectJson( + await admin.api.get( + `/api/v1/posts?boardId=${board.id}&limit=2&cursor=${page1.meta.pagination.cursor}` + ), + 200 + ) + expect(page2.data.map((p: { id: string }) => p.id)).toEqual([first.id]) + expect(page2.meta.pagination.hasMore).toBe(false) + + // limit is clamped to at least 1; a non-numeric limit means 20. + const one = await expectJson( + await admin.api.get(`/api/v1/posts?boardId=${board.id}&limit=-5`), + 200 + ) + expect(one.data).toHaveLength(1) + expect(one.meta.pagination.hasMore).toBe(true) + const all = await expectJson( + await admin.api.get(`/api/v1/posts?boardId=${board.id}&limit=abc`), + 200 + ) + expect(all.data).toHaveLength(3) + await admin.api.dispose() + } + ) + + test( + 'API-R-004 post reads need read:feedback and post.view_private', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} post`) + const comment = ( + await expectJson( + await admin.api.post(`/api/v1/posts/${post.id}/comments`, { + data: { content: `${marker} comment` }, + }), + 201 + ) + ).data + const paths = [ + '/api/v1/posts', + `/api/v1/posts/${post.id}`, + `/api/v1/posts/${post.id}/comments`, + `/api/v1/posts/${post.id}/activity`, + `/api/v1/posts/${post.id}/voters`, + `/api/v1/comments/${comment.id}`, + ] + + for (const scopes of [['read:chat'], ['write:changelog']]) { + const k = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + scopes, + }) + for (const path of paths) { + await expectError( + await k.api.get(path), + 403, + 'FORBIDDEN', + "This API key is missing the 'read:feedback' scope required by 'post.view_private'" + ) + } + await k.api.dispose() + } + + // A creator without post.view_private: the permission is checked first. + const mate = newTeammate(`Reader ${marker}`, ['member.view']) + const narrow = await keyApi(playwright, baseURL, { + creatorEmail: mate.email, + scopes: ['read:feedback'], + }) + for (const path of paths) { + await expectError( + await narrow.api.get(path), + 403, + 'FORBIDDEN', + "Requires the 'post.view_private' permission" + ) + } + + // Positive control: write:feedback implies read. + const writer = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + scopes: ['write:feedback'], + }) + for (const path of paths) { + const res = await writer.api.get(path) + expect(res.status(), `${path}: ${await res.text()}`).toBe(200) + } + for (const k of [admin, narrow, writer]) await k.api.dispose() + } + ) +}) + +test.describe('REST posts: create', () => { + test( + 'API-R-009 creating a post answers 201, auto-votes, subscribes the author and announces it', + { tag: '@smoke' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + name: `Key ${marker}`, + }) + const board = await newBoard(admin.api, marker) + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.created']) + const res = await admin.api.post('/api/v1/posts', { + data: { boardId: board.id, title: `${marker} created`, content: 'Some **markdown**' }, + }) + const { data } = await expectJson(res, 201) + expect(Object.keys(data).sort()).toEqual([ + 'authorName', + 'boardId', + 'content', + 'createdAt', + 'id', + 'statusId', + 'title', + 'updatedAt', + 'voteCount', + ]) + expect(data).toMatchObject({ + title: `${marker} created`, + content: 'Some **markdown**', + voteCount: 1, + boardId: board.id, + // The key itself is the author. + authorName: `Key ${marker}`, + }) + expect(data.id).toMatch(/^post_/) + + // The author (the key's principal) auto-votes and is subscribed. + const votes = await votesOf(data.id) + expect(votes.map((v) => v.principalId)).toEqual([admin.principalId]) + expect(await subscriptionsOf(data.id)).toEqual({ [admin.principalId]: 'author' }) + + const [created] = await waitForActivity(data.id, 'post.created') + expect(created.metadata).toMatchObject({ boardName: board.name }) + + const [delivery] = await deliveriesOf(marker, 'post.created', data.id) + const event = bodyOf<{ post: Record }>(delivery) + expect(event.type).toBe('post.created') + expect(event.data.post).toMatchObject({ + id: data.id, + title: `${marker} created`, + boardSlug: board.slug, + authorName: `Key ${marker}`, + voteCount: 1, + }) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + } + } + ) + + test( + 'API-R-010 a post created without statusId lands in the open status', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + // The contested half (open slug versus a different workspace default) is + // an owner question and needs a workspace flip; this pins only the part + // both rules agree on in a workspace whose default is "open". + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} no status`) + expect(post.statusId).toBe(await statusIdBySlug('open')) + const planned = await statusIdBySlug('planned') + const explicit = await newPost(admin.api, board.id, `${marker} planned`, { + statusId: planned, + }) + expect(explicit.statusId).toBe(planned) + await admin.api.dispose() + } + ) + + test( + 'API-R-011 create post validation and not-found refusals', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const { api } = admin + const board = await newBoard(api, marker) + const post = (data: Record) => api.post('/api/v1/posts', { data }) + + const empty = await expectError(await post({}), 400, 'BAD_REQUEST', 'Invalid request body') + expect(Object.keys(empty.error.details.errors).sort()).toEqual(['boardId', 'title']) + const blank = await expectError( + await post({ boardId: board.id, title: '' }), + 400, + 'BAD_REQUEST' + ) + expect(blank.error.details.errors.title).toBeTruthy() + + await expectError( + await post({ boardId: board.id, title: 'x'.repeat(201) }), + 400, + 'BAD_REQUEST' + ) + const exactly200 = await expectJson( + await post({ boardId: board.id, title: `${marker}`.padEnd(200, 'x') }), + 201 + ) + expect(exactly200.data.title).toHaveLength(200) + await expectError( + await post({ boardId: board.id, title: `${marker} long`, content: 'y'.repeat(10_001) }), + 400, + 'BAD_REQUEST' + ) + + await expectError( + await post({ boardId: 'nope', title: marker }), + 400, + 'VALIDATION_ERROR', + 'Invalid board ID format' + ) + await expectError( + await post({ boardId: board.id, title: marker, statusId: 'nope' }), + 400, + 'VALIDATION_ERROR', + 'Invalid status ID format' + ) + await expectError( + await post({ boardId: board.id, title: marker, tagIds: ['nope'] }), + 400, + 'VALIDATION_ERROR', + 'Invalid tag IDs format' + ) + await expectError( + await post({ boardId: generateId('board'), title: marker }), + 404, + 'NOT_FOUND', + 'Board not found' + ) + await expectError( + await post({ boardId: board.id, title: marker, statusId: generateId('post_status') }), + 404, + 'NOT_FOUND', + 'Status not found' + ) + await expectError( + await post({ boardId: board.id, title: ' ' }), + 400, + 'VALIDATION_ERROR', + 'Title is required' + ) + + // A soft-deleted board is not found either. + const gone = await newBoard(api, `${marker}-gone`) + expect((await api.delete(`/api/v1/boards/${gone.id}`)).status()).toBe(204) + await expectError( + await post({ boardId: gone.id, title: marker }), + 404, + 'NOT_FOUND', + 'Board not found' + ) + await api.dispose() + } + ) + + test( + 'API-R-014 an admin key posts on behalf of a customer, backdated', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + // An admin's personal key holds the admin role (a workspace key on the + // Admin preset is role member; only Owner maps to admin). + const admin = await keyApi(playwright, baseURL, { creatorEmail: people.people.admin.email }) + const board = await newBoard(admin.api, marker) + const email = `${marker}@customers.example` + const customer = await seedCustomer(email, `Customer ${marker}`) + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.created']) + const post = await newPost(admin.api, board.id, `${marker} on behalf`, { + authorPrincipalId: customer.principalId, + createdAt: '2024-01-02T00:00:00Z', + }) + expect(post.authorName).toBe(`Customer ${marker}`) + expect(post.createdAt).toBe('2024-01-02T00:00:00.000Z') + expect((await postRow(post.id)).principal_id).toBe(uuid(customer.principalId)) + expect((await votesOf(post.id)).map((v) => v.principalId)).toEqual([customer.principalId]) + expect(await subscriptionsOf(post.id)).toEqual({ [customer.principalId]: 'author' }) + + const [delivery] = await deliveriesOf(marker, 'post.created', post.id) + expect(bodyOf<{ post: Record }>(delivery).data.post).toMatchObject({ + authorName: `Customer ${marker}`, + authorEmail: email, + }) + + await expectError( + await admin.api.post('/api/v1/posts', { + data: { + boardId: board.id, + title: marker, + authorPrincipalId: generateId('principal'), + }, + }), + 404, + 'NOT_FOUND', + 'User not found' + ) + await expectError( + await admin.api.post('/api/v1/posts', { + data: { boardId: board.id, title: marker, authorPrincipalId: admin.principalId }, + }), + 400, + 'VALIDATION_ERROR', + 'authorPrincipalId may not reference a service principal' + ) + await expectError( + await admin.api.post('/api/v1/posts', { + data: { boardId: board.id, title: marker, authorPrincipalId: 'bad' }, + }), + 400, + 'VALIDATION_ERROR', + 'Invalid authorPrincipalId format' + ) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + } + } + ) + + test( + 'API-R-016 a read-only board refuses new posts until it is reopened', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + await expectJson( + await admin.api.patch(`/api/v1/boards/${board.id}`, { data: { readOnly: true } }), + 200 + ) + await expectError( + await admin.api.post('/api/v1/posts', { + data: { boardId: board.id, title: `${marker} refused` }, + }), + 403, + 'FORBIDDEN', + "This board isn't taking new feedback right now." + ) + const [{ n }] = await supportDb()` + SELECT count(*)::int AS n FROM posts WHERE board_id = ${uuid(board.id)}` + expect(n).toBe(0) + + await expectJson( + await admin.api.patch(`/api/v1/boards/${board.id}`, { data: { readOnly: false } }), + 200 + ) + await newPost(admin.api, board.id, `${marker} accepted`) + await admin.api.dispose() + } + ) + + test( + 'API-R-018 import mode skips subscriptions, activity and webhooks for an admin key only', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + // An admin's personal key holds the admin role; the manager key is role member. + const admin = await keyApi( + playwright, + baseURL, + { creatorEmail: people.people.admin.email }, + { 'x-import-mode': 'true' } + ) + const member = await keyApi( + playwright, + baseURL, + { creatorEmail: people.people.admin.email, kind: 'workspace', roleKey: 'manager' }, + { 'x-import-mode': 'true' } + ) + const board = await newBoard(admin.api, marker) + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.created']) + const imported = await newPost(admin.api, board.id, `${marker} imported`) + const live = await newPost(member.api, board.id, `${marker} member`) + + // The member key's import header is ignored: everything fires. Its + // delivery is the control that the imported post's would have arrived. + await deliveriesOf(marker, 'post.created', live.id) + await waitForActivity(live.id, 'post.created') + expect(await subscriptionsOf(live.id)).toEqual({ [member.principalId]: 'author' }) + + expect((await votesOf(imported.id)).map((v) => v.principalId)).toEqual([admin.principalId]) + expect(await subscriptionsOf(imported.id)).toEqual({}) + expect(await activityOf(imported.id, 'post.created')).toEqual([]) + const all = await sink.deliveries(marker) + expect(all.filter((d) => d.body.includes(imported.id))).toEqual([]) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + await member.api.dispose() + } + } + ) +}) + +test.describe('REST posts: update, delete, merge', () => { + test( + "API-R-022 changing a post's status notifies its subscribers once", + { tag: '@smoke' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const email = `${marker}@customers.example` + const customer = await seedCustomer(email, `Customer ${marker}`) + const inProgress = await statusIdBySlug('in_progress') + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.status_changed']) + const post = await newPost(admin.api, board.id, `${marker} status`) + // The customer votes through the key, which subscribes them. + await expectJson( + await admin.api.post(`/api/v1/posts/${post.id}/vote/proxy`, { + data: { voterPrincipalId: customer.principalId }, + }), + 200 + ) + + const patched = await expectJson( + await admin.api.patch(`/api/v1/posts/${post.id}`, { data: { statusId: inProgress } }), + 200 + ) + expect(patched.data.statusId).toBe(inProgress) + + const [delivery] = await deliveriesOf(marker, 'post.status_changed', post.id) + expect(bodyOf(delivery).data).toMatchObject({ + previousStatus: 'Open', + newStatus: 'In Progress', + }) + const [changed] = await waitForActivity(post.id, 'status.changed') + expect(changed.metadata).toMatchObject({ + fromName: 'Open', + toName: 'In Progress', + toSlug: 'in_progress', + }) + const mail = await waitForMail({ to: email, subject: 'In Progress' }) + expect(mail.Subject).toBe('Your feedback is now In Progress!') + await pollFor('status bell', async () => + (await bellsFor(customer.principalId, post.id)).includes('post_status_changed') + ? true + : null + ) + // The key's own principal is never notified. + expect(await bellsFor(admin.principalId, post.id)).toEqual([]) + + // The same status again is a no-op; a later change is the control. + await expectJson( + await admin.api.patch(`/api/v1/posts/${post.id}`, { data: { statusId: inProgress } }), + 200 + ) + await expectJson( + await admin.api.patch(`/api/v1/posts/${post.id}`, { + data: { statusId: await statusIdBySlug('complete') }, + }), + 200 + ) + await pollFor('second status change', async () => + (await activityOf(post.id, 'status.changed')).length >= 2 ? true : null + ) + const changes = await activityOf(post.id, 'status.changed') + expect(changes.map((c) => c.metadata.toSlug)).toEqual(['in_progress', 'complete']) + const deliveries = await deliveriesOf(marker, 'post.status_changed', post.id, { + count: 2, + }) + expect(deliveries).toHaveLength(2) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + } + } + ) + + test( + 'API-R-025 PATCH checks the permission and scope of every field it carries', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} original`) + const patch = (k: { api: typeof admin.api }, data: Record) => + k.api.patch(`/api/v1/posts/${post.id}`, { data }) + + // (a) Contributor: no post.edit, but status, tags and owner are allowed. + const contributor = await keyApi(playwright, baseURL, { + creatorEmail: people.people.contributor.email, + scopes: ['write:feedback'], + }) + await expectError( + await patch(contributor, { title: `${marker} contributor` }), + 403, + 'FORBIDDEN', + "Requires the 'post.edit' permission" + ) + await expectJson( + await patch(contributor, { + statusId: await statusIdBySlug('planned'), + tagIds: [], + ownerPrincipalId: people.people.admin.principalId, + }), + 200 + ) + + // (b) post.edit without post.set_status: refused before anything is written. + const mate = newTeammate(`Editor ${marker}`, ['post.view_private', 'post.edit']) + const editor = await keyApi(playwright, baseURL, { + creatorEmail: mate.email, + scopes: ['write:feedback'], + }) + await expectError( + await patch(editor, { + title: `${marker} changed`, + statusId: await statusIdBySlug('complete'), + }), + 403, + 'FORBIDDEN', + "Requires the 'post.set_status' permission" + ) + expect((await postRow(post.id)).title).toBe(`${marker} original`) + await expectJson(await patch(editor, { title: `${marker} edited` }), 200) + + // (c) read-only scope on a write field. + const reader = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + scopes: ['read:feedback'], + }) + await expectError( + await patch(reader, { tagIds: [] }), + 403, + 'FORBIDDEN', + "This API key is missing the 'write:feedback' scope required by 'post.set_tags'" + ) + for (const k of [admin, contributor, editor, reader]) await k.api.dispose() + } + ) + + test( + 'API-R-026 a PATCH with no recognised field is refused to a key that cannot read posts', + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'PATCH /posts/:id with {} checks no permission or scope and returns the post ' + + '(apps/web/src/routes/api/v1/posts/$postId.ts:117, permissionsForPostPatch :31-38)', + }, + }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} secret`) + const chat = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + scopes: ['read:chat'], + }) + // Control: the same key is refused the read. + await expectError(await chat.api.get(`/api/v1/posts/${post.id}`), 403, 'FORBIDDEN') + + for (const data of [{}, { boardId: generateId('board') }]) { + const res = await chat.api.patch(`/api/v1/posts/${post.id}`, { data }) + const text = await res.text() + expect(res.status(), text).toBeGreaterThanOrEqual(400) + expect(text).not.toContain(`${marker} secret`) + } + await admin.api.dispose() + await chat.api.dispose() + } + ) + + test( + "API-R-027 PATCH tags with an unknown tag id is refused and keeps the post's tags", + { + tag: ['@core', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'updatePost deletes every tag assignment, then the insert of an unknown or repeated ' + + 'tag id fails outside a transaction: 500 and the post loses its tags ' + + '(apps/web/src/lib/server/domains/posts/post.service.ts:480-486)', + }, + }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const a = await newTag(admin.api, `${marker}-a`) + const b = await newTag(admin.api, `${marker}-b`) + const post = await newPost(admin.api, board.id, `${marker} tagged`, { tagIds: [a.id, b.id] }) + const before = [a.id, b.id].sort() + expect(await postTagIds(post.id)).toEqual(before) + + for (const tagIds of [ + [a.id, generateId('post_tag')], + [a.id, a.id], + ]) { + const res = await admin.api.patch(`/api/v1/posts/${post.id}`, { data: { tagIds } }) + const text = await res.text() + expect([400, 404], text).toContain(res.status()) + expect(await postTagIds(post.id)).toEqual(before) + } + await admin.api.dispose() + } + ) + + test( + 'API-R-031 deleting a post soft-deletes it, announces it and recounts the canonical post', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const canonical = await newPost(admin.api, board.id, `${marker} canonical`) + const dup = await newPost(admin.api, board.id, `${marker} duplicate`) + const customer = await seedCustomer(`${marker}@customers.example`) + await expectJson( + await admin.api.post(`/api/v1/posts/${dup.id}/vote/proxy`, { + data: { voterPrincipalId: customer.principalId }, + }), + 200 + ) + const merged = await expectJson( + await admin.api.post(`/api/v1/posts/${dup.id}/merge`, { + data: { canonicalPostId: canonical.id }, + }), + 200 + ) + // The key's own vote is shared; the customer's adds one. + expect(merged.data.canonicalPost.voteCount).toBe(2) + + const contributor = await keyApi(playwright, baseURL, { + creatorEmail: people.people.contributor.email, + scopes: ['write:feedback'], + }) + await expectError( + await contributor.api.delete(`/api/v1/posts/${dup.id}`), + 403, + 'FORBIDDEN', + "Requires the 'post.delete' permission" + ) + + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.deleted']) + const res = await admin.api.delete(`/api/v1/posts/${dup.id}`) + expect(res.status()).toBe(204) + expect(await res.text()).toBe('') + + const row = await postRow(dup.id) + expect(row.deleted_at).not.toBeNull() + expect(row.deleted_by_principal_id).toBe(uuid(admin.principalId)) + await waitForActivity(dup.id, 'post.deleted') + const [delivery] = await deliveriesOf(marker, 'post.deleted', dup.id) + expect(bodyOf<{ post: Record }>(delivery).data.post).toMatchObject({ + id: dup.id, + boardSlug: board.slug, + }) + + const canon = await expectJson(await admin.api.get(`/api/v1/posts/${canonical.id}`), 200) + expect(canon.data.voteCount).toBe(1) + + const got = await expectJson(await admin.api.get(`/api/v1/posts/${dup.id}`), 200) + expect(got.data.deletedAt).toEqual(expect.any(String)) + + // A deleted (unmerged) post leaves the list; showDeleted lists it. + const plain = await newPost(admin.api, board.id, `${marker} plain`) + expect((await admin.api.delete(`/api/v1/posts/${plain.id}`)).status()).toBe(204) + const list = await expectJson(await admin.api.get(`/api/v1/posts?boardId=${board.id}`), 200) + expect(list.data.map((p: { id: string }) => p.id)).toEqual([canonical.id]) + const withDeleted = await expectJson( + await admin.api.get(`/api/v1/posts?boardId=${board.id}&showDeleted=true`), + 200 + ) + const deleted = withDeleted.data.find((p: { id: string }) => p.id === plain.id) + expect(deleted?.deletedAt).toEqual(expect.any(String)) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + await contributor.api.dispose() + } + } + ) + + test( + 'API-R-033 merging a duplicate counts a shared voter once and lists the duplicate', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const canonical = await newPost(admin.api, board.id, `${marker} canonical`) + const dup = await newPost(admin.api, board.id, `${marker} duplicate`) + const onlyDup = await seedCustomer(`${marker}-d@customers.example`) + const onlyCanon = await seedCustomer(`${marker}-c@customers.example`) + const proxy = (postId: string, voterPrincipalId: string) => + admin.api.post(`/api/v1/posts/${postId}/vote/proxy`, { data: { voterPrincipalId } }) + await expectJson(await proxy(dup.id, onlyDup.principalId), 200) + await expectJson(await proxy(canonical.id, onlyCanon.principalId), 200) + + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.merged']) + const merged = await expectJson( + await admin.api.post(`/api/v1/posts/${dup.id}/merge`, { + data: { canonicalPostId: canonical.id }, + }), + 200 + ) + // The key voted on both (as author): counted once. Plus one customer each. + expect(merged.data).toEqual({ + canonicalPost: { id: canonical.id, voteCount: 3 }, + duplicatePost: { id: dup.id }, + }) + + const row = await postRow(dup.id) + expect(row.canonical_post_id).toBe(uuid(canonical.id)) + expect(row.merged_at).not.toBeNull() + expect(row.merged_by_principal_id).toBe(uuid(admin.principalId)) + + const [mergedIn] = await waitForActivity(canonical.id, 'post.merged_in') + expect(JSON.stringify(mergedIn.metadata)).toContain(`${marker} duplicate`) + await waitForActivity(dup.id, 'post.merged_away') + + const [delivery] = await deliveriesOf(marker, 'post.merged', dup.id) + expect(delivery.body).toContain(canonical.id) + + const canon = await expectJson(await admin.api.get(`/api/v1/posts/${canonical.id}`), 200) + expect(canon.data.mergedPosts).toEqual([ + expect.objectContaining({ id: dup.id, title: `${marker} duplicate` }), + ]) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + } + } + ) +}) + +test.describe('REST posts: key matrices', () => { + // One test per scope set, so no test waits on many key scripts. GET + // /boards (a bare read any key passes) is left out: whether it should need + // read:feedback is an owner question. + const ALLOWED = { listPosts: 200, createPost: 201, vote: 200, pending: 200, createTag: 201 } + const REFUSED = { listPosts: 403, createPost: 403, vote: 403, pending: 403, createTag: 403 } + const SCOPE_MATRIX: Array<[string, string[] | null, Record, string]> = [ + [ + 'read:feedback', + ['read:feedback'], + { ...REFUSED, listPosts: 200 }, + "This API key is missing the 'write:feedback' scope required by 'post.create'", + ], + ['write:feedback', ['write:feedback'], ALLOWED, ''], + [ + 'write:changelog', + ['write:changelog'], + REFUSED, + "This API key is missing the 'write:feedback' scope required by 'post.create'", + ], + [ + 'read:chat', + ['read:chat'], + REFUSED, + "This API key is missing the 'write:feedback' scope required by 'post.create'", + ], + ['legacy NULL scopes', null, ALLOWED, ''], + ] + for (const [label, scopes, expected, createRefusal] of SCOPE_MATRIX) { + test( + `API-R-103 a ${label} key on the feedback routes`, + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const target = await newPost(admin.api, board.id, `${marker} target`) + const k = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + ...(scopes ? { scopes } : { legacy: true }), + }) + const create = await k.api.post('/api/v1/posts', { + data: { boardId: board.id, title: `${marker} by key` }, + }) + const createBody = await create.text() + const out = { + listPosts: (await k.api.get(`/api/v1/posts?boardId=${board.id}`)).status(), + createPost: create.status(), + vote: (await k.api.post(`/api/v1/posts/${target.id}/vote`)).status(), + pending: (await k.api.get('/api/v1/moderation/pending')).status(), + createTag: ( + await k.api.post('/api/v1/tags', { data: { name: `${marker}-tag`.slice(0, 50) } }) + ).status(), + } + expect(out).toEqual(expected) + // The refusal names the scope and the permission. + if (createRefusal) expect(JSON.parse(createBody).error.message).toBe(createRefusal) + await k.api.dispose() + await admin.api.dispose() + } + ) + } + + test( + "API-R-104 a Contributor's key reaches the writes its role grants and no others", + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const customer = await seedCustomer(`${marker}@customers.example`) + const c = await keyApi(playwright, baseURL, { + creatorEmail: people.people.contributor.email, + scopes: ['write:feedback'], + }) + const { api } = c + + // Allowed. + const post = ( + await expectJson( + await api.post('/api/v1/posts', { data: { boardId: board.id, title: `${marker} c` } }), + 201 + ) + ).data + const other = await newPost(admin.api, board.id, `${marker} other`) + await expectJson( + await api.patch(`/api/v1/posts/${post.id}`, { + data: { + statusId: await statusIdBySlug('planned'), + tagIds: [], + ownerPrincipalId: people.people.contributor.principalId, + }, + }), + 200 + ) + await expectJson(await api.post(`/api/v1/posts/${other.id}/vote`), 200) + await expectJson( + await api.post(`/api/v1/posts/${other.id}/vote/proxy`, { + data: { voterPrincipalId: customer.principalId }, + }), + 200 + ) + const comment = ( + await expectJson( + await api.post(`/api/v1/posts/${post.id}/comments`, { data: { content: marker } }), + 201 + ) + ).data + await expectJson( + await api.post(`/api/v1/posts/${other.id}/merge`, { data: { canonicalPostId: post.id } }), + 200 + ) + + // Refused, each naming its permission. + const refusals: Array<[string, Promise>>]> = [ + ['post.edit', api.patch(`/api/v1/posts/${post.id}`, { data: { title: 'x' } })], + ['post.delete', api.delete(`/api/v1/posts/${post.id}`)], + ['comment.edit', api.patch(`/api/v1/comments/${comment.id}`, { data: { content: 'x' } })], + ['comment.edit', api.delete(`/api/v1/comments/${comment.id}`)], + ['board.manage', api.post('/api/v1/boards', { data: { name: `${marker} b` } })], + ['board.manage', api.patch(`/api/v1/boards/${board.id}`, { data: { name: 'x' } })], + [ + 'status.manage', + api.post('/api/v1/statuses', { + data: { + name: 'x', + slug: `${marker}`.slice(0, 40).replace(/-/g, '_'), + color: '#000000', + category: 'active', + }, + }), + ], + ['tag.manage', api.post('/api/v1/tags', { data: { name: `${marker}-t`.slice(0, 50) } })], + ['roadmap.manage', api.post('/api/v1/roadmaps', { data: { name: `${marker} r` } })], + ] + for (const [perm, pending] of refusals) { + await expectError(await pending, 403, 'FORBIDDEN', `Requires the '${perm}' permission`) + } + await admin.api.dispose() + await api.dispose() + } + ) +}) + +test.describe('REST posts: nightly', () => { + test( + 'API-R-002 list filters: board, status slug, tags, search, dates, sort, deleted', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const { api } = admin + const board = await newBoard(api, marker) + const tagA = await newTag(api, `${marker}-a`) + const tagB = await newTag(api, `${marker}-b`) + const planned = await statusIdBySlug('planned') + const old = await newPost(api, board.id, `${marker} old zebra`, { tagIds: [tagA.id] }) + const mid = await newPost(api, board.id, `${marker} mid`, { + statusId: planned, + tagIds: [tagB.id], + }) + const top = await newPost(api, board.id, `${marker} top`) + const gone = await newPost(api, board.id, `${marker} gone`) + expect((await api.delete(`/api/v1/posts/${gone.id}`)).status()).toBe(204) + // Spread the dates: old is two days back, mid yesterday. + await supportDb()`UPDATE posts SET created_at = NOW() - interval '2 days' WHERE id = ${uuid(old.id)}` + await supportDb()`UPDATE posts SET created_at = NOW() - interval '1 day' WHERE id = ${uuid(mid.id)}` + // top gets a second vote so sort=votes puts it first. + const c = await seedCustomer(`${marker}@customers.example`) + await expectJson( + await api.post(`/api/v1/posts/${top.id}/vote/proxy`, { + data: { voterPrincipalId: c.principalId }, + }), + 200 + ) + const ids = async (q: string) => + (await expectJson(await api.get(`/api/v1/posts?boardId=${board.id}&${q}`), 200)).data.map( + (p: { id: string }) => p.id + ) + const day = (offset: number) => + new Date(Date.now() - offset * 86_400_000).toISOString().slice(0, 10) + + expect(await ids('')).toEqual([top.id, mid.id, old.id]) + expect(await ids('status=planned')).toEqual([mid.id]) + expect(await ids(`tagIds=${tagA.id},${tagB.id}`)).toEqual([mid.id, old.id]) + expect(await ids('search=zebra')).toEqual([old.id]) + expect(await ids(`dateTo=${day(2)}`)).toEqual([old.id]) + expect(await ids(`dateFrom=${day(1)}T00:00:00Z`)).toEqual([top.id, mid.id]) + expect(await ids('sort=oldest')).toEqual([old.id, mid.id, top.id]) + expect((await ids('sort=votes'))[0]).toBe(top.id) + expect(await ids('showDeleted=true')).toEqual([gone.id]) + await api.dispose() + } + ) + + test( + 'API-R-003 malformed list filters are dropped, not refused', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const { api } = admin + const board = await newBoard(api, marker) + const tag = await newTag(api, `${marker}-t`) + const tagged = await newPost(api, board.id, `${marker} tagged`, { tagIds: [tag.id] }) + const plain = await newPost(api, board.id, `${marker} plain`) + const ids = async (q: string) => + (await expectJson(await api.get(`/api/v1/posts?${q}`), 200)).data.map( + (p: { id: string }) => p.id + ) + // An invalid board id is dropped: the newest posts of the whole workspace. + expect(await ids('boardId=invalid&search=' + encodeURIComponent(marker))).toEqual( + expect.arrayContaining([tagged.id, plain.id]) + ) + expect(await ids(`boardId=${board.id}&tagIds=junk,${tag.id}`)).toEqual([tagged.id]) + expect(await ids(`boardId=${board.id}&sort=banana`)).toEqual([plain.id, tagged.id]) + expect(await ids(`boardId=${board.id}&dateFrom=notadate`)).toEqual([plain.id, tagged.id]) + await api.dispose() + } + ) + + test( + 'API-R-005 one post reads in full, including a deleted one', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const { api } = admin + const board = await newBoard(api, marker) + const tag = await newTag(api, `${marker}-t`) + const canonical = await newPost(api, board.id, `${marker} canonical`, { + tagIds: [tag.id], + }) + const dup = await newPost(api, board.id, `${marker} dup`) + await expectJson( + await api.patch(`/api/v1/posts/${canonical.id}`, { + data: { ownerPrincipalId: people.people.admin.principalId }, + }), + 200 + ) + await expectJson( + await api.post(`/api/v1/posts/${dup.id}/merge`, { + data: { canonicalPostId: canonical.id }, + }), + 200 + ) + const { data } = await expectJson(await api.get(`/api/v1/posts/${canonical.id}`), 200) + expect(data).toMatchObject({ + id: canonical.id, + title: `${marker} canonical`, + content: 'Body', + contentJson: expect.objectContaining({ type: 'doc' }), + boardId: board.id, + boardSlug: board.slug, + ownerPrincipalId: people.people.admin.principalId, + tags: [{ id: tag.id, name: `${marker}-t`, color: expect.any(String) }], + pinnedComment: null, + canonicalPostId: null, + deletedAt: null, + eta: null, + mergedPosts: [ + expect.objectContaining({ + id: dup.id, + title: `${marker} dup`, + mergedAt: expect.any(String), + }), + ], + }) + + expect((await api.delete(`/api/v1/posts/${canonical.id}`)).status()).toBe(204) + const deleted = await expectJson(await api.get(`/api/v1/posts/${canonical.id}`), 200) + expect(deleted.data.deletedAt).toEqual(expect.any(String)) + await api.dispose() + } + ) + + test( + 'API-R-006 malformed, wrong-prefix and unknown post ids', + { tag: '@nightly' }, + async ({ playwright, baseURL, people }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + for (const id of ['post_invalid123', generateId('board')]) { + await expectError( + await api.get(`/api/v1/posts/${id}`), + 400, + 'VALIDATION_ERROR', + 'Invalid post ID format' + ) + } + await expectError( + await api.get(`/api/v1/posts/${generateId('post')}`), + 404, + 'NOT_FOUND', + 'Post not found' + ) + await api.dispose() + } + ) + + test( + 'API-R-007 the activity log lists REST changes newest first, by the key', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + name: `Key ${marker}`, + }) + const { api } = admin + const board = await newBoard(api, marker) + const tag = await newTag(api, `${marker}-t`) + const post = await newPost(api, board.id, `${marker} logged`) + await waitForActivity(post.id, 'post.created') + await expectJson( + await api.patch(`/api/v1/posts/${post.id}`, { + data: { statusId: await statusIdBySlug('planned') }, + }), + 200 + ) + await waitForActivity(post.id, 'status.changed') + await expectJson( + await api.patch(`/api/v1/posts/${post.id}`, { data: { tagIds: [tag.id] } }), + 200 + ) + await waitForActivity(post.id, 'tags.added') + await expectJson( + await api.patch(`/api/v1/posts/${post.id}`, { + data: { ownerPrincipalId: people.people.admin.principalId }, + }), + 200 + ) + await waitForActivity(post.id, 'owner.assigned') + + const { data } = await expectJson(await api.get(`/api/v1/posts/${post.id}/activity`), 200) + expect(data.map((a: { type: string }) => a.type)).toEqual([ + 'owner.assigned', + 'tags.added', + 'status.changed', + 'post.created', + ]) + expect(data[2]).toMatchObject({ + postId: post.id, + principalId: admin.principalId, + actorName: `Key ${marker}`, + metadata: expect.objectContaining({ toName: 'Planned', toSlug: 'planned' }), + }) + expect(data[1].metadata.tagNames).toEqual([`${marker}-t`]) + + const unknown = await expectJson( + await api.get(`/api/v1/posts/${generateId('post')}/activity`), + 200 + ) + expect(unknown.data).toEqual([]) + await api.dispose() + } + ) + + test( + 'API-R-008 the voters list pages with a cursor and ignores a malformed one', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + name: `Key ${marker}`, + }) + const { api } = admin + const board = await newBoard(api, marker) + const post = await newPost(api, board.id, `${marker} voters`) + const a = await seedCustomer(`${marker}-a@customers.example`, `Voter A ${marker}`) + const b = await seedCustomer(`${marker}-b@customers.example`, `Voter B ${marker}`) + for (const v of [a, b]) { + await expectJson( + await api.post(`/api/v1/posts/${post.id}/vote/proxy`, { + data: { voterPrincipalId: v.principalId }, + }), + 200 + ) + } + const url = `/api/v1/posts/${post.id}/voters` + const page1 = await expectJson(await api.get(`${url}?limit=2`), 200) + expect(page1.data).toHaveLength(2) + expect(page1.meta.pagination.hasMore).toBe(true) + const page2 = await expectJson( + await api.get(`${url}?limit=2&cursor=${page1.meta.pagination.cursor}`), + 200 + ) + expect(page2.data).toHaveLength(1) + expect(page2.meta.pagination.hasMore).toBe(false) + const all = [...page1.data, ...page2.data] + expect(new Set(all.map((v: { principalId: string }) => v.principalId))).toEqual( + new Set([admin.principalId, a.principalId, b.principalId]) + ) + expect( + all.find((v: { principalId: string }) => v.principalId === a.principalId) + ).toMatchObject({ + displayName: `Voter A ${marker}`, + email: `${marker}-a@customers.example`, + isAnonymous: false, + sourceType: 'proxy', + addedByName: `Key ${marker}`, + }) + const garbage = await expectJson(await api.get(`${url}?limit=2&cursor=garbage`), 200) + expect(garbage.data.map((v: { principalId: string }) => v.principalId)).toEqual( + page1.data.map((v: { principalId: string }) => v.principalId) + ) + await api.dispose() + } + ) + + test( + 'API-R-012 an unknown or repeated tag id on create is refused without leaving a post', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'createPost inserts tag assignments without looking the tags up; an unknown tag id ' + + '(foreign key) or a repeated one (primary key) answers 500 ' + + '(apps/web/src/lib/server/domains/posts/post.service.ts:271-276)', + }, + }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const tag = await newTag(api, `${marker}-t`) + for (const tagIds of [[generateId('post_tag')], [tag.id, tag.id]]) { + const res = await api.post('/api/v1/posts', { + data: { boardId: board.id, title: `${marker} tags`, tagIds }, + }) + const text = await res.text() + expect([400, 404], text).toContain(res.status()) + } + const [{ n }] = await supportDb()` + SELECT count(*)::int AS n FROM posts WHERE board_id = ${uuid(board.id)}` + expect(n).toBe(0) + await api.dispose() + } + ) + + test( + 'API-R-013 a soft-deleted status is not found on create or update', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'createPost and updatePost look the status up without a deletedAt filter, so a ' + + 'deleted status is accepted (apps/web/src/lib/server/domains/posts/post.service.ts:148, :393-394)', + }, + }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const status = ( + await expectJson( + await api.post('/api/v1/statuses', { + data: { + name: `S ${marker}`.slice(0, 50), + slug: `s_${Date.now().toString(36)}_${test.info().workerIndex}`, + color: '#123456', + category: 'active', + }, + }), + 201 + ) + ).data + expect((await api.delete(`/api/v1/statuses/${status.id}`)).status()).toBe(204) + await expectError( + await api.post('/api/v1/posts', { + data: { boardId: board.id, title: `${marker} deleted status`, statusId: status.id }, + }), + 404, + 'NOT_FOUND', + 'Status not found' + ) + const post = await newPost(api, board.id, `${marker} live`) + await expectError( + await api.patch(`/api/v1/posts/${post.id}`, { data: { statusId: status.id } }), + 404, + 'NOT_FOUND', + 'Status not found' + ) + await api.dispose() + } + ) + + test( + 'API-R-020 a malformed JSON body is a bad request, not a server error', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const post = await newPost(api, board.id, `${marker} json`) + const raw = { headers: { 'content-type': 'application/json' }, data: '{"title":' } + for (const [method, path] of [ + ['post', '/api/v1/posts'], + ['patch', `/api/v1/posts/${post.id}`], + ['post', `/api/v1/posts/${post.id}/comments`], + ['post', `/api/v1/posts/${post.id}/merge`], + ['post', '/api/v1/boards'], + ['post', '/api/v1/tags'], + ] as const) { + await expectError(await api[method](path, raw), 400, 'BAD_REQUEST') + } + await api.dispose() + } + ) + + test( + 'API-R-021 editing title and content answers the post and announces the changed fields', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} before`) + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.updated']) + const { data } = await expectJson( + await admin.api.patch(`/api/v1/posts/${post.id}`, { + data: { title: `${marker} after`, content: 'New body' }, + }), + 200 + ) + expect(Object.keys(data).sort()).toEqual([ + 'boardId', + 'content', + 'contentJson', + 'createdAt', + 'id', + 'ownerPrincipalId', + 'statusId', + 'title', + 'updatedAt', + 'voteCount', + ]) + expect(data).toMatchObject({ title: `${marker} after`, content: 'New body' }) + const [delivery] = await deliveriesOf(marker, 'post.updated', post.id) + expect( + (bodyOf<{ changedFields: string[] }>(delivery).data.changedFields ?? []).sort() + ).toEqual(['content', 'title']) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + } + } + ) + + test( + "API-R-023 replacing a post's tags logs what was added and removed", + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const [a, b, c] = [ + await newTag(api, `${marker}-a`), + await newTag(api, `${marker}-b`), + await newTag(api, `${marker}-c`), + ] + const post = await newPost(api, board.id, `${marker} tags`, { tagIds: [a.id, b.id] }) + await expectJson( + await api.patch(`/api/v1/posts/${post.id}`, { data: { tagIds: [b.id, c.id] } }), + 200 + ) + expect(await postTagIds(post.id)).toEqual([b.id, c.id].sort()) + const [added] = await waitForActivity(post.id, 'tags.added') + expect(added.metadata.tagNames).toEqual([`${marker}-c`]) + const [removed] = await waitForActivity(post.id, 'tags.removed') + expect(removed.metadata.tagNames).toEqual([`${marker}-a`]) + await expectJson(await api.patch(`/api/v1/posts/${post.id}`, { data: { tagIds: [] } }), 200) + expect(await postTagIds(post.id)).toEqual([]) + await api.dispose() + } + ) + + test( + "API-R-024 assigning and unassigning a post's owner", + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} owner`) + const owner = people.people.agentB.principalId + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.owner_assigned']) + await expectJson( + await admin.api.patch(`/api/v1/posts/${post.id}`, { data: { ownerPrincipalId: owner } }), + 200 + ) + const [assigned] = await waitForActivity(post.id, 'owner.assigned') + expect(assigned.metadata.ownerName).toBe(people.people.agentB.displayName) + const [delivery] = await deliveriesOf(marker, 'post.owner_assigned', post.id) + expect(bodyOf(delivery).data).toMatchObject({ ownerPrincipalId: owner }) + await pollFor('owner bell', async () => + (await bellsFor(owner, post.id)).includes('post_owner_assigned') ? true : null + ) + + await expectJson( + await admin.api.patch(`/api/v1/posts/${post.id}`, { data: { ownerPrincipalId: null } }), + 200 + ) + await waitForActivity(post.id, 'owner.unassigned') + expect((await postRow(post.id)).owner_principal_id).toBeNull() + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + } + } + ) + + test( + 'API-R-028 a deleted post cannot be edited', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'updatePost never checks deletedAt, so PATCH edits a soft-deleted post and fires ' + + 'status events (apps/web/src/lib/server/domains/posts/post.service.ts:379-383)', + }, + }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const post = await newPost(api, board.id, `${marker} deleted`) + expect((await api.delete(`/api/v1/posts/${post.id}`)).status()).toBe(204) + await expectError( + await api.patch(`/api/v1/posts/${post.id}`, { + data: { statusId: await statusIdBySlug('complete') }, + }), + 404, + 'NOT_FOUND', + 'Post not found' + ) + expect((await postRow(post.id)).status_id).toBe(uuid(await statusIdBySlug('open'))) + await api.dispose() + } + ) + + test( + 'API-R-029 PATCH validation refusals', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const post = await newPost(api, board.id, `${marker} validation`) + const patch = (data: Record, id = post.id) => + api.patch(`/api/v1/posts/${id}`, { data }) + await expectError(await patch({ title: '' }), 400, 'BAD_REQUEST') + await expectError( + await patch({ title: ' ' }), + 400, + 'VALIDATION_ERROR', + 'Title cannot be empty' + ) + await expectError(await patch({ content: 'y'.repeat(10_001) }), 400, 'BAD_REQUEST') + await expectError( + await patch({ statusId: 'x' }), + 400, + 'VALIDATION_ERROR', + 'Invalid status ID format' + ) + await expectError( + await patch({ statusId: generateId('post_status') }), + 404, + 'NOT_FOUND', + 'Status not found' + ) + await expectError( + await patch({ tagIds: ['x'] }), + 400, + 'VALIDATION_ERROR', + 'Invalid tag IDs format' + ) + await expectError( + await patch({ title: 'x' }, 'nope'), + 400, + 'VALIDATION_ERROR', + 'Invalid post ID format' + ) + await expectError( + await patch({ title: 'x' }, generateId('post')), + 404, + 'NOT_FOUND', + 'Post not found' + ) + expect((await postRow(post.id)).title).toBe(`${marker} validation`) + await api.dispose() + } + ) + + test( + 'API-R-032 deleting twice is refused; a missing post is not found', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const post = await newPost(api, board.id, `${marker} twice`) + expect((await api.delete(`/api/v1/posts/${post.id}`)).status()).toBe(204) + await expectError( + await api.delete(`/api/v1/posts/${post.id}`), + 403, + 'FORBIDDEN', + 'Post has already been deleted' + ) + await expectError( + await api.delete(`/api/v1/posts/${generateId('post')}`), + 404, + 'NOT_FOUND', + 'Post not found' + ) + await waitForActivity(post.id, 'post.deleted') + expect(await activityOf(post.id, 'post.deleted')).toHaveLength(1) + await api.dispose() + } + ) + + test( + 'API-R-034 merge refusals', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const { api } = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(api, marker) + const [a, b, c, d] = [ + await newPost(api, board.id, `${marker} a`), + await newPost(api, board.id, `${marker} b`), + await newPost(api, board.id, `${marker} c`), + await newPost(api, board.id, `${marker} d`), + ] + const merge = (dup: string, canonicalPostId: unknown) => + api.post(`/api/v1/posts/${dup}/merge`, { data: { canonicalPostId } }) + + await expectError( + await merge(a.id, a.id), + 400, + 'VALIDATION_ERROR', + 'A post cannot be merged into itself' + ) + await expectJson(await merge(b.id, a.id), 200) + await expectError( + await merge(b.id, c.id), + 409, + 'CONFLICT', + 'This post is already merged into another post. Unmerge it first.' + ) + await expectError( + await merge(c.id, b.id), + 400, + 'VALIDATION_ERROR', + 'Cannot merge into a post that is itself merged. Choose the canonical post instead.' + ) + await expectError( + await merge(a.id, c.id), + 409, + 'CONFLICT', + 'A canonical post with merged children cannot itself be merged.' + ) + await expectError(await merge(d.id, generateId('post')), 404, 'NOT_FOUND', 'Post not found') + await expectError( + await api.post(`/api/v1/posts/${d.id}/merge`, { data: {} }), + 400, + 'BAD_REQUEST' + ) + await expectError( + await merge(d.id, 'nope'), + 400, + 'VALIDATION_ERROR', + 'Invalid canonical post ID format' + ) + const mate = newTeammate(`Merger ${marker}`, ['post.view_private']) + const narrow = await keyApi(playwright, baseURL, { + creatorEmail: mate.email, + scopes: ['write:feedback'], + }) + await expectError( + await narrow.api.post(`/api/v1/posts/${d.id}/merge`, { data: { canonicalPostId: c.id } }), + 403, + 'FORBIDDEN', + "Requires the 'post.merge' permission" + ) + await narrow.api.dispose() + await api.dispose() + } + ) +}) diff --git a/apps/web/e2e/tests/platform/rest-votes.spec.ts b/apps/web/e2e/tests/platform/rest-votes.spec.ts new file mode 100644 index 0000000000..8bacfb9828 --- /dev/null +++ b/apps/web/e2e/tests/platform/rest-votes.spec.ts @@ -0,0 +1,427 @@ +/** + * REST v1 votes: the key's own vote toggle and proxy votes for someone else. + * + * Journeys: API-R-035, API-R-037, API-R-038, API-R-039, API-R-040, + * API-R-041, API-R-042, API-R-043. API-R-036 (REST needs + * post.vote_on_behalf, MCP vote_post needs none) is an owner question and is + * not pinned either way. + * + * Every test makes its own board, posts, keys and customers. + */ +import { generateId } from '@quackback/ids' +import { test, expect } from '../../support/fixtures' +import { expectJson, seedCustomer } from '../../support/api-client' +import { deliveriesOf, bodyOf, subscribe, unsubscribe, type Hook } from '../../support/webhooks' +import { sink } from '../../support/webhook-sink-client' +import { pollFor } from '../../support/db' +import { + activityOf, + expectError, + keyApi, + newBoard, + newPost, + subscriptionsOf, + votesOf, + waitForActivity, +} from '../../product/api-rest' + +test.describe.configure({ timeout: 60_000 }) + +test.describe('REST votes: the key votes as itself', () => { + test( + "API-R-035 the vote route toggles the key's own vote and announces only the vote", + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const voter = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const post = await newPost(admin.api, board.id, `${marker} vote`) + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.voted']) + const first = await expectJson(await voter.api.post(`/api/v1/posts/${post.id}/vote`), 200) + expect(first.data).toEqual({ voted: true, voteCount: 2 }) + expect((await votesOf(post.id)).map((v) => v.principalId).sort()).toEqual( + [admin.principalId, voter.principalId].sort() + ) + expect((await subscriptionsOf(post.id))[voter.principalId]).toBe('vote') + const [delivery] = await deliveriesOf(marker, 'post.voted', post.id) + expect(bodyOf(delivery).type).toBe('post.voted') + + const second = await expectJson(await voter.api.post(`/api/v1/posts/${post.id}/vote`), 200) + expect(second.data).toEqual({ voted: false, voteCount: 1 }) + expect((await votesOf(post.id)).map((v) => v.principalId)).toEqual([admin.principalId]) + + // An unvote never fires post.voted: a third (re-)vote is the control. + await expectJson(await voter.api.post(`/api/v1/posts/${post.id}/vote`), 200) + await deliveriesOf(marker, 'post.voted', post.id, { count: 2 }) + const all = (await sink.deliveries(marker)).filter( + (d) => d.headers['x-quackback-event'] === 'post.voted' + ) + expect(all).toHaveLength(2) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + await voter.api.dispose() + } + } + ) + + test( + 'API-R-037 a read-only board takes votes back but refuses new ones; deleted posts and boards are not found', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const voter = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} read-only`) + const vote = () => voter.api.post(`/api/v1/posts/${post.id}/vote`) + + expect((await expectJson(await vote(), 200)).data.voted).toBe(true) + await expectJson( + await admin.api.patch(`/api/v1/boards/${board.id}`, { data: { readOnly: true } }), + 200 + ) + expect((await expectJson(await vote(), 200)).data).toEqual({ voted: false, voteCount: 1 }) + await expectError( + await vote(), + 403, + 'FORBIDDEN', + "This board isn't taking new feedback right now." + ) + + // A soft-deleted post, and a post whose board was deleted. + const open = await newBoard(admin.api, `${marker}-b`) + const deletedPost = await newPost(admin.api, open.id, `${marker} deleted`) + expect((await admin.api.delete(`/api/v1/posts/${deletedPost.id}`)).status()).toBe(204) + await expectError( + await voter.api.post(`/api/v1/posts/${deletedPost.id}/vote`), + 404, + 'NOT_FOUND', + 'Post not found' + ) + const orphan = await newPost(admin.api, open.id, `${marker} orphan`) + // Control: the orphan is votable while its board lives. + await expectJson(await voter.api.post(`/api/v1/posts/${orphan.id}/vote`), 200) + expect((await admin.api.delete(`/api/v1/boards/${open.id}`)).status()).toBe(204) + await expectError( + await voter.api.post(`/api/v1/posts/${orphan.id}/vote`), + 404, + 'NOT_FOUND', + 'Post not found' + ) + await admin.api.dispose() + await voter.api.dispose() + } + ) + + test( + 'API-R-038 a vote through a merged duplicate counts on the canonical post', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const voter = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const canonical = await newPost(admin.api, board.id, `${marker} canonical`) + const dup = await newPost(admin.api, board.id, `${marker} duplicate`) + await expectJson( + await admin.api.post(`/api/v1/posts/${dup.id}/merge`, { + data: { canonicalPostId: canonical.id }, + }), + 200 + ) + let hook: Hook | undefined + try { + hook = await subscribe(admin.api, marker, ['post.voted']) + const res = await expectJson(await voter.api.post(`/api/v1/posts/${dup.id}/vote`), 200) + expect(res.data).toEqual({ voted: true, voteCount: 2 }) + expect((await votesOf(canonical.id)).map((v) => v.principalId)).toContain(voter.principalId) + expect((await votesOf(dup.id)).map((v) => v.principalId)).not.toContain(voter.principalId) + const [delivery] = await deliveriesOf(marker, 'post.voted', canonical.id) + expect(bodyOf<{ post: { id: string } }>(delivery).data.post.id).toBe(canonical.id) + + // A proxy vote on the canonical post for a voter who voted through the + // duplicate is not a second vote. + const customer = await seedCustomer(`${marker}@customers.example`) + await expectJson( + await admin.api.post(`/api/v1/posts/${dup.id}/vote/proxy`, { + data: { voterPrincipalId: customer.principalId }, + }), + 200 + ) + const again = await expectJson( + await admin.api.post(`/api/v1/posts/${canonical.id}/vote/proxy`, { + data: { voterPrincipalId: customer.principalId }, + }), + 200 + ) + expect(again.data.voted).toBe(false) + } finally { + await unsubscribe(admin.api, hook) + await admin.api.dispose() + await voter.api.dispose() + } + } + ) +}) + +test.describe('REST votes: proxy votes', () => { + test( + 'API-R-039 a proxy vote records the source and adder and subscribes the voter', + { tag: '@core' }, + async ({ playwright, baseURL, people, marker }) => { + // Whether a proxy vote should send post.voted is an owner question; not pinned. + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} proxy`) + const customer = await seedCustomer(`${marker}@customers.example`) + + const res = await expectJson( + await admin.api.post(`/api/v1/posts/${post.id}/vote/proxy`, { + data: { voterPrincipalId: customer.principalId }, + }), + 200 + ) + expect(res.data).toEqual({ voted: true, voteCount: 2 }) + const vote = (await votesOf(post.id)).find((v) => v.principalId === customer.principalId) + expect(vote).toMatchObject({ sourceType: 'proxy', addedBy: admin.principalId }) + expect((await subscriptionsOf(post.id))[customer.principalId]).toBe('vote') + const [activity] = await waitForActivity(post.id, 'vote.proxy') + expect(activity.metadata).toEqual({ voterPrincipalId: customer.principalId }) + + const voters = await expectJson(await admin.api.get(`/api/v1/posts/${post.id}/voters`), 200) + expect( + voters.data.find((v: { principalId: string }) => v.principalId === customer.principalId) + ).toMatchObject({ sourceType: 'proxy' }) + await admin.api.dispose() + } + ) + + test( + 'API-R-040 a repeated proxy vote changes nothing', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} twice`) + const a = await seedCustomer(`${marker}-a@customers.example`) + const b = await seedCustomer(`${marker}-b@customers.example`) + const proxy = (voterPrincipalId: string) => + admin.api.post(`/api/v1/posts/${post.id}/vote/proxy`, { data: { voterPrincipalId } }) + + expect((await expectJson(await proxy(a.principalId), 200)).data.voted).toBe(true) + const again = await expectJson(await proxy(a.principalId), 200) + expect(again.data).toEqual({ voted: false, voteCount: 2 }) + // A later vote for b is the control that the activity writer has run. + await expectJson(await proxy(b.principalId), 200) + await pollFor('second proxy activity', async () => + (await activityOf(post.id, 'vote.proxy')).length >= 2 ? true : null + ) + const rows = await activityOf(post.id, 'vote.proxy') + expect(rows.map((r) => r.metadata.voterPrincipalId)).toEqual([a.principalId, b.principalId]) + await admin.api.dispose() + } + ) + + test( + 'API-R-041 proxy vote validation refusals', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const other = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} validation`) + const url = `/api/v1/posts/${post.id}/vote/proxy` + + const empty = await expectError( + await admin.api.post(url, { data: {} }), + 400, + 'BAD_REQUEST', + 'Invalid request body' + ) + expect(empty.error.details.errors.voterPrincipalId).toBeTruthy() + await expectError( + await admin.api.post(url, { data: { voterPrincipalId: 'x' } }), + 400, + 'VALIDATION_ERROR', + 'Invalid voter principal ID format' + ) + await expectError( + await admin.api.post('/api/v1/posts/nope/vote/proxy', { + data: { voterPrincipalId: other.principalId }, + }), + 400, + 'VALIDATION_ERROR', + 'Invalid post ID format' + ) + await expectError( + await admin.api.post(`/api/v1/posts/${generateId('post')}/vote/proxy`, { + data: { voterPrincipalId: other.principalId }, + }), + 404, + 'NOT_FOUND', + 'Post not found' + ) + // Another key's service principal is accepted as a voter. + expect( + ( + await expectJson( + await admin.api.post(url, { data: { voterPrincipalId: other.principalId } }), + 200 + ) + ).data.voted + ).toBe(true) + await admin.api.dispose() + await other.api.dispose() + } + ) + + test( + 'API-R-041 a proxy vote for an unknown voter is a not-found refusal, not a server error', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'POST /posts/:id/vote/proxy never looks the voter up; the vote insert hits the ' + + 'principal foreign key and answers 500 ' + + '(apps/web/src/routes/api/v1/posts/$postId.vote.proxy.ts:43-63, ' + + 'apps/web/src/lib/server/domains/posts/post.voting.ts addVoteOnBehalf)', + }, + }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} unknown voter`) + const res = await admin.api.post(`/api/v1/posts/${post.id}/vote/proxy`, { + data: { voterPrincipalId: generateId('principal') }, + }) + const text = await res.text() + expect([400, 404], text).toContain(res.status()) + await admin.api.dispose() + } + ) + + test( + 'API-R-042 an admin key backdates a proxy vote in import mode; a member key cannot', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + // An admin's personal key holds the admin role; the manager workspace key is role member. + const admin = await keyApi( + playwright, + baseURL, + { creatorEmail: people.people.admin.email }, + { 'x-import-mode': 'true' } + ) + const member = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + roleKey: 'manager', + }) + const board = await newBoard(member.api, marker) + const post = await newPost(member.api, board.id, `${marker} backdated`) + const a = await seedCustomer(`${marker}-a@customers.example`) + const b = await seedCustomer(`${marker}-b@customers.example`) + const createdAt = '2023-05-01T00:00:00Z' + + await expectJson( + await admin.api.post(`/api/v1/posts/${post.id}/vote/proxy`, { + data: { voterPrincipalId: a.principalId, createdAt }, + }), + 200 + ) + await expectJson( + await member.api.post(`/api/v1/posts/${post.id}/vote/proxy`, { + data: { voterPrincipalId: b.principalId, createdAt }, + }), + 200 + ) + // The member's vote writes its activity; that is the control for the admin's absence. + const [activity] = await waitForActivity(post.id, 'vote.proxy') + expect(activity.metadata.voterPrincipalId).toBe(b.principalId) + expect(await activityOf(post.id, 'vote.proxy')).toHaveLength(1) + + const votes = await votesOf(post.id) + const va = votes.find((v) => v.principalId === a.principalId) + const vb = votes.find((v) => v.principalId === b.principalId) + expect(va?.createdAt.toISOString()).toBe('2023-05-01T00:00:00.000Z') + expect(Date.now() - (vb?.createdAt.getTime() ?? 0)).toBeLessThan(5 * 60_000) + await admin.api.dispose() + await member.api.dispose() + } + ) + + test( + 'API-R-043 removing a proxy vote is idempotent and keeps the subscription', + { tag: '@nightly' }, + async ({ playwright, baseURL, people, marker }) => { + const admin = await keyApi(playwright, baseURL, { + creatorEmail: people.people.admin.email, + kind: 'workspace', + }) + const board = await newBoard(admin.api, marker) + const post = await newPost(admin.api, board.id, `${marker} remove`) + const customer = await seedCustomer(`${marker}@customers.example`) + const url = `/api/v1/posts/${post.id}/vote/proxy` + await expectJson( + await admin.api.post(url, { data: { voterPrincipalId: customer.principalId } }), + 200 + ) + // Removal works on a read-only board. + await expectJson( + await admin.api.patch(`/api/v1/boards/${board.id}`, { data: { readOnly: true } }), + 200 + ) + + const first = await admin.api.delete(url, { + data: { voterPrincipalId: customer.principalId }, + }) + expect(first.status(), await first.text()).toBe(204) + expect((await votesOf(post.id)).map((v) => v.principalId)).not.toContain(customer.principalId) + await waitForActivity(post.id, 'vote.removed') + const second = await admin.api.delete(url, { + data: { voterPrincipalId: customer.principalId }, + }) + expect(second.status()).toBe(204) + expect((await subscriptionsOf(post.id))[customer.principalId]).toBe('vote') + + await expectError(await admin.api.delete(url), 400, 'BAD_REQUEST') + // The second removal wrote no activity (the 400 above ran after it). + expect(await activityOf(post.id, 'vote.removed')).toHaveLength(1) + await admin.api.dispose() + } + ) +}) From aba36079bdc6da33d3a03a801004772cd7d903af Mon Sep 17 00:00:00 2001 From: James Morton Date: Fri, 20 Nov 2026 01:26:11 +0000 Subject: [PATCH 2/2] test(e2e): steady REST posts and votes specs under parallel runs Count only this post's webhook deliveries (the webhook is workspace-wide), search the whole workspace by a word no other post carries, and leave the order of an unknown sort unpinned. --- apps/web/e2e/tests/platform/rest-posts.spec.ts | 13 +++++++++---- apps/web/e2e/tests/platform/rest-votes.spec.ts | 3 ++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/apps/web/e2e/tests/platform/rest-posts.spec.ts b/apps/web/e2e/tests/platform/rest-posts.spec.ts index 031146e9a9..e253964ca6 100644 --- a/apps/web/e2e/tests/platform/rest-posts.spec.ts +++ b/apps/web/e2e/tests/platform/rest-posts.spec.ts @@ -1083,18 +1083,23 @@ test.describe('REST posts: nightly', () => { const { api } = admin const board = await newBoard(api, marker) const tag = await newTag(api, `${marker}-t`) - const tagged = await newPost(api, board.id, `${marker} tagged`, { tagIds: [tag.id] }) - const plain = await newPost(api, board.id, `${marker} plain`) + // A word no other post has, for the workspace-wide search below. + const word = `zq${Date.now().toString(36)}w${test.info().workerIndex}` + const tagged = await newPost(api, board.id, `${marker} tagged ${word}`, { tagIds: [tag.id] }) + const plain = await newPost(api, board.id, `${marker} plain ${word}`) const ids = async (q: string) => (await expectJson(await api.get(`/api/v1/posts?${q}`), 200)).data.map( (p: { id: string }) => p.id ) // An invalid board id is dropped: the newest posts of the whole workspace. - expect(await ids('boardId=invalid&search=' + encodeURIComponent(marker))).toEqual( + expect(await ids(`boardId=invalid&limit=100&search=${word}`)).toEqual( expect.arrayContaining([tagged.id, plain.id]) ) expect(await ids(`boardId=${board.id}&tagIds=junk,${tag.id}`)).toEqual([tagged.id]) - expect(await ids(`boardId=${board.id}&sort=banana`)).toEqual([plain.id, tagged.id]) + // An unknown sort is not refused; which order it takes is unspecified. + expect((await ids(`boardId=${board.id}&sort=banana`)).sort()).toEqual( + [plain.id, tagged.id].sort() + ) expect(await ids(`boardId=${board.id}&dateFrom=notadate`)).toEqual([plain.id, tagged.id]) await api.dispose() } diff --git a/apps/web/e2e/tests/platform/rest-votes.spec.ts b/apps/web/e2e/tests/platform/rest-votes.spec.ts index 8bacfb9828..009bcbce39 100644 --- a/apps/web/e2e/tests/platform/rest-votes.spec.ts +++ b/apps/web/e2e/tests/platform/rest-votes.spec.ts @@ -59,10 +59,11 @@ test.describe('REST votes: the key votes as itself', () => { expect((await votesOf(post.id)).map((v) => v.principalId)).toEqual([admin.principalId]) // An unvote never fires post.voted: a third (re-)vote is the control. + // The webhook is workspace-wide, so count this post's deliveries only. await expectJson(await voter.api.post(`/api/v1/posts/${post.id}/vote`), 200) await deliveriesOf(marker, 'post.voted', post.id, { count: 2 }) const all = (await sink.deliveries(marker)).filter( - (d) => d.headers['x-quackback-event'] === 'post.voted' + (d) => d.headers['x-quackback-event'] === 'post.voted' && d.body.includes(post.id) ) expect(all).toHaveLength(2) } finally {