fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { fetchAllRows } from '../fetch-all'
|
||||
|
||||
const PAGE_SIZE = 1000
|
||||
|
||||
type Row = { id: string; value?: number }
|
||||
|
||||
/**
|
||||
* Build a queryFn that serves predefined pages keyed by the `from` offset.
|
||||
* Mirrors how `fetchAllRows` drives PostgREST `.range(from, to)`.
|
||||
*/
|
||||
function pagedQuery(pages: Record<number, Row[]>) {
|
||||
return ({ from }: { from: number; to: number }) =>
|
||||
Promise.resolve({ data: pages[from] ?? [], error: null })
|
||||
}
|
||||
|
||||
function makeRows(start: number, count: number): Row[] {
|
||||
return Array.from({ length: count }, (_, i) => ({ id: String(start + i), value: 1 }))
|
||||
}
|
||||
|
||||
describe('fetchAllRows', () => {
|
||||
it('returns a single page as-is and stops (page < PAGE_SIZE)', async () => {
|
||||
const rows = makeRows(0, 3)
|
||||
const out = await fetchAllRows<Row>(pagedQuery({ 0: rows }))
|
||||
expect(out).toHaveLength(3)
|
||||
expect(out.map((r) => r.id)).toEqual(['0', '1', '2'])
|
||||
})
|
||||
|
||||
it('paginates across multiple pages and concatenates in order', async () => {
|
||||
const page1 = makeRows(0, PAGE_SIZE) // full page → fetch continues
|
||||
const page2 = makeRows(PAGE_SIZE, 5) // partial page → stop
|
||||
const out = await fetchAllRows<Row>(pagedQuery({ 0: page1, [PAGE_SIZE]: page2 }))
|
||||
expect(out).toHaveLength(PAGE_SIZE + 5)
|
||||
expect(out[0].id).toBe('0')
|
||||
expect(out[out.length - 1].id).toBe(String(PAGE_SIZE + 4))
|
||||
})
|
||||
|
||||
it('throws when the query returns an error', async () => {
|
||||
await expect(
|
||||
fetchAllRows<Row>(() => Promise.resolve({ data: null, error: { message: 'boom' } })),
|
||||
).rejects.toThrow('boom')
|
||||
})
|
||||
|
||||
it('propagates the driver SQLSTATE so a timeout stays dispatchable', async () => {
|
||||
// This is the highest-traffic error strip point in the codebase: every
|
||||
// paginated read goes through it. It used to throw `new Error(msg)`, which
|
||||
// dropped `code`, so a statement timeout (57014) reached the structured
|
||||
// error layer anonymous and resolved to UNKNOWN_ERROR instead of the
|
||||
// retryable TRANSIENT_ERROR. gnubok_query_journal failed this way 164
|
||||
// times in 60 days at a p50 of 8 110 ms.
|
||||
const failure = fetchAllRows<Row>(() =>
|
||||
Promise.resolve({
|
||||
data: null,
|
||||
error: { message: 'canceling statement due to statement timeout', code: '57014' },
|
||||
}),
|
||||
)
|
||||
await expect(failure).rejects.toMatchObject({ code: '57014' })
|
||||
// And the message stays verbatim: query_journal's sanitizeDbError matches
|
||||
// on the existing text.
|
||||
await expect(failure).rejects.toThrow('canceling statement due to statement timeout')
|
||||
})
|
||||
|
||||
it('does not render "undefined" when the driver sends no message', async () => {
|
||||
await expect(
|
||||
fetchAllRows<Row>(() => Promise.resolve({ data: null, error: { code: '08006' } as never })),
|
||||
).rejects.toThrow(/^(?!.*undefined).*$/)
|
||||
})
|
||||
|
||||
it('returns [] when the first page is empty', async () => {
|
||||
const out = await fetchAllRows<Row>(pagedQuery({ 0: [] }))
|
||||
expect(out).toEqual([])
|
||||
})
|
||||
|
||||
// ── The regression-critical behaviour: an unstable cross-page order ──
|
||||
// (a query missing a stable .order()) can return the same row on two
|
||||
// pages. This is the mechanism behind the doubled-balance bugs (#790/#791).
|
||||
|
||||
it('dedupeBy drops a row duplicated across page boundaries (keeps first)', async () => {
|
||||
const page1 = makeRows(0, PAGE_SIZE) // ids 0..999
|
||||
// Unstable order: page 2 re-serves id "999" (already on page 1) plus a new id.
|
||||
const page2: Row[] = [
|
||||
{ id: '999', value: 1 },
|
||||
{ id: '1000', value: 1 },
|
||||
]
|
||||
const out = await fetchAllRows<Row>(
|
||||
pagedQuery({ 0: page1, [PAGE_SIZE]: page2 }),
|
||||
{ dedupeBy: (r) => r.id },
|
||||
)
|
||||
// 1001 unique ids (0..1000), the duplicate "999" removed → no doubling.
|
||||
expect(out).toHaveLength(PAGE_SIZE + 1)
|
||||
const ids = out.map((r) => r.id)
|
||||
expect(ids.filter((id) => id === '999')).toHaveLength(1)
|
||||
expect(new Set(ids).size).toBe(out.length)
|
||||
})
|
||||
|
||||
it('without dedupeBy, cross-page duplicates pass through (unsafe default)', async () => {
|
||||
const page1 = makeRows(0, PAGE_SIZE)
|
||||
const page2: Row[] = [{ id: '999', value: 1 }]
|
||||
const out = await fetchAllRows<Row>(pagedQuery({ 0: page1, [PAGE_SIZE]: page2 }))
|
||||
expect(out).toHaveLength(PAGE_SIZE + 1)
|
||||
expect(out.map((r) => r.id).filter((id) => id === '999')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('dedupeBy is a no-op for a single page (no cross-page duplicates possible)', async () => {
|
||||
const rows: Row[] = [
|
||||
{ id: 'a' },
|
||||
{ id: 'b' },
|
||||
{ id: 'a' }, // an intra-page repeat is left untouched: single page is trusted
|
||||
]
|
||||
const out = await fetchAllRows<Row>(pagedQuery({ 0: rows }), { dedupeBy: (r) => r.id })
|
||||
expect(out).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
classifyProxyRequest,
|
||||
createProxyTimings,
|
||||
formatProxyServerTiming,
|
||||
proxyRouteTemplate,
|
||||
timed,
|
||||
} from '../proxy-timing'
|
||||
|
||||
describe('classifyProxyRequest', () => {
|
||||
it('treats /api paths as api regardless of headers', () => {
|
||||
const headers = new Headers({ 'next-router-prefetch': '1', rsc: '1' })
|
||||
expect(classifyProxyRequest('/api/settings', headers)).toBe('api')
|
||||
})
|
||||
|
||||
it('recognises app-router prefetch and RSC requests by header', () => {
|
||||
expect(
|
||||
classifyProxyRequest('/invoices', new Headers({ 'Next-Router-Prefetch': '1', RSC: '1' })),
|
||||
).toBe('prefetch')
|
||||
expect(classifyProxyRequest('/invoices', new Headers({ RSC: '1' }))).toBe('rsc')
|
||||
})
|
||||
|
||||
it('falls back to page for a plain document request', () => {
|
||||
expect(classifyProxyRequest('/invoices', new Headers())).toBe('page')
|
||||
})
|
||||
})
|
||||
|
||||
describe('proxyRouteTemplate', () => {
|
||||
it('replaces UUID and numeric segments with placeholders', () => {
|
||||
expect(proxyRouteTemplate('/invoices/6f1c2a3e-1234-4bcd-9abc-0123456789ab/edit')).toBe(
|
||||
'/invoices/:id/edit',
|
||||
)
|
||||
expect(proxyRouteTemplate('/salary/runs/42')).toBe('/salary/runs/:n')
|
||||
})
|
||||
|
||||
it('collapses token-carrying prefixes so secrets never reach the log', () => {
|
||||
expect(proxyRouteTemplate('/invite/9f8e7d6c5b4a3928171605f4e3d2c1b0')).toBe('/invite/*')
|
||||
expect(proxyRouteTemplate('/payslip/abc')).toBe('/payslip/*')
|
||||
expect(proxyRouteTemplate('/auth/callback')).toBe('/auth/*')
|
||||
expect(proxyRouteTemplate('/auth')).toBe('/auth/*')
|
||||
})
|
||||
|
||||
it('masks long opaque segments outside the known prefixes', () => {
|
||||
expect(proxyRouteTemplate('/e/sector/aVeryLongOpaqueSlugThatLooksLikeAToken')).toBe(
|
||||
'/e/sector/:token',
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps ordinary routes and the root untouched', () => {
|
||||
expect(proxyRouteTemplate('/settings/company')).toBe('/settings/company')
|
||||
expect(proxyRouteTemplate('/')).toBe('/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatProxyServerTiming', () => {
|
||||
it('emits one mw-* metric per phase plus the total', () => {
|
||||
const timing = { authMs: 12, sessionMs: 3, companyMs: 40, mfaMs: 0 }
|
||||
expect(formatProxyServerTiming(timing, 61)).toBe(
|
||||
'mw-auth;dur=12, mw-session;dur=3, mw-company;dur=40, mw-mfa;dur=0, mw-total;dur=61',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('timed', () => {
|
||||
it('returns the wrapped value and accumulates elapsed time on the key', async () => {
|
||||
const timing = createProxyTimings()
|
||||
const value = await timed(timing, 'sessionMs', async () => 'ok')
|
||||
expect(value).toBe('ok')
|
||||
await timed(timing, 'sessionMs', async () => undefined)
|
||||
expect(timing.sessionMs).toBeGreaterThanOrEqual(0)
|
||||
expect(timing.authMs).toBe(0)
|
||||
})
|
||||
|
||||
it('still records time when the wrapped call throws', async () => {
|
||||
const timing = createProxyTimings()
|
||||
await expect(
|
||||
timed(timing, 'authMs', async () => {
|
||||
throw new Error('boom')
|
||||
}),
|
||||
).rejects.toThrow('boom')
|
||||
expect(timing.authMs).toBeGreaterThanOrEqual(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { insertDraftJournalEntry, seedCompany } from '@/tests/pg/fixtures'
|
||||
import { withUserContext } from '@/tests/pg/setup'
|
||||
|
||||
describe('rls.pg: tenant isolation on journal_entries', () => {
|
||||
it('returns only the authenticated user\'s company rows', async () => {
|
||||
const a = await seedCompany()
|
||||
const b = await seedCompany()
|
||||
|
||||
// One entry in each tenant.
|
||||
const entryA = await insertDraftJournalEntry({
|
||||
userId: a.userId,
|
||||
companyId: a.companyId,
|
||||
fiscalPeriodId: a.fiscalPeriodId,
|
||||
})
|
||||
await insertDraftJournalEntry({
|
||||
userId: b.userId,
|
||||
companyId: b.companyId,
|
||||
fiscalPeriodId: b.fiscalPeriodId,
|
||||
})
|
||||
|
||||
// user A should see exactly entryA and nothing from tenant B.
|
||||
const rows = await withUserContext(a.userId, async (client) => {
|
||||
const res = await client.query<{ id: string; company_id: string }>(
|
||||
`SELECT id, company_id FROM public.journal_entries`,
|
||||
)
|
||||
return res.rows
|
||||
})
|
||||
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]!.id).toBe(entryA)
|
||||
expect(rows[0]!.company_id).toBe(a.companyId)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { createServerClientMock, cookiesMock } = vi.hoisted(() => ({
|
||||
createServerClientMock: vi.fn(),
|
||||
cookiesMock: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@supabase/ssr', () => ({
|
||||
createServerClient: createServerClientMock,
|
||||
}))
|
||||
|
||||
vi.mock('next/headers', () => ({
|
||||
cookies: cookiesMock,
|
||||
}))
|
||||
|
||||
describe('createServiceClient', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', 'https://project.supabase.co')
|
||||
vi.stubEnv('NEXT_PUBLIC_SUPABASE_ANON_KEY', 'anon-key')
|
||||
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'service-role-key')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('uses the service-role key with a cookie-free client', async () => {
|
||||
const serviceClient = { kind: 'service' }
|
||||
createServerClientMock.mockReturnValue(serviceClient)
|
||||
const { createServiceClient } = await import('../server')
|
||||
|
||||
expect(createServiceClient()).toBe(serviceClient)
|
||||
expect(createServerClientMock).toHaveBeenCalledWith(
|
||||
'https://project.supabase.co',
|
||||
'service-role-key',
|
||||
expect.objectContaining({ cookies: expect.any(Object) }),
|
||||
)
|
||||
const options = createServerClientMock.mock.calls[0][2] as {
|
||||
cookies: { getAll: () => unknown[]; setAll: () => void }
|
||||
}
|
||||
expect(options.cookies.getAll()).toEqual([])
|
||||
expect(() => options.cookies.setAll()).not.toThrow()
|
||||
expect(cookiesMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const createClientMock = vi.fn(() => ({ from: vi.fn() }))
|
||||
|
||||
vi.mock('@supabase/supabase-js', () => ({
|
||||
createClient: (...args: unknown[]) => createClientMock(...(args as [])),
|
||||
}))
|
||||
|
||||
import { createServiceRoleClient, SERVER_AUTH_OPTIONS } from '../service-client'
|
||||
|
||||
/** The auth block supabase-js was actually constructed with. */
|
||||
function authArg() {
|
||||
const [, , options] = createClientMock.mock.calls[0] as unknown as [
|
||||
string,
|
||||
string,
|
||||
{ auth?: Record<string, unknown> } | undefined,
|
||||
]
|
||||
return options?.auth
|
||||
}
|
||||
|
||||
describe('createServiceRoleClient', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('disables the auth refresh ticker', () => {
|
||||
// The whole point: autoRefreshToken defaults to true, and off-browser
|
||||
// auth-js starts a 30 s setInterval that is never cleared. unref() keeps
|
||||
// the process exitable but leaves the timer a GC root, so every client
|
||||
// retains its request scope until the heap is gone.
|
||||
createServiceRoleClient('https://example.supabase.co', 'service-key')
|
||||
|
||||
expect(authArg()).toMatchObject({ autoRefreshToken: false, persistSession: false })
|
||||
})
|
||||
|
||||
it('passes url and key through unchanged', () => {
|
||||
createServiceRoleClient('https://example.supabase.co', 'service-key')
|
||||
|
||||
const [url, key] = createClientMock.mock.calls[0] as unknown as [string, string]
|
||||
expect(url).toBe('https://example.supabase.co')
|
||||
expect(key).toBe('service-key')
|
||||
})
|
||||
|
||||
it('keeps caller options that are not auth', () => {
|
||||
createServiceRoleClient('https://example.supabase.co', 'service-key', {
|
||||
db: { schema: 'public' },
|
||||
global: { headers: { 'x-test': '1' } },
|
||||
})
|
||||
|
||||
const [, , options] = createClientMock.mock.calls[0] as unknown as [
|
||||
string,
|
||||
string,
|
||||
{ db?: unknown; global?: unknown },
|
||||
]
|
||||
expect(options.db).toEqual({ schema: 'public' })
|
||||
expect(options.global).toEqual({ headers: { 'x-test': '1' } })
|
||||
})
|
||||
|
||||
it('refuses to let a caller re-enable the ticker', () => {
|
||||
// SERVER_AUTH_OPTIONS is spread last precisely so this cannot happen: a
|
||||
// caller copying an old snippet must not be able to reintroduce the leak.
|
||||
createServiceRoleClient('https://example.supabase.co', 'service-key', {
|
||||
auth: { autoRefreshToken: true, persistSession: true },
|
||||
})
|
||||
|
||||
expect(authArg()).toMatchObject({ autoRefreshToken: false, persistSession: false })
|
||||
})
|
||||
|
||||
it('keeps unrelated auth options the caller set', () => {
|
||||
createServiceRoleClient('https://example.supabase.co', 'service-key', {
|
||||
auth: { storageKey: 'custom-key' },
|
||||
})
|
||||
|
||||
expect(authArg()).toMatchObject({
|
||||
storageKey: 'custom-key',
|
||||
autoRefreshToken: false,
|
||||
persistSession: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('exports the options it applies', () => {
|
||||
expect(SERVER_AUTH_OPTIONS).toEqual({ persistSession: false, autoRefreshToken: false })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user