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,271 @@
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { contentDisposition } from '@/lib/api/content-disposition'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import {
|
||||
OPAQUE_DOCUMENT_CSP,
|
||||
STORAGE_PROXY_ROUTE,
|
||||
documentKeyFromProxyPath,
|
||||
inlineSafeMimeType,
|
||||
readBodyWithCap,
|
||||
resolveUpstreamStorageUrl,
|
||||
} from '@/lib/core/documents/storage-proxy'
|
||||
|
||||
/**
|
||||
* /api/storage/[...path]: same-origin proxy for signed Supabase Storage URLs.
|
||||
*
|
||||
* Why: agent sandboxes (Claude Desktop's code execution among them) only let
|
||||
* traffic out to the host the MCP server runs on. Signed Storage URLs point
|
||||
* at <project>.supabase.co, so the MCP model-free upload (PUT bytes to
|
||||
* upload_url) and signed document downloads were blocked inside such
|
||||
* sandboxes. The MCP tools now hand out URLs under this route instead (see
|
||||
* lib/core/documents/storage-proxy.ts), and this handler forwards them to
|
||||
* Storage unchanged.
|
||||
*
|
||||
* What the browser is told about the bytes is NOT taken from Storage. The
|
||||
* object's Content-Type and Content-Disposition are whatever the uploader
|
||||
* declared on PUT, and the proxy serves anonymous visitors on the app
|
||||
* origin: relaying them would let an HTML or SVG upload run scripts with our
|
||||
* origin's authority. Downloads are therefore served as opaque attachments
|
||||
* (application/octet-stream + OPAQUE_DOCUMENT_CSP) unless the object is a
|
||||
* document whose DB-validated mime type is natively inline-safe (PDF, raster
|
||||
* images), in which case that type is served.
|
||||
*
|
||||
* Auth: deliberately NOT withRouteContext. The caller is a sandbox with no
|
||||
* session, and the signed token in the query string is the credential:
|
||||
* Storage validates it against the exact object path on every request, the
|
||||
* same way it would on the public Storage host. The proxy only forwards
|
||||
* signed object paths on the documents bucket, only to our own Storage
|
||||
* origin, with a token present; it never mints, reads or relays any key.
|
||||
*
|
||||
* GET/HEAD /api/storage/sign/documents/<key>?token=... download
|
||||
* PUT /api/storage/upload/sign/documents/<key>?token=... upload
|
||||
*/
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
export const maxDuration = 60
|
||||
|
||||
const log = createLogger('api/storage-proxy')
|
||||
|
||||
/**
|
||||
* Above every caller's own cap (MCP upload 10 MB, document max 10 MB). The
|
||||
* browser inbox path does not come through here at all: this handler buffers
|
||||
* the PUT body inside a function, so on hosted it sits under the same 4.5 MB
|
||||
* platform ceiling, and the browser PUTs to the raw signed Storage URL
|
||||
* instead (lib/documents/direct-upload.ts).
|
||||
*/
|
||||
const MAX_UPLOAD_BYTES = 50 * 1024 * 1024
|
||||
|
||||
const REQUEST_HEADERS_FORWARDED = [
|
||||
'content-type',
|
||||
'cache-control',
|
||||
'x-upsert',
|
||||
'range',
|
||||
'if-none-match',
|
||||
'if-modified-since',
|
||||
] as const
|
||||
|
||||
// Deliberately without content-type and content-disposition: both are
|
||||
// uploader-declared object metadata (see the module comment).
|
||||
const RESPONSE_HEADERS_FORWARDED = [
|
||||
'content-length',
|
||||
'content-range',
|
||||
'accept-ranges',
|
||||
'cache-control',
|
||||
'etag',
|
||||
'last-modified',
|
||||
] as const
|
||||
|
||||
// The sandbox fetch is not a browser, but a browser-based MCP client would
|
||||
// need these and they cost nothing: the token still gates every request.
|
||||
const CORS_HEADERS: Record<string, string> = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, HEAD, PUT, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Cache-Control, x-upsert, Range',
|
||||
'Access-Control-Max-Age': '600',
|
||||
}
|
||||
|
||||
function withCors(response: Response): Response {
|
||||
for (const [key, value] of Object.entries(CORS_HEADERS)) {
|
||||
response.headers.set(key, value)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
function objectPathOf(request: Request): string {
|
||||
const { pathname } = new URL(request.url)
|
||||
const prefix = `${STORAGE_PROXY_ROUTE}/`
|
||||
return pathname.startsWith(prefix) ? pathname.slice(prefix.length) : ''
|
||||
}
|
||||
|
||||
interface ServedDocument {
|
||||
/** Canonical inline-safe type from the document row, or null when the row is missing or its type is not inline-safe. */
|
||||
mimeType: string | null
|
||||
fileName: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the document row behind a proxied download key. Runs only after
|
||||
* Storage has accepted the signed token, so the caller has already proven
|
||||
* access to exactly this object; the row adds nothing they could not read
|
||||
* from the bytes. Every failure (no row, DB error, unsafe type) falls back
|
||||
* to the opaque default rather than trusting anything else.
|
||||
*/
|
||||
async function lookupServedDocument(objectPath: string): Promise<ServedDocument> {
|
||||
const key = documentKeyFromProxyPath(objectPath)
|
||||
if (!key) return { mimeType: null, fileName: null }
|
||||
try {
|
||||
const { data, error } = await createServiceClient()
|
||||
.from('document_attachments')
|
||||
.select('mime_type, file_name')
|
||||
.eq('storage_path', key)
|
||||
.limit(1)
|
||||
if (error) {
|
||||
log.warn('storage proxy document lookup failed', { message: error.message })
|
||||
return { mimeType: null, fileName: null }
|
||||
}
|
||||
const row = (data as { mime_type: string | null; file_name: string | null }[] | null)?.[0]
|
||||
if (!row) return { mimeType: null, fileName: null }
|
||||
return { mimeType: inlineSafeMimeType(row.mime_type), fileName: row.file_name }
|
||||
} catch (error) {
|
||||
log.warn('storage proxy document lookup threw', { message: (error as Error).message })
|
||||
return { mimeType: null, fileName: null }
|
||||
}
|
||||
}
|
||||
|
||||
/** Last segment of the object key, decoded, as the filename of last resort. */
|
||||
function fileNameFromObjectPath(objectPath: string): string {
|
||||
const last = objectPath.split('/').pop() ?? ''
|
||||
try {
|
||||
return decodeURIComponent(last) || 'download'
|
||||
} catch {
|
||||
return last || 'download'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide Content-Type / Content-Disposition / CSP for a GET or HEAD from
|
||||
* what the database says about the object, never from Storage's echo of
|
||||
* the uploader's metadata. Storage's own `?download[=name]` convention is
|
||||
* honoured for the disposition and filename so callers see the same
|
||||
* behaviour they got from the raw signed URL.
|
||||
*/
|
||||
async function servedContentHeaders(
|
||||
objectPath: string,
|
||||
search: URLSearchParams,
|
||||
upstreamOk: boolean,
|
||||
): Promise<Record<string, string>> {
|
||||
const served = upstreamOk
|
||||
? await lookupServedDocument(objectPath)
|
||||
: { mimeType: null, fileName: null }
|
||||
const downloadParam = search.get('download')
|
||||
const fileName = downloadParam || served.fileName || fileNameFromObjectPath(objectPath)
|
||||
|
||||
if (served.mimeType) {
|
||||
return {
|
||||
'Content-Type': served.mimeType,
|
||||
'Content-Disposition': contentDisposition(
|
||||
downloadParam === null ? 'inline' : 'attachment',
|
||||
fileName,
|
||||
),
|
||||
}
|
||||
}
|
||||
return {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'Content-Disposition': contentDisposition('attachment', fileName),
|
||||
'Content-Security-Policy': OPAQUE_DOCUMENT_CSP,
|
||||
}
|
||||
}
|
||||
|
||||
function rejected(reason: 'unsupported_path' | 'missing_token' | 'storage_unconfigured') {
|
||||
const code =
|
||||
reason === 'unsupported_path'
|
||||
? 'STORAGE_PROXY_UNSUPPORTED_PATH'
|
||||
: reason === 'missing_token'
|
||||
? 'STORAGE_PROXY_TOKEN_REQUIRED'
|
||||
: 'STORAGE_PROXY_UNCONFIGURED'
|
||||
return withCors(errorResponseFromCode(code, log))
|
||||
}
|
||||
|
||||
async function proxy(request: Request, method: 'GET' | 'HEAD' | 'PUT'): Promise<Response> {
|
||||
const url = new URL(request.url)
|
||||
const objectPath = objectPathOf(request)
|
||||
const resolved = resolveUpstreamStorageUrl(objectPath, url.searchParams)
|
||||
if (!resolved.ok) return rejected(resolved.reason)
|
||||
|
||||
const headers = new Headers()
|
||||
for (const name of REQUEST_HEADERS_FORWARDED) {
|
||||
const value = request.headers.get(name)
|
||||
if (value) headers.set(name, value)
|
||||
}
|
||||
|
||||
let body: ArrayBuffer | undefined
|
||||
if (method === 'PUT') {
|
||||
const declared = Number(request.headers.get('content-length') ?? '0')
|
||||
if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES) {
|
||||
return withCors(errorResponseFromCode('STORAGE_PROXY_BODY_TOO_LARGE', log))
|
||||
}
|
||||
// Stream with a cap: the declared length is advisory (absent or wrong),
|
||||
// and the token is only validated upstream, so never buffer an unbounded
|
||||
// body before measuring it.
|
||||
const read = await readBodyWithCap(request.body, MAX_UPLOAD_BYTES)
|
||||
if (read === null) {
|
||||
return withCors(errorResponseFromCode('STORAGE_PROXY_BODY_TOO_LARGE', log))
|
||||
}
|
||||
body = read
|
||||
if (!headers.has('content-type')) headers.set('content-type', 'application/octet-stream')
|
||||
}
|
||||
|
||||
let upstream: Response
|
||||
try {
|
||||
upstream = await fetch(resolved.url, {
|
||||
method,
|
||||
headers,
|
||||
...(body ? { body } : {}),
|
||||
redirect: 'manual',
|
||||
cache: 'no-store',
|
||||
})
|
||||
} catch (error) {
|
||||
log.error('storage proxy upstream request failed', error as Error, { method })
|
||||
return withCors(errorResponseFromCode('STORAGE_PROXY_UPSTREAM_UNAVAILABLE', log))
|
||||
}
|
||||
|
||||
const responseHeaders = new Headers(CORS_HEADERS)
|
||||
for (const name of RESPONSE_HEADERS_FORWARDED) {
|
||||
const value = upstream.headers.get(name)
|
||||
if (value) responseHeaders.set(name, value)
|
||||
}
|
||||
// Never let a served document be sniffed into something executable.
|
||||
responseHeaders.set('X-Content-Type-Options', 'nosniff')
|
||||
|
||||
if (method === 'PUT') {
|
||||
// Storage answers an upload with its own small JSON envelope ({ Key }),
|
||||
// not object bytes, so its type is safe to relay.
|
||||
const upstreamType = upstream.headers.get('content-type')
|
||||
if (upstreamType) responseHeaders.set('Content-Type', upstreamType)
|
||||
} else {
|
||||
const served = await servedContentHeaders(objectPath, url.searchParams, upstream.ok)
|
||||
for (const [key, value] of Object.entries(served)) responseHeaders.set(key, value)
|
||||
}
|
||||
|
||||
return new Response(method === 'HEAD' ? null : upstream.body, {
|
||||
status: upstream.status,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
return proxy(request, 'GET')
|
||||
}
|
||||
|
||||
export async function HEAD(request: Request) {
|
||||
return proxy(request, 'HEAD')
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
return proxy(request, 'PUT')
|
||||
}
|
||||
|
||||
export async function OPTIONS() {
|
||||
return new Response(null, { status: 204, headers: CORS_HEADERS })
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const SUPABASE = 'https://pwxtzglxptnnvjrpixpg.supabase.co'
|
||||
const OPAQUE_CSP = "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:"
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
|
||||
// document_attachments lookup behind a proxied download: (table, columns,
|
||||
// filter column, filter value) => { data, error }.
|
||||
const documentLookup = vi.fn()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: () => ({
|
||||
from: (table: string) => ({
|
||||
select: (columns: string) => ({
|
||||
eq: (column: string, value: string) => ({
|
||||
limit: () => documentLookup(table, columns, column, value),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}))
|
||||
|
||||
import { GET, HEAD, OPTIONS, PUT } from '../[...path]/route'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', SUPABASE)
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.accounted.se')
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
fetchMock.mockReset()
|
||||
documentLookup.mockReset()
|
||||
documentLookup.mockResolvedValue({ data: [], error: null })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
function upstreamResponse(body: string | null, init: ResponseInit = {}) {
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/pdf', 'content-length': String(body?.length ?? 0) },
|
||||
...init,
|
||||
})
|
||||
}
|
||||
|
||||
function pdfRow(fileName = 'kvitto.pdf', mimeType: string | null = 'application/pdf') {
|
||||
return { data: [{ mime_type: mimeType, file_name: fileName }], error: null }
|
||||
}
|
||||
|
||||
describe('/api/storage/[...path] same-origin Storage proxy', () => {
|
||||
it('forwards a signed upload PUT (bytes, content-type, token) to our Storage host', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({ Key: 'documents/x' }), { status: 200, headers: { 'content-type': 'application/json' } }))
|
||||
const bytes = new TextEncoder().encode('%PDF-1.4 hello')
|
||||
const request = new Request(
|
||||
'https://app.accounted.se/api/storage/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig',
|
||||
{ method: 'PUT', headers: { 'content-type': 'application/pdf', 'x-upsert': 'false' }, body: bytes },
|
||||
)
|
||||
|
||||
const response = await PUT(request)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('access-control-allow-origin')).toBe('*')
|
||||
// Storage's own JSON envelope, not object bytes: relayed as-is.
|
||||
expect(response.headers.get('content-type')).toBe('application/json')
|
||||
expect(response.headers.get('content-security-policy')).toBeNull()
|
||||
expect(documentLookup).not.toHaveBeenCalled()
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
|
||||
expect(url).toBe(
|
||||
`${SUPABASE}/storage/v1/object/upload/sign/documents/co-1/user-1/pending/up-1/faktura%20maj.pdf?token=eyJ.sig`,
|
||||
)
|
||||
expect(init.method).toBe('PUT')
|
||||
const headers = init.headers as Headers
|
||||
expect(headers.get('content-type')).toBe('application/pdf')
|
||||
expect(headers.get('x-upsert')).toBe('false')
|
||||
expect(new TextDecoder().decode(init.body as ArrayBuffer)).toBe('%PDF-1.4 hello')
|
||||
})
|
||||
|
||||
it('streams a signed download GET and serves the DB-validated type when it is inline-safe', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
upstreamResponse('%PDF-1.4 bytes', {
|
||||
headers: {
|
||||
'content-type': 'text/html',
|
||||
'content-disposition': 'inline; filename="evil.html"',
|
||||
'set-cookie': 'leak=1',
|
||||
'etag': '"abc"',
|
||||
},
|
||||
}),
|
||||
)
|
||||
documentLookup.mockResolvedValue(pdfRow('kvitto.pdf'))
|
||||
const request = new Request(
|
||||
'https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig',
|
||||
)
|
||||
|
||||
const response = await GET(request)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.text()).toBe('%PDF-1.4 bytes')
|
||||
// The upstream (uploader-declared) type and disposition are ignored; the
|
||||
// document row decides, and its filename is what the browser sees.
|
||||
expect(response.headers.get('content-type')).toBe('application/pdf')
|
||||
expect(response.headers.get('content-disposition')).toBe(
|
||||
`inline; filename="kvitto.pdf"; filename*=UTF-8''kvitto.pdf`,
|
||||
)
|
||||
expect(response.headers.get('content-security-policy')).toBeNull()
|
||||
expect(response.headers.get('x-content-type-options')).toBe('nosniff')
|
||||
expect(response.headers.get('etag')).toBe('"abc"')
|
||||
expect(response.headers.get('set-cookie')).toBeNull()
|
||||
expect(documentLookup).toHaveBeenCalledWith(
|
||||
'document_attachments',
|
||||
'mime_type, file_name',
|
||||
'storage_path',
|
||||
'co-1/user-1/kvitto.pdf',
|
||||
)
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
|
||||
expect(url).toBe(`${SUPABASE}/storage/v1/object/sign/documents/co-1/user-1/kvitto.pdf?token=eyJ.sig`)
|
||||
expect(init.method).toBe('GET')
|
||||
})
|
||||
|
||||
it('looks the document up by its percent-decoded key and tolerates legacy type spelling', async () => {
|
||||
fetchMock.mockResolvedValue(upstreamResponse('%PDF-1.4 bytes'))
|
||||
documentLookup.mockResolvedValue(pdfRow('kvitto maj.pdf', 'Application/PDF; charset=binary'))
|
||||
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto%20maj.pdf?token=t'),
|
||||
)
|
||||
|
||||
expect(response.headers.get('content-type')).toBe('application/pdf')
|
||||
expect(documentLookup).toHaveBeenCalledWith(
|
||||
'document_attachments',
|
||||
'mime_type, file_name',
|
||||
'storage_path',
|
||||
'co-1/user-1/kvitto maj.pdf',
|
||||
)
|
||||
})
|
||||
|
||||
it("honours Storage's ?download convention for an inline-safe type", async () => {
|
||||
fetchMock.mockResolvedValue(upstreamResponse('%PDF-1.4 bytes'))
|
||||
documentLookup.mockResolvedValue(pdfRow('kvitto.pdf'))
|
||||
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=t&download='),
|
||||
)
|
||||
|
||||
expect(response.headers.get('content-type')).toBe('application/pdf')
|
||||
expect(response.headers.get('content-disposition')).toContain('attachment; filename="kvitto.pdf"')
|
||||
|
||||
const named = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=t&download=mars.pdf'),
|
||||
)
|
||||
expect(named.headers.get('content-disposition')).toContain('attachment; filename="mars.pdf"')
|
||||
})
|
||||
|
||||
it('serves a document whose stored type is active content as an opaque attachment', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
upstreamResponse('<script>alert(document.cookie)</script>', {
|
||||
headers: { 'content-type': 'text/html', 'content-disposition': 'inline; filename="mail.html"' },
|
||||
}),
|
||||
)
|
||||
documentLookup.mockResolvedValue(pdfRow('mail.html', 'text/html'))
|
||||
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/mail.html?token=t'),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.text()).toBe('<script>alert(document.cookie)</script>')
|
||||
expect(response.headers.get('content-type')).toBe('application/octet-stream')
|
||||
expect(response.headers.get('content-disposition')).toBe(
|
||||
`attachment; filename="mail.html"; filename*=UTF-8''mail.html`,
|
||||
)
|
||||
expect(response.headers.get('content-security-policy')).toBe(OPAQUE_CSP)
|
||||
expect(response.headers.get('x-content-type-options')).toBe('nosniff')
|
||||
})
|
||||
|
||||
it.each(['image/svg+xml', 'application/xml', 'application/xhtml+xml', 'application/json'])(
|
||||
'never serves %s from the proxy with its own type',
|
||||
async (mimeType) => {
|
||||
fetchMock.mockResolvedValue(upstreamResponse('<x/>', { headers: { 'content-type': mimeType } }))
|
||||
documentLookup.mockResolvedValue(pdfRow('underlag', mimeType))
|
||||
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/underlag?token=t'),
|
||||
)
|
||||
|
||||
expect(response.headers.get('content-type')).toBe('application/octet-stream')
|
||||
expect(response.headers.get('content-disposition')).toContain('attachment')
|
||||
expect(response.headers.get('content-security-policy')).toBe(OPAQUE_CSP)
|
||||
},
|
||||
)
|
||||
|
||||
it('serves an object without a document row (audit-package zip) as an opaque attachment named after its key', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
upstreamResponse('PK...', {
|
||||
headers: { 'content-type': 'text/html', 'content-disposition': 'inline; filename="x.html"' },
|
||||
}),
|
||||
)
|
||||
documentLookup.mockResolvedValue({ data: [], error: null })
|
||||
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/user-1/audit-packages/1700_audit%202026.zip?token=t'),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('content-type')).toBe('application/octet-stream')
|
||||
expect(response.headers.get('content-disposition')).toBe(
|
||||
`attachment; filename="1700_audit 2026.zip"; filename*=UTF-8''1700_audit%202026.zip`,
|
||||
)
|
||||
expect(response.headers.get('content-security-policy')).toBe(OPAQUE_CSP)
|
||||
})
|
||||
|
||||
it('fails closed to the opaque default when the document lookup errors or throws', async () => {
|
||||
fetchMock.mockResolvedValue(upstreamResponse('%PDF-1.4 bytes'))
|
||||
|
||||
documentLookup.mockResolvedValue({ data: null, error: { message: 'db down' } })
|
||||
const errored = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=t'),
|
||||
)
|
||||
expect(errored.status).toBe(200)
|
||||
expect(errored.headers.get('content-type')).toBe('application/octet-stream')
|
||||
expect(errored.headers.get('content-security-policy')).toBe(OPAQUE_CSP)
|
||||
|
||||
fetchMock.mockResolvedValue(upstreamResponse('%PDF-1.4 bytes'))
|
||||
documentLookup.mockRejectedValue(new Error('network'))
|
||||
const thrown = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=t'),
|
||||
)
|
||||
expect(thrown.status).toBe(200)
|
||||
expect(thrown.headers.get('content-type')).toBe('application/octet-stream')
|
||||
expect(thrown.headers.get('content-security-policy')).toBe(OPAQUE_CSP)
|
||||
})
|
||||
|
||||
it('does not consult the database when Storage rejects the token', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ statusCode: '400', error: 'InvalidJWT' }), {
|
||||
status: 400,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}),
|
||||
)
|
||||
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=bad'),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(documentLookup).not.toHaveBeenCalled()
|
||||
expect(response.headers.get('content-type')).toBe('application/octet-stream')
|
||||
expect(response.headers.get('content-security-policy')).toBe(OPAQUE_CSP)
|
||||
})
|
||||
|
||||
it('answers HEAD without a body and with the same served headers as GET', async () => {
|
||||
fetchMock.mockResolvedValue(upstreamResponse(null, { headers: { 'content-type': 'text/html', 'content-length': '14' } }))
|
||||
documentLookup.mockResolvedValue(pdfRow('kvitto.pdf'))
|
||||
|
||||
const response = await HEAD(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/user-1/kvitto.pdf?token=t', { method: 'HEAD' }),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.body).toBeNull()
|
||||
expect(response.headers.get('content-type')).toBe('application/pdf')
|
||||
expect(response.headers.get('content-length')).toBe('14')
|
||||
expect(response.headers.get('content-security-policy')).toBeNull()
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]
|
||||
expect(init.method).toBe('HEAD')
|
||||
})
|
||||
|
||||
it('answers HEAD without a body and relays the upstream status', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 404, headers: { 'content-type': 'application/json' } }))
|
||||
|
||||
const response = await HEAD(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/missing.pdf?token=t', { method: 'HEAD' }),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(response.body).toBeNull()
|
||||
expect(documentLookup).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses paths outside the signed documents-bucket allowlist without touching Storage', async () => {
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/public/documents/a.pdf?token=t'),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
const body = (await response.json()) as { error: { code: string } }
|
||||
expect(body.error.code).toBe('STORAGE_PROXY_UNSUPPORTED_PATH')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a link without its signed token', async () => {
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/a.pdf'),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = (await response.json()) as { error: { code: string } }
|
||||
expect(body.error.code).toBe('STORAGE_PROXY_TOKEN_REQUIRED')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an oversized upload before forwarding it', async () => {
|
||||
const request = new Request(
|
||||
'https://app.accounted.se/api/storage/upload/sign/documents/co-1/big.pdf?token=t',
|
||||
{ method: 'PUT', headers: { 'content-length': String(51 * 1024 * 1024) }, body: 'x' },
|
||||
)
|
||||
|
||||
const response = await PUT(request)
|
||||
|
||||
expect(response.status).toBe(413)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an oversized upload that lies about (or omits) its content-length, without buffering it all', async () => {
|
||||
let pulled = 0
|
||||
const endless = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
pulled++
|
||||
controller.enqueue(new Uint8Array(1024 * 1024))
|
||||
},
|
||||
})
|
||||
const request = new Request(
|
||||
'https://app.accounted.se/api/storage/upload/sign/documents/co-1/big.pdf?token=t',
|
||||
{ method: 'PUT', body: endless, duplex: 'half' } as RequestInit,
|
||||
)
|
||||
|
||||
const response = await PUT(request)
|
||||
|
||||
expect(response.status).toBe(413)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(pulled).toBeLessThan(60)
|
||||
})
|
||||
|
||||
it('reports Storage being unreachable as 502 instead of crashing', async () => {
|
||||
fetchMock.mockRejectedValue(new Error('ECONNRESET'))
|
||||
|
||||
const response = await GET(
|
||||
new Request('https://app.accounted.se/api/storage/sign/documents/co-1/a.pdf?token=t'),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(502)
|
||||
const body = (await response.json()) as { error: { code: string } }
|
||||
expect(body.error.code).toBe('STORAGE_PROXY_UPSTREAM_UNAVAILABLE')
|
||||
})
|
||||
|
||||
it('answers CORS preflight', async () => {
|
||||
const response = await OPTIONS()
|
||||
expect(response.status).toBe(204)
|
||||
expect(response.headers.get('access-control-allow-methods')).toContain('PUT')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user