docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,123 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
let key = {
|
||||
id: 'key-1', orgNumber: 'x', instanceUrl: 'https://i', scopes: ['skatteverket'], status: 'active' as const,
|
||||
currentPeriodEnd: null as string | null, limits: { bank_connections_per_company: 1, skv_connections_per_company: 1, sync_min_interval_s: 0 },
|
||||
}
|
||||
vi.mock('@/lib/connect/hosted/with-connector-auth', () => ({
|
||||
withConnectorAuth: (_o: string, h: (r: Request, c: unknown) => Promise<Response>) => (r: Request) =>
|
||||
h(r, { requestId: 't', log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, supabase: {}, key }),
|
||||
}))
|
||||
const hh = vi.hoisted(() => ({ budget: vi.fn(), find: vi.fn(), touch: vi.fn() }))
|
||||
vi.mock('@/lib/connect/hosted/upstream-budget', () => ({ reserveUpstream: (...a: unknown[]) => hh.budget(...a) }))
|
||||
vi.mock('@/lib/connect/hosted/ledger', () => ({ findByHandle: (...a: unknown[]) => hh.find(...a), touchConnection: (...a: unknown[]) => hh.touch(...a) }))
|
||||
vi.mock('@/lib/connect/upstreams/skatteverket-oauth', () => ({
|
||||
SKV_API_BASES: {
|
||||
moms: () => 'https://api.skv/momsdeklaration/v1',
|
||||
skattekonto: () => 'https://api.skv/skattekonto/v2',
|
||||
'agd-inlamning': () => 'https://api.skv/agd/inlamning/v1',
|
||||
'agd-period': () => 'https://api.skv/agd/period/v1',
|
||||
},
|
||||
skvGatewayHeaders: () => ({ Client_Id: 'gw', Client_Secret: 'gws', skv_client_correlation_id: 'corr' }),
|
||||
}))
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
function req(method: string, path: string, token = 'user-token', body?: string): Request {
|
||||
const headers: Record<string, string> = { 'x-connector-upstream-authorization': `Bearer ${token}` }
|
||||
return new Request(`https://app.gnubok.se/api/connect/skv/api${path}`, { method, headers, ...(body !== undefined ? { body } : {}) })
|
||||
}
|
||||
function skvOk(body: unknown, status = 200) {
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
key = { ...key, scopes: ['skatteverket'] }
|
||||
hh.budget.mockResolvedValue({ ok: true })
|
||||
hh.find.mockResolvedValue({ id: 'l1' })
|
||||
})
|
||||
|
||||
describe('skv data proxy', () => {
|
||||
it('rejects dot-segment traversal, raw and percent-encoded', async () => {
|
||||
// Raw ../ and %2E dot segments are normalized away by the WHATWG URL
|
||||
// parser before the route sees them (they cannot escape past the route
|
||||
// prefix). What survives to splitPath is an encoded separator INSIDE a
|
||||
// segment, which would traverse once the upstream fetch re-normalizes:
|
||||
// those must be rejected here.
|
||||
for (const path of ['/moms/a%2Fb', '/moms/..%2Fx', '/moms/a%5Cb']) {
|
||||
const res = await GET(req('GET', path))
|
||||
expect(res.status, path).toBe(403)
|
||||
expect((await res.json()).code).toBe('CONNECTOR_PATH_NOT_ALLOWED')
|
||||
}
|
||||
})
|
||||
|
||||
it('403 without the scope', async () => {
|
||||
key = { ...key, scopes: [] }
|
||||
expect((await GET(req('GET', '/moms/deklarationer'))).status).toBe(403)
|
||||
})
|
||||
it('403 on an unknown service', async () => {
|
||||
const res = await GET(req('GET', '/unknown/x'))
|
||||
expect(res.status).toBe(403)
|
||||
expect((await res.json()).code).toBe('CONNECTOR_PATH_NOT_ALLOWED')
|
||||
})
|
||||
it('400 without a user token', async () => {
|
||||
const res = await GET(new Request('https://app.gnubok.se/api/connect/skv/api/moms/x', { method: 'GET' }))
|
||||
expect(res.status).toBe(400)
|
||||
expect((await res.json()).code).toBe('CONNECTOR_UPSTREAM_TOKEN_MISSING')
|
||||
})
|
||||
it('404 when the token is not owned by this key', async () => {
|
||||
hh.find.mockResolvedValue(null)
|
||||
expect((await GET(req('GET', '/moms/x'))).status).toBe(404)
|
||||
})
|
||||
it('forwards a GET with the user Bearer + Arcim gateway headers to the right backing API', async () => {
|
||||
skvOk({ ok: true })
|
||||
const res = await GET(req('GET', '/skattekonto/saldo?period=2026-08'))
|
||||
expect(res.status).toBe(200)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('https://api.skv/skattekonto/v2/saldo?period=2026-08')
|
||||
expect(init.headers.Authorization).toBe('Bearer user-token')
|
||||
expect(init.headers.Client_Id).toBe('gw')
|
||||
expect(hh.touch).toHaveBeenCalledWith(expect.anything(), 'l1')
|
||||
})
|
||||
it('forwards a POST body to the AGI inlämning API', async () => {
|
||||
skvOk({ id: 'u1' }, 201)
|
||||
const res = await POST(req('POST', '/agd-inlamning/underlag', 'user-token', '<xml/>'))
|
||||
expect(res.status).toBe(201)
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('https://api.skv/agd/inlamning/v1/underlag')
|
||||
expect(fetchMock.mock.calls[0][1].body).toBe('<xml/>')
|
||||
})
|
||||
it('forwards SKV diagnostic headers (WWW-Authenticate, x-skv-*) but nothing else', async () => {
|
||||
// The instance's 401 classifier reads WWW-Authenticate (insufficient_scope
|
||||
// → MISSING_SCOPE) and the x-skv-* family on body-less gateway
|
||||
// rejections; stripping them blinded connector-mode classification.
|
||||
fetchMock.mockResolvedValueOnce(new Response('', {
|
||||
status: 401,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'WWW-Authenticate': 'Bearer error="insufficient_scope", scope="agd"',
|
||||
'x-skv-trace': 'abc',
|
||||
'x-amzn-requestid': 'req-1',
|
||||
'set-cookie': 'secret=1',
|
||||
'x-internal-other': 'nope',
|
||||
},
|
||||
}))
|
||||
const res = await GET(req('GET', '/moms/x'))
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get('WWW-Authenticate')).toBe('Bearer error="insufficient_scope", scope="agd"')
|
||||
expect(res.headers.get('x-skv-trace')).toBe('abc')
|
||||
expect(res.headers.get('x-amzn-requestid')).toBe('req-1')
|
||||
expect(res.headers.get('set-cookie')).toBeNull()
|
||||
expect(res.headers.get('x-internal-other')).toBeNull()
|
||||
})
|
||||
|
||||
it('429 when the budget is exhausted', async () => {
|
||||
hh.budget.mockResolvedValue({ ok: false, scope: 'hour', retryAfterSec: 3600 })
|
||||
const res = await GET(req('GET', '/moms/x'))
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBe('3600')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,132 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withConnectorAuth, type ConnectorContext } from '@/lib/connect/hosted/with-connector-auth'
|
||||
import { reserveUpstream } from '@/lib/connect/hosted/upstream-budget'
|
||||
import { findByHandle, touchConnection } from '@/lib/connect/hosted/ledger'
|
||||
import { SKV_API_BASES, skvGatewayHeaders } from '@/lib/connect/upstreams/skatteverket-oauth'
|
||||
|
||||
/**
|
||||
* Skatteverket data proxy for self-hosted instances.
|
||||
*
|
||||
* ANY /api/connect/skv/api/<service>/<path>
|
||||
* Authorization: Bearer <the END USER's SKV access token, from the instance>
|
||||
* X-Connector-Key: gnubok_ck_... (the instance's key auth)
|
||||
*
|
||||
* The instance holds the user token (it did the BankID flow through our
|
||||
* broker); it presents that token as the upstream Bearer while proving its
|
||||
* own subscription with X-Connector-Key. The proxy checks that the presented
|
||||
* token belongs to a connection this key owns (ledger), then adds Arcim's
|
||||
* API-gateway client credentials (Client_Id/Client_Secret) and forwards to
|
||||
* the right SKV backing API. Arcim's gateway secret never leaves us.
|
||||
*
|
||||
* <service> is one of the SKV_API_BASES keys (moms, skattekonto,
|
||||
* agd-inlamning, agd-period): an allowlist, never an open passthrough.
|
||||
*/
|
||||
|
||||
const FETCH_TIMEOUT_MS = 20_000
|
||||
|
||||
function requireScope(ctx: ConnectorContext): NextResponse | null {
|
||||
if (ctx.key.scopes.includes('skatteverket')) return null
|
||||
return NextResponse.json({ error: 'This connector key does not include Skatteverket', code: 'CONNECTOR_SCOPE_MISSING' }, { status: 403 })
|
||||
}
|
||||
|
||||
function splitPath(request: Request): { service: string; rest: string; query: string } | null {
|
||||
const marker = '/api/connect/skv/api'
|
||||
const idx = request.url.indexOf(marker)
|
||||
if (idx === -1) return null
|
||||
const after = request.url.slice(idx + marker.length)
|
||||
const [pathPart, ...q] = after.split('?')
|
||||
const segments = pathPart.split('/').filter(Boolean)
|
||||
if (segments.length === 0) return null
|
||||
// Traversal guard: a '.'/'..' segment (raw or percent-encoded) would let
|
||||
// the proxied URL escape the allowlisted service base once fetch
|
||||
// normalizes it. Decode each segment and reject dot segments and anything
|
||||
// that decodes to contain a path separator.
|
||||
for (const seg of segments) {
|
||||
let decoded: string
|
||||
try {
|
||||
decoded = decodeURIComponent(seg)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (decoded === '.' || decoded === '..' || decoded.includes('/') || decoded.includes('\\')) return null
|
||||
}
|
||||
const [service, ...restSegs] = segments
|
||||
return { service, rest: `/${restSegs.join('/')}`, query: q.length ? `?${q.join('?')}` : '' }
|
||||
}
|
||||
|
||||
/** The end-user SKV token the instance forwards, from the upstream-Authorization header. */
|
||||
function userToken(request: Request): string | null {
|
||||
const h = request.headers.get('x-connector-upstream-authorization') || request.headers.get('authorization')
|
||||
if (!h?.startsWith('Bearer ')) return null
|
||||
return h.slice(7).trim() || null
|
||||
}
|
||||
|
||||
async function handle(request: Request, ctx: ConnectorContext): Promise<Response> {
|
||||
const scopeError = requireScope(ctx)
|
||||
if (scopeError) return scopeError
|
||||
|
||||
const parts = splitPath(request)
|
||||
if (!parts || !(parts.service in SKV_API_BASES)) {
|
||||
return NextResponse.json({ error: 'Unknown Skatteverket service', code: 'CONNECTOR_PATH_NOT_ALLOWED' }, { status: 403 })
|
||||
}
|
||||
const token = userToken(request)
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: 'Missing user token', code: 'CONNECTOR_UPSTREAM_TOKEN_MISSING' }, { status: 400 })
|
||||
}
|
||||
const owned = await findByHandle(ctx.supabase, { keyId: ctx.key.id, service: 'skatteverket', handle: token })
|
||||
if (!owned) {
|
||||
return NextResponse.json({ error: 'Unknown Skatteverket connection for this key', code: 'CONNECTOR_NOT_OWNED' }, { status: 404 })
|
||||
}
|
||||
const budget = await reserveUpstream(ctx.supabase, 'skatteverket')
|
||||
if (!budget.ok) {
|
||||
return NextResponse.json({ error: 'Skatteverket connector is busy', code: 'CONNECTOR_RATE_LIMITED' }, { status: 429, headers: { 'Retry-After': String(budget.retryAfterSec) } })
|
||||
}
|
||||
await touchConnection(ctx.supabase, owned.id)
|
||||
|
||||
const url = `${SKV_API_BASES[parts.service]()}${parts.rest}${parts.query}`
|
||||
const contentType = request.headers.get('x-connector-upstream-content-type') || request.headers.get('content-type') || 'application/json'
|
||||
const method = request.method
|
||||
const hasBody = method !== 'GET' && method !== 'HEAD'
|
||||
const body = hasBody ? await request.text() : undefined
|
||||
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
signal: controller.signal,
|
||||
// A followed redirect would resend the gateway Client_Secret headers.
|
||||
redirect: 'error',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...skvGatewayHeaders(),
|
||||
...(hasBody ? { 'Content-Type': contentType } : {}),
|
||||
},
|
||||
...(body !== undefined && body.length > 0 ? { body } : {}),
|
||||
})
|
||||
const text = await res.text()
|
||||
if ([204, 205, 304].includes(res.status)) return new NextResponse(null, { status: res.status })
|
||||
// Forward SKV's diagnostic headers: WWW-Authenticate carries OAuth's
|
||||
// machine-readable failure reason (the instance's insufficient_scope →
|
||||
// MISSING_SCOPE classification depends on it), and the x-skv-*/x-amzn-*/
|
||||
// x-api-* families are the only signal on body-less gateway rejections.
|
||||
// Nothing secret rides in them; stripping them blinded the instance's
|
||||
// 401 classifier (skeptic finding on PR6b-2).
|
||||
const headers: Record<string, string> = { 'Content-Type': res.headers.get('content-type') ?? 'application/json' }
|
||||
res.headers.forEach((v, k) => {
|
||||
const lk = k.toLowerCase()
|
||||
if (lk === 'www-authenticate' || lk.startsWith('x-skv-') || lk.startsWith('x-amzn-') || lk.startsWith('x-api-')) {
|
||||
headers[k] = v
|
||||
}
|
||||
})
|
||||
return new NextResponse(text, { status: res.status, headers })
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
export const GET = withConnectorAuth('connect.skv', handle)
|
||||
export const POST = withConnectorAuth('connect.skv', handle)
|
||||
export const PUT = withConnectorAuth('connect.skv', handle)
|
||||
export const PATCH = withConnectorAuth('connect.skv', handle)
|
||||
export const DELETE = withConnectorAuth('connect.skv', handle)
|
||||
Reference in New Issue
Block a user