fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Å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:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,355 @@
/**
* Tests for the nightly document integrity-verify cron.
*
* Covers the production defects fixed in this route:
* - the run must fit its budget (maxDuration 300 + batch default 200),
* - a document whose storage object cannot be downloaded must surface as an
* audit incident (INTEGRITY_FAILURE / DOCUMENT_OBJECT_MISSING) AND get a
* ledger row so it stops head-blocking the queue,
* - the queue and the stamp both live in document_integrity_checks: the route
* must never write to document_attachments, whose UPDATE trigger
* (enforce_period_lock_documents, migration 017) rejects every document
* linked to a closed/locked period and wedged the cron at 200/200 rejected,
* - and a rejected ledger or audit write must be counted, logged and reported
* rather than discarded, which is why the stall went unnoticed for weeks.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createHash } from 'node:crypto'
import { NextResponse } from 'next/server'
import { verifyCronSecret } from '@/lib/auth/cron'
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn(() => null),
}))
interface MockDoc {
id: string
user_id: string
company_id: string
storage_path: string
sha256_hash: string
file_name: string
last_checked_at: string | null
}
const state = {
documents: [] as MockDoc[],
fetchError: null as { message: string } | null,
downloadResults: new Map<string, { data: unknown; error: { message: string } | null }>(),
rpcCalls: [] as Array<{ fn: string; args: Record<string, unknown> }>,
ledgerInserts: [] as Array<Record<string, unknown>>,
ledgerInsertError: null as { message: string } | null,
auditInserts: [] as Array<Record<string, unknown>>,
auditInsertError: null as { message: string } | null,
}
function makeMockClient() {
return {
rpc: (fn: string, args: Record<string, unknown>) => {
state.rpcCalls.push({ fn, args })
return Promise.resolve({
data: state.fetchError ? null : state.documents,
error: state.fetchError,
})
},
from: (table: string) => {
if (table === 'document_integrity_checks') {
return {
insert: (row: Record<string, unknown>) => {
state.ledgerInserts.push(row)
return Promise.resolve({ error: state.ledgerInsertError })
},
}
}
if (table === 'audit_log') {
return {
insert: (row: Record<string, unknown>) => {
state.auditInserts.push(row)
return Promise.resolve({ error: state.auditInsertError })
},
}
}
if (table === 'document_attachments') {
// The whole point of the fix: a write here runs through
// enforce_period_lock_documents() and is rejected for every document
// linked to a closed/locked period.
throw new Error('the verify cron must never write to document_attachments')
}
throw new Error(`unexpected table: ${table}`)
},
storage: {
from: () => ({
download: (path: string) =>
Promise.resolve(
state.downloadResults.get(path) ?? {
data: null,
error: { message: 'Object not found' },
}
),
}),
},
}
}
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(() => makeMockClient()),
}))
import { GET, maxDuration } from '../route'
function cronRequest(): Request {
return new Request('http://localhost:3000/api/documents/verify/cron')
}
function makeDoc(overrides: Partial<MockDoc> = {}): MockDoc {
return {
id: 'doc-1',
user_id: 'user-1',
company_id: 'company-1',
storage_path: 'user-1/company-1/inbox/file.pdf',
sha256_hash: 'deadbeef',
file_name: 'file.pdf',
last_checked_at: null,
...overrides,
}
}
/** Register a downloadable object whose bytes hash to the returned sha256. */
function registerObject(path: string, content: string): string {
const buf = Buffer.from(content, 'utf8')
const arrayBuffer = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
state.downloadResults.set(path, {
data: { arrayBuffer: async () => arrayBuffer },
error: null,
})
return createHash('sha256').update(buf).digest('hex')
}
beforeEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'
delete process.env.DOCUMENT_VERIFY_BATCH_SIZE
state.documents = []
state.fetchError = null
state.downloadResults.clear()
state.rpcCalls = []
state.ledgerInserts = []
state.ledgerInsertError = null
state.auditInserts = []
state.auditInsertError = null
})
describe('GET /api/documents/verify/cron', () => {
it('returns 401 when the cron secret is invalid', async () => {
vi.mocked(verifyCronSecret).mockReturnValueOnce(
NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
)
const response = await GET(cronRequest())
expect(response.status).toBe(401)
expect(state.rpcCalls).toHaveLength(0)
})
it('declares a 300s function budget', () => {
expect(maxDuration).toBe(300)
})
it('draws the batch from the ledger queue, 200 by default, env override honored', async () => {
await GET(cronRequest())
expect(state.rpcCalls).toEqual([
{ fn: 'next_documents_for_integrity_check', args: { p_limit: 200 } },
])
process.env.DOCUMENT_VERIFY_BATCH_SIZE = '50'
await GET(cronRequest())
expect(state.rpcCalls[1]).toEqual({
fn: 'next_documents_for_integrity_check',
args: { p_limit: 50 },
})
})
it('appends a passed ledger row on a successful verification', async () => {
const doc = makeDoc()
const hash = registerObject(doc.storage_path, '%PDF-1.4 demo content')
state.documents = [{ ...doc, sha256_hash: hash }]
const response = await GET(cronRequest())
const json = await response.json()
expect(json).toEqual({
processed: 1,
verified: 1,
failures: 0,
missingObjects: 0,
writeFailures: 0,
errors: 0,
})
expect(state.ledgerInserts).toHaveLength(1)
expect(state.ledgerInserts[0]).toMatchObject({
document_id: doc.id,
company_id: doc.company_id,
result: 'passed',
expected_sha256: hash,
computed_sha256: hash,
storage_path: doc.storage_path,
detail: null,
})
expect(state.ledgerInserts[0].checked_at).toEqual(expect.any(String))
expect(state.auditInserts).toHaveLength(0)
})
it('writes an INTEGRITY_FAILURE audit row and a hash_mismatch ledger row on mismatch', async () => {
const doc = makeDoc({ sha256_hash: 'not-the-real-hash' })
registerObject(doc.storage_path, 'tampered content')
state.documents = [doc]
const response = await GET(cronRequest())
const json = await response.json()
expect(json.failures).toBe(1)
expect(json.missingObjects).toBe(0)
expect(json.writeFailures).toBe(0)
expect(state.auditInserts).toHaveLength(1)
expect(state.auditInserts[0].action).toBe('INTEGRITY_FAILURE')
expect(String(state.auditInserts[0].description)).not.toContain('DOCUMENT_OBJECT_MISSING')
expect(state.ledgerInserts).toHaveLength(1)
expect(state.ledgerInserts[0]).toMatchObject({
document_id: doc.id,
result: 'hash_mismatch',
expected_sha256: 'not-the-real-hash',
})
})
it('verifies via the company-scoped fallback key when a concurrent backfill re-homed the object', async () => {
// The batch snapshot carries a stale legacy pointer: mid-batch, the
// Phase B backfill copied the object to the company-scoped key and
// removed the source. This must NOT produce a permanent false
// DOCUMENT_OBJECT_MISSING audit row for a healthy document.
const doc = makeDoc({
id: 'doc-repointed',
storage_path: 'documents/user-1/1_receipt.pdf',
})
const hash = registerObject('documents/company-1/user-1/1_receipt.pdf', 'healthy bytes')
state.documents = [{ ...doc, sha256_hash: hash }]
const response = await GET(cronRequest())
const json = await response.json()
expect(state.auditInserts).toHaveLength(0)
expect(state.ledgerInserts.map((row) => row.document_id)).toEqual(['doc-repointed'])
expect(json).toEqual({
processed: 1,
verified: 1,
failures: 0,
missingObjects: 0,
writeFailures: 0,
errors: 0,
})
})
it('surfaces a missing storage object as an audit incident AND an object_missing ledger row', async () => {
const missing = makeDoc({ id: 'doc-missing', storage_path: 'user-1/company-1/gone.pdf' })
const healthy = makeDoc({ id: 'doc-healthy', storage_path: 'user-1/company-1/ok.pdf' })
const healthyHash = registerObject(healthy.storage_path, 'healthy content')
state.documents = [missing, { ...healthy, sha256_hash: healthyHash }]
const response = await GET(cronRequest())
const json = await response.json()
// The audit row is the incident surface for the missing object.
expect(state.auditInserts).toHaveLength(1)
const audit = state.auditInserts[0]
expect(audit.action).toBe('INTEGRITY_FAILURE')
expect(audit.record_id).toBe('doc-missing')
expect(String(audit.description)).toContain('DOCUMENT_OBJECT_MISSING')
expect(audit.new_state).toMatchObject({ reason: 'DOCUMENT_OBJECT_MISSING' })
// Both documents get a ledger row: the failing one must stop head-blocking
// the queue, and the healthy one was verified.
expect(state.ledgerInserts.map((row) => row.document_id).sort()).toEqual([
'doc-healthy',
'doc-missing',
])
expect(state.ledgerInserts.find((row) => row.document_id === 'doc-missing')).toMatchObject({
result: 'object_missing',
computed_sha256: null,
})
expect(json).toEqual({
processed: 2,
verified: 1,
failures: 0,
missingObjects: 1,
writeFailures: 0,
errors: 1,
})
})
it('does not write a ledger row when the audit insert fails, so it retries next run', async () => {
const missing = makeDoc({ id: 'doc-missing', storage_path: 'user-1/company-1/gone.pdf' })
state.documents = [missing]
state.auditInsertError = { message: 'insert blocked' }
const response = await GET(cronRequest())
const json = await response.json()
expect(state.auditInserts).toHaveLength(1)
expect(state.ledgerInserts).toHaveLength(0)
expect(json.missingObjects).toBe(0)
expect(json.writeFailures).toBe(1)
expect(json.errors).toBe(1)
})
it('reports a rejected ledger write instead of swallowing it', async () => {
const doc = makeDoc()
const hash = registerObject(doc.storage_path, 'healthy content')
state.documents = [{ ...doc, sha256_hash: hash }]
state.ledgerInsertError = { message: 'permission denied for table document_integrity_checks' }
const response = await GET(cronRequest())
const json = await response.json()
expect(state.ledgerInserts).toHaveLength(1)
expect(json).toEqual({
processed: 1,
verified: 0,
failures: 0,
missingObjects: 0,
writeFailures: 1,
errors: 1,
})
})
it('counts a rejected audit write on a hash mismatch as a write failure', async () => {
const doc = makeDoc({ sha256_hash: 'not-the-real-hash' })
registerObject(doc.storage_path, 'tampered content')
state.documents = [doc]
state.auditInsertError = { message: 'insert blocked' }
const response = await GET(cronRequest())
const json = await response.json()
expect(state.auditInserts).toHaveLength(1)
expect(state.ledgerInserts).toHaveLength(0)
expect(json.failures).toBe(0)
expect(json.writeFailures).toBe(1)
expect(json.errors).toBe(1)
})
it('returns an error envelope when the queue fetch fails', async () => {
state.fetchError = { message: 'db down' }
const response = await GET(cronRequest())
expect(response.status).toBeGreaterThanOrEqual(500)
})
it('reports zero processed when there is nothing to verify', async () => {
const response = await GET(cronRequest())
const json = await response.json()
expect(json).toEqual({ message: 'No documents to verify', processed: 0 })
})
})
+272
View File
@@ -0,0 +1,272 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { downloadDocumentObject } from '@/lib/core/documents/document-service'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/documents/verify/cron: nightly 03:00 UTC (schedule in vercel.json).
* Spot-checks WORM archive integrity by recomputing SHA-256 for the next
* batch of documents and appending the outcome to document_integrity_checks.
* Hash mismatches and unreadable storage objects additionally get an
* INTEGRITY_FAILURE row in the audit log, which is the durable incident
* surface.
*
* Both the queue and the stamp live in document_integrity_checks and NOT in
* document_attachments.last_integrity_check_at (now legacy): any UPDATE of a
* document linked to an entry in a closed/locked period is rejected by
* enforce_period_lock_documents() (migration 017, legally required and never
* touched), which had this cron wedged at 200 of 200 rejected per night with
* both write errors discarded. See
* supabase/migrations/20260901130000_document_integrity_checks.sql.
*/
// Vercel function budget; verification is sequential, see batch size below.
export const maxDuration = 300
// Measured ~0.8s per document (download + hash + ledger append), so 200
// documents finish in ~160s with headroom inside the 300s budget. The previous
// default of 500 hit the platform timeout around item ~250 every night, so the
// tail of the queue was never reached.
const DEFAULT_VERIFY_BATCH_SIZE = 200
type ServiceClient = ReturnType<typeof createServiceRoleClient>
type IntegrityResult = 'passed' | 'hash_mismatch' | 'object_missing'
/** One row of public.next_documents_for_integrity_check(). */
interface QueuedDocument {
id: string
user_id: string
company_id: string
storage_path: string
sha256_hash: string
file_name: string
last_checked_at: string | null
}
/**
* Append the outcome of one check to the integrity ledger. The write error is
* returned, never swallowed: a lost ledger row leaves the document at the head
* of the queue, and discarding exactly this error is why the control stayed
* dead for weeks without anyone noticing.
*/
async function recordCheck(
supabase: ServiceClient,
doc: QueuedDocument,
result: IntegrityResult,
computedHash: string | null,
detail: string | null
): Promise<{ error: { message: string } | null }> {
const { error } = await supabase.from('document_integrity_checks').insert({
company_id: doc.company_id,
document_id: doc.id,
checked_at: new Date().toISOString(),
expected_sha256: doc.sha256_hash,
computed_sha256: computedHash,
storage_path: doc.storage_path,
result,
detail,
})
return { error }
}
export const GET = withCronContext('cron.documents_verify', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const batchSize =
parseInt(process.env.DOCUMENT_VERIFY_BATCH_SIZE || '', 10) || DEFAULT_VERIFY_BATCH_SIZE
// Least-recently-checked first, never-checked ahead of those, tie-broken on
// created_at so the drain is a deterministic FIFO rather than heap order.
const { data, error: fetchError } = await supabase.rpc('next_documents_for_integrity_check', {
p_limit: batchSize,
})
if (fetchError) {
ctx.log.error('failed to fetch documents for verify', fetchError)
return errorResponse(fetchError, ctx.log, { requestId: ctx.requestId })
}
const documents = (data ?? []) as QueuedDocument[]
if (documents.length === 0) {
return NextResponse.json({ message: 'No documents to verify', processed: 0 })
}
let verified = 0
let failures = 0
let missingObjects = 0
// Ledger and audit writes the database rejected. Counted, logged and shipped
// in the response so a broken write path shows up on the first run instead
// of weeks later.
let writeFailures = 0
const summary = await ctx.forEach('document', documents, async (doc, itemCtx) => {
// Dual-layout download: the batch is snapshotted up front, and a
// concurrent Phase B backfill (scripts/backfill-document-storage-paths.ts)
// can re-home an object from the legacy uploader-scoped key to the
// company-scoped key (and later remove the source) mid-batch, leaving
// doc.storage_path stale. Trusting the stale pointer here wrote a
// PERMANENT false DOCUMENT_OBJECT_MISSING INTEGRITY_FAILURE row into the
// immutable audit log for a healthy document. The helper tries the
// stored pointer first, then the alternate layout.
const { blob: fileData, error: downloadError } = await downloadDocumentObject(
supabase,
doc.storage_path,
doc.company_id
)
if (downloadError || !fileData) {
// The storage object is unreadable: surface it as an incident in the
// audit log. The action stays INTEGRITY_FAILURE because the DB check
// constraint audit_log_action_check allows a fixed set of actions;
// the DOCUMENT_OBJECT_MISSING marker in description and new_state
// distinguishes a missing object from a hash mismatch.
const reason = downloadError?.message || 'download_failed'
const { error: auditError } = await supabase.from('audit_log').insert({
user_id: doc.user_id,
company_id: doc.company_id,
action: 'INTEGRITY_FAILURE',
table_name: 'document_attachments',
record_id: doc.id,
description: `DOCUMENT_OBJECT_MISSING: storage object for document "${doc.file_name}" at "${doc.storage_path}" could not be downloaded: ${reason}`,
old_state: { sha256_hash: doc.sha256_hash },
new_state: { reason: 'DOCUMENT_OBJECT_MISSING', download_error: reason },
})
if (auditError) {
// Append no ledger row, so the document keeps its place at the head of
// the queue and the incident write is re-attempted on the next run.
writeFailures++
itemCtx.log.error('audit insert failed for missing object', new Error(auditError.message), {
documentId: doc.id,
})
throw new Error(`audit insert failed for missing object: ${auditError.message}`)
}
const { error: ledgerError } = await recordCheck(
supabase,
doc,
'object_missing',
null,
`DOCUMENT_OBJECT_MISSING: ${reason}`
)
if (ledgerError) {
writeFailures++
itemCtx.log.error('integrity ledger write failed', new Error(ledgerError.message), {
documentId: doc.id,
result: 'object_missing',
})
throw new Error(`integrity ledger write failed: ${ledgerError.message}`)
}
missingObjects++
itemCtx.log.error('document object missing', new Error(reason), {
documentId: doc.id,
fileName: doc.file_name,
storagePath: doc.storage_path,
})
throw new Error(`DOCUMENT_OBJECT_MISSING: ${reason}`)
}
const buffer = await fileData.arrayBuffer()
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
const computedHash = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
const isValid = computedHash === doc.sha256_hash
if (!isValid) {
// Audit row before ledger row: if the ledger row landed first and the
// audit write then failed, the document would leave the queue with the
// incident lost. This order re-checks it tomorrow instead.
const { error: auditError } = await supabase.from('audit_log').insert({
user_id: doc.user_id,
company_id: doc.company_id,
action: 'INTEGRITY_FAILURE',
table_name: 'document_attachments',
record_id: doc.id,
description: `Integrity check failed for document "${doc.file_name}": stored hash ${doc.sha256_hash}, computed hash ${computedHash}`,
old_state: { sha256_hash: doc.sha256_hash },
new_state: { computed_hash: computedHash },
})
if (auditError) {
writeFailures++
itemCtx.log.error('audit insert failed for hash mismatch', new Error(auditError.message), {
documentId: doc.id,
})
throw new Error(`audit insert failed for hash mismatch: ${auditError.message}`)
}
}
const { error: ledgerError } = await recordCheck(
supabase,
doc,
isValid ? 'passed' : 'hash_mismatch',
computedHash,
isValid ? null : `stored hash ${doc.sha256_hash}, computed hash ${computedHash}`
)
if (ledgerError) {
writeFailures++
itemCtx.log.error('integrity ledger write failed', new Error(ledgerError.message), {
documentId: doc.id,
result: isValid ? 'passed' : 'hash_mismatch',
})
throw new Error(`integrity ledger write failed: ${ledgerError.message}`)
}
if (!isValid) {
itemCtx.log.error('integrity failure', new Error('hash_mismatch'), {
documentId: doc.id,
fileName: doc.file_name,
storedHash: doc.sha256_hash,
computedHash,
})
failures++
} else {
verified++
}
})
ctx.log.info('document verify summary', {
processed: summary.total,
verified,
failures,
missingObjects,
writeFailures,
downloadErrors: summary.failed,
})
if (writeFailures > 0) {
// Loud on its own line: a rejected ledger write means the queue does not
// advance, which is exactly the silent stall this cron just came out of.
ctx.log.error('integrity ledger writes rejected', new Error('integrity_write_failed'), {
processed: summary.total,
writeFailures,
})
}
return NextResponse.json({
processed: summary.total,
verified,
failures,
missingObjects,
writeFailures,
errors: summary.failed,
})
})