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>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
6e8d76a9cb
commit
18cbc4c30a
@@ -67,8 +67,17 @@ function ownerMembership() {
|
||||
getByraMembershipMock.mockResolvedValue({ teamId: 'team-1', teamName: 'Siffra', role: 'owner' })
|
||||
}
|
||||
|
||||
function uploadRequest(type = 'image/png', size = 128): Request {
|
||||
const file = new File([new Uint8Array(size)], 'logo.png', { type })
|
||||
// The route decides the type by magic bytes (never by the declared type), so
|
||||
// the default fixture is a real PNG signature padded to `size`.
|
||||
const PNG_MAGIC = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
function fixtureBytes(magic: number[] | null, size: number): Uint8Array<ArrayBuffer> {
|
||||
const bytes = new Uint8Array(new ArrayBuffer(Math.max(size, magic?.length ?? 0)))
|
||||
if (magic) bytes.set(magic, 0)
|
||||
return bytes
|
||||
}
|
||||
|
||||
function uploadRequest(type = 'image/png', size = 128, magic: number[] | null = PNG_MAGIC): Request {
|
||||
const file = new File([fixtureBytes(magic, size)], 'logo.png', { type })
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
return new Request('http://localhost/api/byra/brand/logo', { method: 'POST', body: formData })
|
||||
@@ -122,7 +131,7 @@ describe('POST /api/byra/brand/logo', () => {
|
||||
it('returns 400 for a disallowed file type', async () => {
|
||||
authed()
|
||||
ownerMembership()
|
||||
const res = await POST(uploadRequest('application/pdf'))
|
||||
const res = await POST(uploadRequest('application/pdf', 128, null))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
@@ -177,4 +186,12 @@ describe('DELETE /api/byra/brand/logo', () => {
|
||||
expect(updateMock).toHaveBeenCalledWith({ logo_url: null })
|
||||
expect(clearBrandCacheMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses an SVG even when declared as image/png (magic bytes decide)', async () => {
|
||||
const svg = Array.from(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"><script>1</script></svg>'))
|
||||
const response = await POST(uploadRequest('image/png', svg.length, svg))
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('Otillåten filtyp. Tillåtna: PNG, JPG, WebP.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { detectFileMagic } from '@/lib/core/documents/document-service'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { requireByraBrandAccess } from '@/lib/byra/brand-access'
|
||||
@@ -23,7 +24,14 @@ import { LOGO_UPLOAD_MAX_BYTES, LOGO_UPLOAD_MAX_MB } from '@/lib/invoices/brandi
|
||||
* instance that handled the write.
|
||||
*/
|
||||
|
||||
const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp']
|
||||
// Raster formats only, decided by the file's magic bytes (detectFileMagic),
|
||||
// never by the client-declared Content-Type: the logos bucket is PUBLIC and a
|
||||
// scripted SVG on a public URL is a script-capable document.
|
||||
const LOGO_TYPE_EXTENSIONS: Record<string, string> = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/webp': 'webp',
|
||||
}
|
||||
|
||||
async function purgeLogoFiles(
|
||||
serviceClient: ReturnType<typeof createServiceClient>,
|
||||
@@ -60,12 +68,6 @@ export async function POST(request: Request) {
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: 'Ingen fil angiven' }, { status: 400 })
|
||||
}
|
||||
if (!ALLOWED_TYPES.includes(file.type)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Otillåten filtyp. Tillåtna: PNG, JPG, SVG, WebP.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
if (file.size > LOGO_UPLOAD_MAX_BYTES) {
|
||||
return NextResponse.json(
|
||||
{ error: `Filen är för stor (max ${LOGO_UPLOAD_MAX_MB} MB).` },
|
||||
@@ -74,20 +76,21 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
const mimeToExt: Record<string, string> = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/svg+xml': 'svg',
|
||||
'image/webp': 'webp',
|
||||
const detectedType = detectFileMagic(new Uint8Array(buffer))
|
||||
const ext = detectedType ? LOGO_TYPE_EXTENSIONS[detectedType] : undefined
|
||||
if (!detectedType || !ext) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Otillåten filtyp. Tillåtna: PNG, JPG, WebP.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
const ext = mimeToExt[file.type] ?? 'png'
|
||||
const storagePath = `byra/${teamId}/logo-${Date.now()}.${ext}`
|
||||
|
||||
await purgeLogoFiles(serviceClient, teamId)
|
||||
|
||||
const { error: uploadError } = await serviceClient.storage
|
||||
.from('logos')
|
||||
.upload(storagePath, buffer, { contentType: file.type, upsert: true })
|
||||
.upload(storagePath, buffer, { contentType: detectedType, upsert: true })
|
||||
if (uploadError) {
|
||||
return NextResponse.json(
|
||||
{ error: `Uppladdning misslyckades: ${getUserErrorMessage(uploadError)}` },
|
||||
|
||||
@@ -110,7 +110,19 @@ describe('GET /api/documents/[id]/inline', () => {
|
||||
expect(disposition).toContain('filename="kvitto f_rvaring.pdf"')
|
||||
expect(res.headers.get('Content-Type')).toBe('application/pdf')
|
||||
expect(res.headers.get('Cache-Control')).toBe('private, no-store')
|
||||
// The mail-body CSP is HTML-only: it must not restrict PDF rendering.
|
||||
// PDF is natively inline-safe: the sandboxing CSP would break Chrome's
|
||||
// built-in viewer, so it must be absent here.
|
||||
expect(res.headers.get('Content-Security-Policy')).toBeNull()
|
||||
})
|
||||
|
||||
it('serves raster images without the sandboxing CSP', async () => {
|
||||
enqueue({ data: makeDoc({ file_name: 'kvitto.png', mime_type: 'image/png' }), error: null })
|
||||
downloadMock.mockResolvedValue({ data: new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])]), error: null })
|
||||
|
||||
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('image/png')
|
||||
expect(res.headers.get('Content-Security-Policy')).toBeNull()
|
||||
})
|
||||
|
||||
@@ -137,4 +149,72 @@ describe('GET /api/documents/[id]/inline', () => {
|
||||
)
|
||||
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
|
||||
})
|
||||
|
||||
// Allow-list, not deny-list: every type outside PDF/raster images is
|
||||
// uploader-controlled active content on this origin and must be sandboxed,
|
||||
// while still rendering inline (Peppol XML archives, iXBRL, JSON previews).
|
||||
it.each([
|
||||
['application/xml', 'peppol-faktura.xml', '<?xml version="1.0"?><Invoice/>'],
|
||||
['text/xml', 'peppol-faktura.xml', '<?xml version="1.0"?><Invoice/>'],
|
||||
[
|
||||
'application/xhtml+xml',
|
||||
'arsredovisning.xhtml',
|
||||
'<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><script>alert(1)</script></html>',
|
||||
],
|
||||
[
|
||||
'image/svg+xml',
|
||||
'logga.svg',
|
||||
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(document.cookie)</script></svg>',
|
||||
],
|
||||
['application/json', 'psd2-svar.json', '{"transactions":[]}'],
|
||||
])('serves %s inline but under the sandboxing CSP', async (mimeType, fileName, body) => {
|
||||
enqueue({ data: makeDoc({ file_name: fileName, mime_type: mimeType }), error: null })
|
||||
downloadMock.mockResolvedValue({ data: new Blob([body]), error: null })
|
||||
|
||||
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe(mimeType)
|
||||
expect(res.headers.get('Content-Disposition')).toContain('inline')
|
||||
expect(res.headers.get('Content-Security-Policy')).toBe(
|
||||
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
|
||||
)
|
||||
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff')
|
||||
})
|
||||
|
||||
it('sandboxes a legacy row whose type is spoofed with casing or parameters', async () => {
|
||||
enqueue({
|
||||
data: makeDoc({ file_name: 'faktura.html', mime_type: 'TEXT/HTML; charset=utf-8' }),
|
||||
error: null,
|
||||
})
|
||||
|
||||
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Security-Policy')).toBe(
|
||||
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
|
||||
)
|
||||
})
|
||||
|
||||
it('sandboxes an unknown type the extension fallback cannot resolve', async () => {
|
||||
enqueue({ data: makeDoc({ file_name: 'underlag.bin', mime_type: null }), error: null })
|
||||
|
||||
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
|
||||
expect(res.headers.get('Content-Security-Policy')).toBe(
|
||||
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the extension fallback for legacy PDF rows without adding the CSP', async () => {
|
||||
enqueue({ data: makeDoc({ file_name: 'kvitto.pdf', mime_type: null }), error: null })
|
||||
|
||||
const res = await GET(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toBe('application/pdf')
|
||||
expect(res.headers.get('Content-Security-Policy')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { contentDisposition } from '@/lib/api/content-disposition'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { OPAQUE_DOCUMENT_CSP, inlineSafeMimeType } from '@/lib/core/documents/storage-proxy'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
@@ -18,6 +19,14 @@ import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-m
|
||||
* Defense in depth: the user's cookie-bound client authorizes access
|
||||
* (RLS + explicit company_id filter) before the service-role client
|
||||
* fetches the file from the non-public `documents` bucket.
|
||||
*
|
||||
* Content types are served on an allow-list basis: only the natively
|
||||
* inline-safe types (INLINE_SAFE_MIME_TYPES: PDF and raster images) render
|
||||
* with the app origin's authority. Every other resolved type is served
|
||||
* under OPAQUE_DOCUMENT_CSP, which keeps it opaque-origin and script-free
|
||||
* while still letting the preview render (HTML mail bodies, Peppol XML,
|
||||
* iXBRL). The mime_type column was client-declared for legacy rows, so the
|
||||
* decision cannot trust it beyond membership in the allow-list.
|
||||
*/
|
||||
|
||||
const EXTENSION_MIME_MAP: Record<string, string> = {
|
||||
@@ -92,20 +101,17 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
// content. Without nosniff a tampered file_name extension could
|
||||
// serve a stored document under an attacker-chosen MIME type.
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
// text/html documents are attacker-controlled mail bodies from the
|
||||
// invoice inbox. Served inline on the app origin they would execute
|
||||
// scripts with our origin's authority: CSP sandbox (no tokens) makes
|
||||
// the rendered document opaque-origin and script-free wherever it is
|
||||
// opened, iframe or direct tab. The source policy blocks outbound
|
||||
// requests on top of that: sandbox alone still loads remote images,
|
||||
// so a tracking pixel would notify the sender when the preview is
|
||||
// opened. Inline styles and embedded data:/blob: images keep working.
|
||||
...(contentType === 'text/html'
|
||||
? {
|
||||
'Content-Security-Policy':
|
||||
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
|
||||
}
|
||||
: {}),
|
||||
// Allow-list, not deny-list: anything that is not a natively
|
||||
// inline-safe type (text/html mail bodies, XHTML, XML, SVG, JSON,
|
||||
// unknown or legacy types) is uploader-controlled active content
|
||||
// when rendered on this origin. The sandboxing policy neutralises
|
||||
// scripts and outbound requests for all of them while the preview
|
||||
// keeps rendering; see OPAQUE_DOCUMENT_CSP. PDF and raster images
|
||||
// are exempt because the directive would also break Chrome's
|
||||
// built-in PDF viewer (it renders through an internal <embed>).
|
||||
...(inlineSafeMimeType(contentType)
|
||||
? {}
|
||||
: { 'Content-Security-Policy': OPAQUE_DOCUMENT_CSP }),
|
||||
},
|
||||
})
|
||||
},
|
||||
|
||||
@@ -9,15 +9,31 @@ vi.mock('@/extensions/general/enable-banking/lib/api-client', () => ({
|
||||
}))
|
||||
|
||||
// Use hoisted to safely create mock objects referenced in vi.mock factories
|
||||
const { mockFrom, mockUpsertFromPsd2, mockAllocate, mockSupersede, mockCrossCompanyContext } =
|
||||
vi.hoisted(() => {
|
||||
const mockFrom = vi.fn()
|
||||
const mockUpsertFromPsd2 = vi.fn()
|
||||
const mockAllocate = vi.fn()
|
||||
const mockSupersede = vi.fn()
|
||||
const mockCrossCompanyContext = vi.fn()
|
||||
return { mockFrom, mockUpsertFromPsd2, mockAllocate, mockSupersede, mockCrossCompanyContext }
|
||||
})
|
||||
const {
|
||||
mockFrom,
|
||||
mockUpsertFromPsd2,
|
||||
mockAllocate,
|
||||
mockSupersede,
|
||||
mockCrossCompanyContext,
|
||||
mockGetUser,
|
||||
} = vi.hoisted(() => {
|
||||
const mockFrom = vi.fn()
|
||||
const mockUpsertFromPsd2 = vi.fn()
|
||||
const mockAllocate = vi.fn()
|
||||
const mockSupersede = vi.fn()
|
||||
const mockCrossCompanyContext = vi.fn()
|
||||
// The cookie session the callback binds the completion to. Every pending
|
||||
// row in this suite belongs to 'user-1', so that is the default session.
|
||||
const mockGetUser = vi.fn()
|
||||
return {
|
||||
mockFrom,
|
||||
mockUpsertFromPsd2,
|
||||
mockAllocate,
|
||||
mockSupersede,
|
||||
mockCrossCompanyContext,
|
||||
mockGetUser,
|
||||
}
|
||||
})
|
||||
|
||||
// The supersede pass has its own unit tests (extensions/general/enable-banking/
|
||||
// __tests__/supersede.test.ts); here it is mocked so these tests assert the
|
||||
@@ -43,6 +59,9 @@ vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: vi.fn().mockResolvedValue({
|
||||
from: mockFrom,
|
||||
}),
|
||||
createClient: vi.fn().mockResolvedValue({
|
||||
auth: { getUser: mockGetUser },
|
||||
}),
|
||||
}))
|
||||
|
||||
const CURRENCY_DEFAULTS: Record<string, string> = {
|
||||
@@ -104,6 +123,7 @@ function mockChain(result: { data?: unknown; error?: unknown }) {
|
||||
describe('GET /api/extensions/enable-banking/callback', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetUser.mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null })
|
||||
mockUpsertFromPsd2.mockResolvedValue(undefined)
|
||||
mockSupersede.mockResolvedValue({ supersededIds: [], dedupScopeByIban: new Map() })
|
||||
// No sibling company claims anything by default; individual tests override.
|
||||
@@ -149,6 +169,120 @@ describe('GET /api/extensions/enable-banking/callback', () => {
|
||||
expect(decodeURIComponent(location)).toContain('Starta bankkopplingen på nytt')
|
||||
})
|
||||
|
||||
// The state token proves the callback belongs to a flow WE started, not that
|
||||
// the browser completing it is the initiator's. A victim lured into
|
||||
// approving a consent someone else started must not have their bank
|
||||
// attached to that someone's company.
|
||||
describe('initiator binding', () => {
|
||||
const PENDING_ROW = {
|
||||
id: 'conn-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
bank_name: 'TestBank',
|
||||
status: 'pending',
|
||||
session_id: null,
|
||||
accounts_data: null,
|
||||
}
|
||||
|
||||
it('refuses a consent completed by a different user and leaves the row untouched', async () => {
|
||||
const chain = mockChain({ data: PENDING_ROW, error: null })
|
||||
mockFrom.mockReturnValue(chain)
|
||||
mockGetUser.mockResolvedValue({ data: { user: { id: 'user-2' } }, error: null })
|
||||
|
||||
const response = await GET(makeRequest({ code: 'auth-code', state: 'valid-state' }))
|
||||
|
||||
expect(response.status).toBe(307)
|
||||
const location = new URL(response.headers.get('location') || '')
|
||||
expect(location.pathname).toBe('/settings/banking')
|
||||
expect(location.searchParams.get('bank_error')).toContain('annat användarkonto')
|
||||
expect(location.searchParams.get('bank_name')).toBe('TestBank')
|
||||
expect(location.searchParams.has('select_accounts')).toBe(false)
|
||||
|
||||
// The code was never exchanged and nothing was written: the row keeps
|
||||
// waiting for its initiator (only the lookup touched the table).
|
||||
expect(mockCreateSession).not.toHaveBeenCalled()
|
||||
expect(mockFrom).toHaveBeenCalledTimes(1)
|
||||
expect(chain.update).not.toHaveBeenCalled()
|
||||
expect(chain.delete).not.toHaveBeenCalled()
|
||||
expect(mockUpsertFromPsd2).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sends an anonymous browser to /login with the callback URL preserved', async () => {
|
||||
const chain = mockChain({ data: PENDING_ROW, error: null })
|
||||
mockFrom.mockReturnValue(chain)
|
||||
mockGetUser.mockResolvedValue({ data: { user: null }, error: null })
|
||||
|
||||
const response = await GET(makeRequest({ code: 'auth-code', state: 'valid-state' }))
|
||||
|
||||
expect(response.status).toBe(307)
|
||||
const location = new URL(response.headers.get('location') || '')
|
||||
expect(location.origin).toBe('http://localhost:3000')
|
||||
expect(location.pathname).toBe('/login')
|
||||
expect(location.searchParams.get('next')).toBe(
|
||||
'/api/extensions/enable-banking/callback?code=auth-code&state=valid-state',
|
||||
)
|
||||
|
||||
expect(mockCreateSession).not.toHaveBeenCalled()
|
||||
expect(chain.update).not.toHaveBeenCalled()
|
||||
expect(chain.delete).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('finalizes as before when the session belongs to the initiator', async () => {
|
||||
// mockConnectionFlow is the suite's standard script for the finalize
|
||||
// path (function declaration below, hoisted into this scope).
|
||||
mockConnectionFlow(PENDING_ROW)
|
||||
mockGetUser.mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null })
|
||||
mockCreateSession.mockResolvedValue({
|
||||
session_id: 'sess-1',
|
||||
accounts: [],
|
||||
access: { valid_until: '2027-12-31T00:00:00Z' },
|
||||
aspsp: { name: 'TestBank', country: 'SE' },
|
||||
})
|
||||
|
||||
const response = await GET(makeRequest({ code: 'auth-code', state: 'valid-state' }))
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mockGetUser).toHaveBeenCalledTimes(1)
|
||||
expect(mockCreateSession).toHaveBeenCalledWith('auth-code', undefined)
|
||||
expect(await response.text()).toContain('select_accounts=conn-1')
|
||||
})
|
||||
|
||||
it('does not consult the session for an unknown state (nothing to bind to)', async () => {
|
||||
mockFrom.mockImplementation(() => mockChain({ data: null, error: { message: 'not found' } }))
|
||||
|
||||
await GET(makeRequest({ code: 'auth-code', state: 'unknown-state' }))
|
||||
|
||||
expect(mockGetUser).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves the hosted connector bounce alone (server-to-server, HMAC-verified)', async () => {
|
||||
// The hosted proxy callback never finalizes anything: it verifies the
|
||||
// signed connector state and bounces the browser to the instance, whose
|
||||
// own callback then runs the binding against ITS session.
|
||||
vi.stubEnv('CONNECTOR_STATE_SECRET', 'test-connector-secret')
|
||||
const { signConnectorState } = await import('@/lib/connect/hosted/state')
|
||||
const connectorState = signConnectorState({
|
||||
kid: 'key-1',
|
||||
svc: 'bank',
|
||||
ret: 'https://instance.example.se/api/extensions/enable-banking/callback',
|
||||
st: 'instance-state',
|
||||
cref: 'company-ref',
|
||||
})
|
||||
|
||||
const response = await GET(makeRequest({ code: 'auth-code', state: connectorState }))
|
||||
|
||||
expect(response.status).toBe(307)
|
||||
const location = new URL(response.headers.get('location') || '')
|
||||
expect(location.origin).toBe('https://instance.example.se')
|
||||
expect(location.searchParams.get('state')).toBe('instance-state')
|
||||
expect(location.searchParams.get('code')).toBe('auth-code')
|
||||
expect(mockGetUser).not.toHaveBeenCalled()
|
||||
expect(mockFrom).not.toHaveBeenCalled()
|
||||
vi.unstubAllEnvs()
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'http://localhost:3000')
|
||||
})
|
||||
})
|
||||
|
||||
it('threads connector_state from the query into createSession (connector mode)', async () => {
|
||||
// In connector mode the hosted callback bounces the browser back here with
|
||||
// the signed connector_state echoed alongside code + the instance's own
|
||||
|
||||
@@ -20,6 +20,10 @@ import { supersedeSiblingConnections } from '@/extensions/general/enable-banking
|
||||
import { getBankConnectionErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { renderFinalizeShell, renderFinalizeRedirect } from './finalize-page'
|
||||
import { isConnectorState, verifyConnectorState } from '@/lib/connect/hosted/state'
|
||||
import {
|
||||
requireFlowInitiator,
|
||||
FLOW_INITIATOR_MISMATCH_MESSAGE,
|
||||
} from '@/lib/auth/oauth-flow-binding'
|
||||
|
||||
// This route emits bank_connection.consent_granted / .cash_account_mirror_failed
|
||||
// (ASVS V16 / GDPR Art.30 audit events). ensureInitialized() must run at module
|
||||
@@ -269,6 +273,31 @@ export async function GET(request: Request) {
|
||||
)
|
||||
}
|
||||
|
||||
// The state token proves this callback belongs to a flow we started; it
|
||||
// says nothing about WHO is completing it. Bind the completion to the
|
||||
// initiator's own cookie session before any finalize work: otherwise a
|
||||
// victim lured into approving a consent someone else started would have
|
||||
// their bank accounts attached to that someone's company. The connector
|
||||
// branch above is exempt on purpose (server-to-server, HMAC-verified).
|
||||
const initiator = await requireFlowInitiator(request, pendingConnection.user_id, {
|
||||
flow: 'enable-banking.callback',
|
||||
})
|
||||
if (!initiator.ok) {
|
||||
if (initiator.reason === 'no_session') {
|
||||
// Session expired mid-flow: sign in and the callback re-runs with the
|
||||
// same code + state. Nothing on the row changes.
|
||||
return initiator.response
|
||||
}
|
||||
// A different user completed it. Refuse without exchanging the code and
|
||||
// without touching the row: it keeps waiting for its initiator and the
|
||||
// stale-pending cleanup reaps it if nobody comes back.
|
||||
const params = new URLSearchParams({
|
||||
bank_error: FLOW_INITIATOR_MISMATCH_MESSAGE,
|
||||
...(pendingConnection.bank_name ? { bank_name: pendingConnection.bank_name } : {}),
|
||||
})
|
||||
return NextResponse.redirect(`${baseUrl}/settings/banking?${params.toString()}`)
|
||||
}
|
||||
|
||||
// Kick the finalize work off eagerly, decoupled from the response stream:
|
||||
// if the user closes the tab mid-stream, the stream is cancelled but this
|
||||
// promise keeps running, so the session persistence, cash-account mirror
|
||||
|
||||
@@ -9,10 +9,16 @@ vi.mock('@/extensions/general/stripe/lib/connect', () => ({
|
||||
fetchAccountDisplayName: (...args: unknown[]) => mockFetchAccountDisplayName(...args),
|
||||
}))
|
||||
|
||||
const { mockFrom } = vi.hoisted(() => ({ mockFrom: vi.fn() }))
|
||||
const { mockFrom, mockGetUser } = vi.hoisted(() => ({
|
||||
mockFrom: vi.fn(),
|
||||
// The cookie session the callback binds the completion to. Every pending
|
||||
// row in this suite belongs to 'user-1', so that is the default session.
|
||||
mockGetUser: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: vi.fn().mockResolvedValue({ from: mockFrom }),
|
||||
createClient: vi.fn().mockResolvedValue({ auth: { getUser: mockGetUser } }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
@@ -50,6 +56,7 @@ describe('GET /api/extensions/stripe/callback', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockGetUser.mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null })
|
||||
mockExchangeCodeForAccount.mockResolvedValue({
|
||||
stripeAccountId: 'acct_123',
|
||||
livemode: false,
|
||||
@@ -146,4 +153,64 @@ describe('GET /api/extensions/stripe/callback', () => {
|
||||
)
|
||||
expect(mockFrom).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// The state token proves the callback belongs to a flow WE started, not that
|
||||
// the browser completing it is the initiator's. A victim lured into
|
||||
// approving a Connect someone else started must not have their Stripe
|
||||
// account attached to that someone's company.
|
||||
describe('initiator binding', () => {
|
||||
const PENDING_ROW = { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' }
|
||||
|
||||
it('refuses a consent completed by a different user without burning the code or marking the row', async () => {
|
||||
const findChain = mockChain({ data: PENDING_ROW })
|
||||
mockFrom.mockReturnValue(findChain)
|
||||
mockGetUser.mockResolvedValue({ data: { user: { id: 'user-2' } }, error: null })
|
||||
|
||||
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
|
||||
|
||||
expect(response.status).toBe(307)
|
||||
const location = decodeURIComponent(response.headers.get('location') || '')
|
||||
expect(location.startsWith('http://localhost:3000/import?mode=stripe&stripe_error=')).toBe(true)
|
||||
// The panel shows an unknown stripe_error value verbatim, so the param
|
||||
// carries the Swedish explanation itself.
|
||||
expect(location).toContain('annat användarkonto')
|
||||
expect(location).not.toContain('stripe_connected')
|
||||
|
||||
// Only the lookup touched the database: no oauth_used_codes insert (the
|
||||
// code stays valid for the initiator), no update on the row.
|
||||
expect(mockFrom).toHaveBeenCalledTimes(1)
|
||||
expect(findChain.insert).not.toHaveBeenCalled()
|
||||
expect(findChain.update).not.toHaveBeenCalled()
|
||||
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sends an anonymous browser to /login with the callback URL preserved', async () => {
|
||||
const findChain = mockChain({ data: PENDING_ROW })
|
||||
mockFrom.mockReturnValue(findChain)
|
||||
mockGetUser.mockResolvedValue({ data: { user: null }, error: null })
|
||||
|
||||
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
|
||||
|
||||
expect(response.status).toBe(307)
|
||||
const location = new URL(response.headers.get('location') || '')
|
||||
expect(location.origin).toBe('http://localhost:3000')
|
||||
expect(location.pathname).toBe('/login')
|
||||
expect(location.searchParams.get('next')).toBe(
|
||||
`/api/extensions/stripe/callback?code=ac_123&state=${OAUTH_STATE}`,
|
||||
)
|
||||
|
||||
expect(mockFrom).toHaveBeenCalledTimes(1)
|
||||
expect(findChain.insert).not.toHaveBeenCalled()
|
||||
expect(findChain.update).not.toHaveBeenCalled()
|
||||
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not consult the session for an unknown state (nothing to bind to)', async () => {
|
||||
mockFrom.mockReturnValueOnce(mockChain({ data: null, error: { code: 'PGRST116' } }))
|
||||
|
||||
await GET(makeRequest({ code: 'ac_123', state: 'unknown-state' }))
|
||||
|
||||
expect(mockGetUser).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,6 +3,10 @@ import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { hashAuthCode } from '@/lib/auth/oauth-codes'
|
||||
import {
|
||||
requireFlowInitiator,
|
||||
FLOW_INITIATOR_MISMATCH_MESSAGE,
|
||||
} from '@/lib/auth/oauth-flow-binding'
|
||||
import {
|
||||
exchangeCodeForAccount,
|
||||
fetchAccountDisplayName,
|
||||
@@ -90,6 +94,29 @@ export async function GET(request: Request) {
|
||||
)
|
||||
}
|
||||
|
||||
// The state token proves this callback belongs to a flow we started; it
|
||||
// says nothing about WHO is completing it. Bind the completion to the
|
||||
// initiator's own cookie session BEFORE the code is burned below:
|
||||
// otherwise a victim lured into approving a Stripe Connect someone else
|
||||
// started would have their Stripe account attached to that someone's
|
||||
// company. Stripe's redirect is a top-level navigation, so the
|
||||
// initiator's cookies are present on the legitimate path.
|
||||
const initiator = await requireFlowInitiator(request, pendingConnection.user_id, {
|
||||
flow: 'stripe.callback',
|
||||
})
|
||||
if (!initiator.ok) {
|
||||
if (initiator.reason === 'no_session') {
|
||||
// Session expired mid-flow: sign in and the callback re-runs with
|
||||
// the same (still unused) code + state. The row is untouched.
|
||||
return initiator.response
|
||||
}
|
||||
// A different user completed it. Refuse without exchanging the code
|
||||
// and without marking the row: it stays pending for its initiator.
|
||||
return NextResponse.redirect(
|
||||
`${returnUrl}&stripe_error=${encodeURIComponent(FLOW_INITIATOR_MISMATCH_MESSAGE)}`,
|
||||
)
|
||||
}
|
||||
|
||||
// Replay protection (OAuth 2.1 §4.1.2): a code may be exchanged once.
|
||||
// The PRIMARY KEY on oauth_used_codes rejects a second insert.
|
||||
const { error: replayError } = await supabase
|
||||
|
||||
@@ -150,7 +150,11 @@ describe('POST /api/extensions/woocommerce/callback', () => {
|
||||
const activation = updates[0][0] as Record<string, string | boolean | null>
|
||||
expect(activation.status).toBe('active')
|
||||
expect(activation.transaction_sync_enabled).toBe(true)
|
||||
expect(activation.oauth_state).toBeNull()
|
||||
// The state survives activation on purpose: this POST has no browser
|
||||
// session, so the browser leg (../return) binds the completion to the
|
||||
// initiator by looking the row up with this same state and consumes it
|
||||
// there. Replay is blocked by the status 'pending' scope instead.
|
||||
expect(activation).not.toHaveProperty('oauth_state')
|
||||
expect(activation.store_name).toBe('Testbutiken')
|
||||
// Secrets never stored in plaintext, and they decrypt back.
|
||||
expect(String(activation.consumer_key_encrypted)).not.toContain('ck_new')
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: vi.fn(),
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/extensions/loader', () => ({ loadExtensions: vi.fn() }))
|
||||
vi.mock('@/lib/extensions/registry', () => ({ extensionRegistry: { get: vi.fn() } }))
|
||||
|
||||
import { GET } from '../return/route'
|
||||
import { createServiceClient, createClient } from '@/lib/supabase/server'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const STATE = '123e4567-e89b-12d3-a456-426614174000'
|
||||
const BASE = 'http://localhost:3000'
|
||||
const CONNECTED = `${BASE}/import?mode=woocommerce&woocommerce_connected=true`
|
||||
|
||||
function makeReturnRequest(params: Record<string, string>): Request {
|
||||
const url = new URL(`${BASE}/api/extensions/woocommerce/return`)
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v)
|
||||
return new Request(url.toString())
|
||||
}
|
||||
|
||||
function mockServiceClient() {
|
||||
const queued = createQueuedMockSupabase()
|
||||
vi.mocked(createServiceClient).mockResolvedValue(
|
||||
queued.supabase as unknown as Awaited<ReturnType<typeof createServiceClient>>,
|
||||
)
|
||||
return queued
|
||||
}
|
||||
|
||||
function mockSession(userId: string | null) {
|
||||
const getUser = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ data: { user: userId ? { id: userId } : null }, error: null })
|
||||
vi.mocked(createClient).mockResolvedValue({ auth: { getUser } } as never)
|
||||
return getUser
|
||||
}
|
||||
|
||||
const ROW = (status: 'pending' | 'active') => ({
|
||||
id: 'conn-1',
|
||||
user_id: 'user-1',
|
||||
status,
|
||||
})
|
||||
|
||||
describe('GET /api/extensions/woocommerce/return', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', BASE)
|
||||
vi.mocked(extensionRegistry.get).mockReturnValue(
|
||||
{ id: 'woocommerce' } as ReturnType<typeof extensionRegistry.get>,
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('refuses with 503 when the extension is disabled', async () => {
|
||||
vi.mocked(extensionRegistry.get).mockReturnValue(undefined)
|
||||
const res = await GET(makeReturnRequest({ success: '1', user_id: STATE }))
|
||||
expect(res.status).toBe(503)
|
||||
})
|
||||
|
||||
it('closes the pending row and reports the denial when the store says no', async () => {
|
||||
const { supabase, enqueue, findCall } = mockServiceClient()
|
||||
enqueue({ data: null })
|
||||
|
||||
const res = await GET(makeReturnRequest({ success: '0', user_id: STATE }))
|
||||
|
||||
expect(res.headers.get('location')).toBe(
|
||||
`${BASE}/import?mode=woocommerce&woocommerce_error=denied`,
|
||||
)
|
||||
const update = findCall('woocommerce_connections', 'update')?.[0] as Record<string, unknown>
|
||||
expect(update).toMatchObject({ status: 'error', oauth_state: null })
|
||||
expect(supabase.from).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
describe('approved leg (success=1)', () => {
|
||||
it('hands an active row over to its initiator and consumes the state', async () => {
|
||||
const { enqueue, findCalls } = mockServiceClient()
|
||||
const getUser = mockSession('user-1')
|
||||
enqueue({ data: ROW('active') }) // lookup by oauth_state
|
||||
enqueue({ data: null }) // consume update
|
||||
|
||||
const res = await GET(makeReturnRequest({ success: '1', user_id: STATE }))
|
||||
|
||||
expect(res.status).toBe(307)
|
||||
expect(res.headers.get('location')).toBe(CONNECTED)
|
||||
expect(getUser).toHaveBeenCalledTimes(1)
|
||||
const updates = findCalls('woocommerce_connections', 'update')
|
||||
expect(updates).toHaveLength(1)
|
||||
expect(updates[0][0]).toEqual({ oauth_state: null })
|
||||
})
|
||||
|
||||
it('leaves a still-pending row untouched for the initiator (the callback still needs the state)', async () => {
|
||||
const { enqueue, findCalls } = mockServiceClient()
|
||||
mockSession('user-1')
|
||||
enqueue({ data: ROW('pending') })
|
||||
|
||||
const res = await GET(makeReturnRequest({ success: '1', user_id: STATE }))
|
||||
|
||||
expect(res.headers.get('location')).toBe(CONNECTED)
|
||||
expect(findCalls('woocommerce_connections', 'update')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('revokes an already-activated row when a different user completes the handshake', async () => {
|
||||
const { enqueue, findCalls, calls } = mockServiceClient()
|
||||
mockSession('user-2')
|
||||
enqueue({ data: ROW('active') })
|
||||
enqueue({ data: null }) // revoke update
|
||||
|
||||
const res = await GET(makeReturnRequest({ success: '1', user_id: STATE }))
|
||||
|
||||
expect(res.status).toBe(307)
|
||||
expect(res.headers.get('location')).toBe(
|
||||
`${BASE}/import?mode=woocommerce&woocommerce_error=wrong_user`,
|
||||
)
|
||||
const updates = findCalls('woocommerce_connections', 'update')
|
||||
expect(updates).toHaveLength(1)
|
||||
// The store's keys the callback stored for the wrong company are gone,
|
||||
// the state is consumed, and the row says why.
|
||||
expect(updates[0][0]).toMatchObject({
|
||||
status: 'error',
|
||||
oauth_state: null,
|
||||
consumer_key_encrypted: null,
|
||||
consumer_secret_encrypted: null,
|
||||
})
|
||||
expect(String((updates[0][0] as Record<string, unknown>).error_message)).toContain(
|
||||
'annat användarkonto',
|
||||
)
|
||||
// Scoped to this row, never a blanket update.
|
||||
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
||||
expect(eqCalls).toContainEqual(['id', 'conn-1'])
|
||||
})
|
||||
|
||||
it('closes a still-pending row when a different user completes it, so the late callback cannot activate it', async () => {
|
||||
const { enqueue, findCalls } = mockServiceClient()
|
||||
mockSession('user-2')
|
||||
enqueue({ data: ROW('pending') })
|
||||
enqueue({ data: null })
|
||||
|
||||
const res = await GET(makeReturnRequest({ success: '1', user_id: STATE }))
|
||||
|
||||
expect(res.headers.get('location')).toBe(
|
||||
`${BASE}/import?mode=woocommerce&woocommerce_error=wrong_user`,
|
||||
)
|
||||
const updates = findCalls('woocommerce_connections', 'update')
|
||||
expect(updates).toHaveLength(1)
|
||||
expect(updates[0][0]).toMatchObject({ status: 'error', oauth_state: null })
|
||||
})
|
||||
|
||||
it('sends an anonymous browser to /login with the return URL preserved and touches nothing', async () => {
|
||||
const { enqueue, findCalls } = mockServiceClient()
|
||||
mockSession(null)
|
||||
enqueue({ data: ROW('active') })
|
||||
|
||||
const res = await GET(makeReturnRequest({ success: '1', user_id: STATE }))
|
||||
|
||||
expect(res.status).toBe(307)
|
||||
const location = new URL(res.headers.get('location') || '')
|
||||
expect(location.origin).toBe(BASE)
|
||||
expect(location.pathname).toBe('/login')
|
||||
expect(location.searchParams.get('next')).toBe(
|
||||
`/api/extensions/woocommerce/return?success=1&user_id=${STATE}`,
|
||||
)
|
||||
expect(findCalls('woocommerce_connections', 'update')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('does not consult the session when no row carries the state (already consumed or unknown)', async () => {
|
||||
const { enqueue, findCalls } = mockServiceClient()
|
||||
const getUser = mockSession('user-2')
|
||||
enqueue({ data: null, error: { message: 'no rows', code: 'PGRST116' } })
|
||||
|
||||
const res = await GET(makeReturnRequest({ success: '1', user_id: STATE }))
|
||||
|
||||
expect(res.headers.get('location')).toBe(CONNECTED)
|
||||
expect(getUser).not.toHaveBeenCalled()
|
||||
expect(findCalls('woocommerce_connections', 'update')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('redirects without a database round trip when the state is missing or not a uuid', async () => {
|
||||
const { supabase } = mockServiceClient()
|
||||
|
||||
const res1 = await GET(makeReturnRequest({ success: '1' }))
|
||||
const res2 = await GET(makeReturnRequest({ success: '1', user_id: 'not-a-uuid' }))
|
||||
|
||||
expect(res1.headers.get('location')).toBe(CONNECTED)
|
||||
expect(res2.headers.get('location')).toBe(CONNECTED)
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -132,7 +132,12 @@ export async function POST(request: Request) {
|
||||
status: 'active',
|
||||
connected_at: new Date().toISOString(),
|
||||
error_message: null,
|
||||
oauth_state: null, // Clear to prevent replay
|
||||
// oauth_state is deliberately KEPT here. This POST is server-to-server
|
||||
// (the store calls it, no browser session), so the initiator check has
|
||||
// to happen on the browser leg (../return), which locates the row by
|
||||
// this same state and consumes it there. Replay is still blocked: both
|
||||
// the lookup above and this update are scoped to status 'pending', so
|
||||
// an active row can never be activated again.
|
||||
// Feed-only product: connecting the store means fetching its orders, so
|
||||
// the nightly feed starts on by default; the panel toggle is the opt-out.
|
||||
transaction_sync_enabled: true,
|
||||
|
||||
@@ -3,17 +3,32 @@ import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { loadExtensions } from '@/lib/extensions/loader'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import {
|
||||
requireFlowInitiator,
|
||||
FLOW_INITIATOR_MISMATCH_MESSAGE,
|
||||
} from '@/lib/auth/oauth-flow-binding'
|
||||
|
||||
const log = createLogger('woocommerce/return')
|
||||
|
||||
// The state is a UUID we generated; anything else cannot match a row (and the
|
||||
// column is typed uuid, which would error opaquely on a non-UUID filter).
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
/**
|
||||
* GET /api/extensions/woocommerce/return
|
||||
*
|
||||
* Browser leg of the wc-auth handshake: WooCommerce redirects the merchant
|
||||
* here with ?success=1|0&user_id=<our oauth_state>. The credentials arrive on
|
||||
* the separate server-to-server callback (usually before this redirect, but
|
||||
* ordering is not guaranteed), so on success this route only sends the user
|
||||
* back to the import page; the panel polls /status until the row is active.
|
||||
* ordering is not guaranteed); the panel polls /status until the row is
|
||||
* active.
|
||||
*
|
||||
* This leg is the only point in the handshake where a browser session is
|
||||
* present, so it is where the completion is bound to the user who started the
|
||||
* flow: the callback POST has no cookies (the store calls it) and so leaves
|
||||
* the oauth_state on the row for this route to verify against and consume.
|
||||
* Without that binding a victim lured into approving a connect someone else
|
||||
* started would have their store's orders flowing into that someone's books.
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
loadExtensions()
|
||||
@@ -34,7 +49,7 @@ export async function GET(request: Request) {
|
||||
const returnUrl = `${baseUrl}/import?mode=woocommerce`
|
||||
|
||||
if (success === '1') {
|
||||
return NextResponse.redirect(`${returnUrl}&woocommerce_connected=true`)
|
||||
return completeApproved(request, state, returnUrl)
|
||||
}
|
||||
|
||||
// Denied (or malformed): close out the pending row so its state can never
|
||||
@@ -60,3 +75,93 @@ export async function GET(request: Request) {
|
||||
|
||||
return NextResponse.redirect(`${returnUrl}&woocommerce_error=denied`)
|
||||
}
|
||||
|
||||
/**
|
||||
* The approved leg: find the row this state belongs to, require that the
|
||||
* browser completing it is the initiator's, then either hand the row over
|
||||
* (consume the state) or take back what the callback stored.
|
||||
*/
|
||||
async function completeApproved(
|
||||
request: Request,
|
||||
state: string | null,
|
||||
returnUrl: string,
|
||||
): Promise<Response> {
|
||||
const connectedUrl = `${returnUrl}&woocommerce_connected=true`
|
||||
|
||||
if (!state || !UUID_RE.test(state)) {
|
||||
// Nothing to bind against. The panel polls /status for the truth, and no
|
||||
// row is finalized by this route on its own.
|
||||
return NextResponse.redirect(connectedUrl)
|
||||
}
|
||||
|
||||
const supabase = await createServiceClient()
|
||||
|
||||
const { data: row, error: findError } = await supabase
|
||||
.from('woocommerce_connections')
|
||||
.select('id, user_id, status')
|
||||
.eq('oauth_state', state)
|
||||
.in('status', ['pending', 'active'])
|
||||
.single()
|
||||
|
||||
if (findError || !row) {
|
||||
// Already consumed (a re-visit of the return URL), superseded, or unknown:
|
||||
// there is nothing left to bind. The panel polls /status for the truth.
|
||||
return NextResponse.redirect(connectedUrl)
|
||||
}
|
||||
|
||||
const initiator = await requireFlowInitiator(request, row.user_id, {
|
||||
flow: 'woocommerce.return',
|
||||
})
|
||||
|
||||
if (!initiator.ok) {
|
||||
if (initiator.reason === 'no_session') {
|
||||
// Session expired mid-handshake: sign in and this route re-runs with
|
||||
// the same state. The row is untouched (it still carries the state).
|
||||
return initiator.response
|
||||
}
|
||||
// A different user completed it. The callback POST may already have
|
||||
// activated the row with the store's keys (it usually lands before this
|
||||
// redirect), so refusing means taking that back: keys wiped, state
|
||||
// consumed, row parked in 'error' with the reason. A still-pending row is
|
||||
// closed the same way so the late callback finds nothing to activate.
|
||||
const { error: revokeError } = await supabase
|
||||
.from('woocommerce_connections')
|
||||
.update({
|
||||
status: 'error',
|
||||
error_message: FLOW_INITIATOR_MISMATCH_MESSAGE,
|
||||
oauth_state: null,
|
||||
consumer_key_encrypted: null,
|
||||
consumer_secret_encrypted: null,
|
||||
})
|
||||
.eq('id', row.id)
|
||||
.in('status', ['pending', 'active'])
|
||||
if (revokeError) {
|
||||
log.error('failed to revoke connection completed by a non-initiator', {
|
||||
connectionId: row.id,
|
||||
code: revokeError.code,
|
||||
message: revokeError.message,
|
||||
})
|
||||
}
|
||||
return NextResponse.redirect(`${returnUrl}&woocommerce_error=wrong_user`)
|
||||
}
|
||||
|
||||
// Initiator confirmed. An active row has been fully handed over: consume the
|
||||
// state so the token cannot be presented again. A pending row keeps it: the
|
||||
// callback POST has not landed yet and still needs it to find the row.
|
||||
if (row.status === 'active') {
|
||||
const { error: consumeError } = await supabase
|
||||
.from('woocommerce_connections')
|
||||
.update({ oauth_state: null })
|
||||
.eq('id', row.id)
|
||||
.eq('status', 'active')
|
||||
if (consumeError) {
|
||||
log.warn('failed to consume oauth_state after handover', {
|
||||
connectionId: row.id,
|
||||
code: consumeError.code,
|
||||
message: consumeError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.redirect(connectedUrl)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import crypto from 'crypto'
|
||||
|
||||
/**
|
||||
* /authorize with the REAL redirect-URI allowlist. The route tests in
|
||||
* route.test.ts stub resolveRedirectUri; here only the service-role client is
|
||||
* faked, so the tests prove the phishing fix end to end: a redirect URI that
|
||||
* some unrelated account registered is refused for this user, a colleague's
|
||||
* registration is accepted, and built-in Claude never touches the table.
|
||||
*/
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createClient: vi.fn(),
|
||||
serviceClient: vi.fn(),
|
||||
getActiveCompanyId: vi.fn(),
|
||||
getBranding: vi.fn(),
|
||||
createAuthCode: vi.fn<(...args: unknown[]) => string>(() => 'test-auth-code'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/oauth-codes', () => ({
|
||||
createAuthCode: (...args: unknown[]) => mocks.createAuthCode(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => mocks.createClient(),
|
||||
}))
|
||||
|
||||
// The allowlist imports createServiceClientNoCookies from lib/auth/api-keys
|
||||
// (relative path); the alias resolves to the same module, so this stub is
|
||||
// what resolveRedirectUri constructs for its registration lookup.
|
||||
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/auth/api-keys')>()
|
||||
return {
|
||||
...actual,
|
||||
createServiceClientNoCookies: () => mocks.serviceClient(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => mocks.getActiveCompanyId(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/branding/service', () => ({
|
||||
getBranding: () => mocks.getBranding(),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
type Row = Record<string, unknown>
|
||||
|
||||
/**
|
||||
* Minimal PostgREST-shaped fake over in-memory tables: eq/is filters are
|
||||
* applied, everything else is a no-op, and the chain resolves to the filtered
|
||||
* rows (all rows when awaited, first row via maybeSingle).
|
||||
*/
|
||||
function fakeServiceClient(tables: Record<string, Row[]>) {
|
||||
const from = vi.fn((table: string) => {
|
||||
const filters: [string, unknown][] = []
|
||||
const run = () =>
|
||||
(tables[table] ?? []).filter((row) =>
|
||||
filters.every(([col, val]) => (val === null ? row[col] == null : row[col] === val)),
|
||||
)
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'order', 'range', 'limit']) chain[method] = () => chain
|
||||
chain.eq = (col: string, val: unknown) => {
|
||||
filters.push([col, val])
|
||||
return chain
|
||||
}
|
||||
chain.is = (col: string, val: unknown) => {
|
||||
filters.push([col, val])
|
||||
return chain
|
||||
}
|
||||
chain.maybeSingle = async () => ({ data: run()[0] ?? null, error: null })
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve({ data: run(), error: null })
|
||||
return chain
|
||||
})
|
||||
return { from }
|
||||
}
|
||||
|
||||
function userClient(userId: string, role = 'owner') {
|
||||
const chainFor = (result: { data: unknown; error: unknown }) => {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'eq', 'is', 'order', 'range', 'limit']) chain[method] = () => chain
|
||||
chain.single = async () => result
|
||||
chain.maybeSingle = async () => result
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve(result)
|
||||
return chain
|
||||
}
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: { id: userId } }, error: null }),
|
||||
mfa: {
|
||||
getAuthenticatorAssuranceLevel: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ data: { currentLevel: 'aal2', nextLevel: 'aal2' }, error: null }),
|
||||
listFactors: vi.fn().mockResolvedValue({ data: { totp: [] }, error: null }),
|
||||
},
|
||||
},
|
||||
from: vi.fn((table: string) =>
|
||||
table === 'company_members'
|
||||
? chainFor({ data: { role }, error: null })
|
||||
: chainFor({ data: { company_name: 'Test AB' }, error: null }),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
const DB = {
|
||||
oauth_client_registrations: [
|
||||
// A colleague of user-1 (both in company-1) registered this one.
|
||||
{ id: 'reg-1', user_id: 'user-2', client_name: 'Byråns bot', redirect_uri: 'https://app.example.com/cb', revoked_at: null },
|
||||
// An unrelated account on the same instance registered this one.
|
||||
{ id: 'reg-2', user_id: 'user-9', client_name: 'Claude (Anthropic)', redirect_uri: 'https://claude-login.example/cb', revoked_at: null },
|
||||
// user-1's own registration.
|
||||
{ id: 'reg-3', user_id: 'user-1', client_name: 'Min egen app', redirect_uri: 'https://mine.example/cb', revoked_at: null },
|
||||
],
|
||||
company_members: [
|
||||
{ id: 'm1', user_id: 'user-1', company_id: 'company-1', role: 'owner' },
|
||||
{ id: 'm2', user_id: 'user-2', company_id: 'company-1', role: 'member' },
|
||||
{ id: 'm3', user_id: 'user-9', company_id: 'company-9', role: 'owner' },
|
||||
],
|
||||
}
|
||||
|
||||
function authorizeUrl(redirectUri: string): string {
|
||||
const url = new URL('http://localhost/api/mcp-oauth/authorize')
|
||||
url.searchParams.set('response_type', 'code')
|
||||
url.searchParams.set('redirect_uri', redirectUri)
|
||||
url.searchParams.set('code_challenge', 'abc')
|
||||
url.searchParams.set('code_challenge_method', 'S256')
|
||||
url.searchParams.set('state', 'xyz')
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
function consentForm(): FormData {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
const sig = crypto.createHmac('sha256', key).update('').digest('base64url')
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', '')
|
||||
formData.set('scope_binding_sig', sig)
|
||||
formData.append('scopes', 'reports:read')
|
||||
return formData
|
||||
}
|
||||
|
||||
describe('/api/mcp-oauth/authorize with the real redirect-URI allowlist', () => {
|
||||
let service: ReturnType<typeof fakeServiceClient>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
service = fakeServiceClient(DB)
|
||||
mocks.serviceClient.mockReturnValue(service)
|
||||
mocks.createClient.mockResolvedValue(userClient('user-1'))
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('GET rejects a redirect URI registered by an unrelated user, even one named like Claude', async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://claude-login.example/cb')))
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('invalid_request')
|
||||
expect(body.error_description).toBe('redirect_uri is not allowed')
|
||||
})
|
||||
|
||||
it('POST rejects the same URI and mints no code', async () => {
|
||||
const response = await POST(
|
||||
new Request(authorizeUrl('https://claude-login.example/cb'), { method: 'POST', body: consentForm() }),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
expect(mocks.createAuthCode).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('GET accepts a redirect URI registered by a colleague in a shared company and names it', async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://app.example.com/cb')))
|
||||
expect(response.status).toBe(200)
|
||||
const html = await response.text()
|
||||
expect(html).toContain('Byråns bot')
|
||||
expect(html).toContain('Registrerad av en kollega')
|
||||
expect(html).toContain('app.example.com')
|
||||
expect(html).not.toContain('Verifierad')
|
||||
})
|
||||
|
||||
it("GET accepts the consenting user's own registration", async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://mine.example/cb')))
|
||||
expect(response.status).toBe(200)
|
||||
const html = await response.text()
|
||||
expect(html).toContain('Min egen app')
|
||||
expect(html).toContain('Registrerad av dig')
|
||||
})
|
||||
|
||||
it('POST for a colleague registration issues a code to that URI', async () => {
|
||||
const response = await POST(
|
||||
new Request(authorizeUrl('https://app.example.com/cb'), { method: 'POST', body: consentForm() }),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.origin).toBe('https://app.example.com')
|
||||
expect(location.searchParams.get('code')).toBe('test-auth-code')
|
||||
})
|
||||
|
||||
it('GET accepts the built-in Claude callback without consulting the registration table', async () => {
|
||||
const response = await GET(new Request(authorizeUrl('https://claude.ai/api/mcp/auth_callback')))
|
||||
expect(response.status).toBe(200)
|
||||
expect(mocks.serviceClient).not.toHaveBeenCalled()
|
||||
expect(service.from).not.toHaveBeenCalled()
|
||||
const html = await response.text()
|
||||
expect(html).toContain('Claude (Anthropic)')
|
||||
expect(html).toContain('Verifierad')
|
||||
})
|
||||
})
|
||||
@@ -1,24 +1,32 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import crypto from 'crypto'
|
||||
import type { RedirectUriResolution } from '@/lib/auth/oauth-allowlist'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createClient: vi.fn(),
|
||||
isAllowedRedirectUri: vi.fn(),
|
||||
resolveRedirectUri: vi.fn(),
|
||||
getActiveCompanyId: vi.fn(),
|
||||
getBranding: vi.fn(),
|
||||
createAuthCode: vi.fn<(...args: unknown[]) => string>(() => 'test-auth-code'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/oauth-codes', () => ({
|
||||
createAuthCode: vi.fn(() => 'test-auth-code'),
|
||||
createAuthCode: (...args: unknown[]) => mocks.createAuthCode(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => mocks.createClient(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/oauth-allowlist', () => ({
|
||||
isAllowedRedirectUri: (...args: unknown[]) => mocks.isAllowedRedirectUri(...args),
|
||||
}))
|
||||
// Only the redirect-URI resolution is replaced: the role cap helpers from the
|
||||
// same module run for real so the tests exercise the actual ceiling logic.
|
||||
vi.mock('@/lib/auth/oauth-allowlist', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/auth/oauth-allowlist')>()
|
||||
return {
|
||||
...actual,
|
||||
resolveRedirectUri: (...args: unknown[]) => mocks.resolveRedirectUri(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => mocks.getActiveCompanyId(...args),
|
||||
@@ -30,18 +38,50 @@ vi.mock('@/lib/branding/service', () => ({
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
const CLAUDE: RedirectUriResolution = { allowed: true, kind: 'built_in', provider: 'claude' }
|
||||
const CHATGPT: RedirectUriResolution = { allowed: true, kind: 'built_in', provider: 'chatgpt' }
|
||||
const REGISTERED: RedirectUriResolution = {
|
||||
allowed: true,
|
||||
kind: 'registered',
|
||||
clientName: 'Byråns bokföringsbot',
|
||||
registeredByConsentingUser: false,
|
||||
}
|
||||
|
||||
function buildAuthorizeUrl(params: Record<string, string>): string {
|
||||
const url = new URL('http://localhost/api/mcp-oauth/authorize')
|
||||
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v))
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Chainable query stub: every builder method returns the chain, and the chain
|
||||
* resolves to `result` whether awaited directly or via single()/maybeSingle().
|
||||
*/
|
||||
function tableChain(result: { data: unknown; error: unknown }) {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'eq', 'is', 'in', 'order', 'range', 'limit']) {
|
||||
chain[method] = vi.fn(() => chain)
|
||||
}
|
||||
chain.single = vi.fn().mockResolvedValue(result)
|
||||
chain.maybeSingle = vi.fn().mockResolvedValue(result)
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve(result)
|
||||
return chain
|
||||
}
|
||||
|
||||
type Membership = { role: string | null } | { error: string }
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string; email?: string } | null,
|
||||
companyName = 'Test AB',
|
||||
aal: { currentLevel: string; nextLevel: string } = { currentLevel: 'aal2', nextLevel: 'aal2' },
|
||||
verifiedFactors: number = aal.nextLevel === 'aal2' ? 1 : 0,
|
||||
membership: Membership = { role: 'owner' },
|
||||
) {
|
||||
const settingsResult = { data: { company_name: companyName }, error: null }
|
||||
const membershipResult =
|
||||
'error' in membership
|
||||
? { data: null, error: { message: membership.error } }
|
||||
: { data: membership.role === null ? null : { role: membership.role }, error: null }
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user }, error: null }),
|
||||
@@ -58,25 +98,43 @@ function buildSupabase(
|
||||
}),
|
||||
},
|
||||
},
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnValue({
|
||||
eq: vi.fn().mockReturnValue({
|
||||
single: vi.fn().mockResolvedValue({
|
||||
data: { company_name: companyName },
|
||||
error: null,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
from: vi.fn((table: string) =>
|
||||
table === 'company_members' ? tableChain(membershipResult) : tableChain(settingsResult),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrors getScopeSigningKey/signScopeBinding in the route so a POST can
|
||||
// present a scope binding that verifies against the test service key.
|
||||
function signScope(scopeParam: string): string {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
return crypto.createHmac('sha256', key).update(scopeParam).digest('base64url')
|
||||
}
|
||||
|
||||
function consentForm(scopeParam: string, scopes: string[] = []): FormData {
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', scopeParam)
|
||||
formData.set('scope_binding_sig', signScope(scopeParam))
|
||||
for (const s of scopes) formData.append('scopes', s)
|
||||
return formData
|
||||
}
|
||||
|
||||
function checkboxFor(html: string, scope: string): string | undefined {
|
||||
return html.match(new RegExp(`<input[^>]*value="${scope}"[^>]*>`))?.[0]
|
||||
}
|
||||
|
||||
function lastMintedPayload(): Record<string, unknown> {
|
||||
const calls = mocks.createAuthCode.mock.calls as unknown[][]
|
||||
return calls[calls.length - 1]![0] as Record<string, unknown>
|
||||
}
|
||||
|
||||
describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -188,22 +246,12 @@ describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
|
||||
// Every row starts checked: the deliberate act is the visible Allow
|
||||
// click, and unticking stays available per row inside the details fold.
|
||||
const writeRow = html.match(/<input[^>]*value="transactions:write"[^>]*>/)?.[0]
|
||||
expect(writeRow).toBeDefined()
|
||||
expect(writeRow!).toContain('checked')
|
||||
|
||||
const approveRow = html.match(/<input[^>]*value="pending_operations:approve"[^>]*>/)?.[0]
|
||||
expect(approveRow).toBeDefined()
|
||||
expect(approveRow!).toContain('checked')
|
||||
|
||||
const bookkeepingRow = html.match(/<input[^>]*value="bookkeeping:write"[^>]*>/)?.[0]
|
||||
expect(bookkeepingRow).toBeDefined()
|
||||
expect(bookkeepingRow!).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:write')).toContain('checked')
|
||||
expect(checkboxFor(html, 'pending_operations:approve')).toContain('checked')
|
||||
expect(checkboxFor(html, 'bookkeeping:write')).toContain('checked')
|
||||
|
||||
// The :read counterpart is pre-checked too.
|
||||
const readRow = html.match(/<input[^>]*value="transactions:read"[^>]*>/)?.[0]
|
||||
expect(readRow).toBeDefined()
|
||||
expect(readRow!).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
})
|
||||
|
||||
it('renders only the requested scopes when the client passes them explicitly', async () => {
|
||||
@@ -229,8 +277,8 @@ describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
expect(html).not.toContain('value="bookkeeping:write"')
|
||||
})
|
||||
|
||||
it('rejects disallowed redirect_uri before any CSP would be emitted', async () => {
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(false)
|
||||
it('rejects a redirect_uri the allowlist refuses for this user before any CSP would be emitted', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue({ allowed: false })
|
||||
const request = new Request(
|
||||
buildAuthorizeUrl({
|
||||
response_type: 'code',
|
||||
@@ -246,6 +294,296 @@ describe('GET /api/mcp-oauth/authorize: CSP', () => {
|
||||
// untrusted origin. A 400 here keeps the allowlist as the single source
|
||||
// of truth for which origins can land at this endpoint.
|
||||
})
|
||||
|
||||
it('binds the redirect_uri check to the consenting user on GET and POST', async () => {
|
||||
// The allowlist can only tell a colleague's registration from a
|
||||
// stranger's when it knows who is consenting. Both handlers must pass it.
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
scope: 'mcp',
|
||||
}
|
||||
await GET(new Request(buildAuthorizeUrl(params)))
|
||||
expect(mocks.resolveRedirectUri).toHaveBeenLastCalledWith(
|
||||
'https://claude.ai/api/mcp/auth_callback',
|
||||
undefined,
|
||||
{ consentingUserId: 'user-1' },
|
||||
)
|
||||
|
||||
await POST(new Request(buildAuthorizeUrl(params), { method: 'POST', body: consentForm('mcp') }))
|
||||
expect(mocks.resolveRedirectUri).toHaveBeenLastCalledWith(
|
||||
'https://claude.ai/api/mcp/auth_callback',
|
||||
undefined,
|
||||
{ consentingUserId: 'user-1' },
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('client identity on the consent page', () => {
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
scope: 'mcp',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('names Claude as a verified client and shows the redirect host', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
const html = await (await GET(new Request(buildAuthorizeUrl(params)))).text()
|
||||
|
||||
expect(html).toContain('Claude (Anthropic)')
|
||||
expect(html).toContain('Verifierad')
|
||||
expect(html).toContain('Skickar dig vidare till')
|
||||
expect(html).toContain('claude.ai')
|
||||
// The generic "en extern applikation" wording is gone: the client is named.
|
||||
expect(html).not.toContain('En extern applikation')
|
||||
})
|
||||
|
||||
it('names ChatGPT for chatgpt.com callbacks', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CHATGPT)
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(
|
||||
buildAuthorizeUrl({ ...params, redirect_uri: 'https://chatgpt.com/connector/oauth/abc' }),
|
||||
),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(html).toContain('ChatGPT (OpenAI)')
|
||||
expect(html).toContain('chatgpt.com')
|
||||
})
|
||||
|
||||
it('shows client_name and redirect host for a DB-registered client, never marked verified', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue(REGISTERED)
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(buildAuthorizeUrl({ ...params, redirect_uri: 'https://app.example.com/cb' })),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(html).toContain('Byråns bokföringsbot')
|
||||
expect(html).toContain('app.example.com')
|
||||
expect(html).toContain('Registrerad av en kollega')
|
||||
expect(html).not.toContain('Verifierad')
|
||||
expect(html).not.toContain('Claude')
|
||||
})
|
||||
|
||||
it('HTML-escapes a hostile client_name', async () => {
|
||||
mocks.resolveRedirectUri.mockResolvedValue({
|
||||
...REGISTERED,
|
||||
clientName: '<img src=x onerror=alert(1)>Claude (Anthropic)',
|
||||
registeredByConsentingUser: true,
|
||||
})
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(buildAuthorizeUrl({ ...params, redirect_uri: 'https://app.example.com/cb' })),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(html).not.toContain('<img src=x')
|
||||
expect(html).toContain('<img src=x onerror=alert(1)>')
|
||||
expect(html).toContain('Registrerad av dig')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scope defaults for DB-registered clients', () => {
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://app.example.com/cb',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.resolveRedirectUri.mockResolvedValue(REGISTERED)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('pre-checks only read scopes when a registered client sends no scope', async () => {
|
||||
// The ceiling stays ALL_SCOPES so the user can still opt in, but a
|
||||
// registration is just a URL a member typed into settings: writes and
|
||||
// approval must be a deliberate tick, never a default.
|
||||
const html = await (await GET(new Request(buildAuthorizeUrl(params)))).text()
|
||||
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
expect(checkboxFor(html, 'reports:read')).toContain('checked')
|
||||
|
||||
expect(checkboxFor(html, 'transactions:write')).toBeDefined()
|
||||
expect(checkboxFor(html, 'transactions:write')).not.toContain('checked')
|
||||
expect(checkboxFor(html, 'bookkeeping:write')).not.toContain('checked')
|
||||
expect(checkboxFor(html, 'pending_operations:approve')).not.toContain('checked')
|
||||
expect(checkboxFor(html, 'webhooks:manage')).not.toContain('checked')
|
||||
|
||||
expect(html).toContain('Endast läs förvalt')
|
||||
expect(html).toContain('Endast läsbehörigheter är förvalda')
|
||||
})
|
||||
|
||||
it('pre-checks write scopes only when the registered client explicitly requested them', async () => {
|
||||
const html = await (
|
||||
await GET(
|
||||
new Request(
|
||||
buildAuthorizeUrl({ ...params, scope: 'transactions:read transactions:write' }),
|
||||
),
|
||||
)
|
||||
).text()
|
||||
|
||||
expect(checkboxFor(html, 'transactions:write')).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
// Not requested: not even rendered.
|
||||
expect(html).not.toContain('value="pending_operations:approve"')
|
||||
})
|
||||
|
||||
it('states the segregation-of-duties rule when stage and approve scopes are both on offer', async () => {
|
||||
const html = await (await GET(new Request(buildAuthorizeUrl(params)))).text()
|
||||
expect(html).toContain('medgivande')
|
||||
|
||||
const readOnly = await (
|
||||
await GET(new Request(buildAuthorizeUrl({ ...params, scope: 'transactions:read' })))
|
||||
).text()
|
||||
expect(readOnly).not.toContain('medgivande')
|
||||
})
|
||||
})
|
||||
|
||||
describe('role cap on consent', () => {
|
||||
const params = {
|
||||
response_type: 'code',
|
||||
redirect_uri: 'https://claude.ai/api/mcp/auth_callback',
|
||||
code_challenge: 'abc',
|
||||
code_challenge_method: 'S256',
|
||||
scope: 'mcp',
|
||||
state: 'xyz',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
|
||||
it('viewer: GET offers read scopes only and says why', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'viewer' }),
|
||||
)
|
||||
const response = await GET(new Request(buildAuthorizeUrl(params)))
|
||||
expect(response.status).toBe(200)
|
||||
const html = await response.text()
|
||||
|
||||
expect(checkboxFor(html, 'transactions:read')).toContain('checked')
|
||||
expect(html).not.toContain('value="transactions:write"')
|
||||
expect(html).not.toContain('value="pending_operations:approve"')
|
||||
expect(html).not.toContain('value="webhooks:manage"')
|
||||
expect(html).toContain('läsare')
|
||||
})
|
||||
|
||||
it('viewer: POST caps a forged write selection to read scopes and records the company', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'viewer' }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['transactions:read', 'transactions:write', 'pending_operations:approve']),
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
expect(new URL(response.headers.get('location')!).searchParams.get('code')).toBe('test-auth-code')
|
||||
|
||||
const payload = lastMintedPayload()
|
||||
expect(payload.scopes).toEqual(['transactions:read'])
|
||||
expect(payload.companyId).toBe('company-1')
|
||||
expect(payload.userId).toBe('user-1')
|
||||
})
|
||||
|
||||
it('viewer: a write-only client request is bounced with invalid_scope instead of a read grant it never asked for', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'viewer' }),
|
||||
)
|
||||
const response = await GET(
|
||||
new Request(buildAuthorizeUrl({ ...params, scope: 'transactions:write' })),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.origin).toBe('https://claude.ai')
|
||||
expect(location.searchParams.get('error')).toBe('invalid_scope')
|
||||
expect(location.searchParams.get('state')).toBe('xyz')
|
||||
expect(location.searchParams.get('code')).toBeNull()
|
||||
})
|
||||
|
||||
it('member: POST keeps requested write and approve scopes', async () => {
|
||||
// Mirrors app/api/settings/api-keys: any writer role may hold approve;
|
||||
// the stage+approve combination is acknowledged, not blocked.
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: 'member' }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['transactions:read', 'transactions:write', 'pending_operations:approve']),
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
expect(lastMintedPayload().scopes).toEqual([
|
||||
'transactions:read',
|
||||
'transactions:write',
|
||||
'pending_operations:approve',
|
||||
])
|
||||
})
|
||||
|
||||
it('no membership row: caps to read scopes rather than trusting the form', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { role: null }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['reports:read', 'bookkeeping:write']),
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
expect(lastMintedPayload().scopes).toEqual(['reports:read'])
|
||||
})
|
||||
|
||||
it('GET fails closed with server_error when the role lookup errors', async () => {
|
||||
// A transient error must neither widen the grant (treat as owner) nor
|
||||
// silently downgrade a legitimate connection to read-only.
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { error: 'boom' }),
|
||||
)
|
||||
const response = await GET(new Request(buildAuthorizeUrl(params)))
|
||||
expect(response.status).toBe(500)
|
||||
expect((await response.json()).error).toBe('server_error')
|
||||
})
|
||||
|
||||
it('POST fails closed with server_error when the role lookup errors', async () => {
|
||||
mocks.createClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, 'Test AB', undefined, undefined, { error: 'boom' }),
|
||||
)
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(params), { method: 'POST', body: consentForm('mcp', ['reports:read']) }),
|
||||
)
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.searchParams.get('error')).toBe('server_error')
|
||||
expect(location.searchParams.get('code')).toBeNull()
|
||||
expect(mocks.createAuthCode).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('MFA step-up on /api/mcp-oauth/authorize', () => {
|
||||
@@ -267,7 +605,7 @@ describe('MFA step-up on /api/mcp-oauth/authorize', () => {
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -407,15 +745,10 @@ describe('account with no company yet (issue #1814)', () => {
|
||||
state: 'xyz',
|
||||
}
|
||||
|
||||
function signScope(scopeParam: string): string {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
return crypto.createHmac('sha256', key).update(scopeParam).digest('base64url')
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue(null)
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -431,7 +764,7 @@ describe('account with no company yet (issue #1814)', () => {
|
||||
expect(html).toContain('ny@example.se')
|
||||
expect(html).toContain('inget företag')
|
||||
expect(html).not.toContain('Test AB')
|
||||
// No company to look up: company_settings is never queried.
|
||||
// No company to look up: neither company_settings nor company_members is queried.
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -441,30 +774,28 @@ describe('account with no company yet (issue #1814)', () => {
|
||||
const response = await GET(new Request(buildAuthorizeUrl(authorizeParams)))
|
||||
const html = await response.text()
|
||||
|
||||
const companiesWrite = html.match(/<input[^>]*value="companies:write"[^>]*>/)?.[0]
|
||||
expect(companiesWrite).toBeDefined()
|
||||
expect(companiesWrite!).toContain('checked')
|
||||
const transactionsWrite = html.match(/<input[^>]*value="transactions:write"[^>]*>/)?.[0]
|
||||
expect(transactionsWrite).toBeDefined()
|
||||
expect(transactionsWrite!).toContain('checked')
|
||||
expect(checkboxFor(html, 'companies:write')).toContain('checked')
|
||||
expect(checkboxFor(html, 'transactions:write')).toContain('checked')
|
||||
})
|
||||
|
||||
it('POST still issues an authorization code', async () => {
|
||||
it('POST still issues an authorization code with no role cap and a null company', async () => {
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1', email: 'ny@example.se' }))
|
||||
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', 'mcp')
|
||||
formData.set('scope_binding_sig', signScope('mcp'))
|
||||
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: formData }),
|
||||
new Request(buildAuthorizeUrl(authorizeParams), {
|
||||
method: 'POST',
|
||||
body: consentForm('mcp', ['companies:write', 'companies:read']),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(303)
|
||||
const location = new URL(response.headers.get('location')!)
|
||||
expect(location.searchParams.get('code')).toBe('test-auth-code')
|
||||
expect(location.searchParams.get('state')).toBe('xyz')
|
||||
|
||||
const payload = lastMintedPayload()
|
||||
expect(payload.companyId).toBeNull()
|
||||
expect(payload.scopes).toEqual(['companies:write', 'companies:read'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -478,19 +809,12 @@ describe('RFC 9207 iss parameter on authorization responses', () => {
|
||||
state: 'xyz',
|
||||
}
|
||||
|
||||
// Mirrors getScopeSigningKey/signScopeBinding in the route so the POST can
|
||||
// present a scope binding that verifies against the test service key.
|
||||
function signScope(scopeParam: string): string {
|
||||
const key = crypto.createHash('sha256').update('oauth-scope:test-service-key').digest()
|
||||
return crypto.createHmac('sha256', key).update(scopeParam).digest('base64url')
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-service-key'
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.test.example')
|
||||
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1' }))
|
||||
mocks.isAllowedRedirectUri.mockResolvedValue(true)
|
||||
mocks.resolveRedirectUri.mockResolvedValue(CLAUDE)
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
mocks.getBranding.mockReturnValue({ appName: 'gnubok' })
|
||||
})
|
||||
@@ -500,13 +824,8 @@ describe('RFC 9207 iss parameter on authorization responses', () => {
|
||||
})
|
||||
|
||||
it('includes iss alongside code and state on the success redirect', async () => {
|
||||
const formData = new FormData()
|
||||
formData.set('consent', 'allow')
|
||||
formData.set('scope_binding', 'mcp')
|
||||
formData.set('scope_binding_sig', signScope('mcp'))
|
||||
|
||||
const response = await POST(
|
||||
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: formData }),
|
||||
new Request(buildAuthorizeUrl(authorizeParams), { method: 'POST', body: consentForm('mcp') }),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(303)
|
||||
|
||||
@@ -6,13 +6,19 @@ import { createAuthCode } from '@/lib/auth/oauth-codes'
|
||||
import { shouldEnforceMfa } from '@/lib/auth/mfa'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { isAllowedRedirectUri } from '@/lib/auth/oauth-allowlist'
|
||||
import {
|
||||
capScopesForRole,
|
||||
lookupCompanyRole,
|
||||
resolveRedirectUri,
|
||||
type RedirectUriResolution,
|
||||
} from '@/lib/auth/oauth-allowlist'
|
||||
import { resolveDiscoveryBaseUrl } from '@/lib/api/v1/base-url'
|
||||
import {
|
||||
ALL_SCOPES,
|
||||
API_KEY_SCOPES,
|
||||
DEFAULT_OAUTH_SCOPES,
|
||||
SCOPE_GROUPS,
|
||||
findStageApproveConflict,
|
||||
scopeKind,
|
||||
validateScopes,
|
||||
type ApiKeyScope,
|
||||
@@ -173,9 +179,10 @@ function errorRedirect(request: Request, redirectUri: string, state: string | nu
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
const redirectUri = url.searchParams.get('redirect_uri')
|
||||
// state and code_challenge are carried through to the POST handler via
|
||||
// the form action's url.search, so we don't read them here: they're only
|
||||
// validated on POST.
|
||||
// state is read only to echo it on error redirects issued from GET;
|
||||
// code_challenge is carried through to the POST handler via the form
|
||||
// action's url.search and validated there.
|
||||
const state = url.searchParams.get('state')
|
||||
const codeChallengeMethod = url.searchParams.get('code_challenge_method') || 'S256'
|
||||
const responseType = url.searchParams.get('response_type')
|
||||
const scopeParam = url.searchParams.get('scope')
|
||||
@@ -222,9 +229,13 @@ export async function GET(request: Request) {
|
||||
const mfaRedirect = await requireAal2(supabase, user, request)
|
||||
if (mfaRedirect) return mfaRedirect
|
||||
|
||||
// Validate redirect_uri against allowlist (prevents open redirect). Passing
|
||||
// the authenticated client makes the trust boundary explicit (SOC 2 CC6.1).
|
||||
if (!(await isAllowedRedirectUri(redirectUri, supabase))) {
|
||||
// Validate redirect_uri against the allowlist (prevents open redirect) and
|
||||
// resolve who the client is. DB-registered URIs are bound to the consenting
|
||||
// user: only their own or a colleague's registration counts, so a stranger
|
||||
// cannot register a callback and phish consent from every account on the
|
||||
// instance (SOC 2 CC6.1).
|
||||
const resolution = await resolveRedirectUri(redirectUri, undefined, { consentingUserId: user.id })
|
||||
if (!resolution.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
|
||||
{ status: 400 }
|
||||
@@ -238,6 +249,7 @@ export async function GET(request: Request) {
|
||||
const companyId = await getActiveCompanyId(supabase, user.id)
|
||||
|
||||
let companyName: string | null = null
|
||||
let role: string | null = null
|
||||
if (companyId) {
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
@@ -245,15 +257,41 @@ export async function GET(request: Request) {
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
companyName = settings?.company_name || user.email || null
|
||||
|
||||
// The user's role in the company shown on this page caps what the page
|
||||
// may offer (viewer = read-only). A failed lookup is a hard stop, not a
|
||||
// silent downgrade or widening.
|
||||
const lookup = await lookupCompanyRole(supabase, user.id, companyId)
|
||||
if (lookup.error) {
|
||||
return NextResponse.json(
|
||||
{ error: 'server_error', error_description: 'Could not resolve your role in the company' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
role = lookup.role
|
||||
}
|
||||
|
||||
const appNameLower = escapeHtml(getBranding().appName.toLowerCase())
|
||||
|
||||
// Client identity and the host the browser will be sent to after consent.
|
||||
// Both are shown unconditionally so a look-alike registration cannot pass
|
||||
// for Claude and the user always sees where the code is going.
|
||||
const client = describeClient(resolution)
|
||||
const redirectHost = new URL(redirectUri).host
|
||||
const clientRowsHtml = `<div class="fact">
|
||||
<span class="fact-label">Klient</span>
|
||||
<span class="fact-value">${escapeHtml(client.name)} <span class="fact-tag${client.verified ? ' verified' : ''}">${escapeHtml(client.tag)}</span></span>
|
||||
</div>
|
||||
<div class="fact">
|
||||
<span class="fact-label">Skickar dig vidare till</span>
|
||||
<span class="fact-value fact-host">${escapeHtml(redirectHost)}</span>
|
||||
</div>`
|
||||
|
||||
const accountRowHtml = companyName
|
||||
? `<span class="account-label">Företag</span>
|
||||
<span class="account-name">${escapeHtml(companyName)}</span>`
|
||||
: `<span class="account-label">Konto</span>
|
||||
<span class="account-name">${escapeHtml(user.email ?? '')}</span>`
|
||||
? `<span class="fact-label">Företag</span>
|
||||
<span class="fact-value">${escapeHtml(companyName)}</span>`
|
||||
: `<span class="fact-label">Konto</span>
|
||||
<span class="fact-value">${escapeHtml(user.email ?? '')}</span>`
|
||||
const noCompanyNoteHtml = companyId
|
||||
? ''
|
||||
: `<p class="note">Du har inget företag i ${appNameLower} ännu. Du kan ansluta ändå: skapa företaget i appen så använder anslutningen det automatiskt, utan att du behöver ansluta på nytt.</p>`
|
||||
@@ -271,25 +309,71 @@ export async function GET(request: Request) {
|
||||
const scopeBindingValue = scopeParam ?? ''
|
||||
const scopeBindingSignature = signScopeBinding(scopeBindingValue)
|
||||
|
||||
// Two-level model for the consent UI:
|
||||
// Three inputs shape the consent UI:
|
||||
//
|
||||
// - Client requested specific scopes → ceiling = that set, pre-checked =
|
||||
// that set (RFC 6749 §3.3 strict least-privilege).
|
||||
// - Client passed no scope (or only the legacy `mcp` marker, Claude's
|
||||
// connector today) → ceiling = ALL_SCOPES and pre-checked = ALL_SCOPES:
|
||||
// one-click consent (founder decision 2026-08-26; the read-only default
|
||||
// killed the agent flow with an insufficient-scope dead-end mid-chat).
|
||||
// The mitigations that make full-by-default defensible: every write is
|
||||
// STAGED for explicit approval before anything touches the ledger, the
|
||||
// full scope list stays on the page (collapsed but expandable) with
|
||||
// every row untickable, the warn line states the staging rule above the
|
||||
// button, and the grant is revocable under Inställningar › API-nycklar.
|
||||
// RFC 6749 §3.3 lets the resource owner authorise the set presented;
|
||||
// the consent is the click on a page that shows exactly that set.
|
||||
const grantCeiling = new Set<ApiKeyScope>(parsed.scopes ?? ALL_SCOPES)
|
||||
const preChecked = new Set<ApiKeyScope>(parsed.scopes ?? ALL_SCOPES)
|
||||
// - Ceiling: the client's requested scopes (RFC 6749 §3.3 strict
|
||||
// least-privilege), or ALL_SCOPES when it passed none (or only the
|
||||
// legacy `mcp` marker, Claude's connector today), then capped to what
|
||||
// the user's role in the selected company permits (viewer = read-only).
|
||||
// Rows outside the ceiling are not rendered; the POST handler enforces
|
||||
// the same bound server-side.
|
||||
// - Pre-checked, built-in client (Claude, ChatGPT, localhost): the whole
|
||||
// ceiling. One-click consent (founder decision 2026-08-26; the read-only
|
||||
// default killed the agent flow with an insufficient-scope dead-end
|
||||
// mid-chat). The mitigations that make full-by-default defensible: every
|
||||
// write is STAGED for explicit approval before anything touches the
|
||||
// ledger, the full scope list stays on the page (collapsed but
|
||||
// expandable) with every row untickable, the warn line states the
|
||||
// staging rule above the button, and the grant is revocable under
|
||||
// Inställningar › API-nycklar. RFC 6749 §3.3 lets the resource owner
|
||||
// authorise the set presented; the consent is the click on a page that
|
||||
// shows exactly that set.
|
||||
// - Pre-checked, DB-registered client: only what it explicitly asked for,
|
||||
// or the :read scopes when it asked for nothing. Write and approve
|
||||
// scopes stay unticked until the user opts in: a registration is just a
|
||||
// URL some member typed into settings, not a vetted integration.
|
||||
const clientCeiling: ApiKeyScope[] = parsed.scopes ?? [...ALL_SCOPES]
|
||||
const roleCapped = companyId ? capScopesForRole(clientCeiling, role) : clientCeiling
|
||||
if (roleCapped.length === 0) {
|
||||
return errorRedirect(
|
||||
request,
|
||||
redirectUri,
|
||||
state,
|
||||
'invalid_scope',
|
||||
'None of the requested scopes are available to your role in this company'
|
||||
)
|
||||
}
|
||||
const roleLimited = roleCapped.length < clientCeiling.length
|
||||
const grantCeiling = new Set<ApiKeyScope>(roleCapped)
|
||||
const preChecked = new Set<ApiKeyScope>(
|
||||
resolution.kind === 'built_in' || parsed.scopes
|
||||
? roleCapped
|
||||
: roleCapped.filter((s) => scopeKind(s) === 'read')
|
||||
)
|
||||
const allPreChecked = preChecked.size === grantCeiling.size
|
||||
const ceilingHasWrite = roleCapped.some((s) => scopeKind(s) === 'write')
|
||||
const scopeCheckboxesHtml = renderScopeCheckboxes(preChecked, grantCeiling)
|
||||
|
||||
const ledeHtml = !ceilingHasWrite
|
||||
? `${escapeHtml(client.name)} begär läsåtkomst till ditt ${appNameLower}-konto. Inga skrivbehörigheter ingår.`
|
||||
: allPreChecked
|
||||
? `${escapeHtml(client.name)} begär åtkomst till ditt ${appNameLower}-konto. Alla behörigheter är förvalda; varje skrivning kräver ändå ditt godkännande innan den bokförs.`
|
||||
: `${escapeHtml(client.name)} begär åtkomst till ditt ${appNameLower}-konto. Endast läsbehörigheter är förvalda: skrivbehörigheter måste du själv välja nedan, och varje skrivning kräver ändå ditt godkännande innan den bokförs.`
|
||||
const roleNoteHtml = roleLimited
|
||||
? `<p class="note">Din roll i företaget är läsare, så bara läsbehörigheter kan ges här.</p>`
|
||||
: ''
|
||||
const summaryHintHtml = allPreChecked
|
||||
? 'Alla förvalda · visa och justera'
|
||||
: 'Endast läs förvalt · visa och justera'
|
||||
// Segregation of duties: a key that can both stage and approve lets the
|
||||
// agent commit bookkeeping without a human review in the app. Mirrors
|
||||
// app/api/settings/api-keys, where the same combination needs an explicit
|
||||
// acknowledgement: here the statement sits above the button and the token
|
||||
// route records the consent click as that acknowledgement.
|
||||
const sodNoteHtml = findStageApproveConflict(roleCapped)
|
||||
? ` Ger du både skriv- och godkännandebehörighet kan klienten både förbereda och godkänna bokföring utan din granskning i ${appNameLower}; ditt godkännande här registreras som ett medgivande till det.`
|
||||
: ''
|
||||
|
||||
// Render consent page
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="sv">
|
||||
@@ -388,31 +472,59 @@ export async function GET(request: Request) {
|
||||
line-height: 1.55;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.account {
|
||||
.facts {
|
||||
background: var(--muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0 0.875rem;
|
||||
margin-bottom: 1.75rem;
|
||||
}
|
||||
.fact {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
background: var(--muted);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.75rem 0.875rem;
|
||||
margin-bottom: 1.75rem;
|
||||
padding: 0.625rem 0;
|
||||
}
|
||||
.account-label {
|
||||
.fact + .fact { border-top: 1px solid var(--border); }
|
||||
.fact-label {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--fg-faint);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.account-name {
|
||||
.fact-value {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--fg);
|
||||
text-align: right;
|
||||
word-break: break-word;
|
||||
}
|
||||
.fact-host {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
.fact-tag {
|
||||
display: inline-block;
|
||||
margin-left: 0.375rem;
|
||||
font-size: 0.625rem;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
padding: 0.0625rem 0.375rem;
|
||||
border-radius: 4px;
|
||||
background: var(--secondary);
|
||||
color: var(--fg-muted);
|
||||
border: 1px solid var(--border-strong);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.fact-tag.verified {
|
||||
background: hsl(140 40% 94%);
|
||||
color: hsl(150 45% 24%);
|
||||
border-color: hsl(140 35% 78%);
|
||||
}
|
||||
.note {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--fg-muted);
|
||||
@@ -636,12 +748,16 @@ export async function GET(request: Request) {
|
||||
<main class="card" role="main">
|
||||
<div class="eyebrow">${appNameLower} · mcp</div>
|
||||
<h1>Anslut MCP-klient</h1>
|
||||
<p class="lede">En extern applikation begär åtkomst till ditt ${appNameLower}-konto. Alla behörigheter är förvalda; varje skrivning kräver ändå ditt godkännande innan den bokförs.</p>
|
||||
<p class="lede">${ledeHtml}</p>
|
||||
|
||||
<div class="account">
|
||||
${accountRowHtml}
|
||||
<div class="facts">
|
||||
${clientRowsHtml}
|
||||
<div class="fact">
|
||||
${accountRowHtml}
|
||||
</div>
|
||||
</div>
|
||||
${noCompanyNoteHtml}
|
||||
${roleNoteHtml}
|
||||
|
||||
<form method="POST" action="${escapeHtml(url.pathname + url.search)}" id="consent-form">
|
||||
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
|
||||
@@ -650,7 +766,7 @@ export async function GET(request: Request) {
|
||||
<details class="scopes-details">
|
||||
<summary>
|
||||
<span class="scopes-title">Behörigheter</span>
|
||||
<span class="scopes-summary-hint">Alla förvalda · visa och justera</span>
|
||||
<span class="scopes-summary-hint">${summaryHintHtml}</span>
|
||||
<svg class="scopes-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M6 4l4 4-4 4" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
</summary>
|
||||
<div class="scopes-header">
|
||||
@@ -670,7 +786,7 @@ export async function GET(request: Request) {
|
||||
<path d="M8 5v3.5" stroke-linecap="round"/>
|
||||
<circle cx="8" cy="11" r="0.5" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
<span>Skrivbehörigheter låter agenten stagea verifikationer, fakturor och löner. Varje skrivoperation kräver ditt godkännande i ${appNameLower} innan den skrivs till databasen.</span>
|
||||
<span>Skrivbehörigheter låter agenten stagea verifikationer, fakturor och löner. Varje skrivoperation kräver ditt godkännande i ${appNameLower} innan den skrivs till databasen.${sodNoteHtml}</span>
|
||||
</div>
|
||||
|
||||
<div class="actions">
|
||||
@@ -711,7 +827,7 @@ export async function GET(request: Request) {
|
||||
// returns a 303 to the OAuth client's callback (e.g. claude.ai), and CSP
|
||||
// form-action re-checks every hop in the redirect chain. With only 'self'
|
||||
// the browser would block the post-consent redirect. The origin is safe
|
||||
// to whitelist here because isAllowedRedirectUri() already gated it above.
|
||||
// to whitelist here because resolveRedirectUri() already gated it above.
|
||||
const redirectOrigin = new URL(redirectUri).origin
|
||||
const csp = [
|
||||
"default-src 'none'",
|
||||
@@ -760,19 +876,16 @@ export async function POST(request: Request) {
|
||||
const mfaRedirect = await requireAal2(supabase, user, request)
|
||||
if (mfaRedirect) return mfaRedirect
|
||||
|
||||
// Pass the authenticated client so the lookup is bound to the same session
|
||||
// that the consent display ran under (SOC 2 CC6.1).
|
||||
if (!(await isAllowedRedirectUri(redirectUri, supabase))) {
|
||||
// Same binding as GET: a DB-registered URI must be the consenting user's own
|
||||
// or a colleague's registration (SOC 2 CC6.1).
|
||||
const resolution = await resolveRedirectUri(redirectUri, undefined, { consentingUserId: user.id })
|
||||
if (!resolution.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// No company check here: the auth code carries only the user id, and the
|
||||
// token endpoint resolves (or leaves unbound) the company when it mints the
|
||||
// key. An account without a company may consent (issue #1814).
|
||||
|
||||
// Parse form body
|
||||
const formData = await request.formData()
|
||||
const consent = formData.get('consent')
|
||||
@@ -781,6 +894,27 @@ export async function POST(request: Request) {
|
||||
return errorRedirect(request, redirectUri, state, 'access_denied', 'User denied the request')
|
||||
}
|
||||
|
||||
// The company the consent page showed and the user's role in it. Null for
|
||||
// an account without a company (issue #1814): consent still goes through
|
||||
// uncapped and the token endpoint mints the key unbound. The role caps the
|
||||
// grant below and is re-checked at /token against the same company, which
|
||||
// travels in the code payload.
|
||||
const companyId = await getActiveCompanyId(supabase, user.id)
|
||||
let role: string | null = null
|
||||
if (companyId) {
|
||||
const lookup = await lookupCompanyRole(supabase, user.id, companyId)
|
||||
if (lookup.error) {
|
||||
return errorRedirect(
|
||||
request,
|
||||
redirectUri,
|
||||
state,
|
||||
'server_error',
|
||||
'Could not resolve your role in the company'
|
||||
)
|
||||
}
|
||||
role = lookup.role
|
||||
}
|
||||
|
||||
// Verify the scope binding signed at consent display matches what was
|
||||
// submitted with the form. This pins the form to the GET that minted it,
|
||||
// so an attacker who tricks the user into submitting a crafted form can't
|
||||
@@ -813,7 +947,7 @@ export async function POST(request: Request) {
|
||||
return errorRedirect(request, redirectUri, state, 'invalid_scope', parsed.description)
|
||||
}
|
||||
|
||||
// The user selects scopes via checkboxes on the consent page. Two upper
|
||||
// The user selects scopes via checkboxes on the consent page. Three upper
|
||||
// bounds apply server-side, regardless of what the form posts:
|
||||
//
|
||||
// 1. validateScopes drops any value that isn't in API_KEY_SCOPES: guards
|
||||
@@ -830,14 +964,27 @@ export async function POST(request: Request) {
|
||||
// resource owner's instructions"). The silent fallback when the
|
||||
// user selects nothing remains DEFAULT_OAUTH_SCOPES (read-only),
|
||||
// preserving GDPR Art. 25(2) data-protection-by-default.
|
||||
// 3. The ceiling is capped to the user's role in the selected company: a
|
||||
// viewer cannot hand an agent write scopes the viewer does not hold
|
||||
// themselves, however the form was built.
|
||||
const submittedScopes = formData.getAll('scopes').filter((s): s is string => typeof s === 'string')
|
||||
const validated = validateScopes(submittedScopes)
|
||||
const clientCeiling: ApiKeyScope[] = parsed.scopes ?? [...ALL_SCOPES]
|
||||
const ceilingSet = new Set<ApiKeyScope>(clientCeiling)
|
||||
const roleCapped = companyId ? capScopesForRole(clientCeiling, role) : clientCeiling
|
||||
const ceilingSet = new Set<ApiKeyScope>(roleCapped)
|
||||
const boundedToClient = (validated ?? []).filter(s => ceilingSet.has(s))
|
||||
const grantedScopes: ApiKeyScope[] = boundedToClient.length > 0
|
||||
? boundedToClient
|
||||
: [...DEFAULT_OAUTH_SCOPES].filter(s => ceilingSet.has(s))
|
||||
if (grantedScopes.length === 0) {
|
||||
return errorRedirect(
|
||||
request,
|
||||
redirectUri,
|
||||
state,
|
||||
'invalid_scope',
|
||||
'None of the requested scopes are available to your role in this company'
|
||||
)
|
||||
}
|
||||
|
||||
// Create auth code with userId (NO API key: that's created at /token after PKCE)
|
||||
const code = createAuthCode({
|
||||
@@ -845,6 +992,7 @@ export async function POST(request: Request) {
|
||||
codeChallenge,
|
||||
redirectUri,
|
||||
scopes: grantedScopes,
|
||||
companyId,
|
||||
})
|
||||
|
||||
// Redirect to callback with the code
|
||||
@@ -865,9 +1013,9 @@ export async function POST(request: Request) {
|
||||
* Render the scope checkbox UI grouped by domain. Only scopes in `ceiling`
|
||||
* are surfaced: scopes outside the ceiling are dropped from the consent UI
|
||||
* so the user can't tick boxes that the POST handler would refuse anyway.
|
||||
* The ceiling is either the client's `scope` querystring (when specified)
|
||||
* or DEFAULT_OAUTH_SCOPES (when the client passed no scope), matching the
|
||||
* server-side enforcement in the POST handler.
|
||||
* The ceiling is the client's `scope` querystring (or ALL_SCOPES when it
|
||||
* passed none) capped to the user's role, matching the server-side
|
||||
* enforcement in the POST handler.
|
||||
*/
|
||||
function renderScopeCheckboxes(
|
||||
preChecked: Set<ApiKeyScope>,
|
||||
@@ -928,6 +1076,33 @@ function scopeRow(scope: ApiKeyScope, checked: boolean, kind: 'read' | 'write'):
|
||||
`
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable identity of the client behind an allowed redirect URI, for
|
||||
* the consent page. Built-in patterns are named after the connector that owns
|
||||
* the callback host (and marked verified, since only that vendor can receive
|
||||
* the code there); DB registrations show the name the registering member
|
||||
* typed in settings, tagged with who registered it, never as verified.
|
||||
*/
|
||||
function describeClient(
|
||||
resolution: Exclude<RedirectUriResolution, { allowed: false }>,
|
||||
): { name: string; tag: string; verified: boolean } {
|
||||
if (resolution.kind === 'built_in') {
|
||||
switch (resolution.provider) {
|
||||
case 'claude':
|
||||
return { name: 'Claude (Anthropic)', tag: 'Verifierad', verified: true }
|
||||
case 'chatgpt':
|
||||
return { name: 'ChatGPT (OpenAI)', tag: 'Verifierad', verified: true }
|
||||
case 'local':
|
||||
return { name: 'Lokal utveckling (localhost)', tag: 'Din egen dator', verified: false }
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: resolution.clientName,
|
||||
tag: resolution.registeredByConsentingUser ? 'Registrerad av dig' : 'Registrerad av en kollega',
|
||||
verified: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every interpolation into the consent-page template goes through this,
|
||||
* including the form's own action attribute (url.pathname + url.search).
|
||||
|
||||
@@ -15,10 +15,14 @@ import { truncateIp } from '@/lib/api/v1/with-api-v1'
|
||||
*
|
||||
* Security model:
|
||||
* - Anonymous by design (RFC 7591 §3 allows it); the endpoint does NOT
|
||||
* write to oauth_client_registrations: only owner/admin users can
|
||||
* write to oauth_client_registrations: members with a writer role
|
||||
* insert via /api/settings/oauth-clients. This endpoint just echoes
|
||||
* a client_id back to callers whose redirect_uris are already on the
|
||||
* allowlist.
|
||||
* - With no user session there is nobody to bind a DB registration to, so
|
||||
* any active registration passes here. That is harmless: a code is only
|
||||
* ever minted at /authorize, which accepts a registered URI solely for
|
||||
* the registering user and their colleagues (lib/auth/oauth-allowlist.ts).
|
||||
* - Per-/24 sliding-window rate-limit prevents the endpoint being used
|
||||
* as a high-rate oracle for enumerating registered URIs.
|
||||
* - Error responses are uniform across "built-in", "DB-registered", and
|
||||
|
||||
@@ -36,9 +36,32 @@ function formRequest(body: Record<string, string>) {
|
||||
})
|
||||
}
|
||||
|
||||
const codeExchange = {
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
}
|
||||
|
||||
/**
|
||||
* Query results in the order handleAuthorizationCodeGrant issues them:
|
||||
* used-code insert, expired-code cleanup, (role lookup when a company is
|
||||
* known), api_keys insert. The role step is skipped for companyless grants.
|
||||
*/
|
||||
function exchangeResults(role: { role: string } | null | 'skip' = { role: 'owner' }) {
|
||||
const results: { data?: unknown; error?: unknown }[] = [
|
||||
{ data: null, error: null }, // insert into oauth_used_codes
|
||||
{ data: null, error: null }, // delete expired codes (best-effort)
|
||||
]
|
||||
if (role !== 'skip') results.push({ data: role, error: null }) // company_members role
|
||||
results.push({ data: null, error: null }) // insert into api_keys
|
||||
return results
|
||||
}
|
||||
|
||||
describe('POST /api/mcp-oauth/token', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.getActiveCompanyId.mockResolvedValue('company-1')
|
||||
})
|
||||
|
||||
describe('grant_type validation', () => {
|
||||
@@ -72,20 +95,9 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null }, // insert into oauth_used_codes
|
||||
{ data: null, error: null }, // delete expired codes (best-effort)
|
||||
{ data: null, error: null }, // insert into api_keys
|
||||
])
|
||||
enqueueMany(exchangeResults())
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.access_token).toMatch(/^gnubok_sk_/)
|
||||
@@ -97,11 +109,14 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
it('mints an unbound key (company_id null) when the user has no company yet', async () => {
|
||||
// Signup inside the OAuth popup (issue #1814): the account exists, the
|
||||
// company does not. The key is stored unbound and validateApiKey binds
|
||||
// it on the first call after the company is created.
|
||||
// it on the first call after the company is created. No company means
|
||||
// no role to cap against: the consented scopes go through as-is.
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['companies:read', 'companies:write'],
|
||||
companyId: null,
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
vi.mocked(verifyPkce).mockReturnValue(true)
|
||||
@@ -109,28 +124,19 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null }, // insert into oauth_used_codes
|
||||
{ data: null, error: null }, // delete expired codes (best-effort)
|
||||
{ data: null, error: null }, // insert into api_keys
|
||||
])
|
||||
enqueueMany(exchangeResults('skip'))
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.access_token).toMatch(/^gnubok_sk_/)
|
||||
expect(body.scope).toBe('companies:read companies:write')
|
||||
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted).toBeDefined()
|
||||
expect(inserted.user_id).toBe('user-1')
|
||||
expect(inserted.company_id).toBeNull()
|
||||
expect(findCall('company_members', 'select')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects an already-used auth code (replay)', async () => {
|
||||
@@ -146,14 +152,7 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueue({ data: null, error: { message: 'unique violation' } })
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('invalid_grant')
|
||||
@@ -168,14 +167,7 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
})
|
||||
vi.mocked(verifyPkce).mockReturnValue(false)
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'wrong',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest({ ...codeExchange, code_verifier: 'wrong' }))
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('invalid_grant')
|
||||
@@ -183,6 +175,180 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('company binding and role cap', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(verifyPkce).mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('binds the key to the company carried in the code instead of re-resolving the active company', async () => {
|
||||
// The consent page showed company-7 and capped the grant to the user's
|
||||
// role there; the key must land on that company, not on whatever the
|
||||
// user switched to in the meantime.
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['reports:read'],
|
||||
companyId: 'company-7',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall, findCalls } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'member' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(mocks.getActiveCompanyId).not.toHaveBeenCalled()
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.company_id).toBe('company-7')
|
||||
// The role lookup ran against that same company.
|
||||
const eqArgs = findCalls('company_members', 'eq')
|
||||
expect(eqArgs).toContainEqual(['company_id', 'company-7'])
|
||||
expect(eqArgs).toContainEqual(['user_id', 'user-1'])
|
||||
})
|
||||
|
||||
it('viewer consent yields a read-only key even when the code carries write scopes', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read', 'transactions:write', 'pending_operations:approve', 'reports:read'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'viewer' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.scope.split(' ').sort()).toEqual(['reports:read', 'transactions:read'])
|
||||
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.scopes).toEqual(['transactions:read', 'reports:read'])
|
||||
expect(inserted.sod_acknowledged_at).toBeNull()
|
||||
expect(inserted.sod_acknowledged_by).toBeNull()
|
||||
})
|
||||
|
||||
it('viewer whose code carries only write scopes falls back to the read-only defaults', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['bookkeeping:write'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'viewer' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const granted = (await res.json()).scope.split(' ')
|
||||
expect(granted).toContain('reports:read')
|
||||
expect(granted).not.toContain('bookkeeping:write')
|
||||
expect(granted.every((s: string) => s.endsWith(':read'))).toBe(true)
|
||||
})
|
||||
|
||||
it('membership removed between consent and exchange caps to read-only', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read', 'transactions:write'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults(null))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
expect((await res.json()).scope).toBe('transactions:read')
|
||||
})
|
||||
|
||||
it('records the segregation-of-duties acknowledgement when stage and approve are both granted', async () => {
|
||||
// Mirrors app/api/settings/api-keys: the combination is allowed for a
|
||||
// writer role but leaves a durable self-attestation on the key row.
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:write', 'pending_operations:approve'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'member' }))
|
||||
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
warn.mockRestore()
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.scopes).toEqual(['transactions:write', 'pending_operations:approve'])
|
||||
expect(typeof inserted.sod_acknowledged_at).toBe('string')
|
||||
expect(inserted.sod_acknowledged_by).toBe('user-1')
|
||||
})
|
||||
|
||||
it('records no acknowledgement for a non-conflicting grant', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:write', 'pending_operations:read'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'owner' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const inserted = findCall('api_keys', 'insert')?.[0] as Record<string, unknown>
|
||||
expect(inserted.sod_acknowledged_at).toBeNull()
|
||||
})
|
||||
|
||||
it('returns 500 and mints no key when the role lookup fails', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
|
||||
const { supabase, enqueueMany, findCall } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: { message: 'connection reset' } },
|
||||
])
|
||||
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
error.mockRestore()
|
||||
expect(res.status).toBe(500)
|
||||
expect((await res.json()).error).toBe('server_error')
|
||||
expect(findCall('api_keys', 'insert')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('refresh_token grant', () => {
|
||||
it('rotates both tokens and returns a fresh access_token', async () => {
|
||||
const { token: refreshToken } = generateRefreshToken()
|
||||
@@ -317,20 +483,9 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
])
|
||||
enqueueMany(exchangeResults())
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
// DEFAULT_OAUTH_SCOPES is read-only by design. Write and approval scopes
|
||||
@@ -366,25 +521,35 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany([
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
{ data: null, error: null },
|
||||
])
|
||||
enqueueMany(exchangeResults())
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.scope).toBe('transactions:read invoices:read')
|
||||
})
|
||||
|
||||
it('keeps an owner grant with write scopes intact (no cap for writer roles)', async () => {
|
||||
vi.mocked(decryptAuthCode).mockReturnValue({
|
||||
userId: 'user-1',
|
||||
codeChallenge: 'challenge',
|
||||
redirectUri: 'https://claude.ai/api/cb',
|
||||
scopes: ['transactions:read', 'transactions:write', 'bookkeeping:write'],
|
||||
companyId: 'company-1',
|
||||
exp: Date.now() + 60_000,
|
||||
})
|
||||
vi.mocked(verifyPkce).mockReturnValue(true)
|
||||
|
||||
const { supabase, enqueueMany } = createQueuedMockSupabase()
|
||||
mocks.supabaseFactory.mockReturnValue(supabase)
|
||||
enqueueMany(exchangeResults({ role: 'owner' }))
|
||||
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.scope).toBe('transactions:read transactions:write bookkeeping:write')
|
||||
})
|
||||
|
||||
it('rejects a code whose embedded scopes are all unknown', async () => {
|
||||
// V9.2.1 defense-in-depth: even though /authorize already filters
|
||||
// unknown scopes, the token endpoint must not silently mint a
|
||||
@@ -406,14 +571,7 @@ describe('POST /api/mcp-oauth/token', () => {
|
||||
{ data: null, error: null }, // delete expired codes
|
||||
])
|
||||
|
||||
const res = await POST(
|
||||
formRequest({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'ciphertext',
|
||||
code_verifier: 'verifier',
|
||||
redirect_uri: 'https://claude.ai/api/cb',
|
||||
})
|
||||
)
|
||||
const res = await POST(formRequest(codeExchange))
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('invalid_grant')
|
||||
|
||||
@@ -7,9 +7,11 @@ import {
|
||||
hashRefreshToken,
|
||||
createServiceClientNoCookies,
|
||||
validateScopes,
|
||||
findStageApproveConflict,
|
||||
DEFAULT_OAUTH_SCOPES,
|
||||
type ApiKeyScope,
|
||||
} from '@/lib/auth/api-keys'
|
||||
import { capScopesForRole, lookupCompanyRole } from '@/lib/auth/oauth-allowlist'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
|
||||
const ACCESS_TOKEN_TTL_SECONDS = 3600
|
||||
@@ -126,10 +128,16 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
.lt('created_at', new Date(Date.now() - 10 * 60 * 1000).toISOString())
|
||||
.then(() => {})
|
||||
|
||||
// null for an account that has no company yet (signed up from the OAuth
|
||||
// popup, issue #1814). The key is minted unbound; validateApiKey binds it
|
||||
// to the user's first company on the first call after one exists.
|
||||
const companyId = await getActiveCompanyId(supabase, payload.userId)
|
||||
// Bind the key to the company the consent page showed (carried in the code
|
||||
// payload), so the role cap below is checked against the company the user
|
||||
// actually consented for. Codes minted before the field existed, and
|
||||
// companyless consents (signed up from the OAuth popup, issue #1814),
|
||||
// resolve the active company here instead; null leaves the key unbound and
|
||||
// validateApiKey binds it on the first call after a company exists.
|
||||
const companyId =
|
||||
typeof payload.companyId === 'string' && payload.companyId.length > 0
|
||||
? payload.companyId
|
||||
: await getActiveCompanyId(supabase, payload.userId)
|
||||
|
||||
const { key, hash, prefix } = generateApiKey()
|
||||
const refresh = generateRefreshToken()
|
||||
@@ -155,6 +163,30 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
grantedScopes = DEFAULT_OAUTH_SCOPES
|
||||
}
|
||||
|
||||
// Re-apply the role cap /authorize computed, against the live membership:
|
||||
// a viewer's key is read-only even if the code payload says otherwise, and
|
||||
// a role demoted between consent and exchange is honoured. A failed lookup
|
||||
// is a hard stop rather than a silent downgrade or widening.
|
||||
if (companyId) {
|
||||
const lookup = await lookupCompanyRole(supabase, payload.userId, companyId)
|
||||
if (lookup.error) {
|
||||
console.error('[mcp-oauth/token] role lookup failed', { message: lookup.error })
|
||||
return NextResponse.json(
|
||||
{ error: 'server_error', error_description: 'Failed to resolve company role' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
const capped = capScopesForRole(grantedScopes, lookup.role)
|
||||
grantedScopes = capped.length > 0 ? capped : capScopesForRole(DEFAULT_OAUTH_SCOPES, lookup.role)
|
||||
}
|
||||
|
||||
// Segregation of duties, mirrored from app/api/settings/api-keys: a key
|
||||
// that can both stage and approve is recorded as an acknowledged risk
|
||||
// acceptance. The consent page states the rule above the Allow button, so
|
||||
// the consent click is the self-attestation (ASVS V16.1.1 / SOC 2 CC6.1).
|
||||
const conflictingScope = findStageApproveConflict(grantedScopes)
|
||||
const sodAcknowledgedAt = conflictingScope ? new Date().toISOString() : null
|
||||
|
||||
const { error: insertError } = await supabase
|
||||
.from('api_keys')
|
||||
.insert({
|
||||
@@ -165,6 +197,10 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
name: OAUTH_MCP_KEY_NAME,
|
||||
scopes: grantedScopes,
|
||||
refresh_token_hash: refresh.hash,
|
||||
// Literal keys (null when no conflict): the no-phantom-columns scanner
|
||||
// resolves object literals only, never spreads.
|
||||
sod_acknowledged_at: sodAcknowledgedAt,
|
||||
sod_acknowledged_by: sodAcknowledgedAt ? payload.userId : null,
|
||||
})
|
||||
|
||||
if (insertError) {
|
||||
@@ -181,6 +217,17 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
|
||||
)
|
||||
}
|
||||
|
||||
if (conflictingScope) {
|
||||
// High-risk security event, same shape the manual create route logs.
|
||||
console.warn('[mcp-oauth/token] api_key.sod_acknowledged', {
|
||||
keyPrefix: prefix,
|
||||
conflictingScope,
|
||||
scopes: grantedScopes,
|
||||
acknowledgedBy: payload.userId,
|
||||
companyId,
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
access_token: key,
|
||||
token_type: 'Bearer',
|
||||
|
||||
@@ -19,13 +19,14 @@ vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
const logosBucket = {
|
||||
list: vi.fn().mockResolvedValue({ data: [], error: null }),
|
||||
remove: vi.fn().mockResolvedValue({ data: [], error: null }),
|
||||
upload: vi.fn().mockResolvedValue({ data: {}, error: null }),
|
||||
getPublicUrl: vi.fn().mockReturnValue({ data: { publicUrl: 'https://cdn.example.com/logo.png' } }),
|
||||
}
|
||||
const serviceStorage = {
|
||||
from: vi.fn().mockReturnValue({
|
||||
list: vi.fn().mockResolvedValue({ data: [], error: null }),
|
||||
remove: vi.fn().mockResolvedValue({ data: [], error: null }),
|
||||
upload: vi.fn().mockResolvedValue({ data: {}, error: null }),
|
||||
getPublicUrl: vi.fn().mockReturnValue({ data: { publicUrl: 'https://cdn.example.com/logo.png' } }),
|
||||
}),
|
||||
from: vi.fn().mockReturnValue(logosBucket),
|
||||
}
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
@@ -34,16 +35,27 @@ vi.mock('@/lib/supabase/server', () => ({
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
function makeFormRequest(
|
||||
size = 3,
|
||||
type = 'image/png',
|
||||
name = 'logo.png',
|
||||
): Request {
|
||||
const PNG_MAGIC = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
const JPEG_MAGIC = [0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46]
|
||||
// RIFF <size> WEBP
|
||||
const WEBP_MAGIC = [0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50]
|
||||
const SVG_SOURCE = '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(document.cookie)</script></svg>'
|
||||
|
||||
/** A buffer of `size` bytes that starts with `magic` (zero-padded). */
|
||||
function withMagic(magic: number[], size = 64): Uint8Array<ArrayBuffer> {
|
||||
const bytes = new Uint8Array(new ArrayBuffer(Math.max(size, magic.length)))
|
||||
bytes.set(magic)
|
||||
return bytes
|
||||
}
|
||||
|
||||
function makeFormRequest(content: BlobPart, type = 'image/png', name = 'logo.png'): Request {
|
||||
const fd = new FormData()
|
||||
fd.append('file', new File([new Uint8Array(size)], name, { type }))
|
||||
fd.append('file', new File([content], name, { type }))
|
||||
return new Request('http://localhost/api/settings/logo', { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
const params = { params: Promise.resolve({}) }
|
||||
|
||||
describe('POST /api/settings/logo', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -59,7 +71,7 @@ describe('POST /api/settings/logo', () => {
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await POST(makeFormRequest(), { params: Promise.resolve({}) })
|
||||
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC)), params)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(401)
|
||||
@@ -71,27 +83,70 @@ describe('POST /api/settings/logo', () => {
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const response = await POST(makeFormRequest(), { params: Promise.resolve({}) })
|
||||
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC)), params)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 400 for an unsupported file type', async () => {
|
||||
it('returns 400 when no file is attached', async () => {
|
||||
const fd = new FormData()
|
||||
const response = await POST(
|
||||
makeFormRequest(3, 'application/pdf', 'logo.pdf'),
|
||||
{ params: Promise.resolve({}) },
|
||||
new Request('http://localhost/api/settings/logo', { method: 'POST', body: fd }),
|
||||
params,
|
||||
)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 when the logo exceeds 10 MB', async () => {
|
||||
it('returns 400 for an unsupported file type', async () => {
|
||||
const response = await POST(makeFormRequest(new Uint8Array(3), 'application/pdf', 'logo.pdf'), params)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(logosBucket.upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses SVG even when declared as image/svg+xml (public bucket, script-capable format)', async () => {
|
||||
const response = await POST(makeFormRequest(SVG_SOURCE, 'image/svg+xml', 'logo.svg'), params)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Otillåten filtyp. Tillåtna: PNG, JPG, WebP.')
|
||||
expect(logosBucket.upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses SVG bytes smuggled under a declared image/png type', async () => {
|
||||
const response = await POST(makeFormRequest(SVG_SOURCE, 'image/png', 'logo.png'), params)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('PNG, JPG, WebP')
|
||||
expect(logosBucket.upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses an HTML document declared as an image', async () => {
|
||||
const response = await POST(
|
||||
makeFormRequest(10 * 1024 * 1024 + 1),
|
||||
{ params: Promise.resolve({}) },
|
||||
makeFormRequest('<!doctype html><script>alert(1)</script>', 'image/jpeg', 'logo.jpg'),
|
||||
params,
|
||||
)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(logosBucket.upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a PDF declared as an image', async () => {
|
||||
const response = await POST(makeFormRequest('%PDF-1.4\n%%EOF', 'image/png', 'logo.png'), params)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(logosBucket.upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when the logo exceeds 10 MB', async () => {
|
||||
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC, 10 * 1024 * 1024 + 1)), params)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
@@ -101,22 +156,47 @@ describe('POST /api/settings/logo', () => {
|
||||
it('accepts a logo larger than the previous 2 MB limit', async () => {
|
||||
enqueue({ error: null }) // company_settings update
|
||||
|
||||
const response = await POST(
|
||||
makeFormRequest(2 * 1024 * 1024 + 1),
|
||||
{ params: Promise.resolve({}) },
|
||||
)
|
||||
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC, 2 * 1024 * 1024 + 1)), params)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
})
|
||||
|
||||
it('uploads the logo and returns its public url on the happy path', async () => {
|
||||
it('uploads a PNG under its sniffed type and returns the public url on the happy path', async () => {
|
||||
enqueue({ error: null }) // company_settings update
|
||||
|
||||
const response = await POST(makeFormRequest(), { params: Promise.resolve({}) })
|
||||
const response = await POST(makeFormRequest(withMagic(PNG_MAGIC)), params)
|
||||
const { status, body } = await parseJsonResponse<{ data: { logo_url: string } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.logo_url).toBe('https://cdn.example.com/logo.png')
|
||||
expect(logosBucket.upload).toHaveBeenCalledTimes(1)
|
||||
const [path, , options] = logosBucket.upload.mock.calls[0] as [string, Buffer, { contentType: string }]
|
||||
expect(path).toMatch(/^company-1\/logo-\d+\.png$/)
|
||||
expect(options.contentType).toBe('image/png')
|
||||
})
|
||||
|
||||
it('stores the type the bytes prove, not the declared one (JPEG declared as PNG)', async () => {
|
||||
enqueue({ error: null })
|
||||
|
||||
const response = await POST(makeFormRequest(withMagic(JPEG_MAGIC), 'image/png', 'logo.png'), params)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
const [path, , options] = logosBucket.upload.mock.calls[0] as [string, Buffer, { contentType: string }]
|
||||
expect(path).toMatch(/\.jpg$/)
|
||||
expect(options.contentType).toBe('image/jpeg')
|
||||
})
|
||||
|
||||
it('accepts WebP by magic bytes', async () => {
|
||||
enqueue({ error: null })
|
||||
|
||||
const response = await POST(makeFormRequest(withMagic(WEBP_MAGIC), 'image/webp', 'logo.webp'), params)
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
const [path, , options] = logosBucket.upload.mock.calls[0] as [string, Buffer, { contentType: string }]
|
||||
expect(path).toMatch(/\.webp$/)
|
||||
expect(options.contentType).toBe('image/webp')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,8 +3,22 @@ import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { LOGO_UPLOAD_MAX_BYTES, LOGO_UPLOAD_MAX_MB } from '@/lib/invoices/branding-constants'
|
||||
import { detectFileMagic } from '@/lib/core/documents/document-service'
|
||||
|
||||
const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp']
|
||||
/**
|
||||
* Raster formats only, decided by the file's magic bytes (detectFileMagic),
|
||||
* never by the client-declared Content-Type. The logos bucket is PUBLIC and
|
||||
* the object is served under the type stored here: an SVG (or an HTML file
|
||||
* declared as an image) would be a script-capable document on a public URL,
|
||||
* so SVG is not accepted at all and a declared type that disagrees with the
|
||||
* bytes is ignored in favour of the bytes.
|
||||
*/
|
||||
const LOGO_TYPE_EXTENSIONS: Record<string, string> = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/webp': 'webp',
|
||||
}
|
||||
const LOGO_TYPE_ERROR = 'Otillåten filtyp. Tillåtna: PNG, JPG, WebP.'
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'settings.logo.upload',
|
||||
@@ -16,22 +30,16 @@ export const POST = withRouteContext(
|
||||
return NextResponse.json({ error: 'Ingen fil angiven' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!ALLOWED_TYPES.includes(file.type)) {
|
||||
return NextResponse.json({ error: 'Otillåten filtyp. Tillåtna: PNG, JPG, SVG, WebP.' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (file.size > LOGO_UPLOAD_MAX_BYTES) {
|
||||
return NextResponse.json({ error: `Filen är för stor (max ${LOGO_UPLOAD_MAX_MB} MB).` }, { status: 400 })
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
const mimeToExt: Record<string, string> = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/svg+xml': 'svg',
|
||||
'image/webp': 'webp',
|
||||
const detectedType = detectFileMagic(new Uint8Array(buffer))
|
||||
const ext = detectedType ? LOGO_TYPE_EXTENSIONS[detectedType] : undefined
|
||||
if (!detectedType || !ext) {
|
||||
return NextResponse.json({ error: LOGO_TYPE_ERROR }, { status: 400 })
|
||||
}
|
||||
const ext = mimeToExt[file.type] ?? 'png'
|
||||
const storagePath = `${companyId}/logo-${Date.now()}.${ext}`
|
||||
|
||||
const serviceClient = createServiceClient()
|
||||
@@ -49,7 +57,7 @@ export const POST = withRouteContext(
|
||||
const { error: uploadError } = await serviceClient.storage
|
||||
.from('logos')
|
||||
.upload(storagePath, buffer, {
|
||||
contentType: file.type,
|
||||
contentType: detectedType,
|
||||
upsert: true,
|
||||
})
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
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'
|
||||
@@ -17,6 +22,15 @@ import {
|
||||
* 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
|
||||
@@ -51,10 +65,10 @@ const REQUEST_HEADERS_FORWARDED = [
|
||||
'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-type',
|
||||
'content-length',
|
||||
'content-disposition',
|
||||
'content-range',
|
||||
'accept-ranges',
|
||||
'cache-control',
|
||||
@@ -84,6 +98,85 @@ function objectPathOf(request: Request): string {
|
||||
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'
|
||||
@@ -96,7 +189,8 @@ function rejected(reason: 'unsupported_path' | 'missing_token' | 'storage_unconf
|
||||
|
||||
async function proxy(request: Request, method: 'GET' | 'HEAD' | 'PUT'): Promise<Response> {
|
||||
const url = new URL(request.url)
|
||||
const resolved = resolveUpstreamStorageUrl(objectPathOf(request), url.searchParams)
|
||||
const objectPath = objectPathOf(request)
|
||||
const resolved = resolveUpstreamStorageUrl(objectPath, url.searchParams)
|
||||
if (!resolved.ok) return rejected(resolved.reason)
|
||||
|
||||
const headers = new Headers()
|
||||
@@ -144,6 +238,16 @@ async function proxy(request: Request, method: 'GET' | 'HEAD' | 'PUT'): Promise<
|
||||
// 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,
|
||||
|
||||
@@ -1,15 +1,34 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { GET, HEAD, OPTIONS, PUT } from '../[...path]/route'
|
||||
|
||||
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(() => {
|
||||
@@ -25,6 +44,10 @@ function upstreamResponse(body: string | null, init: ResponseInit = {}) {
|
||||
})
|
||||
}
|
||||
|
||||
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' } }))
|
||||
@@ -38,6 +61,10 @@ describe('/api/storage/[...path] same-origin Storage proxy', () => {
|
||||
|
||||
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(
|
||||
@@ -50,16 +77,18 @@ describe('/api/storage/[...path] same-origin Storage proxy', () => {
|
||||
expect(new TextDecoder().decode(init.body as ArrayBuffer)).toBe('%PDF-1.4 hello')
|
||||
})
|
||||
|
||||
it('streams a signed download GET through and keeps the document headers', async () => {
|
||||
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': 'application/pdf',
|
||||
'content-disposition': 'attachment; filename="kvitto.pdf"',
|
||||
'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',
|
||||
)
|
||||
@@ -68,15 +97,175 @@ describe('/api/storage/[...path] same-origin Storage proxy', () => {
|
||||
|
||||
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('attachment; filename="kvitto.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' } }))
|
||||
|
||||
@@ -86,6 +275,7 @@ describe('/api/storage/[...path] same-origin Storage proxy', () => {
|
||||
|
||||
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 () => {
|
||||
|
||||
Reference in New Issue
Block a user