Match a submission's client token only within its event
Test and deploy / test-and-deploy (pull_request) Successful in 27s

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 <noreply@anthropic.com>
This commit is contained in:
PaddyandClaude Opus 5.5 committed 2026-11-16 18:27:27 +01:00
1 parent f3f4ca2c9f
commit adf723419d
4 files changed
+38 -13

No files matched your search

@@ -7,8 +7,11 @@
-- sees an error and taps "absenden" again; the API now finds the stored token -- 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. -- 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 -- NULL for every row written before this migration and for any client that
-- sends no token; a UNIQUE index allows any number of NULLs. -- sends no token; a UNIQUE index allows any number of NULLs.
ALTER TABLE submissions ALTER TABLE submissions
ADD COLUMN client_token CHAR(36) NULL AFTER ip_hash, 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);
@@ -59,7 +59,7 @@
* clientToken: * clientToken:
* type: string * type: string
* format: uuid * 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: * SubmissionResponse:
* type: object * type: object
* properties: * properties:
@@ -149,10 +149,16 @@ export const normalizeClientToken = (token: unknown): string | null => {
return typeof token === 'string' && CLIENT_TOKEN_RE.test(token) ? token.toLowerCase() : null; return typeof token === 'string' && CLIENT_TOKEN_RE.test(token) ? token.toLowerCase() : null;
}; };
const findSubmissionIdByClientToken = async (clientToken: string): Promise<number | null> => { // 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<number | null> => {
const conn = await NachklangFeedbackDB.getConnection(); const conn = await NachklangFeedbackDB.getConnection();
try { 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; return rows.length > 0 ? rows[0].submission_id : null;
} finally { } finally {
await conn.end(); 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 // Checked before eligibility, so a retry still succeeds if the feedback
// window closed in the seconds after the original saved. // window closed in the seconds after the original saved.
if (clientToken) { if (clientToken) {
const existingId = await findSubmissionIdByClientToken(clientToken); const existingId = await findSubmissionIdByClientToken(clientToken, slug);
if (existingId !== null) { if (existingId !== null) {
logger.info('Feedback submission retry answered with the stored submission', {submissionId: existingId}); logger.info('Feedback submission retry answered with the stored submission', {submissionId: existingId});
return {status: 'OK', submissionId: existingId, newsletterDropped}; return {status: 'OK', submissionId: existingId, newsletterDropped};
@@ -259,9 +265,9 @@ export const submitFeedback = async (slug: string, body: SubmissionRequestBody,
} catch (err: any) { } catch (err: any) {
await conn.rollback(); await conn.rollback();
// Two copies of the same retry both got past the lookup above; the // 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') { if (clientToken && err?.code === 'ER_DUP_ENTRY') {
const existingId = await findSubmissionIdByClientToken(clientToken); const existingId = await findSubmissionIdByClientToken(clientToken, slug);
if (existingId !== null) { if (existingId !== null) {
return {status: 'OK', submissionId: existingId, newsletterDropped}; return {status: 'OK', submissionId: existingId, newsletterDropped};
} }
+22 -6
View File
@@ -23,12 +23,16 @@ const mockGetEventConfigBySlug = getEventConfigBySlug as Mock;
const TOKEN = '3f2b8c1e-4d5a-4b6c-9e7f-0a1b2c3d4e5f'; const TOKEN = '3f2b8c1e-4d5a-4b6c-9e7f-0a1b2c3d4e5f';
const BODY = {answers: [{eventQuestionId: 26, text: 'Danke!'}], clientToken: TOKEN}; 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 // One fake connection serves every query; `existingId` is what a lookup by
// client_token finds, and `insertError` makes the submissions INSERT throw. // client_token finds when it was stored for `existingSlug`, and
const makeConn = ({existingId = null, insertError = null}: {existingId?: number | null; insertError?: any} = {}) => ({ // `insertError` makes the submissions INSERT throw.
query: vi.fn(async (sql: string) => { const makeConn = ({existingId = null, existingSlug = SLUG, insertError = null}: {existingId?: number | null; existingSlug?: string; insertError?: any} = {}) => ({
if (sql.startsWith('SELECT submission_id FROM submissions')) { query: vi.fn(async (sql: string, params: any[] = []) => {
return existingId === null ? [] : [{submission_id: existingId}]; if (sql.startsWith(LOOKUP_SQL)) {
return existingId === null || params[1] !== existingSlug ? [] : [{submission_id: existingId}];
} }
if (sql.startsWith('INSERT INTO submissions')) { if (sql.startsWith('INSERT INTO submissions')) {
if (insertError) throw insertError; if (insertError) throw insertError;
@@ -88,13 +92,25 @@ describe('submitFeedback - client token idempotency', () => {
expect(insert[1]).toContain(TOKEN); 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 () => { it('ignores a malformed token: no lookup, and the row is stored without one', async () => {
const conn = makeConn(); const conn = makeConn();
mockGetConnection.mockResolvedValue(conn); mockGetConnection.mockResolvedValue(conn);
await submitFeedback('sommerkonzert-2026', {...BODY, clientToken: 'not-a-uuid'}, 'hash'); 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'))!; const insert = allQueries(conn).find(([sql]) => sql.startsWith('INSERT INTO submissions'))!;
expect(insert[1]).not.toContain('not-a-uuid'); expect(insert[1]).not.toContain('not-a-uuid');
expect(insert[1][insert[1].length - 1]).toBeNull(); expect(insert[1][insert[1].length - 1]).toBeNull();