fix(entitlements): gate paid MCP tools (send_invoice/agi_submit/vat_declaration_submit) server-side (#846)

The HTTP routes call requireCapability at every paid chokepoint, but the
MCP/agent path bypassed the paywall entirely: the three external-service
tools stage operations whose commit calls the email / Skatteverket services
directly, with no capability check. After the 2026-07-07 trial cutover a
trial-connected non-payer using the gnubok MCP connector could still send
invoice emails and file AGI/VAT.

Close the gap with two layers, mirroring the existing TOOL_SCOPE_MAP gate:

- Dispatch gate (mcp-server/server.ts): MCP_TOOL_CAPABILITY_MAP, checked
  right after the scope check, blocks a non-entitled company before any
  pending op is staged. Emits errorKind='capability_denied' telemetry.
- Commit-time gate (commitPendingOperation): PAID_OPERATION_CAPABILITY_MAP,
  checked before the atomic claim. The real external-service chokepoint —
  applies to the MCP approve tool AND the UI approval path, and closes the
  trial-connected-token window (the grant has expired by commit time). A
  blocked op stays 'pending', so it is re-approvable once the company subscribes.

Adds a transport-free capabilityBlockedError() helper (shared bilingual
copy) and locks both maps with tests (maps, dispatch gate, commit gate).
Only the three write/submit tools are gated; SKV read/local tools stay free
per the statutory carve-out. No DB/migration change; self-hosted stays all-on.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-30 16:38:14 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 5df6199bd1
commit db843a7a5b
9 changed files with 422 additions and 6 deletions
@@ -0,0 +1,91 @@
/**
* Tests for the commit-time capability gate in commitPendingOperation.
*
* This is the twin of the MCP dispatch gate and the true external-service
* chokepoint: it runs BEFORE the atomic claim, so a blocked op stays 'pending'
* (re-approvable once the company subscribes) and an op staged DURING the trial
* cannot be committed once the grant expires — regardless of caller (MCP approve
* tool or the UI approval path).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
import { createQueuedMockSupabase } from '@/tests/helpers'
import type { PendingOperation } from '@/types'
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
return { ...actual, hasCapability: vi.fn() }
})
import { commitPendingOperation } from '../commit'
import { hasCapability } from '@/lib/entitlements/has-capability'
const mockHasCapability = vi.mocked(hasCapability)
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
return {
id: 'op-1',
user_id: 'user-1',
company_id: 'company-1',
operation_type: 'send_invoice',
status: 'pending',
title: 'test',
params: {},
preview_data: {},
result_data: null,
actor_type: 'user',
actor_id: null,
actor_label: null,
risk_level: 'high',
created_at: '2026-06-01T00:00:00Z',
resolved_at: null,
updated_at: '2026-06-01T00:00:00Z',
...overrides,
} as PendingOperation
}
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
describe('commitPendingOperation: capability gate', () => {
it('blocks send_invoice when email_send is not entitled — 403, op left pending', async () => {
mockHasCapability.mockResolvedValue(false)
const { supabase } = createQueuedMockSupabase() // no responses enqueued: the claim must never run
const op = makePendingOp({ operation_type: 'send_invoice', params: { invoice_id: 'inv-1' } })
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
expect(result.status).toBe('failed')
expect(result.http_status).toBe(403)
expect(result.code).toBe('capability_blocked')
expect(mockHasCapability).toHaveBeenCalledWith(supabase, 'company-1', 'email_send')
})
it('blocks submit_vat_declaration when skatteverket is not entitled', async () => {
mockHasCapability.mockResolvedValue(false)
const { supabase } = createQueuedMockSupabase()
const op = makePendingOp({ operation_type: 'submit_vat_declaration', params: { period_type: 'monthly', year: 2025, period: 3 } })
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
expect(result.status).toBe('failed')
expect(result.http_status).toBe(403)
expect(result.code).toBe('capability_blocked')
expect(mockHasCapability).toHaveBeenCalledWith(supabase, 'company-1', 'skatteverket')
})
it('does NOT consult the gate for a free operation type', async () => {
mockHasCapability.mockResolvedValue(false)
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: null, error: null }) // claim resolves to "already claimed" → early 409, before any executor
const op = makePendingOp({ operation_type: 'create_customer', params: { name: 'x' } })
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
// create_customer is not in PAID_OPERATION_CAPABILITY_MAP — the gate is skipped.
expect(mockHasCapability).not.toHaveBeenCalled()
expect(result.status).toBe('failed') // claim returned no row (409); proves we got past the gate
})
})
@@ -21,6 +21,15 @@ import type { SkvSubmitResult } from '@/lib/pending-operations/skatteverket-comm
import type { PendingOperation } from '@/types'
import { commitPendingOperation } from '../commit'
// The commit-time capability gate (PR: gate paid MCP tools) runs hasCapability
// before the atomic claim for submit_vat_declaration/submit_agi. These tests
// isolate the registry/lifecycle wiring, so make the gate transparent here;
// its enforcement is covered by commit-capability-gate.test.ts.
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
return { ...actual, hasCapability: vi.fn().mockResolvedValue(true) }
})
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
return {
id: 'op-1',
+19
View File
@@ -60,6 +60,8 @@ import {
type SkvSubmitResult,
} from '@/lib/pending-operations/skatteverket-commit'
import { getEmailService } from '@/lib/email/service'
import { hasCapability, CAPABILITY_BLOCKED_MESSAGE_SV } from '@/lib/entitlements/has-capability'
import { PAID_OPERATION_CAPABILITY_MAP } from '@/lib/entitlements/keys'
import {
generateInvoiceEmailHtml,
generateInvoiceEmailText,
@@ -3665,6 +3667,23 @@ async function commitPendingOperationInner(
pendingOp: PendingOperation,
opts: CommitOptions = {}
): Promise<CommitResult> {
// ── Capability gate (commit-time twin of the MCP dispatch gate). The actual
// external-service call (email / Skatteverket submit) happens below, so
// this is the true paid chokepoint — it also catches an op STAGED during
// the trial then approved AFTER the grant expired, regardless of caller
// (MCP approve tool or the UI approval path). Checked BEFORE the atomic
// claim so a blocked op stays 'pending' and is re-approvable once the
// company subscribes. Self-hosted short-circuits to all-on in hasCapability.
const requiredCapability = PAID_OPERATION_CAPABILITY_MAP[pendingOp.operation_type]
if (requiredCapability && !(await hasCapability(supabase, companyId, requiredCapability))) {
return {
status: 'failed',
error: CAPABILITY_BLOCKED_MESSAGE_SV,
http_status: 403,
code: 'capability_blocked',
}
}
// ── Atomic claim: flip status pending → committing in a single conditional
// update. If 0 rows are affected, another caller (auto-commit ↔ human
// approval, or two parallel approvals) already claimed this op and we