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:
@@ -0,0 +1,81 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('oauth-clients:delete')
|
||||
|
||||
/**
|
||||
* DELETE /api/settings/oauth-clients/[id] — revoke a redirect URI
|
||||
* registration. Soft-delete via revoked_at so the audit trail survives
|
||||
* and the same URI can be re-registered later.
|
||||
*
|
||||
* Emits an audit event so revocations are visible in processing_history —
|
||||
* revoking an OAuth client is a security-relevant access-control change
|
||||
* (SOC 2 CC7.2). Returns 404 when the row is unknown or already revoked
|
||||
* so callers can surface failures rather than treating "no-op" as success.
|
||||
*/
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { id } = await params
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const { data: rows, error } = await supabase
|
||||
.from('oauth_client_registrations')
|
||||
.update({ revoked_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.is('revoked_at', null)
|
||||
.select('id, redirect_uri, client_name')
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
if (!rows || rows.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'OAuth-klient hittades inte eller är redan återkallad.' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Audit the revocation. Failure to append must not break the user flow —
|
||||
// the revocation has already happened in the DB. We log the appendError
|
||||
// so a systematic outage is visible in operations rather than silently
|
||||
// degraded.
|
||||
try {
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
await appendProcessingHistory({
|
||||
companyId,
|
||||
correlationId: id,
|
||||
aggregateType: 'System',
|
||||
aggregateId: id,
|
||||
eventType: 'OAuthClientRevoked',
|
||||
payload: {
|
||||
client_id: id,
|
||||
// Note: redirect_uri may contain a host the user identifies with their
|
||||
// own infrastructure but is not PII per Art. 4(1). Stored to satisfy
|
||||
// SOC 2 CC7.2 "what was revoked" evidence trail.
|
||||
redirect_uri: rows[0].redirect_uri,
|
||||
},
|
||||
actor: { type: 'user', id: user.id },
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (auditErr) {
|
||||
log.warn('Failed to append OAuthClientRevoked audit event', auditErr)
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* GET /api/settings/oauth-clients — list the current user's registered
|
||||
* redirect URIs.
|
||||
* POST /api/settings/oauth-clients — register a new redirect URI for use
|
||||
* with the MCP OAuth flow.
|
||||
*
|
||||
* Built-in patterns (claude.ai, claude.com, localhost) bypass this table
|
||||
* entirely — registrations here are only for self-hosted custom apps.
|
||||
*/
|
||||
|
||||
const RegistrationSchema = z.object({
|
||||
client_name: z.string().trim().min(1).max(100),
|
||||
// Require https for non-loopback URIs. We reject loopback here because
|
||||
// localhost is already on the built-in allowlist — there's no reason to
|
||||
// register it explicitly.
|
||||
redirect_uri: z
|
||||
.string()
|
||||
.url('redirect_uri must be a valid URL')
|
||||
.refine((u) => u.startsWith('https://'), 'redirect_uri must use https://')
|
||||
.refine(
|
||||
(u) => !/^https:\/\/(localhost|127\.0\.0\.1|::1)(:|\/|$)/i.test(u),
|
||||
'localhost is already allowed without registration'
|
||||
)
|
||||
.max(500),
|
||||
})
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('oauth_client_registrations')
|
||||
.select('id, client_name, redirect_uri, created_at, revoked_at')
|
||||
.eq('user_id', user.id)
|
||||
.order('created_at', { ascending: false })
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
let body: z.infer<typeof RegistrationSchema>
|
||||
try {
|
||||
const json = await request.json()
|
||||
body = RegistrationSchema.parse(json)
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Invalid request body' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('oauth_client_registrations')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
client_name: body.client_name,
|
||||
redirect_uri: body.redirect_uri,
|
||||
})
|
||||
.select('id, client_name, redirect_uri, created_at')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
// Unique-index violation on redirect_uri → 409
|
||||
if (error.code === '23505') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Den här redirect URI:n är redan registrerad.' },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
Reference in New Issue
Block a user