fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const mockSupabase = {
|
||||
auth: { getUser: vi.fn() },
|
||||
from: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
const getActiveCompanyIdMock = vi.fn()
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
|
||||
}))
|
||||
|
||||
const requireWritePermissionMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
|
||||
}))
|
||||
|
||||
import { PATCH } from '../route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
const params = { params: Promise.resolve({ id: 'key-1' }) }
|
||||
|
||||
/**
|
||||
* Chainable proxy over .update().eq().eq().is().select().maybeSingle().
|
||||
* Records the update payload and every .eq()/.is() filter, so the tests can
|
||||
* assert on tenant scoping rather than trusting it.
|
||||
*/
|
||||
function setupFrom(result: { data?: unknown; error?: unknown }) {
|
||||
const updateSpy = vi.fn()
|
||||
const filters: Array<[string, unknown]> = []
|
||||
|
||||
mockSupabase.from.mockImplementation(() => {
|
||||
const chain: Record<string, unknown> = {}
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_t, prop) {
|
||||
if (prop === 'update') {
|
||||
return (payload: unknown) => {
|
||||
updateSpy(payload)
|
||||
return new Proxy(chain, handler)
|
||||
}
|
||||
}
|
||||
if (prop === 'eq' || prop === 'is') {
|
||||
return (col: string, val: unknown) => {
|
||||
filters.push([col, val])
|
||||
return new Proxy(chain, handler)
|
||||
}
|
||||
}
|
||||
if (prop === 'maybeSingle' || prop === 'single') {
|
||||
return () =>
|
||||
Promise.resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
}
|
||||
return () => new Proxy(chain, handler)
|
||||
},
|
||||
}
|
||||
return new Proxy(chain, handler)
|
||||
})
|
||||
|
||||
return { updateSpy, filters }
|
||||
}
|
||||
|
||||
function patch(body: unknown) {
|
||||
return createMockRequest('/api/settings/api-keys/key-1', { method: 'PATCH', body })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
getActiveCompanyIdMock.mockResolvedValue('company-1')
|
||||
requireWritePermissionMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('PATCH /api/settings/api-keys/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('sets a ceiling and scopes the update to the active company and unrevoked keys', async () => {
|
||||
const { updateSpy, filters } = setupFrom({
|
||||
data: { id: 'key-1', unattended_commit_limit: 5000 },
|
||||
})
|
||||
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { unattended_commit_limit: number }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.unattended_commit_limit).toBe(5000)
|
||||
expect(updateSpy).toHaveBeenCalledWith({ unattended_commit_limit: 5000 })
|
||||
// Tenant scoping is the whole security story of this route: without the
|
||||
// company_id filter, any authenticated user could raise any key's
|
||||
// authority by guessing an id.
|
||||
expect(filters).toContainEqual(['company_id', 'company-1'])
|
||||
expect(filters).toContainEqual(['id', 'key-1'])
|
||||
expect(filters).toContainEqual(['revoked_at', null])
|
||||
})
|
||||
|
||||
it('accepts null to clear the ceiling', async () => {
|
||||
const { updateSpy } = setupFrom({ data: { id: 'key-1', unattended_commit_limit: null } })
|
||||
const res = await PATCH(patch({ unattended_commit_limit: null }), params)
|
||||
expect(res.status).toBe(200)
|
||||
expect(updateSpy).toHaveBeenCalledWith({ unattended_commit_limit: null })
|
||||
})
|
||||
|
||||
it('rejects zero, negatives and non-numbers with 400', async () => {
|
||||
setupFrom({ data: { id: 'key-1' } })
|
||||
for (const bad of [0, -1, '5000', {}]) {
|
||||
const res = await PATCH(patch({ unattended_commit_limit: bad }), params)
|
||||
expect(res.status).toBe(400)
|
||||
}
|
||||
})
|
||||
|
||||
it('requires the field rather than treating an empty body as "clear it"', async () => {
|
||||
setupFrom({ data: { id: 'key-1' } })
|
||||
const res = await PATCH(patch({}), params)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the key belongs to another company or is revoked', async () => {
|
||||
setupFrom({ data: null })
|
||||
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 500 when the update fails', async () => {
|
||||
setupFrom({ error: { message: 'boom' } })
|
||||
const res = await PATCH(patch({ unattended_commit_limit: 5000 }), params)
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
* Approval authority in SEK: the largest amount this key may commit with no
|
||||
* human in the loop. null clears the ceiling (unlimited, the default).
|
||||
*
|
||||
* Bounded at 1 000 000 000 so a typo cannot store a number the numeric(14,2)
|
||||
* column would reject at insert time with a raw Postgres error. The DB CHECK
|
||||
* (> 0) is the real guarantee; this is the friendly message in front of it.
|
||||
*/
|
||||
const patchSchema = z.object({
|
||||
unattended_commit_limit: z.number().positive().max(1_000_000_000).nullable(),
|
||||
})
|
||||
|
||||
/**
|
||||
* DELETE /api/settings/api-keys/[id]: Revoke an API key (soft delete)
|
||||
*/
|
||||
export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'api_key.revoke',
|
||||
async (_request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
const { error } = await supabase
|
||||
.from('api_keys')
|
||||
.update({ revoked_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.is('revoked_at', null)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
/**
|
||||
* PATCH /api/settings/api-keys/[id]: set the key's unattended commit limit.
|
||||
*
|
||||
* Deliberately narrow: name and scopes are NOT editable here. Silently
|
||||
* widening a key's scopes after the fact would defeat the point of showing the
|
||||
* scope list at creation, and the separation-of-duties check
|
||||
* (findStageApproveConflict) runs only on POST.
|
||||
*/
|
||||
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'api_key.update',
|
||||
async (request, ctx, { params }) => {
|
||||
const { id } = await params
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
const validation = await validateBody(request, patchSchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
// Revoked keys are deliberately excluded: raising a limit on a key that no
|
||||
// longer authenticates reads as re-enabling it, and it does not.
|
||||
const { data, error } = await supabase
|
||||
.from('api_keys')
|
||||
.update({ unattended_commit_limit: validation.data.unattended_commit_limit })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.is('revoked_at', null)
|
||||
.select('id, unattended_commit_limit')
|
||||
.maybeSingle()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: 'API-nyckeln hittades inte.' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,246 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
// ── Mocks ──────────────────────────────────────────────────────────
|
||||
// withRouteContext resolves auth via requireAuth (createClient under the hood),
|
||||
// the active company via getActiveCompanyId, and the write gate via
|
||||
// requireWritePermission. Mock all three so we can drive each branch.
|
||||
|
||||
const mockSupabase = {
|
||||
auth: { getUser: vi.fn() },
|
||||
from: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
const getActiveCompanyIdMock = vi.fn()
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
|
||||
}))
|
||||
|
||||
const requireWritePermissionMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
// Records the payload passed to .insert(), and lets us program the count
|
||||
// returned by the quota pre-check and the row returned by the insert.
|
||||
function setupFrom(opts: {
|
||||
count?: number | null
|
||||
insertResult?: { data?: unknown; error?: unknown }
|
||||
}) {
|
||||
const insertSpy = vi.fn()
|
||||
|
||||
mockSupabase.from.mockImplementation(() => {
|
||||
// The quota pre-check: .select(..., { head: true }).eq().is() → resolves
|
||||
// to { count }. The insert: .insert().select().single() → resolves to the
|
||||
// row. We expose both via a single chainable proxy whose terminal value
|
||||
// depends on whether insert() was called.
|
||||
let isInsert = false
|
||||
const result = () =>
|
||||
isInsert
|
||||
? Promise.resolve({
|
||||
data: opts.insertResult?.data ?? null,
|
||||
error: opts.insertResult?.error ?? null,
|
||||
})
|
||||
: Promise.resolve({ count: opts.count ?? 0, data: null, error: null })
|
||||
|
||||
const chain: Record<string, unknown> = {}
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => resolve(result() as unknown)
|
||||
}
|
||||
if (prop === 'insert') {
|
||||
return (payload: unknown) => {
|
||||
isInsert = true
|
||||
insertSpy(payload)
|
||||
return new Proxy(chain, handler)
|
||||
}
|
||||
}
|
||||
if (prop === 'single' || prop === 'maybeSingle') {
|
||||
return () => result()
|
||||
}
|
||||
return () => new Proxy(chain, handler)
|
||||
},
|
||||
}
|
||||
return new Proxy(chain, handler)
|
||||
})
|
||||
|
||||
return { insertSpy }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
getActiveCompanyIdMock.mockResolvedValue('company-1')
|
||||
requireWritePermissionMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('POST /api/settings/api-keys', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: { name: 'k', scopes: ['reports:read'] },
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid scope', async () => {
|
||||
setupFrom({ count: 0 })
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: { name: 'k', scopes: ['totally:bogus'] },
|
||||
}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('API_KEY_SCOPE_INVALID')
|
||||
})
|
||||
|
||||
it('returns 400 for the reserved OAuth marker name (would fake a Claude connection)', async () => {
|
||||
const { insertSpy } = setupFrom({ count: 0 })
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: { name: ' MCP-klient (OAuth) ', scopes: ['reports:read'] },
|
||||
}),
|
||||
{ params: Promise.resolve({}) },
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: { code: string; details: { field: string; reason: string } }
|
||||
}>(res)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
expect(body.error.details).toMatchObject({ field: 'name', reason: 'reserved' })
|
||||
expect(insertSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 409 API_KEY_SOD_CONFLICT for stage+approve without acknowledgement', async () => {
|
||||
setupFrom({ count: 0 })
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'k',
|
||||
scopes: ['invoices:write', 'pending_operations:approve'],
|
||||
},
|
||||
}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: { code: string; details: { conflicting_scope: string; approve_scope: string } }
|
||||
}>(res)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('API_KEY_SOD_CONFLICT')
|
||||
expect(body.error.details.conflicting_scope).toBe('invoices:write')
|
||||
expect(body.error.details.approve_scope).toBe('pending_operations:approve')
|
||||
})
|
||||
|
||||
it('records sod_acknowledged_at/by in the insert when acknowledge_sod is true', async () => {
|
||||
const { insertSpy } = setupFrom({
|
||||
count: 0,
|
||||
insertResult: {
|
||||
data: {
|
||||
id: 'ak-1',
|
||||
key_prefix: 'gnubok_sk_abcd',
|
||||
name: 'k',
|
||||
scopes: ['invoices:write', 'pending_operations:approve'],
|
||||
created_at: '2026-06-05T10:00:00Z',
|
||||
},
|
||||
},
|
||||
})
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'k',
|
||||
scopes: ['invoices:write', 'pending_operations:approve'],
|
||||
acknowledge_sod: true,
|
||||
},
|
||||
}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { key: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.key).toMatch(/^gnubok_sk_/)
|
||||
|
||||
expect(insertSpy).toHaveBeenCalledTimes(1)
|
||||
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
|
||||
expect(payload.sod_acknowledged_by).toBe('user-1')
|
||||
expect(typeof payload.sod_acknowledged_at).toBe('string')
|
||||
// ISO timestamp
|
||||
expect(payload.sod_acknowledged_at).toMatch(/^\d{4}-\d{2}-\d{2}T/)
|
||||
})
|
||||
|
||||
it('creates a clean key without approve scope and does not set SoD fields', async () => {
|
||||
const { insertSpy } = setupFrom({
|
||||
count: 0,
|
||||
insertResult: {
|
||||
data: {
|
||||
id: 'ak-2',
|
||||
key_prefix: 'gnubok_sk_efgh',
|
||||
name: 'reader',
|
||||
scopes: ['reports:read'],
|
||||
created_at: '2026-06-05T10:00:00Z',
|
||||
},
|
||||
},
|
||||
})
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: { name: 'reader', scopes: ['reports:read'] },
|
||||
}),
|
||||
)
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(200)
|
||||
|
||||
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
|
||||
expect(payload).not.toHaveProperty('sod_acknowledged_at')
|
||||
expect(payload).not.toHaveProperty('sod_acknowledged_by')
|
||||
expect(payload.scopes).toEqual(['reports:read'])
|
||||
// Default mode is live, bound to the active company.
|
||||
expect(payload.mode).toBe('live')
|
||||
expect(payload.company_id).toBe('company-1')
|
||||
})
|
||||
|
||||
it('creates a test key bound to the active company with mode=test', async () => {
|
||||
const { insertSpy } = setupFrom({
|
||||
count: 0,
|
||||
insertResult: {
|
||||
data: {
|
||||
id: 'ak-3',
|
||||
key_prefix: 'gnubok_sk_test_abc',
|
||||
name: 'pilot',
|
||||
scopes: ['reports:read'],
|
||||
mode: 'test',
|
||||
created_at: '2026-06-05T10:00:00Z',
|
||||
},
|
||||
},
|
||||
})
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: { name: 'pilot', scopes: ['reports:read'], mode: 'test' },
|
||||
}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { key: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
// Real generateApiKey('test') runs: the returned secret carries the infix.
|
||||
expect(body.data.key).toMatch(/^gnubok_sk_test_/)
|
||||
|
||||
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
|
||||
expect(payload.mode).toBe('test')
|
||||
// Test keys are simulation-only: they bind to the active company (the v1
|
||||
// wrapper forces dry-run so they never persist).
|
||||
expect(payload.company_id).toBe('company-1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
generateApiKey,
|
||||
DEFAULT_SCOPES,
|
||||
OAUTH_MCP_KEY_NAME,
|
||||
validateScopes,
|
||||
findStageApproveConflict,
|
||||
} from '@/lib/auth/api-keys'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { ApiKeyMode, ApiKeyScope } from '@/lib/auth/api-keys'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
/** GET /api/settings/api-keys: list the company's API keys (key value never returned). */
|
||||
export const GET = withRouteContext(
|
||||
'api_key.list',
|
||||
async (_request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
// Both live and test keys for the active company. (Test keys are bound to the
|
||||
// active company too: they're simulation-only, so they never write real data.)
|
||||
const { data, error } = await supabase
|
||||
.from('api_keys')
|
||||
.select('id, key_prefix, name, scopes, mode, rate_limit_rpm, unattended_commit_limit, last_used_at, revoked_at, created_at')
|
||||
.eq('company_id', companyId)
|
||||
.order('created_at', { ascending: false })
|
||||
|
||||
if (error) {
|
||||
log.error('api_keys list failed', error)
|
||||
return errorResponse(error, log, { requestId })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* POST /api/settings/api-keys: create a new API key.
|
||||
*
|
||||
* Returns the full key exactly once; after this the prefix is the only
|
||||
* stored representation.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'api_key.create',
|
||||
async (request, ctx) => {
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
|
||||
let name = 'Unnamed key'
|
||||
let scopes: ApiKeyScope[] = DEFAULT_SCOPES
|
||||
let acknowledgeSod = false
|
||||
let mode: ApiKeyMode = 'live'
|
||||
try {
|
||||
const body = await request.json()
|
||||
if (body.name && typeof body.name === 'string') {
|
||||
name = body.name.slice(0, 100)
|
||||
}
|
||||
acknowledgeSod = body.acknowledge_sod === true
|
||||
if (body.mode === 'test') mode = 'test'
|
||||
const parsed = validateScopes(body.scopes)
|
||||
if (parsed) {
|
||||
scopes = parsed
|
||||
} else if (body.scopes !== undefined) {
|
||||
return errorResponseFromCode('API_KEY_SCOPE_INVALID', log, {
|
||||
requestId,
|
||||
details: { received: body.scopes },
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Empty body: use defaults.
|
||||
}
|
||||
|
||||
// The OAuth token route's key name is the marker the Hem checklist reads
|
||||
// as "connected to Claude" (there is no source column). A hand-minted key
|
||||
// with that name would tick the step without any connection, so the name
|
||||
// is reserved for the OAuth path.
|
||||
if (name.trim() === OAUTH_MCP_KEY_NAME) {
|
||||
return errorResponseFromCode('VALIDATION_ERROR', log, {
|
||||
requestId,
|
||||
details: { field: 'name', reason: 'reserved', reserved: OAUTH_MCP_KEY_NAME },
|
||||
})
|
||||
}
|
||||
|
||||
// Both live and test keys bind to the active company. A test key is
|
||||
// simulation-only (the v1 wrapper forces dry-run on every write) so it can
|
||||
// safely point at the real company without ever persisting anything.
|
||||
|
||||
// Segregation of duties: warn + require explicit acknowledgement (not block)
|
||||
// when a single key both stages bookkeeping AND can approve it. Surfacing a
|
||||
// 409 lets the UI raise an explicit confirm dialog and the agent inform the
|
||||
// user before re-POSTing with acknowledge_sod: true.
|
||||
const conflictingScope = findStageApproveConflict(scopes)
|
||||
if (conflictingScope && !acknowledgeSod) {
|
||||
return errorResponseFromCode('API_KEY_SOD_CONFLICT', log, {
|
||||
requestId,
|
||||
details: {
|
||||
conflicting_scope: conflictingScope,
|
||||
approve_scope: 'pending_operations:approve',
|
||||
},
|
||||
})
|
||||
}
|
||||
const sodAcknowledgedAt = conflictingScope ? new Date().toISOString() : null
|
||||
|
||||
const { count } = await supabase
|
||||
.from('api_keys')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.is('revoked_at', null)
|
||||
|
||||
if (count !== null && count >= 10) {
|
||||
return errorResponseFromCode('API_KEY_QUOTA_EXCEEDED', log, {
|
||||
requestId,
|
||||
details: { activeCount: count, limit: 10 },
|
||||
})
|
||||
}
|
||||
|
||||
const { key, hash, prefix } = generateApiKey(mode)
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('api_keys')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
company_id: companyId,
|
||||
key_hash: hash,
|
||||
key_prefix: prefix,
|
||||
name,
|
||||
scopes,
|
||||
mode,
|
||||
...(sodAcknowledgedAt
|
||||
? { sod_acknowledged_at: sodAcknowledgedAt, sod_acknowledged_by: user.id }
|
||||
: {}),
|
||||
})
|
||||
.select('id, key_prefix, name, scopes, mode, created_at')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
log.error('api_key insert failed', error)
|
||||
return errorResponseFromCode('API_KEY_CREATE_FAILED', log, {
|
||||
requestId,
|
||||
details: { reason: getUserErrorMessage(error) },
|
||||
})
|
||||
}
|
||||
|
||||
if (sodAcknowledgedAt) {
|
||||
// High-risk security event: the creator self-attested the stage+approve
|
||||
// combination. The durable record is the sod_acknowledged_* pair on the
|
||||
// key row; this structured entry additionally lands the acceptance in
|
||||
// the logging pipeline (ASVS V16.1.1 / SOC 2 CC6.1).
|
||||
log.warn('api_key.sod_acknowledged', {
|
||||
keyId: data.id,
|
||||
keyPrefix: data.key_prefix,
|
||||
conflictingScope,
|
||||
scopes,
|
||||
acknowledgedBy: user.id,
|
||||
companyId,
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
...data,
|
||||
key, // only time the full key is returned
|
||||
},
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
Reference in New Issue
Block a user