|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + * |
| 4 | + * v2 query route: predicate parsing, unconditional name→id translation |
| 5 | + * (session auth included — the string grammar is name-keyed for every caller), |
| 6 | + * cursor validation, and the response envelope. |
| 7 | + */ |
| 8 | +import { hybridAuthMockFns } from '@sim/testing' |
| 9 | +import { NextRequest } from 'next/server' |
| 10 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 11 | +import type { TableDefinition } from '@/lib/table/types' |
| 12 | + |
| 13 | +const { mockCheckAccess, mockQueryRows, mockGate } = vi.hoisted(() => ({ |
| 14 | + mockCheckAccess: vi.fn(), |
| 15 | + mockQueryRows: vi.fn(), |
| 16 | + mockGate: vi.fn(), |
| 17 | +})) |
| 18 | + |
| 19 | +vi.mock('@/app/api/table/utils', async () => { |
| 20 | + const { NextResponse } = await import('next/server') |
| 21 | + return { |
| 22 | + checkAccess: mockCheckAccess, |
| 23 | + accessError: (result: { status: number }) => |
| 24 | + NextResponse.json({ error: 'Access denied' }, { status: result.status }), |
| 25 | + tablesV2GateError: mockGate, |
| 26 | + } |
| 27 | +}) |
| 28 | + |
| 29 | +vi.mock('@/lib/table', async () => { |
| 30 | + // row-wire pulls the column-keys helpers through this barrel. |
| 31 | + const columnKeys = await import('@/lib/table/column-keys') |
| 32 | + return { ...columnKeys } |
| 33 | +}) |
| 34 | + |
| 35 | +vi.mock('@/lib/table/rows/service', () => ({ |
| 36 | + queryRows: mockQueryRows, |
| 37 | +})) |
| 38 | + |
| 39 | +import { encodeCursor } from '@/lib/table/rows/cursor' |
| 40 | +import { POST } from '@/app/api/table/[tableId]/query/route' |
| 41 | + |
| 42 | +function buildTable(): TableDefinition { |
| 43 | + return { |
| 44 | + id: 'tbl_1', |
| 45 | + name: 'People', |
| 46 | + description: null, |
| 47 | + schema: { |
| 48 | + columns: [ |
| 49 | + { id: 'col_aaa', name: 'name', type: 'string' }, |
| 50 | + { id: 'col_bbb', name: 'wins', type: 'number' }, |
| 51 | + ], |
| 52 | + }, |
| 53 | + metadata: null, |
| 54 | + rowCount: 0, |
| 55 | + maxRows: 100, |
| 56 | + workspaceId: 'workspace-1', |
| 57 | + createdBy: 'user-1', |
| 58 | + archivedAt: null, |
| 59 | + createdAt: new Date('2024-01-01'), |
| 60 | + updatedAt: new Date('2024-01-01'), |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +function authAs(authType: 'session' | 'internal_jwt') { |
| 65 | + hybridAuthMockFns.mockCheckSessionOrInternalAuth.mockResolvedValue({ |
| 66 | + success: true, |
| 67 | + userId: 'user-1', |
| 68 | + authType, |
| 69 | + }) |
| 70 | +} |
| 71 | + |
| 72 | +function callQuery(body: Record<string, unknown>) { |
| 73 | + const req = new NextRequest('http://localhost:3000/api/table/tbl_1/query', { |
| 74 | + method: 'POST', |
| 75 | + headers: { 'Content-Type': 'application/json' }, |
| 76 | + body: JSON.stringify(body), |
| 77 | + }) |
| 78 | + return POST(req, { params: Promise.resolve({ tableId: 'tbl_1' }) }) |
| 79 | +} |
| 80 | + |
| 81 | +const EMPTY_RESULT = { |
| 82 | + rows: [], |
| 83 | + rowCount: 0, |
| 84 | + totalCount: 0, |
| 85 | + limit: 0, |
| 86 | + offset: 0, |
| 87 | + nextCursor: null, |
| 88 | +} |
| 89 | + |
| 90 | +describe('POST /api/table/[tableId]/query', () => { |
| 91 | + beforeEach(() => { |
| 92 | + vi.clearAllMocks() |
| 93 | + mockCheckAccess.mockResolvedValue({ ok: true, table: buildTable() }) |
| 94 | + mockQueryRows.mockResolvedValue(EMPTY_RESULT) |
| 95 | + mockGate.mockResolvedValue(null) |
| 96 | + }) |
| 97 | + |
| 98 | + it('returns 404 when the tables-v2-api flag is off', async () => { |
| 99 | + const { NextResponse } = await import('next/server') |
| 100 | + authAs('session') |
| 101 | + mockGate.mockResolvedValue(NextResponse.json({ error: 'Not found' }, { status: 404 })) |
| 102 | + const res = await callQuery({ workspaceId: 'workspace-1' }) |
| 103 | + expect(res.status).toBe(404) |
| 104 | + expect(mockQueryRows).not.toHaveBeenCalled() |
| 105 | + }) |
| 106 | + |
| 107 | + it('runs the flag gate only after the access check, so it cannot leak a cohort oracle', async () => { |
| 108 | + authAs('session') |
| 109 | + mockCheckAccess.mockResolvedValue({ ok: false, status: 403 }) |
| 110 | + const res = await callQuery({ workspaceId: 'workspace-1' }) |
| 111 | + expect(res.status).toBe(403) |
| 112 | + expect(mockGate).not.toHaveBeenCalled() |
| 113 | + }) |
| 114 | + |
| 115 | + it('translates predicate/sort column names to storage ids for SESSION auth too', async () => { |
| 116 | + authAs('session') |
| 117 | + const res = await callQuery({ |
| 118 | + workspaceId: 'workspace-1', |
| 119 | + predicate: { |
| 120 | + all: [ |
| 121 | + { field: 'name', op: 'eq', value: 'John' }, |
| 122 | + { field: 'wins', op: 'gte', value: 10 }, |
| 123 | + ], |
| 124 | + }, |
| 125 | + sort: [{ field: 'wins', direction: 'desc' }], |
| 126 | + }) |
| 127 | + |
| 128 | + expect(res.status).toBe(200) |
| 129 | + const options = mockQueryRows.mock.calls[0][1] |
| 130 | + expect(options.predicate).toEqual({ |
| 131 | + all: [ |
| 132 | + { field: 'col_aaa', op: 'eq', value: 'John' }, |
| 133 | + { field: 'col_bbb', op: 'gte', value: 10 }, |
| 134 | + ], |
| 135 | + }) |
| 136 | + expect(options.sort).toEqual({ col_bbb: 'desc' }) |
| 137 | + expect(options.withExecutions).toBe(false) |
| 138 | + }) |
| 139 | + |
| 140 | + it('rejects a keyset cursor combined with a custom sort', async () => { |
| 141 | + authAs('internal_jwt') |
| 142 | + const cursor = encodeCursor({ |
| 143 | + lastRow: { id: 'row_1', orderKey: 'a1' }, |
| 144 | + keysetValid: true, |
| 145 | + nextOffset: 1, |
| 146 | + }) |
| 147 | + const res = await callQuery({ |
| 148 | + workspaceId: 'workspace-1', |
| 149 | + sort: [{ field: 'wins', direction: 'desc' }], |
| 150 | + cursor, |
| 151 | + }) |
| 152 | + |
| 153 | + expect(res.status).toBe(400) |
| 154 | + const body = await res.json() |
| 155 | + expect(body.error).toMatch(/not valid for a sorted query/) |
| 156 | + expect(body.code).toBe('CURSOR_SORT_CONFLICT') |
| 157 | + expect(mockQueryRows).not.toHaveBeenCalled() |
| 158 | + }) |
| 159 | + |
| 160 | + it('returns 400 (not 500) for a cursor that decodes to a JSON primitive', async () => { |
| 161 | + authAs('internal_jwt') |
| 162 | + const res = await callQuery({ |
| 163 | + workspaceId: 'workspace-1', |
| 164 | + cursor: Buffer.from('42').toString('base64url'), |
| 165 | + }) |
| 166 | + |
| 167 | + expect(res.status).toBe(400) |
| 168 | + const body = await res.json() |
| 169 | + expect(body.error).toBe('Invalid cursor') |
| 170 | + expect(body.code).toBe('INVALID_CURSOR') |
| 171 | + }) |
| 172 | + |
| 173 | + it('returns 400 for a predicate referencing an unknown column', async () => { |
| 174 | + authAs('internal_jwt') |
| 175 | + const res = await callQuery({ |
| 176 | + workspaceId: 'workspace-1', |
| 177 | + predicate: { all: [{ field: 'nope', op: 'eq', value: 1 }] }, |
| 178 | + }) |
| 179 | + |
| 180 | + expect(res.status).toBe(400) |
| 181 | + expect((await res.json()).error).toMatch(/Unknown filter column/) |
| 182 | + }) |
| 183 | + |
| 184 | + it('passes nextCursor through the response envelope and skips the count on later pages', async () => { |
| 185 | + authAs('internal_jwt') |
| 186 | + mockQueryRows.mockResolvedValue({ ...EMPTY_RESULT, nextCursor: 'tok' }) |
| 187 | + const cursor = encodeCursor({ |
| 188 | + lastRow: { id: 'row_1', orderKey: 'a1' }, |
| 189 | + keysetValid: true, |
| 190 | + nextOffset: 1, |
| 191 | + }) |
| 192 | + |
| 193 | + const res = await callQuery({ workspaceId: 'workspace-1', cursor }) |
| 194 | + |
| 195 | + expect(res.status).toBe(200) |
| 196 | + const body = await res.json() |
| 197 | + expect(body.data.nextCursor).toBe('tok') |
| 198 | + const options = mockQueryRows.mock.calls[0][1] |
| 199 | + expect(options.includeTotal).toBe(false) |
| 200 | + expect(options.after).toEqual({ orderKey: 'a1', id: 'row_1' }) |
| 201 | + }) |
| 202 | +}) |
0 commit comments