diff --git a/apps/web/src/lib/server/domains/posts/__tests__/post-service-writes.db.test.ts b/apps/web/src/lib/server/domains/posts/__tests__/post-service-writes.db.test.ts new file mode 100644 index 0000000000..80b106f516 --- /dev/null +++ b/apps/web/src/lib/server/domains/posts/__tests__/post-service-writes.db.test.ts @@ -0,0 +1,262 @@ +/** + * Post writes against a real database: tags, statuses and deleted posts on + * createPost / updatePost, and the voter lookup on addVoteOnBehalf. Each case + * here once answered a 500 or wrote what it should have refused. + */ +import { afterAll, afterEach, beforeEach, expect, it, vi } from 'vitest' +import { + createId, + type BoardId, + type PostId, + type PostStatusId, + type PostTagId, + type PrincipalId, +} from '@quackback/ids' +import { createDbTestFixture, testDb } from '@/lib/server/__tests__/db-test-fixture' +import { + boards, + eq, + posts, + postStatuses, + postTagAssignments, + postTags, + postVotes, + principal, + user, +} from '@/lib/server/db' +import { DEFAULT_BOARD_ACCESS } from '@/lib/shared/db-types' +import { NotFoundError, ValidationError } from '@/lib/shared/errors' +import { DEFAULT_PORTAL_CONFIG } from '@/lib/server/domains/settings/settings.types' + +const dispatchPostStatusChanged = vi.hoisted(() => vi.fn()) +vi.mock('@/lib/server/db', async (original) => ({ + ...(await original()), + db: (await import('@/lib/server/__tests__/db-test-fixture')).testDb, +})) +vi.mock('@/lib/server/events/dispatch', async (original) => ({ + ...(await original()), + dispatchPostStatusChanged, + dispatchPostUpdated: vi.fn(), + dispatchPostOwnerAssigned: vi.fn(), + dispatchPostVoted: vi.fn(), +})) +vi.mock('@/lib/server/domains/activity/activity.service', () => ({ createActivity: vi.fn() })) +vi.mock('@/lib/server/content/rehost-images', () => ({ + rehostExternalImages: async (json: unknown) => json, +})) +vi.mock('@/lib/server/domains/posts/post.autotag', () => ({ autoTagPost: async () => [] })) +vi.mock('@/lib/server/domains/embeddings/embedding.service', () => ({ + generatePostEmbedding: async () => undefined, +})) +vi.mock('@/lib/server/domains/settings/settings.service', async (original) => ({ + ...(await original()), + getPortalConfig: async () => DEFAULT_PORTAL_CONFIG, +})) + +import { createPost, updatePost } from '../post.service' +import { addVoteOnBehalf } from '../post.voting' + +const fixture = await createDbTestFixture() +let admin: PrincipalId +let boardId: BoardId +let open: PostStatusId +let done: PostStatusId +let tagA: PostTagId +let tagB: PostTagId +let postId: PostId + +const teamAuthor = () => ({ + principalId: admin, + actor: { principalId: admin, principalType: 'user', role: 'admin' } as never, +}) +const actor = () => ({ principalId: admin }) + +async function tagsOf(id: PostId) { + const rows = await testDb + .select({ tagId: postTagAssignments.tagId }) + .from(postTagAssignments) + .where(eq(postTagAssignments.postId, id)) + return rows.map((r) => r.tagId).sort() +} + +async function postsOnBoard() { + return testDb.select({ id: posts.id }).from(posts).where(eq(posts.boardId, boardId)) +} + +beforeEach(async () => { + expect(fixture.available).toBe(true) + await fixture.begin() + dispatchPostStatusChanged.mockReset() + admin = createId('principal') + const adminUser = createId('user') + await testDb.insert(user).values({ id: adminUser, name: 'Admin', email: 'admin@example.com' }) + await testDb + .insert(principal) + .values({ id: admin, userId: adminUser, type: 'user', role: 'admin', createdAt: new Date() }) + boardId = createId('board') + await testDb + .insert(boards) + .values({ id: boardId, name: 'Feedback', slug: String(boardId), access: DEFAULT_BOARD_ACCESS }) + open = createId('post_status') + done = createId('post_status') + await testDb.insert(postStatuses).values([ + { id: open, name: 'Open', slug: `open-${open}` }, + { id: done, name: 'Done', slug: `done-${done}` }, + ]) + tagA = createId('post_tag') + tagB = createId('post_tag') + await testDb.insert(postTags).values([ + { id: tagA, name: `a-${tagA}` }, + { id: tagB, name: `b-${tagB}` }, + ]) + postId = createId('post') + await testDb.insert(posts).values({ + id: postId, + boardId, + title: 'An idea', + content: '', + statusId: open, + principalId: admin, + }) + await testDb.insert(postTagAssignments).values([ + { postId, tagId: tagA }, + { postId, tagId: tagB }, + ]) +}) +afterEach(fixture.rollback) +afterAll(fixture.close) + +// ---------------------------------------------------------------- createPost + +it('refuses an unknown tag on create without leaving a post', async () => { + const before = await postsOnBoard() + await expect( + createPost( + { boardId, title: 'Tagged', statusId: open, tagIds: [createId('post_tag')] }, + teamAuthor(), + { skipDispatch: true } + ) + ).rejects.toMatchObject({ constructor: NotFoundError, code: 'TAG_NOT_FOUND' }) + expect(await postsOnBoard()).toEqual(before) +}) + +it('refuses a repeated tag on create without leaving a post', async () => { + const before = await postsOnBoard() + await expect( + createPost({ boardId, title: 'Tagged', statusId: open, tagIds: [tagA, tagA] }, teamAuthor(), { + skipDispatch: true, + }) + ).rejects.toMatchObject({ constructor: ValidationError, code: 'VALIDATION_ERROR' }) + expect(await postsOnBoard()).toEqual(before) +}) + +it('refuses a deleted tag on create', async () => { + await testDb.update(postTags).set({ deletedAt: new Date() }).where(eq(postTags.id, tagB)) + await expect( + createPost({ boardId, title: 'Tagged', statusId: open, tagIds: [tagB] }, teamAuthor(), { + skipDispatch: true, + }) + ).rejects.toMatchObject({ code: 'TAG_NOT_FOUND' }) +}) + +it('creates a post with distinct live tags', async () => { + const post = await createPost( + { boardId, title: 'Tagged', statusId: open, tagIds: [tagA, tagB] }, + teamAuthor(), + { skipDispatch: true } + ) + expect(await tagsOf(post.id)).toEqual([tagA, tagB].sort()) +}) + +it('refuses a deleted status on create', async () => { + await testDb.update(postStatuses).set({ deletedAt: new Date() }).where(eq(postStatuses.id, done)) + const before = await postsOnBoard() + await expect( + createPost({ boardId, title: 'Done already', statusId: done }, teamAuthor(), { + skipDispatch: true, + }) + ).rejects.toMatchObject({ constructor: NotFoundError, code: 'STATUS_NOT_FOUND' }) + expect(await postsOnBoard()).toEqual(before) +}) + +// ---------------------------------------------------------------- updatePost + +it("refuses an unknown tag on update and keeps the post's tags", async () => { + await expect( + updatePost(postId, { tagIds: [tagA, createId('post_tag')] }, actor()) + ).rejects.toMatchObject({ constructor: NotFoundError, code: 'TAG_NOT_FOUND' }) + expect(await tagsOf(postId)).toEqual([tagA, tagB].sort()) +}) + +it("refuses a repeated tag on update and keeps the post's tags", async () => { + await expect(updatePost(postId, { tagIds: [tagA, tagA] }, actor())).rejects.toMatchObject({ + constructor: ValidationError, + code: 'VALIDATION_ERROR', + }) + expect(await tagsOf(postId)).toEqual([tagA, tagB].sort()) +}) + +it('writes nothing when the tags are refused alongside a title change', async () => { + await expect( + updatePost(postId, { title: 'Renamed', tagIds: [createId('post_tag')] }, actor()) + ).rejects.toMatchObject({ code: 'TAG_NOT_FOUND' }) + const row = await testDb.query.posts.findFirst({ where: eq(posts.id, postId) }) + expect(row!.title).toBe('An idea') +}) + +it('keeps a deleted tag the post already carries when the tags are re-sent', async () => { + await testDb.update(postTags).set({ deletedAt: new Date() }).where(eq(postTags.id, tagB)) + await updatePost(postId, { tagIds: [tagA, tagB] }, actor()) + expect(await tagsOf(postId)).toEqual([tagA, tagB].sort()) + await updatePost(postId, { tagIds: [tagA] }, actor()) + await expect(updatePost(postId, { tagIds: [tagA, tagB] }, actor())).rejects.toMatchObject({ + code: 'TAG_NOT_FOUND', + }) +}) + +it('replaces the tags', async () => { + await updatePost(postId, { tagIds: [tagB] }, actor()) + expect(await tagsOf(postId)).toEqual([tagB]) + await updatePost(postId, { tagIds: [] }, actor()) + expect(await tagsOf(postId)).toEqual([]) +}) + +it('refuses a deleted status on update', async () => { + await testDb.update(postStatuses).set({ deletedAt: new Date() }).where(eq(postStatuses.id, done)) + await expect(updatePost(postId, { statusId: done }, actor())).rejects.toMatchObject({ + constructor: NotFoundError, + code: 'STATUS_NOT_FOUND', + }) + const row = await testDb.query.posts.findFirst({ where: eq(posts.id, postId) }) + expect(row!.statusId).toBe(open) +}) + +it('treats a deleted post as not found and announces nothing', async () => { + await testDb.update(posts).set({ deletedAt: new Date() }).where(eq(posts.id, postId)) + await expect(updatePost(postId, { statusId: done }, actor())).rejects.toMatchObject({ + constructor: NotFoundError, + code: 'POST_NOT_FOUND', + }) + const row = await testDb.query.posts.findFirst({ where: eq(posts.id, postId) }) + expect(row!.statusId).toBe(open) + expect(dispatchPostStatusChanged).not.toHaveBeenCalled() +}) + +// ---------------------------------------------------------------- addVoteOnBehalf + +it('refuses a proxy vote for an unknown voter as not found', async () => { + await expect(addVoteOnBehalf(postId, createId('principal'))).rejects.toMatchObject({ + constructor: NotFoundError, + code: 'PRINCIPAL_NOT_FOUND', + }) + const votes = await testDb.select().from(postVotes).where(eq(postVotes.postId, postId)) + expect(votes).toEqual([]) +}) + +it('accepts a proxy vote for any existing principal', async () => { + const service = createId('principal') + await testDb + .insert(principal) + .values({ id: service, type: 'service', role: 'member', createdAt: new Date() }) + expect(await addVoteOnBehalf(postId, service)).toMatchObject({ voted: true }) +}) diff --git a/apps/web/src/lib/server/domains/posts/__tests__/post-service.test.ts b/apps/web/src/lib/server/domains/posts/__tests__/post-service.test.ts index 98b7b498a8..a3322ecd51 100644 --- a/apps/web/src/lib/server/domains/posts/__tests__/post-service.test.ts +++ b/apps/web/src/lib/server/domains/posts/__tests__/post-service.test.ts @@ -26,6 +26,11 @@ const dbDelete = vi.fn(() => ({ where: deleteWhere })) const insertValues = vi.fn() const dbInsert = vi.fn(() => ({ values: insertValues })) +// The transaction handle has its own write spies, so a test can tell a write +// made inside the transaction from one made on the bare db. +const txDelete = vi.fn(() => ({ where: deleteWhere })) +const txInsert = vi.fn(() => ({ values: insertValues })) + vi.mock('@/lib/server/db', async (importOriginal) => { const { sql: realSql } = await vi.importActual('drizzle-orm') @@ -43,6 +48,8 @@ vi.mock('@/lib/server/db', async (importOriginal) => { update: dbUpdate, delete: dbDelete, insert: dbInsert, + transaction: (fn: (tx: unknown) => unknown) => + fn({ update: dbUpdate, delete: txDelete, insert: txInsert }), }, eq: vi.fn(), inArray: vi.fn(), @@ -84,6 +91,10 @@ describe('post.service updatePost', () => { updateReturning.mockReset() deleteWhere.mockReset() insertValues.mockReset() + dbDelete.mockClear() + dbInsert.mockClear() + txDelete.mockClear() + txInsert.mockClear() mockPostsFindFirst.mockResolvedValue({ id: 'post_123' as PostId, @@ -110,10 +121,14 @@ describe('post.service updatePost', () => { name: 'Closed', color: '#111111', }) - selectWhere.mockResolvedValueOnce([{ tagId: 'tag_old' as PostTagId }]).mockResolvedValueOnce([ - { id: 'tag_old' as PostTagId, name: 'Old tag' }, - { id: 'tag_new' as PostTagId, name: 'New tag' }, - ]) + // Current tags, then the live-tag check for the new ones, then the activity names. + selectWhere + .mockResolvedValueOnce([{ tagId: 'tag_old' as PostTagId }]) + .mockResolvedValueOnce([{ id: 'tag_new' as PostTagId }]) + .mockResolvedValueOnce([ + { id: 'tag_old' as PostTagId, name: 'Old tag' }, + { id: 'tag_new' as PostTagId, name: 'New tag' }, + ]) updateReturning.mockResolvedValue([ { id: 'post_123' as PostId, @@ -222,6 +237,22 @@ describe('post.service updatePost', () => { ) }) + it('replaces the tags inside the transaction, never on the bare db', async () => { + const { updatePost } = await import('../post.service') + + await updatePost( + 'post_123' as PostId, + { tagIds: ['tag_new' as PostTagId] }, + { principalId: 'principal_actor' as PrincipalId } + ) + + expect(txDelete).toHaveBeenCalledOnce() + expect(txInsert).toHaveBeenCalledOnce() + expect(insertValues).toHaveBeenCalledWith([{ postId: 'post_123', tagId: 'tag_new' }]) + expect(dbDelete).not.toHaveBeenCalled() + expect(dbInsert).not.toHaveBeenCalled() + }) + it('emits the owner event when a teammate assigns a post to themselves', async () => { mockPostsFindFirst.mockResolvedValueOnce({ id: 'post_123' as PostId, diff --git a/apps/web/src/lib/server/domains/posts/__tests__/post-voting.test.ts b/apps/web/src/lib/server/domains/posts/__tests__/post-voting.test.ts index ed6ba884a3..f0e40724c6 100644 --- a/apps/web/src/lib/server/domains/posts/__tests__/post-voting.test.ts +++ b/apps/web/src/lib/server/domains/posts/__tests__/post-voting.test.ts @@ -161,7 +161,13 @@ describe('addVoteOnBehalf', () => { it('adds a proxy vote successfully', async () => { mockDbExecute.mockResolvedValue([ - { post_exists: true, board_exists: true, newly_voted: true, vote_count: 6 }, + { + post_exists: true, + board_exists: true, + voter_exists: true, + newly_voted: true, + vote_count: 6, + }, ]) const result = await addVoteOnBehalf( @@ -177,7 +183,13 @@ describe('addVoteOnBehalf', () => { it('returns voted: false when vote already exists (idempotent)', async () => { mockDbExecute.mockResolvedValue([ - { post_exists: true, board_exists: true, newly_voted: false, vote_count: 5 }, + { + post_exists: true, + board_exists: true, + voter_exists: true, + newly_voted: false, + vote_count: 5, + }, ]) const result = await addVoteOnBehalf(POST_ID, PRINCIPAL_ID) @@ -204,7 +216,13 @@ describe('addVoteOnBehalf', () => { it('passes source metadata to the CTE', async () => { mockDbExecute.mockResolvedValue([ - { post_exists: true, board_exists: true, newly_voted: true, vote_count: 3 }, + { + post_exists: true, + board_exists: true, + voter_exists: true, + newly_voted: true, + vote_count: 3, + }, ]) const result = await addVoteOnBehalf( diff --git a/apps/web/src/lib/server/domains/posts/__tests__/post.service-mentions.test.ts b/apps/web/src/lib/server/domains/posts/__tests__/post.service-mentions.test.ts index 38d122415c..c7872d19c2 100644 --- a/apps/web/src/lib/server/domains/posts/__tests__/post.service-mentions.test.ts +++ b/apps/web/src/lib/server/domains/posts/__tests__/post.service-mentions.test.ts @@ -67,6 +67,31 @@ vi.mock('@/lib/server/db', async (importOriginal) => { return c } + // Used by updatePost inside its transaction. Echoes back a fake "updated post" using the contentJson + // captured from the call site via updateReturningContentJson. + const update = vi.fn(() => ({ + set: vi.fn(() => ({ + where: vi.fn(() => ({ + returning: vi.fn(async () => [ + { + id: 'post_update' as unknown, + boardId: 'board_b' as unknown, + statusId: 'post_status_open' as unknown, + title: updateReturningTitle, + content: 'Body', + contentJson: updateReturningContentJson, + principalId: 'principal_author' as unknown, + ownerPrincipalId: null, + voteCount: 1, + commentCount: 0, + createdAt: new Date(), + updatedAt: new Date(), + }, + ]), + })), + })), + })) + return { db: { query: { @@ -97,6 +122,7 @@ vi.mock('@/lib/server/db', async (importOriginal) => { }, transaction: vi.fn(async (fn: (tx: unknown) => Promise) => { const tx = { + update, insert: vi.fn((table: { __name?: string }) => { const label = table === undefined @@ -134,30 +160,6 @@ vi.mock('@/lib/server/db', async (importOriginal) => { return fn(tx) }), select: vi.fn(() => ({ from: vi.fn(() => ({ where: vi.fn().mockResolvedValue([]) })) })), - // Used by updatePost. Echoes back a fake "updated post" using the contentJson - // captured from the call site via updateReturningContentJson. - update: vi.fn(() => ({ - set: vi.fn(() => ({ - where: vi.fn(() => ({ - returning: vi.fn(async () => [ - { - id: 'post_update' as unknown, - boardId: 'board_b' as unknown, - statusId: 'post_status_open' as unknown, - title: updateReturningTitle, - content: 'Body', - contentJson: updateReturningContentJson, - principalId: 'principal_author' as unknown, - ownerPrincipalId: null, - voteCount: 1, - commentCount: 0, - createdAt: new Date(), - updatedAt: new Date(), - }, - ]), - })), - })), - })), delete: vi.fn(() => ({ where: vi.fn().mockResolvedValue(undefined) })), insert: vi.fn(() => ({ values: vi.fn().mockResolvedValue(undefined) })), }, diff --git a/apps/web/src/lib/server/domains/posts/post.service.ts b/apps/web/src/lib/server/domains/posts/post.service.ts index cb97948d0d..65b5cde742 100644 --- a/apps/web/src/lib/server/domains/posts/post.service.ts +++ b/apps/web/src/lib/server/domains/posts/post.service.ts @@ -66,6 +66,32 @@ import { assertBoardOpen } from '@/lib/server/domains/plan-limits/plan-limits.bo const log = logger.child({ component: 'posts' }) +/** + * Refuse a tag list the assignment insert would fail on or should not write: + * a repeated id, or one naming no live tag. `kept` are the tags the post + * already carries; they stay assignable after the tag itself is deleted, so + * re-sending a post's current tags never fails. + */ +async function assertAssignableTags( + tagIds: readonly PostTagId[], + kept: readonly PostTagId[] = [] +): Promise { + if (new Set(tagIds).size !== tagIds.length) { + throw new ValidationError('VALIDATION_ERROR', 'Tag IDs must not repeat') + } + const wanted = tagIds.filter((tagId) => !kept.includes(tagId)) + if (wanted.length === 0) return + const live = await db + .select({ id: postTags.id }) + .from(postTags) + .where(and(inArray(postTags.id, wanted), isNull(postTags.deletedAt))) + const found = new Set(live.map((t) => t.id)) + const missing = wanted.find((tagId) => !found.has(tagId)) + if (missing) { + throw new NotFoundError('TAG_NOT_FOUND', `PostTag with ID ${missing} not found`) + } +} + /** * Create a new post * @@ -128,6 +154,9 @@ export async function createPost( }, }) + // Refuse a bad tag list before anything is written, so it leaves no post. + if (input.tagIds) await assertAssignableTags(input.tagIds) + // Validate board exists and get status in parallel. // The deletedAt filter here is load-bearing: rehostExternalImages (below) uploads // to S3 before the locked recheck inside the transaction. Without this filter, a @@ -142,10 +171,12 @@ export async function createPost( ? db .select() .from(postStatuses) - .where(eq(postStatuses.slug, 'open')) + .where(and(eq(postStatuses.slug, 'open'), isNull(postStatuses.deletedAt))) .limit(1) .then((rows) => rows[0]) - : db.query.postStatuses.findFirst({ where: eq(postStatuses.id, input.statusId!) }), + : db.query.postStatuses.findFirst({ + where: and(eq(postStatuses.id, input.statusId!), isNull(postStatuses.deletedAt)), + }), ]) if (!board) { @@ -376,8 +407,10 @@ export async function updatePost( throw new ValidationError('VALIDATION_ERROR', 'Actor principal ID is required for post updates') } - // Get existing post - const existingPost = await db.query.posts.findFirst({ where: eq(posts.id, id) }) + // Get existing post; a deleted post is not found, so it cannot be edited + const existingPost = await db.query.posts.findFirst({ + where: and(eq(posts.id, id), isNull(posts.deletedAt)), + }) if (!existingPost) { throw new NotFoundError('POST_NOT_FOUND', `Post with ID ${id} not found`) } @@ -391,7 +424,9 @@ export async function updatePost( ? db.query.postStatuses.findFirst({ where: eq(postStatuses.id, existingPost.statusId) }) : null, statusChanged - ? db.query.postStatuses.findFirst({ where: eq(postStatuses.id, input.statusId!) }) + ? db.query.postStatuses.findFirst({ + where: and(eq(postStatuses.id, input.statusId!), isNull(postStatuses.deletedAt)), + }) : null, ]) @@ -417,14 +452,16 @@ export async function updatePost( } } - // Capture current tag IDs before update (for activity diff) - let currentTagIds: string[] = [] + // Capture current tag IDs before update (for activity diff), and refuse a + // tag list the replacement would fail on before anything is written + let currentTagIds: PostTagId[] = [] if (input.tagIds !== undefined) { const currentTags = await db .select({ tagId: postTagAssignments.tagId }) .from(postTagAssignments) .where(eq(postTagAssignments.postId, id)) currentTagIds = currentTags.map((t) => t.tagId) + await assertAssignableTags(input.tagIds, currentTagIds) } // Build update data @@ -453,17 +490,31 @@ export async function updatePost( updateData.pinnedAt = input.pinned ? new Date() : null } - // Update the post only if there's data to update - let updatedPost: Post - if (Object.keys(updateData).length > 0) { - const [result] = await db.update(posts).set(updateData).where(eq(posts.id, id)).returning() - if (!result) { - throw new NotFoundError('POST_NOT_FOUND', `Post with ID ${id} not found`) + // Update the post row and replace its tags together: a failed tag insert + // must never leave the post with its old tags deleted. + const updatedPost = await db.transaction(async (tx) => { + let row = existingPost + if (Object.keys(updateData).length > 0) { + const [result] = await tx + .update(posts) + .set(updateData) + .where(and(eq(posts.id, id), isNull(posts.deletedAt))) + .returning() + if (!result) { + throw new NotFoundError('POST_NOT_FOUND', `Post with ID ${id} not found`) + } + row = result } - updatedPost = result - } else { - updatedPost = existingPost - } + if (input.tagIds !== undefined) { + await tx.delete(postTagAssignments).where(eq(postTagAssignments.postId, id)) + if (input.tagIds.length > 0) { + await tx + .insert(postTagAssignments) + .values(input.tagIds.map((tagId) => ({ postId: id, tagId }))) + } + } + return row + }) // Regenerate embedding (and cascade to merge check) if title or content changed if (input.title !== undefined || input.content !== undefined || input.contentJson !== undefined) { @@ -474,17 +525,6 @@ export async function updatePost( .catch((err) => log.error({ err, post_id: id }, 'embedding regen failed')) } - // Update tags if provided - if (input.tagIds !== undefined) { - // Remove all existing tags then add new ones if any - await db.delete(postTagAssignments).where(eq(postTagAssignments.postId, id)) - if (input.tagIds.length > 0) { - await db - .insert(postTagAssignments) - .values(input.tagIds.map((tagId) => ({ postId: id, tagId }))) - } - } - if (statusChanged && newStatus) { const previousStatusName = previousStatus?.name ?? 'Open' await dispatchPostStatusChanged( @@ -565,13 +605,13 @@ export async function updatePost( // Record activity for tag changes if (input.tagIds !== undefined) { - const newTagIds = input.tagIds.map((t) => String(t)) + const newTagIds = input.tagIds const added = newTagIds.filter((t) => !currentTagIds.includes(t)) const removed = currentTagIds.filter((t) => !newTagIds.includes(t)) if (added.length > 0 || removed.length > 0) { // Resolve all tag names in one query - const allChangedIds = [...added, ...removed] as PostTagId[] + const allChangedIds = [...added, ...removed] const tagRows = allChangedIds.length > 0 ? await db diff --git a/apps/web/src/lib/server/domains/posts/post.voting.ts b/apps/web/src/lib/server/domains/posts/post.voting.ts index ed673d30a0..5e22047f76 100644 --- a/apps/web/src/lib/server/domains/posts/post.voting.ts +++ b/apps/web/src/lib/server/domains/posts/post.voting.ts @@ -268,13 +268,8 @@ export async function addVoteOnBehalf( const addedByUuid = addedByPrincipalId ? toUuid(addedByPrincipalId) : null const createdAtSql = createdAt ? sql`${createdAt.toISOString()}::timestamptz` : sql`NOW()` - // Single atomic CTE: validate post/board, insert vote (never delete), update count, auto-subscribe - const result = await db.execute<{ - post_exists: boolean - board_exists: boolean - newly_voted: boolean - vote_count: number - }>(sql` + // Single atomic CTE: validate post/board/voter, insert vote (never delete), update count, auto-subscribe + const result = await db.execute(sql` WITH post_check AS ( SELECT c.id, c.board_id, c.vote_count FROM ${posts} p @@ -294,11 +289,15 @@ export async function addVoteOnBehalf( WHERE id = (SELECT board_id FROM post_check) AND deleted_at IS NULL ), + voter_check AS ( + SELECT 1 FROM ${principal} WHERE id = ${principalUuid}::uuid + ), inserted AS ( INSERT INTO ${postVotes} (id, post_id, principal_id, source_type, source_external_url, added_by_principal_id, created_at, updated_at) SELECT ${voteId}::uuid, (SELECT id FROM post_check), ${principalUuid}::uuid, ${sourceType}, ${sourceExternalUrl}, ${addedByUuid}::uuid, ${createdAtSql}, ${createdAtSql} WHERE EXISTS (SELECT 1 FROM post_check) AND EXISTS (SELECT 1 FROM board_check) + AND EXISTS (SELECT 1 FROM voter_check) AND NOT COALESCE((SELECT closed FROM board_closed), false) AND NOT EXISTS ( SELECT 1 FROM ${postVotes} @@ -327,6 +326,7 @@ export async function addVoteOnBehalf( SELECT EXISTS(SELECT 1 FROM post_check) as post_exists, EXISTS(SELECT 1 FROM board_check) as board_exists, + EXISTS(SELECT 1 FROM voter_check) as voter_exists, EXISTS(SELECT 1 FROM inserted) as newly_voted, COALESCE((SELECT vote_count FROM updated_post), (SELECT vote_count FROM post_check), 0) as vote_count, COALESCE((SELECT closed FROM board_closed), false) as blocked @@ -335,6 +335,7 @@ export async function addVoteOnBehalf( type VoteResultRow = { post_exists: boolean board_exists: boolean + voter_exists: boolean newly_voted: boolean vote_count: number blocked: boolean @@ -350,6 +351,10 @@ export async function addVoteOnBehalf( throw new NotFoundError('BOARD_NOT_FOUND', `Board not found for post ${postId}`) } + if (!row.voter_exists) { + throw new NotFoundError('PRINCIPAL_NOT_FOUND', `Voter with ID ${principalId} not found`) + } + if (row.blocked) throw new BoardReadOnlyError() return { voted: row.newly_voted, voteCount: row.vote_count ?? 0 } diff --git a/apps/web/src/routes/api/v1/posts/$postId.ts b/apps/web/src/routes/api/v1/posts/$postId.ts index f38259e006..2da51f5f18 100644 --- a/apps/web/src/routes/api/v1/posts/$postId.ts +++ b/apps/web/src/routes/api/v1/posts/$postId.ts @@ -1,8 +1,9 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' import { realEmail } from '@/lib/shared/anonymous-email' -import { withApiKeyAuth, assertApiPermissions } from '@/lib/server/domains/api/auth' +import { withApiKeyAuth, assertApiPermissions, assertApiScope } from '@/lib/server/domains/api/auth' import { PERMISSIONS, type PermissionKey } from '@/lib/shared/permissions' +import { scopeForPermission } from '@/lib/shared/api-key-scopes' import { successResponse, noContentResponse, @@ -128,8 +129,14 @@ export const Route = createFileRoute('/api/v1/posts/$postId')({ } // The PATCH body can touch several permission-scoped fields; require the - // granular permission for each field actually present. - assertApiPermissions(auth, permissionsForPostPatch(parsed.data)) + // granular permission for each field actually present. The answer carries + // the post, so the caller must also be able to read it, whatever the body. + const fieldPermissions = permissionsForPostPatch(parsed.data) + assertApiPermissions(auth, [...fieldPermissions, PERMISSIONS.POST_VIEW_PRIVATE]) + if (fieldPermissions.length === 0) { + assertApiScope(auth, scopeForPermission(PERMISSIONS.POST_EDIT)) + return badRequestResponse('The request body has no field to update') + } const statusId = parseOptionalTypeId( parsed.data.statusId, diff --git a/apps/web/src/routes/api/v1/posts/__tests__/$postId.patch.test.ts b/apps/web/src/routes/api/v1/posts/__tests__/$postId.patch.test.ts new file mode 100644 index 0000000000..08b6d6e1c6 --- /dev/null +++ b/apps/web/src/routes/api/v1/posts/__tests__/$postId.patch.test.ts @@ -0,0 +1,126 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { PostId, PrincipalId } from '@quackback/ids' +import { PERMISSIONS, type PermissionKey } from '@/lib/shared/permissions' + +const mockWithApiKeyAuth = vi.fn() +const mockUpdatePost = vi.fn() + +vi.mock('@tanstack/react-router', () => ({ + createFileRoute: vi.fn(() => (opts: unknown) => ({ options: opts })), +})) +vi.mock('@/lib/server/domains/api/auth', async (original) => ({ + ...(await original()), + withApiKeyAuth: (...args: unknown[]) => mockWithApiKeyAuth(...args), +})) +vi.mock('@/lib/server/domains/posts/post.service', () => ({ + updatePost: (...args: unknown[]) => mockUpdatePost(...args), +})) + +import { Route } from '../$postId' + +type RouteOpts = { server: { handlers: { PATCH: (...args: unknown[]) => Promise } } } +const PATCH = (Route as unknown as { options: RouteOpts }).options.server.handlers.PATCH + +const POST_ID = 'post_01kqhxq697fvgat0h1abc12345' as unknown as PostId +const KEY_PRINCIPAL = 'principal_01kqhxq697fvgat0fn8rr1r7ew' as unknown as PrincipalId +const ALL_POST_PERMISSIONS: PermissionKey[] = [ + PERMISSIONS.POST_VIEW_PRIVATE, + PERMISSIONS.POST_EDIT, + PERMISSIONS.POST_SET_STATUS, + PERMISSIONS.POST_SET_TAGS, + PERMISSIONS.POST_SET_OWNER, +] + +function keyAuth(scopes: string[] | null, permissions = ALL_POST_PERMISSIONS) { + return { + principalId: KEY_PRINCIPAL, + role: 'admin', + importMode: false, + permissions: new Set(permissions), + apiKey: { name: 'Key', scopes }, + } +} + +function patch(body: unknown) { + return PATCH({ + request: new Request(`http://test/api/v1/posts/${POST_ID}`, { + method: 'PATCH', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }), + params: { postId: POST_ID }, + }) +} + +const post = { + id: POST_ID, + title: 'A secret idea', + content: '', + contentJson: null, + voteCount: 1, + boardId: 'board_01kqhxq697fvgat0h1abc12345', + statusId: null, + ownerPrincipalId: null, + createdAt: new Date('2026-01-01T00:00:00.000Z'), + updatedAt: new Date('2026-01-01T00:00:00.000Z'), +} + +describe('PATCH /api/v1/posts/:postId', () => { + beforeEach(() => { + mockWithApiKeyAuth.mockReset() + mockUpdatePost.mockReset() + mockUpdatePost.mockResolvedValue(post) + }) + + it.each([[{}], [{ boardId: 'board_01kqhxq697fvgat0h1abc12345' }]])( + 'refuses a key without the feedback scopes a body with no field (%j) and returns no post', + async (body) => { + mockWithApiKeyAuth.mockResolvedValue(keyAuth(['read:chat'])) + const res = await patch(body) + expect(res.status).toBe(403) + expect(await res.text()).not.toContain('A secret idea') + expect(mockUpdatePost).not.toHaveBeenCalled() + } + ) + + it('refuses a read-only key a body with no field', async () => { + mockWithApiKeyAuth.mockResolvedValue(keyAuth(['read:feedback'])) + const res = await patch({}) + expect(res.status).toBe(403) + expect(mockUpdatePost).not.toHaveBeenCalled() + }) + + it('answers a writer a body with no field as a bad request, not the post', async () => { + mockWithApiKeyAuth.mockResolvedValue(keyAuth(['write:feedback'])) + const res = await patch({}) + expect(res.status).toBe(400) + expect(await res.text()).not.toContain('A secret idea') + expect(mockUpdatePost).not.toHaveBeenCalled() + }) + + it('refuses a caller who can set a status but cannot read the post', async () => { + mockWithApiKeyAuth.mockResolvedValue( + keyAuth(null, [PERMISSIONS.POST_SET_STATUS, PERMISSIONS.POST_SET_TAGS]) + ) + const res = await patch({ tagIds: [] }) + expect(res.status).toBe(403) + expect(mockUpdatePost).not.toHaveBeenCalled() + }) + + it('names the field permission first when the caller lacks it', async () => { + mockWithApiKeyAuth.mockResolvedValue(keyAuth(['read:feedback'])) + const res = await patch({ tagIds: [] }) + expect(res.status).toBe(403) + expect((await res.json()).error.message).toBe( + "This API key is missing the 'write:feedback' scope required by 'post.set_tags'" + ) + }) + + it('updates and returns the post for a writer', async () => { + mockWithApiKeyAuth.mockResolvedValue(keyAuth(['write:feedback'])) + const res = await patch({ title: 'Renamed' }) + expect(res.status).toBe(200) + expect((await res.json()).data.id).toBe(POST_ID) + expect(mockUpdatePost).toHaveBeenCalledOnce() + }) +})