0bc81d4c88
* feat(auth): SoD acknowledge on stage+approve keys + agent:write scope for memory tools Segregation of duties on API keys is now warn + explicit acknowledgement (not block): minting a key with any staging write scope AND pending_operations:approve returns 409 API_KEY_SOD_CONFLICT unless the caller re-POSTs with acknowledge_sod: true. The acknowledgement is recorded (sod_acknowledged_at / sod_acknowledged_by) for an auditable risk acceptance (ISO 27001:2022 A.5.3 / BFNAR 2013:2). The create UI surfaces an inline warning and an explicit confirm dialog before submitting the ack — the default "all scopes ticked" create routes through that path. Also introduces the agent:write scope and maps the previously-UNMAPPED memory tools gnubok_remember_fact / gnubok_forget_fact to it. Because unmapped tools were callable by any key, the migration grandfathers agent:write onto every existing non-revoked key with an explicit scope list so nothing regresses; new keys must opt in. agent:write is deliberately excluded from the default grants and is NOT a staging scope (no SoD conflict with approve). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(db): enforce both-or-neither on the SoD acknowledgement pair Review finding (Greptile P2): sod_acknowledged_at/sod_acknowledged_by were independently nullable, so a partial write could silently pass and undermine the auditable risk acceptance (ISO 27001 A.5.3 / SOC 2 CC6.1). Adds a paired-NULL CHECK constraint + pg-real coverage for both partial-write directions. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(auth)+feat(auth): compliance-review round — self-attestation documented, ack logged, SoD boundary assumption captured - Migration header now states explicitly that the SoD acknowledgement is a SELF-attestation by deliberate design (enskild firma has no second person; the claude.ai approval flow needs stage+approve on one credential) — the control objective is informed consent + audit record, not dual control. - The acknowledge_sod=true path now emits a structured log.warn (api_key.sod_acknowledged with key id/prefix, conflicting scope, scopes, acknowledger, company) so the acceptance lands in the logging pipeline in addition to the sod_acknowledged_* columns (ASVS V16.1.1). - STAGING_SCOPES carries the documented system control (BFNAR 2013:2 systemdokumentation) for why agent:write is not a staging scope: memory tools write advisory agent context and cannot stage räkenskapsinformation. Dismissed as by-design/verified: hard-block and second-approver remediations (user decision: warn + acknowledge); scope-update gap (the [id] route only supports DELETE — scopes are immutable post-creation); session-auth concern (withRouteContext is cookie+MFA only; API-key auth exists only on /api/v1 and MCP). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore: re-trigger CI (Supabase Preview 502 infra hiccup) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
145 lines
4.4 KiB
TypeScript
145 lines
4.4 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import {
|
|
generateApiKey,
|
|
DEFAULT_SCOPES,
|
|
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 { ApiKeyScope } from '@/lib/auth/api-keys'
|
|
|
|
/** 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
|
|
|
|
const { data, error } = await supabase
|
|
.from('api_keys')
|
|
.select('id, key_prefix, name, scopes, rate_limit_rpm, 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
|
|
try {
|
|
const body = await request.json()
|
|
if (body.name && typeof body.name === 'string') {
|
|
name = body.name.slice(0, 100)
|
|
}
|
|
acknowledgeSod = body.acknowledge_sod === true
|
|
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.
|
|
}
|
|
|
|
// 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()
|
|
|
|
const { data, error } = await supabase
|
|
.from('api_keys')
|
|
.insert({
|
|
user_id: user.id,
|
|
company_id: companyId,
|
|
key_hash: hash,
|
|
key_prefix: prefix,
|
|
name,
|
|
scopes,
|
|
...(sodAcknowledgedAt
|
|
? { sod_acknowledged_at: sodAcknowledgedAt, sod_acknowledged_by: user.id }
|
|
: {}),
|
|
})
|
|
.select('id, key_prefix, name, scopes, created_at')
|
|
.single()
|
|
|
|
if (error) {
|
|
log.error('api_key insert failed', error)
|
|
return errorResponseFromCode('API_KEY_CREATE_FAILED', log, {
|
|
requestId,
|
|
details: { reason: error.message },
|
|
})
|
|
}
|
|
|
|
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 },
|
|
)
|