Files
accounted/app/api/storage/[...path]/route.ts
T
Jakob Wennberg 18cbc4c30a fix(security): audit remediation 2026-09-01: api_keys identity, viewer gates, OAuth binding, XSS, MFA gate (#2155)
* fix(security): bind api_keys to the caller, lock hash-as-bearer RPCs and provider token tables

Security audit 2026-09-01, critical items.

- api_keys INSERT requires user_id = auth.uid() again (an admin could
  forge a key for any co-member and act as them in every company they
  belong to); SELECT is own-keys-or-admin; a BEFORE trigger freezes the
  identity and credential columns against user-session UPDATEs.
- rotate_mcp_refresh_token and validate_and_increment_api_key become
  service_role only: they match rows by a presented SHA-256, so a hash
  readable by co-members was a bearer credential.
- validate_and_increment_api_key fails closed when the key's user is no
  longer a member of the key's company.
- provider_consent_tokens and provider_otc: the DELETE policies collapsed
  to "caller has any team row" (correlated subquery on a non-existent
  team_members.company_id). All member policies dropped; service_role
  only, matching every existing code path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): role gates, ownership guards and posting integrity in the database

Security audit 2026-09-01, high items at the database layer.

- One table-level guard, enforce_company_writer_role(), blocks the
  read-only viewer role on 55 company-scoped tables including through
  the 15 membership-only SECURITY DEFINER writers. Keyed on the JWT role
  claim so it fires inside definer bodies; no-op for service_role and
  trigger cascades.
- company_members user_id/company_id immutable from user sessions;
  invitations can never grant owner; team_members gains a transition
  guard (admins keep non-owner role moves); companies team_id and
  archiving are owner-only and team attachment needs team membership.
- Direct statements (current_user = authenticated) can no longer insert
  posted headers, add lines under posted verifikat, or post a draft with
  a voucher number the sequence never issued. Sanctioned RPCs run as the
  definer and are untouched; the engine's own draft-then-post shapes
  still pass.
- create_document_version refuses viewers and foreign storage paths;
  validate_version_chain needs membership and loses anon EXECUTE;
  match_documents / match_booking_templates lose anon; cron maintenance
  RPCs become service_role only; the production-only
  seed_asset_categories is dropped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* build: pin tsx as an exact devDependency instead of fetching it with npx at build time

prebuild ran "npx tsx" with no lockfile entry, so every Vercel, Docker
and CI build downloaded tsx@latest and its transitive tree from the
registry with no integrity check, inside the build environment.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): refuse the viewer role on API-key and MCP write paths

The v1 wrapper and the MCP company routing checked company membership
but never role, and both run as service role, so a read-only viewer
holding an API key could post vouchers and change settings through the
API. Mutating methods and non-read scopes now return 403 ROLE_READ_ONLY
for viewers on v1; MCP write tools refuse viewers the same way.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): stop serving uploaded SVG, XML and HTML as executable content on the app origin

Uploads persisted the browser-declared mime type and the inline proxy
served it verbatim, sandboxing only text/html; the storage proxy
forwarded the uploader's Content-Type. Any writer, or any Peppol sender,
could plant a scripted SVG or XHTML that executed on app.gnubok.se.

- inline route: allow-list of natively safe types (PDF, raster images)
  served as before; everything else gets the opaque sandbox CSP.
- storage proxy: octet-stream + attachment + sandbox unless the DB
  mime for the key is on the allow-list.
- document-service: the stored mime is the magic-byte validated type.
- logo upload: magic-byte validation, SVG refused.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): byrå brand logo upload decides the type by magic bytes and drops SVG

Same pattern as the company logo route: the logos bucket is public, so a
scripted SVG (or anything declared as an image) must never land there.
The upload pickers stop advertising SVG.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): bind Enable Banking, Stripe and WooCommerce callbacks to the initiating user

The callbacks resolved the pending row by oauth_state alone, so a
victim who completed an attacker-initiated consent had their bank
account, merchant account or store attached to the attacker's company.
requireFlowInitiator() now requires the cookie session of the user who
started the flow: no session redirects to login with the callback URL
preserved, a different user is refused and nothing is exchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): guard tenant-controlled outbound fetches and surface the disabled rate limiter

WooCommerce and Shopify syncs fetched a member-editable store URL with
plain fetch() and redirect following under the service role, and the
invoice PDF renderer fetched company_settings.logo_url unguarded. All
three go through a new safeFetch() (public-IP validation via url-guard,
https only, redirect: 'manual', body size cap) and re-normalise the
stored host at use time. checkRateLimit() keeps failing open on hosted
but logs one error per process when Upstash is not configured and
exports isRateLimiterConfigured().

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): decide the API MFA gate from server-authenticated factors, not the session cookie

getAuthenticatorAssuranceLevel() without arguments derives nextLevel
from session.user.factors, which comes from the unsigned sb-*-auth-token
cookie. Deleting factors from the cookie made an enrolled account look
like it had nothing to step up to, on every /api route and in
requireAuth. Both gates now read factors from the getUser() result or
listFactors() and the level from the verified JWT claim, and fail closed
on errors. Page-branch gate hardened the same way.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): bind Fortnox/Visma, Gmail and Skatteverket callbacks to the initiating user

The arcim-migration callback exchanged the provider code onto whatever
consent the one-time state named, with no check of who completed the
flow and no org-number comparison, so a phished Fortnox admin handed
their ledger to the attacker's company. provider_otc now records the
initiating user (migration 20260902100000); the callback requires that
session and, after the exchange, refuses a provider company whose org
number differs from the consent's company. The Gmail and Skatteverket
callbacks enforce the same initiator check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): BankID signup confirms the email before linking the identity

Signup created an email-confirmed, MFA-exempt account for any address
the caller typed and returned a magic link, so an attacker could
pre-register a victim's email and keep a permanent BankID login into the
account the victim later adopted. The user is now created unconfirmed,
the identity carries email_verified_at NULL (migration 20260902101000),
bankid_linked is not set until the mailed confirmation is clicked, and
BankID login of a pending identity is refused with the confirmation
re-sent.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(security): bind MCP OAuth redirect URIs to the consenting user and cap scopes

A user-registered redirect URI was allowlisted globally, the consent page
named no client, and all scopes were pre-checked, so one phishing link
handed an attacker a full-scope key for the victim's company. Registered
URIs now resolve only for the registrant or a colleague sharing a
company; the consent page shows the client identity and redirect host;
non-built-in clients default to read-only pre-checks; scopes are capped
by the user's role (viewer: read only) at consent and at /token.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(auth): client follow-ups for BankID confirmation, callback mismatch copy and decision log

- register client handles the new confirmation_sent response from BankID
  signup with the existing inbox screen instead of calling verifyOtp.
- BankID login surfaces the email_unconfirmed explanation.
- WooCommerce settings map woocommerce_error=wrong_user to its own copy.
- Logo help text no longer advertises SVG.
- DECISIONS.md records the audit remediation choices.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(mcp-oauth): literal SoD columns in the api_keys insert so the phantom-column scanner resolves them

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(logo): type the upload fixtures as Uint8Array<ArrayBuffer> so they are valid BlobParts

Fixes the typecheck ratchet on PR #2155 and ratchets the baseline down
by the one legacy error the change removed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 11:38:30 +02:00

272 lines
9.9 KiB
TypeScript

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 })
}