Files
accounted/extensions/general/mcp-server/__tests__/capability-gate.test.ts
T
Jakob WennbergandClaude Sonnet 5 ec27228a8e style: remove em/en dashes repo-wide, add CLAUDE.md rule against them (#890)
Em dashes (—) and en dashes (–) had spread across comments, docs, tests,
and a few UI strings, reading as AI-generated boilerplate rather than
house style. Replaced each with punctuation matching its context: colon
for explanatory clauses, comma for asides, plain hyphen for numeric/legal
ranges (e.g. "21-23§"), "to"/"till" for date ranges, parentheses for
paired-dash asides. messages/en.json and messages/sv.json were fixed by
hand together to keep sv/en in sync.

Left untouched where the dash is the functional subject rather than
decorative punctuation: date-range-parser.ts's separator regex,
charset-repair.ts's CP1252 byte-mapping table (and its test), the SIE
encoding mojibake docs, generic-csv.ts's minus-sign normalizer, the
agent system-prompt files that already instruct against em dashes, and
a golden iXBRL test fixture compared byte-for-byte.

Also fixes two bugs surfaced along the way: an off-by-one in
ApiKeysPanel's scope-label split (a leftover from an earlier partial
pass), and a charset-repair test that had lost the literal en-dash it
exists to verify.

Regenerated the agent atom seed migration (skills:generate) since 27
SKILL.md files changed. Added a CLAUDE.md rule against em/en dashes,
with an explicit carve-out for the functional-dash cases above.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 15:58:06 +02:00

177 lines
7.4 KiB
TypeScript

/**
* Tests for the capability paywall gate in the MCP dispatcher.
*
* The paid external-service tools (send_invoice → email_send, the two
* Skatteverket submissions → skatteverket) must be blocked server-side when the
* company isn't entitled: BEFORE tool.execute() runs, so no pending op is
* staged. The gate sits right after the API-key scope check and mirrors its
* shape, so the test key holds the required SCOPE but the company may lack the
* CAPABILITY. Self-hosted short-circuits hasCapability to all-on (covered in
* lib/entitlements/__tests__/has-capability.test.ts), so here we drive the
* gate directly via a mocked hasCapability.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth/api-keys')>()
// A minimal chainable Supabase stub: only reached if the gate lets a call
// through to execute(); resolves everything to null so execute fails with a
// plain execution error (never capability_blocked).
const chain: unknown = new Proxy(
{},
{
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => resolve({ data: null, error: null })
}
return () => chain
},
},
)
return {
...actual,
extractBearerToken: vi.fn().mockReturnValue('test-token'),
validateApiKey: vi.fn().mockResolvedValue({
userId: 'user-1',
companyId: '11111111-1111-4111-8111-111111111111',
// Holds the SCOPES for every paid tool under test (send_invoice →
// invoices:write, agi_submit → skatteverket:write, upload_document →
// transactions:write) so the scope gate passes and the CAPABILITY gate is
// what we exercise.
scopes: ['invoices:write', 'skatteverket:write', 'reports:read', 'transactions:write'],
apiKeyId: 'key-1',
apiKeyName: 'Test Key',
}),
createServiceClientNoCookies: vi.fn(() => ({ from: () => chain, rpc: () => chain })),
}
})
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
return { ...actual, hasCapability: vi.fn() }
})
import { handleMcpRequest } from '../server'
import { hasCapability } from '@/lib/entitlements/has-capability'
const mockHasCapability = vi.mocked(hasCapability)
function mcpToolCall(name: string, args: Record<string, unknown> = {}): Request {
return new Request('http://localhost:3000/api/extensions/ext/mcp-server/mcp', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test-token' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
})
}
interface ToolCalledEvent {
tool: string
success: boolean
isError: boolean
errorKind: string | null
errorCode: string | null
latencyMs: number
}
function captureNextToolCalled(): Promise<ToolCalledEvent> {
return new Promise((resolve) => {
const off = eventBus.on('mcp.tool_called', (payload) => {
off()
resolve(payload as unknown as ToolCalledEvent)
})
})
}
async function parsedToolResult(response: Response): Promise<{ isError: boolean; payload: Record<string, unknown> }> {
const json = await response.json()
const result = json.result as { isError?: boolean; content: { text: string }[] }
return { isError: result.isError === true, payload: JSON.parse(result.content[0].text) }
}
describe('MCP capability gate', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
it('blocks gnubok_send_invoice when email_send is not entitled: before execute()', async () => {
mockHasCapability.mockResolvedValue(false)
const eventPromise = captureNextToolCalled()
const response = await handleMcpRequest(mcpToolCall('gnubok_send_invoice', { invoice_id: 'inv-1' }))
const { isError, payload } = await parsedToolResult(response)
expect(isError).toBe(true)
expect((payload.error as Record<string, unknown>).capability_blocked).toBe(true)
expect((payload.error as Record<string, unknown>).capability).toBe('email_send')
expect(mockHasCapability).toHaveBeenCalledWith(expect.anything(), '11111111-1111-4111-8111-111111111111', 'email_send')
const event = await eventPromise
expect(event.errorKind).toBe('capability_denied')
expect(event.errorCode).toBe('capability_blocked')
expect(event.success).toBe(false)
// The gate exits before tool.execute(), exactly like scope denial.
expect(event.latencyMs).toBe(0)
})
it('blocks gnubok_agi_submit when skatteverket is not entitled', async () => {
mockHasCapability.mockResolvedValue(false)
const response = await handleMcpRequest(mcpToolCall('gnubok_agi_submit', { salary_run_id: 'sr-1' }))
const { isError, payload } = await parsedToolResult(response)
expect(isError).toBe(true)
expect((payload.error as Record<string, unknown>).capability).toBe('skatteverket')
expect(mockHasCapability).toHaveBeenCalledWith(expect.anything(), '11111111-1111-4111-8111-111111111111', 'skatteverket')
})
it('blocks gnubok_upload_document when ai is not entitled: the paid Bedrock OCR path', async () => {
// gnubok_upload_document runs extractInvoiceFields (Bedrock OCR) inline in
// its handler, NOT through the entitlement-gated uploadAndExtract. The
// central dispatch map is therefore the ONLY paywall on this transport.
// This test locks it so a free-tier connector key can never reach OCR.
mockHasCapability.mockResolvedValue(false)
const response = await handleMcpRequest(
mcpToolCall('gnubok_upload_document', { file_name: 'faktura.pdf', file_content_base64: 'JVBERi0=' }),
)
const { isError, payload } = await parsedToolResult(response)
expect(isError).toBe(true)
expect((payload.error as Record<string, unknown>).capability_blocked).toBe(true)
expect((payload.error as Record<string, unknown>).capability).toBe('ai')
expect(mockHasCapability).toHaveBeenCalledWith(expect.anything(), '11111111-1111-4111-8111-111111111111', 'ai')
})
it('lets a free tool through without consulting the capability gate', async () => {
mockHasCapability.mockResolvedValue(false)
await handleMcpRequest(mcpToolCall('gnubok_list_skills', {}))
// gnubok_list_skills has no MCP_TOOL_CAPABILITY_MAP entry: the gate is skipped entirely.
expect(mockHasCapability).not.toHaveBeenCalled()
})
it('proceeds to execute() when the company IS entitled (no capability_blocked)', async () => {
mockHasCapability.mockResolvedValue(true)
const eventPromise = captureNextToolCalled()
const response = await handleMcpRequest(mcpToolCall('gnubok_send_invoice', { invoice_id: 'inv-1' }))
const { payload } = await parsedToolResult(response)
// Gate passed → execute() runs (and fails for an unrelated reason: email not
// configured / invoice not found). The point is it is NOT capability_blocked.
expect((payload.error as Record<string, unknown> | undefined)?.capability_blocked).toBeUndefined()
expect(mockHasCapability).toHaveBeenCalledWith(expect.anything(), '11111111-1111-4111-8111-111111111111', 'email_send')
const event = await eventPromise
expect(event.errorKind).not.toBe('capability_denied')
})
})