Files
API/test/feedback/submissions.idempotency.test.ts
T
PaddyandClaude Opus 5.5 adf723419d
Test and deploy / test-and-deploy (pull_request) Successful in 27s
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 <noreply@anthropic.com>
2026-11-16 18:27:27 +01:00

144 lines
6.2 KiB
TypeScript

import {vi, describe, it, expect, beforeEach, type Mock} from 'vitest';
vi.mock('../../src/models/feedback/Feedback.db.js', () => ({
NachklangFeedbackDB: {getConnection: vi.fn()}
}));
vi.mock('../../src/models/feedback/public/events.public.service.js', () => ({
getEventConfigBySlug: vi.fn()
}));
vi.mock('../../src/models/feedback/integrations/salesforce.service.js', () => ({
syncNewsletterSignup: vi.fn().mockResolvedValue(undefined)
}));
vi.mock('../../src/middleware/logger.js', () => ({
__esModule: true,
default: {info: vi.fn(), error: vi.fn()}
}));
import {NachklangFeedbackDB} from '../../src/models/feedback/Feedback.db.js';
import {getEventConfigBySlug} from '../../src/models/feedback/public/events.public.service.js';
import {submitFeedback} from '../../src/models/feedback/public/submissions.service.js';
const mockGetConnection = NachklangFeedbackDB.getConnection as Mock;
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 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;
return [{submission_id: 90}];
}
return [];
}),
beginTransaction: vi.fn().mockResolvedValue(undefined),
commit: vi.fn().mockResolvedValue(undefined),
rollback: vi.fn().mockResolvedValue(undefined),
end: vi.fn().mockResolvedValue(undefined)
});
const allQueries = (conn: ReturnType<typeof makeConn>): [string, any[]][] => conn.query.mock.calls as any;
describe('submitFeedback - client token idempotency', () => {
beforeEach(() => {
mockGetConnection.mockReset();
mockGetEventConfigBySlug.mockReset();
mockGetEventConfigBySlug.mockResolvedValue({
status: 'OK',
eventId: 22,
event: {
questions: [{eventQuestionId: 26, questionId: 4, type: 'FREE_TEXT', label: 'Sonstiges', position: 0}],
songs: []
}
});
});
it('returns the already-saved submission for a repeated token without inserting again', async () => {
const conn = makeConn({existingId: 82});
mockGetConnection.mockResolvedValue(conn);
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
expect(result).toEqual({status: 'OK', submissionId: 82, newsletterDropped: false});
expect(allQueries(conn).some(([sql]) => sql.startsWith('INSERT'))).toBe(false);
});
it('still answers a retry with the saved submission after the feedback window closed', async () => {
mockGetConnection.mockResolvedValue(makeConn({existingId: 82}));
mockGetEventConfigBySlug.mockResolvedValue({status: 'CLOSED'});
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
expect(result).toEqual({status: 'OK', submissionId: 82, newsletterDropped: false});
});
it('stores a new token, lowercased, on the submissions row', async () => {
const conn = makeConn();
mockGetConnection.mockResolvedValue(conn);
const result = await submitFeedback('sommerkonzert-2026', {...BODY, clientToken: TOKEN.toUpperCase()}, 'hash');
expect(result).toEqual({status: 'OK', submissionId: 90, newsletterDropped: false});
const insert = allQueries(conn).find(([sql]) => sql.startsWith('INSERT INTO submissions'))!;
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(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();
});
it('resolves a concurrent duplicate that loses the race on the unique index to the winning submission', async () => {
const dupError = Object.assign(new Error('Duplicate entry'), {code: 'ER_DUP_ENTRY', errno: 1062});
const racingConn = makeConn({insertError: dupError});
// First lookup (before the INSERT) finds nothing; the one after the
// duplicate-key error finds the row the other request committed.
const lookupAfterRace = makeConn({existingId: 83});
mockGetConnection
.mockResolvedValueOnce(makeConn())
.mockResolvedValueOnce(racingConn)
.mockResolvedValueOnce(lookupAfterRace);
const result = await submitFeedback('sommerkonzert-2026', BODY, 'hash');
expect(result).toEqual({status: 'OK', submissionId: 83, newsletterDropped: false});
expect(racingConn.rollback).toHaveBeenCalled();
expect(racingConn.commit).not.toHaveBeenCalled();
});
it('rethrows a duplicate-key error when the request carried no token', async () => {
const dupError = Object.assign(new Error('Duplicate entry'), {code: 'ER_DUP_ENTRY', errno: 1062});
mockGetConnection.mockResolvedValue(makeConn({insertError: dupError}));
await expect(submitFeedback('sommerkonzert-2026', {answers: BODY.answers}, 'hash')).rejects.toThrow('Duplicate entry');
});
});