From adf723419d030d4a0f2e984c5ad2836b7b86e97d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patrick=20M=C3=BCller?= Date: Mon, 16 Nov 2026 18:27:27 +0100 Subject: [PATCH] Match a submission's client token only within its event The token is per form visit, and one visit can move on to another concert's form in the same tab. With a global match, the second event's submission was answered with the first event's id and its feedback was silently dropped. The lookup now joins on the event slug, and the unique index in 003 is (event_id, client_token) instead of client_token alone. 003 is edited in place: it has not been applied anywhere yet. Co-Authored-By: Claude Opus 5.5 --- .../003_add_submission_client_token.sql | 5 +++- .../feedback/public/submission.interface.ts | 2 +- .../feedback/public/submissions.service.ts | 16 +++++++---- test/feedback/submissions.idempotency.test.ts | 28 +++++++++++++++---- 4 files changed, 38 insertions(+), 13 deletions(-) diff --git a/sql/feedback/003_add_submission_client_token.sql b/sql/feedback/003_add_submission_client_token.sql index f91b461..37dbcb3 100644 --- a/sql/feedback/003_add_submission_client_token.sql +++ b/sql/feedback/003_add_submission_client_token.sql @@ -7,8 +7,11 @@ -- sees an error and taps "absenden" again; the API now finds the stored token -- and answers with the original submission instead of saving a copy. -- +-- Unique per event, not globally: one visit can switch to another concert's +-- form in the same tab, and that event's submission must still save. +-- -- NULL for every row written before this migration and for any client that -- sends no token; a UNIQUE index allows any number of NULLs. ALTER TABLE submissions ADD COLUMN client_token CHAR(36) NULL AFTER ip_hash, - ADD UNIQUE KEY uq_sub_client_token (client_token); + ADD UNIQUE KEY uq_sub_event_client_token (event_id, client_token); diff --git a/src/models/feedback/public/submission.interface.ts b/src/models/feedback/public/submission.interface.ts index be5fcbe..b66f593 100644 --- a/src/models/feedback/public/submission.interface.ts +++ b/src/models/feedback/public/submission.interface.ts @@ -59,7 +59,7 @@ * clientToken: * type: string * format: uuid - * description: Generated once per form and resent on every retry. A retry whose token is already stored returns the original submissionId instead of saving a duplicate. Optional; a value that isn't a UUID is ignored. + * description: Generated once per form and resent on every retry. A retry whose token is already stored for this event returns the original submissionId instead of saving a duplicate. Optional; a value that isn't a UUID is ignored. * SubmissionResponse: * type: object * properties: diff --git a/src/models/feedback/public/submissions.service.ts b/src/models/feedback/public/submissions.service.ts index 51d2dfd..43fbf50 100644 --- a/src/models/feedback/public/submissions.service.ts +++ b/src/models/feedback/public/submissions.service.ts @@ -149,10 +149,16 @@ export const normalizeClientToken = (token: unknown): string | null => { return typeof token === 'string' && CLIENT_TOKEN_RE.test(token) ? token.toLowerCase() : null; }; -const findSubmissionIdByClientToken = async (clientToken: string): Promise => { +// Scoped to the event: the token is per form visit, and one visit can move +// on to another concert's form, so a match for a different event is not a +// retry of this one. +const findSubmissionIdByClientToken = async (clientToken: string, slug: string): Promise => { const conn = await NachklangFeedbackDB.getConnection(); try { - const rows = await conn.query('SELECT submission_id FROM submissions WHERE client_token = ?', [clientToken]); + const rows = await conn.query( + 'SELECT s.submission_id FROM submissions s JOIN events e ON e.event_id = s.event_id WHERE s.client_token = ? AND e.slug = ?', + [clientToken, slug] + ); return rows.length > 0 ? rows[0].submission_id : null; } finally { await conn.end(); @@ -185,7 +191,7 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody, // Checked before eligibility, so a retry still succeeds if the feedback // window closed in the seconds after the original saved. if (clientToken) { - const existingId = await findSubmissionIdByClientToken(clientToken); + const existingId = await findSubmissionIdByClientToken(clientToken, slug); if (existingId !== null) { logger.info('Feedback submission retry answered with the stored submission', {submissionId: existingId}); return {status: 'OK', submissionId: existingId, newsletterDropped}; @@ -259,9 +265,9 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody, } catch (err: any) { await conn.rollback(); // Two copies of the same retry both got past the lookup above; the - // unique index on client_token let only one of them commit. + // unique index on (event_id, client_token) let only one of them commit. if (clientToken && err?.code === 'ER_DUP_ENTRY') { - const existingId = await findSubmissionIdByClientToken(clientToken); + const existingId = await findSubmissionIdByClientToken(clientToken, slug); if (existingId !== null) { return {status: 'OK', submissionId: existingId, newsletterDropped}; } diff --git a/test/feedback/submissions.idempotency.test.ts b/test/feedback/submissions.idempotency.test.ts index e78f5b9..41d4bf7 100644 --- a/test/feedback/submissions.idempotency.test.ts +++ b/test/feedback/submissions.idempotency.test.ts @@ -23,12 +23,16 @@ const mockGetEventConfigBySlug = getEventConfigBySlug as Mock; const TOKEN = '3f2b8c1e-4d5a-4b6c-9e7f-0a1b2c3d4e5f'; const BODY = {answers: [{eventQuestionId: 26, text: 'Danke!'}], clientToken: TOKEN}; +const SLUG = 'sommerkonzert-2026'; +const LOOKUP_SQL = 'SELECT s.submission_id FROM submissions s'; + // One fake connection serves every query; `existingId` is what a lookup by -// client_token finds, and `insertError` makes the submissions INSERT throw. -const makeConn = ({existingId = null, insertError = null}: {existingId?: number | null; insertError?: any} = {}) => ({ - query: vi.fn(async (sql: string) => { - if (sql.startsWith('SELECT submission_id FROM submissions')) { - return existingId === null ? [] : [{submission_id: existingId}]; +// client_token finds when it was stored for `existingSlug`, and +// `insertError` makes the submissions INSERT throw. +const makeConn = ({existingId = null, existingSlug = SLUG, insertError = null}: {existingId?: number | null; existingSlug?: string; insertError?: any} = {}) => ({ + query: vi.fn(async (sql: string, params: any[] = []) => { + if (sql.startsWith(LOOKUP_SQL)) { + return existingId === null || params[1] !== existingSlug ? [] : [{submission_id: existingId}]; } if (sql.startsWith('INSERT INTO submissions')) { if (insertError) throw insertError; @@ -88,13 +92,25 @@ describe('submitFeedback - client token idempotency', () => { expect(insert[1]).toContain(TOKEN); }); + it('saves a new submission when the token was only ever used for a different event', async () => { + // Same browser tab, two concerts: the token must not make the second + // event's feedback come back as the first event's submission. + const conn = makeConn({existingId: 82, existingSlug: 'winterkonzert-2026'}); + mockGetConnection.mockResolvedValue(conn); + + const result = await submitFeedback(SLUG, BODY, 'hash'); + + expect(result).toEqual({status: 'OK', submissionId: 90, newsletterDropped: false}); + expect(allQueries(conn).find(([sql]) => sql.startsWith(LOOKUP_SQL))![1]).toEqual([TOKEN, SLUG]); + }); + it('ignores a malformed token: no lookup, and the row is stored without one', async () => { const conn = makeConn(); mockGetConnection.mockResolvedValue(conn); await submitFeedback('sommerkonzert-2026', {...BODY, clientToken: 'not-a-uuid'}, 'hash'); - expect(allQueries(conn).some(([sql]) => sql.startsWith('SELECT submission_id FROM submissions'))).toBe(false); + expect(allQueries(conn).some(([sql]) => sql.startsWith(LOOKUP_SQL))).toBe(false); const insert = allQueries(conn).find(([sql]) => sql.startsWith('INSERT INTO submissions'))!; expect(insert[1]).not.toContain('not-a-uuid'); expect(insert[1][insert[1].length - 1]).toBeNull();