|
| 1 | +/** |
| 2 | + * IdempotencyMiddleware unit tests. |
| 3 | + * |
| 4 | + * Uses in-memory stubs for Redis — no real Redis required. |
| 5 | + */ |
| 6 | + |
| 7 | +import { BadRequestException } from '@nestjs/common'; |
| 8 | +import { IdempotencyMiddleware, IDEMPOTENCY_VERSION } from '../common/middleware/idempotency.middleware'; |
| 9 | +import * as cache from '../redis/cache'; |
| 10 | + |
| 11 | +// ── Helpers ─────────────────────────────────────────────────────────────────── |
| 12 | + |
| 13 | +function makeReq(overrides: Partial<{ |
| 14 | + method: string; |
| 15 | + path: string; |
| 16 | + headers: Record<string, string>; |
| 17 | + user: { sub: string }; |
| 18 | +}> = {}): any { |
| 19 | + return { |
| 20 | + method: 'POST', |
| 21 | + path: '/ipfs/upload', |
| 22 | + headers: {}, |
| 23 | + ...overrides, |
| 24 | + }; |
| 25 | +} |
| 26 | + |
| 27 | +function makeRes(): any { |
| 28 | + const res: any = { |
| 29 | + statusCode: 200, |
| 30 | + _headers: {} as Record<string, string>, |
| 31 | + _body: undefined as unknown, |
| 32 | + setHeader(k: string, v: string) { this._headers[k] = v; }, |
| 33 | + status(code: number) { this.statusCode = code; return this; }, |
| 34 | + json(body: unknown) { this._body = body; return this; }, |
| 35 | + }; |
| 36 | + res.json = res.json.bind(res); |
| 37 | + return res; |
| 38 | +} |
| 39 | + |
| 40 | +const VALID_KEY = '550e8400-e29b-41d4-a716-446655440000'; |
| 41 | + |
| 42 | +// ── Tests ───────────────────────────────────────────────────────────────────── |
| 43 | + |
| 44 | +describe('IdempotencyMiddleware', () => { |
| 45 | + let middleware: IdempotencyMiddleware; |
| 46 | + let getEntry: jest.SpyInstance; |
| 47 | + let setEntry: jest.SpyInstance; |
| 48 | + |
| 49 | + beforeEach(() => { |
| 50 | + middleware = new IdempotencyMiddleware(); |
| 51 | + getEntry = jest.spyOn(cache, 'getIdempotencyEntry').mockResolvedValue(null); |
| 52 | + setEntry = jest.spyOn(cache, 'setIdempotencyEntry').mockResolvedValue(undefined); |
| 53 | + }); |
| 54 | + |
| 55 | + afterEach(() => jest.restoreAllMocks()); |
| 56 | + |
| 57 | + test('passes through when no Idempotency-Key header', async () => { |
| 58 | + const req = makeReq(); |
| 59 | + const res = makeRes(); |
| 60 | + const next = jest.fn(); |
| 61 | + await middleware.use(req, res, next); |
| 62 | + expect(next).toHaveBeenCalled(); |
| 63 | + expect(getEntry).not.toHaveBeenCalled(); |
| 64 | + }); |
| 65 | + |
| 66 | + test('rejects malformed key (not UUID v4) with 400', async () => { |
| 67 | + const req = makeReq({ headers: { 'idempotency-key': 'not-a-uuid' } }); |
| 68 | + await expect(middleware.use(req, makeRes(), jest.fn())).rejects.toBeInstanceOf(BadRequestException); |
| 69 | + }); |
| 70 | + |
| 71 | + test('rejects key with wrong UUID version (v1)', async () => { |
| 72 | + const v1Key = '550e8400-e29b-11d4-a716-446655440000'; // version digit = 1 |
| 73 | + const req = makeReq({ headers: { 'idempotency-key': v1Key } }); |
| 74 | + await expect(middleware.use(req, makeRes(), jest.fn())).rejects.toBeInstanceOf(BadRequestException); |
| 75 | + }); |
| 76 | + |
| 77 | + test('cache miss: calls next and stores response on json()', async () => { |
| 78 | + const req = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 79 | + const res = makeRes(); |
| 80 | + const next = jest.fn(); |
| 81 | + |
| 82 | + await middleware.use(req, res, next); |
| 83 | + expect(next).toHaveBeenCalled(); |
| 84 | + |
| 85 | + // Simulate handler writing a response |
| 86 | + res.json({ cid: 'Qm123' }); |
| 87 | + |
| 88 | + // Wait for the async setEntry call |
| 89 | + await new Promise(resolve => setImmediate(resolve)); |
| 90 | + expect(setEntry).toHaveBeenCalledWith( |
| 91 | + expect.any(String), |
| 92 | + { status: 200, body: { cid: 'Qm123' }, version: IDEMPOTENCY_VERSION }, |
| 93 | + expect.any(Number), |
| 94 | + ); |
| 95 | + }); |
| 96 | + |
| 97 | + test('cache hit: replays stored response without calling next', async () => { |
| 98 | + getEntry.mockResolvedValue({ status: 200, body: { cid: 'Qm123' }, version: IDEMPOTENCY_VERSION }); |
| 99 | + const req = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 100 | + const res = makeRes(); |
| 101 | + const next = jest.fn(); |
| 102 | + |
| 103 | + await middleware.use(req, res, next); |
| 104 | + |
| 105 | + expect(next).not.toHaveBeenCalled(); |
| 106 | + expect(res._body).toEqual({ cid: 'Qm123' }); |
| 107 | + expect(res._headers['Idempotency-Replayed']).toBe('true'); |
| 108 | + }); |
| 109 | + |
| 110 | + test('double-submit returns identical body on second call', async () => { |
| 111 | + // First call — cache miss |
| 112 | + const req1 = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 113 | + const res1 = makeRes(); |
| 114 | + await middleware.use(req1, res1, jest.fn()); |
| 115 | + res1.json({ cid: 'QmABC' }); |
| 116 | + await new Promise(resolve => setImmediate(resolve)); |
| 117 | + |
| 118 | + // Capture what was stored |
| 119 | + const stored = setEntry.mock.calls[0][1] as cache.IdempotencyEntry; |
| 120 | + |
| 121 | + // Second call — cache hit |
| 122 | + getEntry.mockResolvedValue(stored); |
| 123 | + const req2 = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 124 | + const res2 = makeRes(); |
| 125 | + const next2 = jest.fn(); |
| 126 | + await middleware.use(req2, res2, next2); |
| 127 | + |
| 128 | + expect(next2).not.toHaveBeenCalled(); |
| 129 | + expect(res2._body).toEqual({ cid: 'QmABC' }); |
| 130 | + }); |
| 131 | + |
| 132 | + test('5xx responses are NOT cached', async () => { |
| 133 | + const req = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 134 | + const res = makeRes(); |
| 135 | + res.statusCode = 503; |
| 136 | + await middleware.use(req, res, jest.fn()); |
| 137 | + res.json({ error: 'service_unavailable' }); |
| 138 | + await new Promise(resolve => setImmediate(resolve)); |
| 139 | + expect(setEntry).not.toHaveBeenCalled(); |
| 140 | + }); |
| 141 | + |
| 142 | + test('4xx error responses ARE cached (replay error to client)', async () => { |
| 143 | + const req = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 144 | + const res = makeRes(); |
| 145 | + res.statusCode = 400; |
| 146 | + await middleware.use(req, res, jest.fn()); |
| 147 | + res.json({ error: 'invalid_file' }); |
| 148 | + await new Promise(resolve => setImmediate(resolve)); |
| 149 | + expect(setEntry).toHaveBeenCalledWith( |
| 150 | + expect.any(String), |
| 151 | + { status: 400, body: { error: 'invalid_file' }, version: IDEMPOTENCY_VERSION }, |
| 152 | + expect.any(Number), |
| 153 | + ); |
| 154 | + }); |
| 155 | + |
| 156 | + test('different subjects produce different cache keys (scope isolation)', async () => { |
| 157 | + const capturedKeys: string[] = []; |
| 158 | + setEntry.mockImplementation(async (key: string) => { capturedKeys.push(key); }); |
| 159 | + |
| 160 | + const req1 = makeReq({ headers: { 'idempotency-key': VALID_KEY }, user: { sub: 'userA' } }); |
| 161 | + const res1 = makeRes(); |
| 162 | + await middleware.use(req1, res1, jest.fn()); |
| 163 | + res1.json({ ok: true }); |
| 164 | + |
| 165 | + const req2 = makeReq({ headers: { 'idempotency-key': VALID_KEY }, user: { sub: 'userB' } }); |
| 166 | + const res2 = makeRes(); |
| 167 | + await middleware.use(req2, res2, jest.fn()); |
| 168 | + res2.json({ ok: true }); |
| 169 | + |
| 170 | + await new Promise(resolve => setImmediate(resolve)); |
| 171 | + expect(capturedKeys[0]).not.toBe(capturedKeys[1]); |
| 172 | + }); |
| 173 | + |
| 174 | + test('Redis unavailable: fails open and calls next', async () => { |
| 175 | + getEntry.mockRejectedValue(new Error('Redis down')); |
| 176 | + const req = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 177 | + const next = jest.fn(); |
| 178 | + // Should not throw — fail open |
| 179 | + await expect(middleware.use(req, makeRes(), next)).resolves.toBeUndefined(); |
| 180 | + expect(next).toHaveBeenCalled(); |
| 181 | + }); |
| 182 | + |
| 183 | + test('version mismatch treated as cache miss', async () => { |
| 184 | + // Stored entry has old version |
| 185 | + getEntry.mockResolvedValue({ status: 200, body: { old: true }, version: IDEMPOTENCY_VERSION - 1 }); |
| 186 | + // getIdempotencyEntry already filters by version — returns null for mismatch |
| 187 | + getEntry.mockResolvedValue(null); |
| 188 | + |
| 189 | + const req = makeReq({ headers: { 'idempotency-key': VALID_KEY } }); |
| 190 | + const next = jest.fn(); |
| 191 | + await middleware.use(req, makeRes(), next); |
| 192 | + expect(next).toHaveBeenCalled(); |
| 193 | + }); |
| 194 | +}); |
0 commit comments