Fix/mcp fixes and bugs (#518)

* feat(voucher): add create voucher and correct entry previews; update commit methods

* feat: add support for pending operations in API key scopes and OAuth client management

- Introduced new API key scopes for reading and approving pending operations.
- Updated the scope groups to include pending operations.
- Added new tools for listing and managing pending operations.
- Implemented OAuth client registration and revocation endpoints.
- Created a UI panel for managing OAuth clients, including registration and revocation.
- Added tests for pending operations tools and OAuth allowlist functionality.
- Implemented a database migration for OAuth client registrations with appropriate policies and constraints.

* feat: Implement OAuth client registration rate limiting and enhance security measures

- Added IP-based rate limiting to the OAuth client registration endpoint to prevent enumeration attacks.
- Introduced a service-role client for allowlist lookups, ensuring trust boundaries are maintained.
- Updated error responses to be uniform across different types of redirect URI validation failures.
- Enhanced tests to reflect changes in OAuth scope handling, ensuring fallback to read-only scopes when no scopes are provided.
- Improved handling of high-risk pending operations, requiring explicit confirmation for approvals.
- Added audit logging for OAuth client revocations and pending operation approvals/rejections to maintain a security audit trail.
- Refactored API key scope management to include default read-only scopes for OAuth-issued keys and added segregation-of-duties checks.
This commit is contained in:
Mattsson
2026-05-18 19:02:42 +02:00
committed by GitHub
parent d27c3dd3dc
commit 16164ea14c
26 changed files with 2363 additions and 154 deletions
+121 -80
View File
@@ -19,85 +19,120 @@ import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Plus, Copy, Check, Trash2, Key, ChevronDown } from 'lucide-react'
import { getBranding } from '@/lib/branding/service'
import type { ApiKeyScope } from '@/lib/auth/api-keys'
const branding = getBranding()
const connectorName = branding.appName.toLowerCase()
const SCOPE_GROUPS = [
type ScopeEntry = {
scope: ApiKeyScope
label: string
/** Number of MCP tools gated by this scope. 0 = REST-API-only scope. */
tools: number
}
type ScopeGroup = {
domain: string
label: string
read: ScopeEntry | null
write: ScopeEntry | null
}
const SCOPE_GROUPS: ScopeGroup[] = [
{
domain: 'transactions',
label: 'Transaktioner',
read: 'transactions:read' as const,
readLabel: 'Läs — lista transaktioner, mallar, kategorier',
readTools: 3,
write: 'transactions:write' as const,
writeLabel: 'Skriv — kategorisera, kvittomatchning, koppling mot faktura',
writeTools: 3,
read: { scope: 'transactions:read', label: 'Läs — lista transaktioner, mallar, kategorier, inbox', tools: 8 },
write: { scope: 'transactions:write', label: 'Skriv — kategorisera, kvittomatchning, koppling mot faktura, dokumentuppladdning', tools: 8 },
},
{
domain: 'customers',
label: 'Kunder',
read: 'customers:read' as const,
readLabel: 'Läs — lista kunder',
readTools: 1,
write: 'customers:write' as const,
writeLabel: 'Skriv — skapa kunder',
writeTools: 1,
read: { scope: 'customers:read', label: 'Läs — lista kunder', tools: 1 },
write: { scope: 'customers:write', label: 'Skriv — skapa kunder', tools: 1 },
},
{
domain: 'invoices',
label: 'Fakturor',
read: 'invoices:read' as const,
readLabel: 'Läs — lista fakturor',
readTools: 1,
write: 'invoices:write' as const,
writeLabel: 'Skriv — skapa, skicka, markera betald/skickad',
writeTools: 4,
read: { scope: 'invoices:read', label: 'Läs — lista fakturor', tools: 1 },
write: { scope: 'invoices:write', label: 'Skriv — skapa, skicka, markera betald/skickad, kreditera, konvertera', tools: 6 },
},
{
domain: 'suppliers',
label: 'Leverantörer',
read: 'suppliers:read' as const,
readLabel: 'Läs — lista leverantörer och leverantörsfakturor',
readTools: 2,
write: null,
writeLabel: null,
writeTools: 0,
read: { scope: 'suppliers:read', label: 'Läs — lista leverantörer och leverantörsfakturor', tools: 2 },
write: { scope: 'suppliers:write', label: 'Skriv — godkänn, kreditera, skapa leverantörsfaktura från inbox', tools: 3 },
},
{
domain: 'reports',
label: 'Rapporter',
read: 'reports:read' as const,
readLabel: 'Läs — kontoplan, huvudbok, balansräkning, resultaträkning, moms, KPI, kundreskontra, leverantörsreskontra, räkenskapsperioder, bankavstämning',
readTools: 11,
read: { scope: 'reports:read', label: 'Läs — kontoplan, huvudbok, BR, RR, moms, KPI, reskontra, perioder, bankavstämning, SIE-export', tools: 18 },
write: null,
writeLabel: null,
writeTools: 0,
},
] as const
{
domain: 'bookkeeping',
label: 'Bokföring',
read: null,
write: { scope: 'bookkeeping:write', label: 'Skriv — stänga/låsa perioder, IB, bokslut, SIE-import, verifikat, korrigeringar (alla stagas)', tools: 11 },
},
{
domain: 'payroll',
label: 'Löner',
read: { scope: 'payroll:read', label: 'Läs — lista anställda, lönekörningar, lönejournal', tools: 3 },
write: { scope: 'payroll:write', label: 'Skriv — skapa lönekörning, beräkna, generera AGI', tools: 3 },
},
{
domain: 'pending_operations',
label: 'Stagade operationer',
read: { scope: 'pending_operations:read', label: 'Läs — lista pending_operations som väntar på godkännande', tools: 1 },
write: { scope: 'pending_operations:approve', label: 'Godkänn — committa eller avvisa staged ops via API (ersätter web-UI:s granskning)', tools: 2 },
},
{
domain: 'documents',
label: 'Dokument (REST API)',
read: { scope: 'documents:read', label: 'Läs — lista och hämta dokumentbilagor', tools: 0 },
write: { scope: 'documents:write', label: 'Skriv — ladda upp och koppla dokument till verifikationer', tools: 0 },
},
{
domain: 'companies',
label: 'Företag (REST API)',
read: { scope: 'companies:read', label: 'Läs — företagsprofiler nyckeln har åtkomst till', tools: 0 },
write: null,
},
{
domain: 'events',
label: 'Händelser (REST API)',
read: { scope: 'events:read', label: 'Läs — polla event_log som webhook-fallback', tools: 0 },
write: null,
},
{
domain: 'webhooks',
label: 'Webhooks (REST API)',
read: null,
write: { scope: 'webhooks:manage', label: 'Hantera — skapa, lista, uppdatera, radera prenumerationer', tools: 0 },
},
{
domain: 'operations',
label: 'Operationer (REST API)',
read: { scope: 'operations:read', label: 'Läs — status för långkörande operationer (import, bokslut, omvärdering)', tools: 0 },
write: null,
},
{
domain: 'compliance',
label: 'Compliance (REST API)',
read: { scope: 'compliance:read', label: 'Läs — pre-flight: momsstängning, bokslutsberedskap, voucher-gap, IB/UB-kontinuitet', tools: 0 },
write: null,
},
]
type Scope =
| 'transactions:read' | 'transactions:write'
| 'customers:read' | 'customers:write'
| 'invoices:read' | 'invoices:write'
| 'suppliers:read'
| 'reports:read'
type Scope = ApiKeyScope
const ALL_SCOPES: Scope[] = SCOPE_GROUPS.flatMap((g) =>
g.write ? [g.read, g.write] : [g.read]
)
/** Map scope key → display label for badges */
const SCOPE_LABELS: Record<Scope, string> = {
'transactions:read': 'Transaktioner (läs)',
'transactions:write': 'Transaktioner (skriv)',
'customers:read': 'Kunder (läs)',
'customers:write': 'Kunder (skriv)',
'invoices:read': 'Fakturor (läs)',
'invoices:write': 'Fakturor (skriv)',
'suppliers:read': 'Leverantörer (läs)',
'reports:read': 'Rapporter (läs)',
}
const ALL_SCOPES: Scope[] = SCOPE_GROUPS.flatMap((g) => {
const out: Scope[] = []
if (g.read) out.push(g.read.scope)
if (g.write) out.push(g.write.scope)
return out
})
interface ApiKey {
id: string
@@ -426,46 +461,52 @@ export function ApiKeysPanel() {
<div key={group.domain} className="space-y-1.5">
<p className="text-sm font-medium">{group.label}</p>
<div className="space-y-1 pl-1">
<label className="flex items-center gap-2 cursor-pointer">
<Checkbox
checked={newKeyScopes.has(group.read)}
onCheckedChange={(checked) => {
setNewKeyScopes((prev) => {
const next = new Set(prev)
if (checked) {
next.add(group.read)
} else {
next.delete(group.read)
// Remove write too — write without read makes no sense
if (group.write) next.delete(group.write)
}
return next
})
}}
/>
<span className="text-xs text-muted-foreground">{group.readLabel}</span>
<span className="text-[10px] tabular-nums text-muted-foreground/60">{group.readTools} verktyg</span>
</label>
{group.write && (
{group.read && (
<label className="flex items-center gap-2 cursor-pointer">
<Checkbox
checked={newKeyScopes.has(group.write)}
checked={newKeyScopes.has(group.read.scope)}
onCheckedChange={(checked) => {
setNewKeyScopes((prev) => {
const next = new Set(prev)
if (checked) {
next.add(group.write!)
// Auto-check read when write is checked
next.add(group.read)
next.add(group.read!.scope)
} else {
next.delete(group.write!)
next.delete(group.read!.scope)
// Remove write too — write without read makes no sense
if (group.write) next.delete(group.write.scope)
}
return next
})
}}
/>
<span className="text-xs text-muted-foreground">{group.writeLabel}</span>
<span className="text-[10px] tabular-nums text-muted-foreground/60">{group.writeTools} verktyg</span>
<span className="text-xs text-muted-foreground">{group.read.label}</span>
<span className="text-[10px] tabular-nums text-muted-foreground/60">
{group.read.tools > 0 ? `${group.read.tools} verktyg` : 'REST'}
</span>
</label>
)}
{group.write && (
<label className="flex items-center gap-2 cursor-pointer">
<Checkbox
checked={newKeyScopes.has(group.write.scope)}
onCheckedChange={(checked) => {
setNewKeyScopes((prev) => {
const next = new Set(prev)
if (checked) {
next.add(group.write!.scope)
// Auto-check read when write is checked (when read exists)
if (group.read) next.add(group.read.scope)
} else {
next.delete(group.write!.scope)
}
return next
})
}}
/>
<span className="text-xs text-muted-foreground">{group.write.label}</span>
<span className="text-[10px] tabular-nums text-muted-foreground/60">
{group.write.tools > 0 ? `${group.write.tools} verktyg` : 'REST'}
</span>
</label>
)}
</div>
+234
View File
@@ -0,0 +1,234 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Plus, Trash2, Globe } from 'lucide-react'
interface OAuthClient {
id: string
client_name: string
redirect_uri: string
created_at: string
revoked_at: string | null
}
export function OAuthClientsPanel() {
const { toast } = useToast()
const { dialogProps: revokeDialogProps, confirm: confirmRevoke } = useDestructiveConfirm()
const [clients, setClients] = useState<OAuthClient[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isCreating, setIsCreating] = useState(false)
const [showCreateDialog, setShowCreateDialog] = useState(false)
const [clientName, setClientName] = useState('')
const [redirectUri, setRedirectUri] = useState('')
const fetchClients = useCallback(async () => {
try {
const res = await fetch('/api/settings/oauth-clients')
const json = await res.json()
if (json.data) {
setClients(json.data.filter((c: OAuthClient) => !c.revoked_at))
}
} catch {
toast({ title: 'Kunde inte hämta OAuth-klienter', variant: 'destructive' })
} finally {
setIsLoading(false)
}
}, [toast])
useEffect(() => {
fetchClients()
}, [fetchClients])
async function handleCreate() {
setIsCreating(true)
try {
const res = await fetch('/api/settings/oauth-clients', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_name: clientName.trim() || 'OAuth-klient',
redirect_uri: redirectUri.trim(),
}),
})
const json = await res.json()
if (!res.ok) {
toast({ title: json.error ?? 'Kunde inte registrera redirect URI', variant: 'destructive' })
return
}
setShowCreateDialog(false)
setClientName('')
setRedirectUri('')
fetchClients()
} catch {
toast({ title: 'Kunde inte registrera redirect URI', variant: 'destructive' })
} finally {
setIsCreating(false)
}
}
async function handleRevoke(id: string, name: string) {
const ok = await confirmRevoke({
title: 'Återkalla OAuth-klient',
description: `"${name}" tas bort från allowlist. Pågående auth-flöden slutar fungera direkt; redan utfärdade API-nycklar fortsätter att gälla tills de återkallas separat.`,
confirmLabel: 'Återkalla',
})
if (!ok) return
try {
const res = await fetch(`/api/settings/oauth-clients/${id}`, { method: 'DELETE' })
if (!res.ok) {
// Surface the server error rather than optimistically pretending the
// revocation succeeded — a silent fail leaves the row in the
// allowlist while the UI says it's gone, which is the opposite of
// what the user expected.
const body = await res.json().catch(() => ({}))
toast({
title: body?.error || 'Kunde inte återkalla klient',
variant: 'destructive',
})
return
}
setClients((prev) => prev.filter((c) => c.id !== id))
toast({ title: 'Klient återkallad' })
} catch {
toast({ title: 'Kunde inte återkalla klient', variant: 'destructive' })
}
}
function formatDate(iso: string) {
return new Date(iso).toLocaleDateString('sv-SE', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>OAuth-klienter</CardTitle>
<CardDescription>
Registrera redirect-URI:er för egenutvecklade MCP-klienter. Claude.ai och localhost
är redan godkända som standard — registrera bara här om du bygger en egen app.
</CardDescription>
</div>
<Button size="sm" onClick={() => setShowCreateDialog(true)}>
<Plus className="mr-1.5 h-3.5 w-3.5" />
Registrera URI
</Button>
</div>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : clients.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<Globe className="h-8 w-8 text-muted-foreground/50 mb-3" />
<p className="text-sm text-muted-foreground">Inga egna OAuth-klienter registrerade.</p>
<p className="text-xs text-muted-foreground mt-1">
Bygger du en agent som ska ansluta via OAuth? Registrera dess callback-URI här.
</p>
</div>
) : (
<div className="space-y-3">
{clients.map((c) => (
<div
key={c.id}
className="flex items-center justify-between rounded-md border px-4 py-3"
>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">{c.client_name}</p>
<div className="flex items-center gap-3 mt-1">
<code className="text-xs text-muted-foreground font-mono truncate">
{c.redirect_uri}
</code>
<span className="text-xs text-muted-foreground whitespace-nowrap">
Registrerad {formatDate(c.created_at)}
</span>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => handleRevoke(c.id, c.client_name)}
aria-label={`Återkalla ${c.client_name}`}
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Registrera redirect URI</DialogTitle>
<DialogDescription>
Måste vara en exakt URL som börjar med https://. Den jämförs sedan ord-för-ord mot
redirect_uri-parametern i OAuth-flödet.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="client-name">Klientnamn</Label>
<Input
id="client-name"
placeholder="t.ex. Min bokföringsagent"
value={clientName}
onChange={(e) => setClientName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="redirect-uri">Redirect URI</Label>
<Input
id="redirect-uri"
type="url"
placeholder="https://min-agent.exempel.se/oauth/callback"
value={redirectUri}
onChange={(e) => setRedirectUri(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && redirectUri && handleCreate()}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreateDialog(false)}>
Avbryt
</Button>
<Button onClick={handleCreate} disabled={isCreating || !redirectUri.trim()}>
{isCreating && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
Registrera
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<DestructiveConfirmDialog {...revokeDialogProps} />
</div>
)
}