diff --git a/console/src/features/settings/security-config-panel.tsx b/console/src/features/settings/security-config-panel.tsx new file mode 100644 index 0000000..c76fdd6 --- /dev/null +++ b/console/src/features/settings/security-config-panel.tsx @@ -0,0 +1,148 @@ +import { useEffect, useState } from 'react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { Loader2 } from 'lucide-react' +import { Badge, Button, Input, Segmented, SettingRow, SettingSection, Switch, toast } from '@/components/ui' +import { useAuth } from '@/lib/auth' +import { type DetectorZone, getSecurityConfig, saveSecurityConfig, type SecurityConfig, type SecurityConfigWrite, type SecurityProfile } from '@/lib/admin' +import { useTranslation } from '@/lib/i18n' + +const KEY = ['security-config'] as const + +const ZONES: { id: DetectorZone; labelKey: 'settings.security.zone.input' | 'settings.security.zone.output' | 'settings.security.zone.tool_return' | 'settings.security.zone.assistant' }[] = [ + { id: 'gateway_input', labelKey: 'settings.security.zone.input' }, + { id: 'gateway_output', labelKey: 'settings.security.zone.output' }, + { id: 'tool_return', labelKey: 'settings.security.zone.tool_return' }, + { id: 'assistant_intent', labelKey: 'settings.security.zone.assistant' }, +] + +type Draft = SecurityConfig & { judge_api_key: string | null } + +function toDraft(config: SecurityConfig): Draft { + return { ...config, judge_api_key: null } +} + +function toWrite(draft: Draft): SecurityConfigWrite { + return { + profile: draft.profile, + zone_overrides: draft.detector_zones, + judge_endpoint: draft.judge_endpoint, + judge_model: draft.judge_model, + judge_api_key: draft.judge_api_key, + judge_timeout_seconds: draft.judge_timeout_seconds, + } +} + +export function SecurityConfigPanel() { + const { t } = useTranslation() + const canManage = useAuth().has('settings.manage') + const queryClient = useQueryClient() + const { data, isLoading, isError } = useQuery({ queryKey: KEY, queryFn: getSecurityConfig }) + const [draft, setDraft] = useState(null) + const [saving, setSaving] = useState(false) + + useEffect(() => { + if (data) setDraft(toDraft(data)) + }, [data]) + + const save = async (body: SecurityConfigWrite) => { + setSaving(true) + try { + const next = await saveSecurityConfig(body) + queryClient.setQueryData(KEY, next) + setDraft(toDraft(next)) + toast.success(t('settings.security.saved')) + } catch (error) { + toast.error((error as Error).message) + } finally { + setSaving(false) + } + } + + if (isLoading || !draft) { + return ( + + + + ) + } + if (isError) { + return

{t('settings.security.load_failed')}

+ } + + const updateZone = (zone: DetectorZone, detector: string, enabled: boolean) => { + setDraft((current) => { + if (!current) return current + const names = current.detector_zones[zone] + const next = enabled ? [...names, detector] : names.filter((name) => name !== detector) + return { ...current, detector_zones: { ...current.detector_zones, [zone]: next } } + }) + } + + const profileItems = [ + { value: 'lightweight', label: t('settings.security.profile.lightweight') }, + { value: 'standard', label: t('settings.security.profile.standard') }, + { value: 'strict', label: t('settings.security.profile.strict') }, + { value: 'air_gapped', label: t('settings.security.profile.air_gapped') }, + ] + + return ( +
+ + + save({ ...toWrite(draft), profile: value as SecurityProfile, zone_overrides: {} })} + items={profileItems} + className="max-w-full overflow-x-auto" + /> + + + {t('settings.security.active')} + + + + +
+ {ZONES.map((zone) => ( +
+
{t(zone.labelKey)}
+
+ {draft.available_detectors.map((detector) => ( + + ))} +
+
+ ))} +
+
+ + + + setDraft({ ...draft, judge_endpoint: event.target.value })} disabled={!canManage || saving} className="w-full" /> + + + setDraft({ ...draft, judge_model: event.target.value })} disabled={!canManage || saving} className="w-full" /> + + + setDraft({ ...draft, judge_api_key: event.target.value })} disabled={!canManage || saving} className="w-full" /> + + + setDraft({ ...draft, judge_timeout_seconds: Number(event.target.value) || 1 })} disabled={!canManage || saving} className="w-28" /> + + + + + +
+ ) +} diff --git a/console/src/features/settings/settings-page.tsx b/console/src/features/settings/settings-page.tsx index d12f0c2..a4d9b4b 100644 --- a/console/src/features/settings/settings-page.tsx +++ b/console/src/features/settings/settings-page.tsx @@ -16,6 +16,7 @@ import { type MessageKey, useTranslation } from '@/lib/i18n' import { cn } from '@/lib/utils' import { BackupSettings } from '../backup/backup-settings' import { GatewayUpstreamPanel } from './gateway-upstream' +import { SecurityConfigPanel } from './security-config-panel' import { useSettingsForm } from './use-console-settings' /** 设置面板统一保存条:仅有未保存更改且具「修改设置」权限时可点。 */ @@ -67,6 +68,7 @@ interface Cat { const CATS: Cat[] = [ { id: 'instance', labelKey: 'settings.cat.instance', icon: SlidersHorizontal, scope: 'global' }, { id: 'gateway', labelKey: 'settings.cat.gateway', icon: ShieldCheck, scope: 'global' }, + { id: 'security', labelKey: 'settings.cat.security', icon: ShieldCheck, scope: 'global' }, { id: 'runtime', labelKey: 'settings.cat.runtime', icon: ServerCog, scope: 'global' }, { id: 'about', labelKey: 'settings.cat.about', icon: Info, scope: 'global' }, { id: 'local', labelKey: 'settings.cat.local', icon: DatabaseBackup, scope: 'personal' }, @@ -154,6 +156,7 @@ export function SettingsPage() {
{cat === 'instance' && } {cat === 'gateway' && } + {cat === 'security' && } {cat === 'runtime' && } {cat === 'local' && } {cat === 'developer' && } diff --git a/console/src/lib/admin/index.ts b/console/src/lib/admin/index.ts index d23d831..bc9f8e6 100644 --- a/console/src/lib/admin/index.ts +++ b/console/src/lib/admin/index.ts @@ -229,3 +229,32 @@ export interface ConsoleSettings extends ConsoleSettingsWrite { export const getConsoleSettings = () => api('/admin/settings') export const saveConsoleSettings = (b: ConsoleSettingsWrite) => api('/admin/settings', { method: 'PUT', body: JSON.stringify(b) }) + +// ── 分级安全配置(四区检测器 + 预设档;judge 密钥只写不回)──────────── +export type SecurityProfile = 'lightweight' | 'standard' | 'strict' | 'air_gapped' +export type DetectorZone = 'gateway_input' | 'gateway_output' | 'tool_return' | 'assistant_intent' + +export interface SecurityConfig { + profile: SecurityProfile + detector_zones: Record + available_detectors: string[] + judge_endpoint: string + judge_model: string + judge_api_key_masked: string + judge_api_key_set: boolean + judge_timeout_seconds: number +} + +export interface SecurityConfigWrite { + profile: SecurityProfile + zone_overrides: Partial> + judge_endpoint: string + judge_model: string + /** null 保留后端现有密钥;空串明确清除。 */ + judge_api_key: string | null + judge_timeout_seconds: number +} + +export const getSecurityConfig = () => api('/admin/security-config') +export const saveSecurityConfig = (b: SecurityConfigWrite) => + api('/admin/security-config', { method: 'PUT', body: JSON.stringify(b) }) diff --git a/console/src/lib/i18n/locales/en/settings.ts b/console/src/lib/i18n/locales/en/settings.ts index 7aec55d..e9af922 100644 --- a/console/src/lib/i18n/locales/en/settings.ts +++ b/console/src/lib/i18n/locales/en/settings.ts @@ -18,6 +18,7 @@ export const settings: Partial> = { 'settings.scope.personal': 'Personal settings', 'settings.cat.instance': 'Instance', 'settings.cat.gateway': 'Upstream', + 'settings.cat.security': 'Security policy', 'settings.cat.runtime': 'Runtime', 'settings.cat.about': 'About', 'settings.cat.local': 'Local preferences', @@ -122,4 +123,33 @@ export const settings: Partial> = { 'settings.up.test_ok': 'Connection OK · {ms}ms', 'settings.up.test_fail': 'Connection failed: {detail}', 'settings.up.saved': 'Saved and applied immediately (no restart needed)', + // Tiered security configuration + 'settings.security.title': 'Tiered security policy', + 'settings.security.desc': 'Choose detectors and presets by zone. Saved settings apply to the security pipeline immediately.', + 'settings.security.load_failed': 'Security configuration is unavailable', + 'settings.security.status': 'Runtime status', + 'settings.security.active': 'Applied', + 'settings.security.profile.label': 'Preset', + 'settings.security.profile.hint': 'Changing a preset clears manual zone overrides.', + 'settings.security.profile.lightweight': 'Lightweight', + 'settings.security.profile.standard': 'Standard', + 'settings.security.profile.strict': 'Strict', + 'settings.security.profile.air_gapped': 'Air-gapped', + 'settings.security.zones.title': 'Zone detectors', + 'settings.security.zones.desc': 'Save changes to make them overrides for the selected preset.', + 'settings.security.zone.input': 'Gateway input', + 'settings.security.zone.output': 'Gateway output', + 'settings.security.zone.tool_return': 'Tool return', + 'settings.security.zone.assistant': 'Assistant tool governance', + 'settings.security.judge.title': 'Judge backend', + 'settings.security.judge.desc': 'Keys are written to the backend only and are always masked here.', + 'settings.security.judge.endpoint': 'Endpoint', + 'settings.security.judge.model': 'Model', + 'settings.security.judge.key': 'API key', + 'settings.security.judge.key_set': 'Set {masked}; leave empty to keep it, then save an empty value to remove it', + 'settings.security.judge.key_unset': 'Not set', + 'settings.security.judge.timeout': 'Timeout (s)', + 'settings.security.save.label': 'Apply security configuration', + 'settings.security.save.hint': 'Applies immediately without a restart.', + 'settings.security.saved': 'Security configuration applied', } diff --git a/console/src/lib/i18n/locales/zh/settings.ts b/console/src/lib/i18n/locales/zh/settings.ts index 00356aa..9d0e25f 100644 --- a/console/src/lib/i18n/locales/zh/settings.ts +++ b/console/src/lib/i18n/locales/zh/settings.ts @@ -16,6 +16,7 @@ export const settings = { 'settings.scope.personal': '个人设置', 'settings.cat.instance': '实例信息', 'settings.cat.gateway': '上游接入', + 'settings.cat.security': '安全策略', 'settings.cat.runtime': '运行状态', 'settings.cat.about': '关于', 'settings.cat.local': '本机偏好', @@ -120,4 +121,33 @@ export const settings = { 'settings.up.test_ok': '连接正常 · {ms}ms', 'settings.up.test_fail': '连接失败:{detail}', 'settings.up.saved': '已保存,立即生效(无需重启)', + // 分级安全配置 + 'settings.security.title': '分级安全策略', + 'settings.security.desc': '按区域选择检测器与预设;保存后立即作用于安全管线。', + 'settings.security.load_failed': '安全配置不可用', + 'settings.security.status': '运行状态', + 'settings.security.active': '已生效', + 'settings.security.profile.label': '预设档', + 'settings.security.profile.hint': '选择预设会重置各区域的手动覆盖。', + 'settings.security.profile.lightweight': '轻量', + 'settings.security.profile.standard': '标准', + 'settings.security.profile.strict': '严格', + 'settings.security.profile.air_gapped': '合规隔离', + 'settings.security.zones.title': '区域检测器', + 'settings.security.zones.desc': '切换后保存,作为当前预设的区域覆盖。', + 'settings.security.zone.input': '网关输入', + 'settings.security.zone.output': '网关出口', + 'settings.security.zone.tool_return': '工具返回', + 'settings.security.zone.assistant': '助手工具治理', + 'settings.security.judge.title': 'Judge 后端', + 'settings.security.judge.desc': '密钥只写入后端,前端始终仅显示掩码。', + 'settings.security.judge.endpoint': '服务地址', + 'settings.security.judge.model': '模型名', + 'settings.security.judge.key': 'API 密钥', + 'settings.security.judge.key_set': '已设置 {masked};留空不改,清空后保存即移除', + 'settings.security.judge.key_unset': '未设置', + 'settings.security.judge.timeout': '超时(秒)', + 'settings.security.save.label': '应用安全配置', + 'settings.security.save.hint': '保存后立即生效,无需重启。', + 'settings.security.saved': '安全配置已应用', } as const diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 9951817..c617f4e 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "枢衡 Fulcrum API", - "version": "0.0.0" + "version": "0.5.0" }, "paths": { "/auth/login": { @@ -575,7 +575,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RoleWrite" + "$ref": "#/components/schemas/RoleUpdate" } } } @@ -1176,6 +1176,185 @@ } } }, + "/admin/teams/{team_id}/members": { + "get": { + "summary": "Team Members", + "operationId": "team_members_admin_teams__team_id__members_get", + "parameters": [ + { + "name": "team_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Team Id" + } + }, + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MembershipDTO" + }, + "title": "Response Team Members Admin Teams Team Id Members Get" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "post": { + "summary": "Add Team Member", + "operationId": "add_team_member_admin_teams__team_id__members_post", + "parameters": [ + { + "name": "team_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Team Id" + } + }, + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TeamMemberWrite" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MembershipDTO" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/admin/teams/{team_id}/members/{user_id}": { + "delete": { + "summary": "Remove Team Member", + "operationId": "remove_team_member_admin_teams__team_id__members__user_id__delete", + "parameters": [ + { + "name": "team_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Team Id" + } + }, + { + "name": "user_id", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "User Id" + } + }, + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/overview/stats": { "get": { "summary": "Overview Stats", @@ -1284,6 +1463,72 @@ } } }, + "/events/{event_id}/resolve": { + "post": { + "summary": "Resolve Event", + "description": "处置一条待审批事件:批准放行 / 维持阻断。落一条带 resolves 的处置判定点(append-only)。\n\n处置后原待审工单从墙上隐去,代之以放行/阻断结果行;原工单与本处置都留在审计链可溯源,\n处置人(actor)、决定与理由一并入证据。", + "operationId": "resolve_event_events__event_id__resolve_post", + "parameters": [ + { + "name": "event_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Event Id" + } + }, + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EventResolveRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EventResolveResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/audit": { "get": { "summary": "Audit Sessions", @@ -1609,10 +1854,10 @@ } } }, - "/assistant/actions": { + "/admin/settings": { "get": { - "summary": "Assistant Actions", - "operationId": "assistant_actions_assistant_actions_get", + "summary": "Get Settings", + "operationId": "get_settings_admin_settings_get", "parameters": [ { "name": "fulcrum_session", @@ -1637,11 +1882,7 @@ "content": { "application/json": { "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/AssistantActionDTO" - }, - "title": "Response Assistant Actions Assistant Actions Get" + "$ref": "#/components/schemas/ConsoleSettingsPublic" } } } @@ -1657,12 +1898,10 @@ } } } - } - }, - "/assistant/plan": { - "post": { - "summary": "Assistant Plan", - "operationId": "assistant_plan_assistant_plan_post", + }, + "put": { + "summary": "Put Settings", + "operationId": "put_settings_admin_settings_put", "parameters": [ { "name": "fulcrum_session", @@ -1686,7 +1925,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AssistantPlanRequest" + "$ref": "#/components/schemas/ConsoleSettingsWrite" } } } @@ -1697,7 +1936,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AssistantPlanResponse" + "$ref": "#/components/schemas/ConsoleSettingsPublic" } } } @@ -1715,10 +1954,10 @@ } } }, - "/admin/gateway-config": { + "/admin/security-config": { "get": { - "summary": "Get Config", - "operationId": "get_config_admin_gateway_config_get", + "summary": "Get Security Config", + "operationId": "get_security_config_admin_security_config_get", "parameters": [ { "name": "fulcrum_session", @@ -1743,7 +1982,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayConfigPublic" + "$ref": "#/components/schemas/SecurityConfigPublicDTO" } } } @@ -1761,8 +2000,8 @@ } }, "put": { - "summary": "Put Config", - "operationId": "put_config_admin_gateway_config_put", + "summary": "Put Security Config", + "operationId": "put_security_config_admin_security_config_put", "parameters": [ { "name": "fulcrum_session", @@ -1786,7 +2025,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayConfigWrite" + "$ref": "#/components/schemas/SecurityConfigWrite" } } } @@ -1797,7 +2036,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayConfigPublic" + "$ref": "#/components/schemas/SecurityConfigPublicDTO" } } } @@ -1815,10 +2054,10 @@ } } }, - "/admin/gateway-config/test": { - "post": { - "summary": "Test Config", - "operationId": "test_config_admin_gateway_config_test_post", + "/assistant/actions": { + "get": { + "summary": "Assistant Actions", + "operationId": "assistant_actions_assistant_actions_get", "parameters": [ { "name": "fulcrum_session", @@ -1837,23 +2076,17 @@ } } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GatewayConfigWrite" - } - } - } - }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayProbeResponse" + "type": "array", + "items": { + "$ref": "#/components/schemas/AssistantActionDTO" + }, + "title": "Response Assistant Actions Assistant Actions Get" } } } @@ -1871,17 +2104,50 @@ } } }, - "/healthz": { + "/assistant/tools": { "get": { - "summary": "Healthz", - "operationId": "healthz_healthz_get", + "summary": "Assistant Tools", + "description": "当前角色可调的工具 = 助手能用的工具(从操作注册表按权限派生,单一真源)。", + "operationId": "assistant_tools_assistant_tools_get", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/HealthResponse" + "type": "array", + "items": { + "$ref": "#/components/schemas/AssistantToolDTO" + }, + "title": "Response Assistant Tools Assistant Tools Get" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" } } } @@ -1889,19 +2155,38 @@ } } }, - "/v1/chat/completions": { + "/assistant/chat": { "post": { - "summary": "Chat Completions", - "operationId": "chat_completions_v1_chat_completions_post", + "summary": "Assistant Chat", + "description": "真执行 Agent:意图→自动跑读类/ui、产出写类待确认提案 + 最终答复 + 执行轨迹。\n\n三道吃狗粮闸门(入口/工具返回/出口)由 AssistantAgent 内部强制;一次会话落一条\nASSISTANT_CHAT 审计。agent 未装配(纯管线测试)时回 503 语义的诚实提示。", + "operationId": "assistant_chat_assistant_chat_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], "requestBody": { + "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChatRequest" + "$ref": "#/components/schemas/AssistantChatRequest" } } - }, - "required": true + } }, "responses": { "200": { @@ -1909,7 +2194,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ChatResponse" + "$ref": "#/components/schemas/AssistantChatResponse" } } } @@ -1927,19 +2212,93 @@ } } }, - "/tools/call": { + "/assistant/chat/stream": { "post": { - "summary": "Tools Call", - "operationId": "tools_call_tools_call_post", + "summary": "Assistant Chat Stream", + "description": "流式真 Agent(SSE):逐字吐最终答复 + 实时下发 step/ui/proposal 事件。\n\n与 /assistant/chat 同语义、同三道闸门;事件 `data: {json}\\n\\n`,类型见 agent.run_stream。", + "operationId": "assistant_chat_stream_assistant_chat_stream_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], "requestBody": { + "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ToolCallRequest" + "$ref": "#/components/schemas/AssistantChatRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} } } }, - "required": true + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/assistant/reset": { + "post": { + "summary": "Assistant Reset", + "description": "清空某会话的多轮记忆(新建会话 / 显式清除上下文)。无记忆存储时静默成功。", + "operationId": "assistant_reset_assistant_reset_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantResetRequest" + } + } + } }, "responses": { "200": { @@ -1947,7 +2306,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ToolCallResponse" + "$ref": "#/components/schemas/AssistantResetResponse" } } } @@ -1965,20 +2324,38 @@ } } }, - "/gateway/chat": { + "/assistant/request-approval": { "post": { - "summary": "Gateway Chat", - "description": "前置网关:判恶意 → 拦截/审核/放行;仅放行时转发企业智能体并回传其真实回复。", - "operationId": "gateway_chat_gateway_chat_post", + "summary": "Assistant Request Approval", + "description": "操作员在对话里「发起审批申请」→ 落一条真·待审批工单(进实时事件·待审批)。\n\n与自动筛查的区别:闸门判 APPROVE 时**不**自动塞待审批(否则无效信息泛滥);助手当面\n提示,只有操作员**显式发起**才在此落 evidence.approval_requested=True 的判定点——\n事件墙据此放行展示(见 events_routes.is_feed_noise)。落同会话审计链,可溯源到发起人。", + "operationId": "assistant_request_approval_assistant_request_approval_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], "requestBody": { + "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayChatRequest" + "$ref": "#/components/schemas/AssistantRequestApprovalRequest" } } - }, - "required": true + } }, "responses": { "200": { @@ -1986,7 +2363,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GatewayChatResponse" + "$ref": "#/components/schemas/AssistantRequestApprovalResponse" } } } @@ -2003,78 +2380,1093 @@ } } } - } - }, - "components": { - "schemas": { - "ApproveRequest": { - "properties": { - "role_id": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" + }, + "/assistant/model-config": { + "get": { + "summary": "Assistant Model Config Get", + "description": "读当前模型接入配置(密钥掩码)。未装配存储 → 返回空未配置态(前端据此亮呼吸灯)。", + "operationId": "assistant_model_config_get_assistant_model_config_get", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantModelConfigDTO" + } } - ], - "title": "Role Id" + } }, - "department_id": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } } - ], - "title": "Department Id" + } } - }, - "type": "object", - "title": "ApproveRequest" + } }, - "AssistantActionDTO": { - "properties": { - "id": { - "type": "string", - "title": "Id" - }, - "label": { - "type": "string", - "title": "Label" - }, - "description": { - "type": "string", - "title": "Description" - }, + "put": { + "summary": "Assistant Model Config Put", + "description": "保存模型接入配置(需 settings.manage)。保存即标记 configured,热加载生效。\n\napi_key=None 保持原密钥(防前端把掩码写回覆盖真值);\"\"=清空;非空=设新值。", + "operationId": "assistant_model_config_put_assistant_model_config_put", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantModelConfigUpdate" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantModelConfigDTO" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/assistant/model-config/test": { + "post": { + "summary": "Assistant Model Config Test", + "description": "用「待保存的表单值」试调一次(不落盘)。api_key=None 时复用已存密钥。", + "operationId": "assistant_model_config_test_assistant_model_config_test_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantModelTestRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantModelTestResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/assistant/confirm": { + "post": { + "summary": "Assistant Confirm", + "description": "确认执行某写提案(带编辑后参数)。纵深 RBAC 在 actuator 内强制;越权 → 403。", + "operationId": "assistant_confirm_assistant_confirm_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantConfirmRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantConfirmResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/assistant/undo": { + "post": { + "summary": "Assistant Undo", + "description": "一键撤销某已执行写操作(逆操作回滚)。撤销与原写操作同权;越权 → 403。", + "operationId": "assistant_undo_assistant_undo_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantUndoRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantUndoResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/assistant/plan": { + "post": { + "summary": "Assistant Plan", + "operationId": "assistant_plan_assistant_plan_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantPlanRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AssistantPlanResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/admin/gateway-config": { + "get": { + "summary": "Get Config", + "operationId": "get_config_admin_gateway_config_get", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GatewayConfigPublic" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "put": { + "summary": "Put Config", + "operationId": "put_config_admin_gateway_config_put", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GatewayConfigWrite" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GatewayConfigPublic" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/admin/gateway-config/test": { + "post": { + "summary": "Test Config", + "operationId": "test_config_admin_gateway_config_test_post", + "parameters": [ + { + "name": "fulcrum_session", + "in": "cookie", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Fulcrum Session" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GatewayConfigWrite" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GatewayProbeResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/healthz": { + "get": { + "summary": "Healthz", + "operationId": "healthz_healthz_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HealthResponse" + } + } + } + } + } + } + }, + "/v1/chat/completions": { + "post": { + "summary": "Chat Completions", + "operationId": "chat_completions_v1_chat_completions_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tools/call": { + "post": { + "summary": "Tools Call", + "operationId": "tools_call_tools_call_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ToolCallRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ToolCallResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/gateway/chat": { + "post": { + "summary": "Gateway Chat", + "description": "前置网关:判恶意 → 拦截/审核/放行;仅放行时转发企业智能体并回传其真实回复。", + "operationId": "gateway_chat_gateway_chat_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GatewayChatRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GatewayChatResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ApproveRequest": { + "properties": { + "role_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Role Id" + }, + "department_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Department Id" + } + }, + "type": "object", + "title": "ApproveRequest" + }, + "AssistantActionDTO": { + "properties": { + "id": { + "type": "string", + "title": "Id" + }, + "label": { + "type": "string", + "title": "Label" + }, + "description": { + "type": "string", + "title": "Description" + }, "risk": { "type": "string", - "title": "Risk" + "title": "Risk" + }, + "requires": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Requires" + }, + "args_hint": { + "type": "string", + "title": "Args Hint", + "default": "" + } + }, + "type": "object", + "required": [ + "id", + "label", + "description", + "risk" + ], + "title": "AssistantActionDTO", + "description": "动作目录条目(供助手面板展示「当前角色能调哪些动作」)。" + }, + "AssistantApprovalRequestDTO": { + "properties": { + "stage": { + "type": "string", + "title": "Stage" + }, + "title": { + "type": "string", + "title": "Title" + }, + "reason": { + "type": "string", + "title": "Reason" + }, + "risk_level": { + "type": "string", + "title": "Risk Level" + }, + "excerpt": { + "type": "string", + "title": "Excerpt", + "default": "" + }, + "score": { + "type": "number", + "title": "Score", + "default": 0.0 + } + }, + "type": "object", + "required": [ + "stage", + "title", + "reason", + "risk_level" + ], + "title": "AssistantApprovalRequestDTO", + "description": "需管理员审批的「待发起申请」(闸判 APPROVE 时产出;不自动落工单)。\n\n助手当面提示操作员「需审批,是否发起?」,由人点「发起申请」(/assistant/request-approval)\n才真正进实时事件·待审批。stage:input=可疑输入待审 / output=回复待人工复核。" + }, + "AssistantChatRequest": { + "properties": { + "message": { + "type": "string", + "maxLength": 4000, + "minLength": 1, + "title": "Message" + }, + "session_id": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Session Id" + } + }, + "type": "object", + "required": [ + "message" + ], + "title": "AssistantChatRequest" + }, + "AssistantChatResponse": { + "properties": { + "session_id": { + "type": "string", + "title": "Session Id" }, - "requires": { + "reply": { + "type": "string", + "title": "Reply" + }, + "blocked": { + "type": "boolean", + "title": "Blocked", + "default": false + }, + "compressed": { + "type": "boolean", + "title": "Compressed", + "default": false + }, + "ui_directives": { "items": { - "type": "string" + "$ref": "#/components/schemas/AssistantUiDirectiveDTO" }, "type": "array", - "title": "Requires" + "title": "Ui Directives" }, - "args_hint": { + "proposed_actions": { + "items": { + "$ref": "#/components/schemas/AssistantProposedActionDTO" + }, + "type": "array", + "title": "Proposed Actions" + }, + "approval_requests": { + "items": { + "$ref": "#/components/schemas/AssistantApprovalRequestDTO" + }, + "type": "array", + "title": "Approval Requests" + }, + "steps": { + "items": { + "$ref": "#/components/schemas/AssistantStepDTO" + }, + "type": "array", + "title": "Steps" + } + }, + "type": "object", + "required": [ + "session_id", + "reply" + ], + "title": "AssistantChatResponse" + }, + "AssistantConfirmRequest": { + "properties": { + "action_token": { "type": "string", - "title": "Args Hint", + "maxLength": 4096, + "minLength": 1, + "title": "Action Token" + }, + "edited_args": { + "additionalProperties": true, + "type": "object", + "title": "Edited Args" + }, + "session_id": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Session Id" + } + }, + "type": "object", + "required": [ + "action_token" + ], + "title": "AssistantConfirmRequest" + }, + "AssistantConfirmResponse": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok" + }, + "summary": { + "type": "string", + "title": "Summary" + }, + "action_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Action Id" + }, + "reversible": { + "type": "boolean", + "title": "Reversible", + "default": false + }, + "undo_preview": { + "type": "string", + "title": "Undo Preview", "default": "" + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error" + } + }, + "type": "object", + "required": [ + "ok", + "summary" + ], + "title": "AssistantConfirmResponse" + }, + "AssistantModelConfigDTO": { + "properties": { + "protocol": { + "type": "string", + "title": "Protocol" + }, + "endpoint": { + "type": "string", + "title": "Endpoint" + }, + "model": { + "type": "string", + "title": "Model" + }, + "api_key_masked": { + "type": "string", + "title": "Api Key Masked" + }, + "api_key_set": { + "type": "boolean", + "title": "Api Key Set" + }, + "timeout_seconds": { + "type": "number", + "title": "Timeout Seconds" + }, + "verify_tls": { + "type": "boolean", + "title": "Verify Tls" + }, + "configured": { + "type": "boolean", + "title": "Configured" + }, + "ready": { + "type": "boolean", + "title": "Ready" + } + }, + "type": "object", + "required": [ + "protocol", + "endpoint", + "model", + "api_key_masked", + "api_key_set", + "timeout_seconds", + "verify_tls", + "configured", + "ready" + ], + "title": "AssistantModelConfigDTO", + "description": "回前端的模型接入配置(密钥掩码,只暴露是否已设置 / 是否配置完成)。" + }, + "AssistantModelConfigUpdate": { + "properties": { + "protocol": { + "type": "string", + "enum": [ + "openai", + "ollama", + "anthropic" + ], + "title": "Protocol" + }, + "endpoint": { + "type": "string", + "maxLength": 512, + "title": "Endpoint" + }, + "model": { + "type": "string", + "maxLength": 128, + "title": "Model" + }, + "api_key": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048 + }, + { + "type": "null" + } + ], + "title": "Api Key" + }, + "timeout_seconds": { + "type": "number", + "maximum": 600.0, + "minimum": 1.0, + "title": "Timeout Seconds", + "default": 90.0 + }, + "verify_tls": { + "type": "boolean", + "title": "Verify Tls", + "default": true + } + }, + "type": "object", + "required": [ + "protocol", + "endpoint", + "model" + ], + "title": "AssistantModelConfigUpdate", + "description": "保存模型接入配置。api_key 语义:None=保持原值;\"\"=清空;非空=设新值(防掩码覆盖真值)。" + }, + "AssistantModelTestRequest": { + "properties": { + "protocol": { + "type": "string", + "enum": [ + "openai", + "ollama", + "anthropic" + ], + "title": "Protocol" + }, + "endpoint": { + "type": "string", + "maxLength": 512, + "title": "Endpoint" + }, + "model": { + "type": "string", + "maxLength": 128, + "title": "Model" + }, + "api_key": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048 + }, + { + "type": "null" + } + ], + "title": "Api Key" + }, + "timeout_seconds": { + "type": "number", + "maximum": 600.0, + "minimum": 1.0, + "title": "Timeout Seconds", + "default": 30.0 + }, + "verify_tls": { + "type": "boolean", + "title": "Verify Tls", + "default": true + } + }, + "type": "object", + "required": [ + "protocol", + "endpoint", + "model" + ], + "title": "AssistantModelTestRequest", + "description": "测试连接:用「待保存的表单值」试调一次(api_key=None 时用已存密钥)。" + }, + "AssistantModelTestResponse": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok" + }, + "detail": { + "type": "string", + "title": "Detail" + }, + "latency_ms": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Latency Ms" } }, "type": "object", "required": [ - "id", - "label", - "description", - "risk" + "ok", + "detail" ], - "title": "AssistantActionDTO", - "description": "动作目录条目(供助手面板展示「当前角色能调哪些动作」)。" + "title": "AssistantModelTestResponse" }, "AssistantPlanRequest": { "properties": { @@ -2146,17 +3538,319 @@ }, "denied": { "type": "boolean", - "title": "Denied", - "default": false + "title": "Denied", + "default": false + } + }, + "type": "object", + "required": [ + "ok", + "reason" + ], + "title": "AssistantPlanResponse", + "description": "规划结果:选了哪个动作、是否准许、是否需二次确认、为什么。" + }, + "AssistantProposedActionDTO": { + "properties": { + "tool": { + "type": "string", + "title": "Tool" + }, + "label": { + "type": "string", + "title": "Label" + }, + "risk": { + "type": "string", + "title": "Risk" + }, + "args": { + "additionalProperties": true, + "type": "object", + "title": "Args" + }, + "requires": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Requires" + }, + "note": { + "type": "string", + "title": "Note", + "default": "" + }, + "action_token": { + "type": "string", + "title": "Action Token", + "default": "" + }, + "reversible": { + "type": "boolean", + "title": "Reversible", + "default": false + }, + "before": { + "additionalProperties": true, + "type": "object", + "title": "Before" + } + }, + "type": "object", + "required": [ + "tool", + "label", + "risk" + ], + "title": "AssistantProposedActionDTO", + "description": "写操作的待确认提案(可编辑卡片;确认走 /assistant/confirm,默认不执行)。" + }, + "AssistantRequestApprovalRequest": { + "properties": { + "session_id": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Session Id" + }, + "stage": { + "type": "string", + "maxLength": 16, + "title": "Stage", + "default": "output" + }, + "reason": { + "type": "string", + "maxLength": 400, + "title": "Reason", + "default": "" + }, + "risk_level": { + "type": "string", + "maxLength": 16, + "title": "Risk Level", + "default": "medium" + }, + "excerpt": { + "type": "string", + "maxLength": 400, + "title": "Excerpt", + "default": "" + }, + "score": { + "type": "number", + "title": "Score", + "default": 0.0 + } + }, + "type": "object", + "title": "AssistantRequestApprovalRequest", + "description": "操作员在对话里「发起审批申请」:把某条 APPROVE 判定落成真·待审批工单。" + }, + "AssistantRequestApprovalResponse": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok", + "default": true + } + }, + "type": "object", + "title": "AssistantRequestApprovalResponse" + }, + "AssistantResetRequest": { + "properties": { + "session_id": { + "type": "string", + "maxLength": 128, + "minLength": 1, + "title": "Session Id" + } + }, + "type": "object", + "required": [ + "session_id" + ], + "title": "AssistantResetRequest", + "description": "清空某会话的多轮记忆(新建会话 / 显式清除上下文)。" + }, + "AssistantResetResponse": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok", + "default": true + } + }, + "type": "object", + "title": "AssistantResetResponse" + }, + "AssistantStepDTO": { + "properties": { + "tool": { + "type": "string", + "title": "Tool" + }, + "kind": { + "type": "string", + "title": "Kind" + }, + "label": { + "type": "string", + "title": "Label" + }, + "ok": { + "type": "boolean", + "title": "Ok" + }, + "detail": { + "type": "string", + "title": "Detail", + "default": "" + } + }, + "type": "object", + "required": [ + "tool", + "kind", + "label", + "ok" + ], + "title": "AssistantStepDTO", + "description": "一步执行轨迹(透明展示助手调了什么)。" + }, + "AssistantToolDTO": { + "properties": { + "name": { + "type": "string", + "title": "Name" + }, + "kind": { + "type": "string", + "title": "Kind" + }, + "label": { + "type": "string", + "title": "Label" + }, + "description": { + "type": "string", + "title": "Description" + }, + "risk": { + "type": "string", + "title": "Risk" + }, + "requires": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Requires" + }, + "reversible": { + "type": "boolean", + "title": "Reversible", + "default": false + } + }, + "type": "object", + "required": [ + "name", + "kind", + "label", + "description", + "risk" + ], + "title": "AssistantToolDTO", + "description": "当前角色可调的一个工具(供助手面板侧栏 + /assistant/tools 列出)。" + }, + "AssistantUiDirectiveDTO": { + "properties": { + "tool": { + "type": "string", + "title": "Tool" + }, + "label": { + "type": "string", + "title": "Label" + }, + "args": { + "additionalProperties": true, + "type": "object", + "title": "Args" + } + }, + "type": "object", + "required": [ + "tool", + "label" + ], + "title": "AssistantUiDirectiveDTO", + "description": "前端待执行的 ui 指令(导航/筛选/开面板)。" + }, + "AssistantUndoRequest": { + "properties": { + "action_id": { + "type": "string", + "maxLength": 128, + "minLength": 1, + "title": "Action Id" + }, + "session_id": { + "anyOf": [ + { + "type": "string", + "maxLength": 128 + }, + { + "type": "null" + } + ], + "title": "Session Id" + } + }, + "type": "object", + "required": [ + "action_id" + ], + "title": "AssistantUndoRequest" + }, + "AssistantUndoResponse": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok" + }, + "summary": { + "type": "string", + "title": "Summary" + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error" } }, "type": "object", "required": [ "ok", - "reason" + "summary" ], - "title": "AssistantPlanResponse", - "description": "规划结果:选了哪个动作、是否准许、是否需二次确认、为什么。" + "title": "AssistantUndoResponse" }, "AuditChainEventDTO": { "properties": { @@ -2271,14 +3965,40 @@ "title": "AuditSessionDTO", "description": "一条会话审计链 + 其 hash-chain 校验结论 + 从链派生的一句话情景。" }, + "BackendModelInfo": { + "properties": { + "endpoint": { + "type": "string", + "title": "Endpoint" + }, + "model_name": { + "type": "string", + "title": "Model Name" + }, + "key_set": { + "type": "boolean", + "title": "Key Set" + } + }, + "type": "object", + "required": [ + "endpoint", + "model_name", + "key_set" + ], + "title": "BackendModelInfo", + "description": "只读:后端模型出站配置(经 .env 注入,不在控制台改;此处仅如实回显)。" + }, "ChatMessage": { "properties": { "role": { "type": "string", + "maxLength": 32, "title": "Role" }, "content": { "type": "string", + "maxLength": 8000, "title": "Content" } }, @@ -2293,13 +4013,15 @@ "properties": { "model": { "type": "string", + "maxLength": 128, "title": "Model", "default": "fulcrum-demo" }, "session_id": { "anyOf": [ { - "type": "string" + "type": "string", + "maxLength": 256 }, { "type": "null" @@ -2312,6 +4034,7 @@ "$ref": "#/components/schemas/ChatMessage" }, "type": "array", + "maxItems": 64, "title": "Messages" } }, @@ -2353,6 +4076,52 @@ ], "title": "ChatResponse" }, + "ConsoleSettingsPublic": { + "properties": { + "instance_name": { + "type": "string", + "maxLength": 64, + "title": "Instance Name", + "default": "枢衡安全控制台" + }, + "environment": { + "type": "string", + "pattern": "^(prod|staging|demo)$", + "title": "Environment", + "default": "demo" + }, + "backend_model": { + "$ref": "#/components/schemas/BackendModelInfo" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "backend_model" + ], + "title": "ConsoleSettingsPublic", + "description": "回前端:真实可写项 + 只读后端模型信息。" + }, + "ConsoleSettingsWrite": { + "properties": { + "instance_name": { + "type": "string", + "maxLength": 64, + "title": "Instance Name", + "default": "枢衡安全控制台" + }, + "environment": { + "type": "string", + "pattern": "^(prod|staging|demo)$", + "title": "Environment", + "default": "demo" + } + }, + "additionalProperties": false, + "type": "object", + "title": "ConsoleSettingsWrite", + "description": "更新控制台实例元信息(真实落盘字段)。" + }, "DepartmentDTO": { "properties": { "id": { @@ -2622,6 +4391,41 @@ "type": "object", "title": "EvalTotalsDTO" }, + "EventResolveRequest": { + "properties": { + "decision": { + "type": "string", + "enum": [ + "allow", + "block" + ], + "title": "Decision" + }, + "note": { + "type": "string", + "maxLength": 400, + "title": "Note", + "default": "" + } + }, + "type": "object", + "required": [ + "decision" + ], + "title": "EventResolveRequest", + "description": "处置一条待审批事件:批准放行(allow)或维持阻断(block)。需 events.handle。" + }, + "EventResolveResponse": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok", + "default": true + } + }, + "type": "object", + "title": "EventResolveResponse" + }, "GatewayChatRequest": { "properties": { "session_id": { @@ -2807,6 +4611,17 @@ "rest_response_path": { "type": "string", "title": "Rest Response Path" + }, + "team_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Team Id" } }, "type": "object", @@ -2912,6 +4727,17 @@ "maxLength": 128, "title": "Rest Response Path", "default": "reply" + }, + "team_id": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Team Id" } }, "type": "object", @@ -3056,6 +4882,35 @@ ], "title": "LoginRequest" }, + "MembershipDTO": { + "properties": { + "user_id": { + "type": "integer", + "title": "User Id" + }, + "team_id": { + "type": "integer", + "title": "Team Id" + }, + "team_role": { + "type": "string", + "title": "Team Role", + "default": "member" + }, + "is_lead": { + "type": "boolean", + "title": "Is Lead", + "default": false + } + }, + "type": "object", + "required": [ + "user_id", + "team_id" + ], + "title": "MembershipDTO", + "description": "成员在某团队的归属(plan/13 P1b):团队内角色 + 是否负责人。" + }, "OutcomeDTO": { "properties": { "tool_name": { @@ -3197,13 +5052,28 @@ "group": { "type": "string", "title": "Group" + }, + "capability": { + "type": "string", + "title": "Capability" + }, + "cap_label": { + "type": "string", + "title": "Cap Label" + }, + "access": { + "type": "string", + "title": "Access" } }, "type": "object", "required": [ "key", "label", - "group" + "group", + "capability", + "cap_label", + "access" ], "title": "PermissionDTO" }, @@ -3338,6 +5208,20 @@ }, "type": "array", "title": "Permissions" + }, + "team_ids": { + "items": { + "type": "integer" + }, + "type": "array", + "title": "Team Ids" + }, + "managed_teams": { + "items": { + "type": "integer" + }, + "type": "array", + "title": "Managed Teams" } }, "type": "object", @@ -3413,6 +5297,11 @@ "type": "integer", "title": "Member Count", "default": 0 + }, + "scope": { + "type": "string", + "title": "Scope", + "default": "org" } }, "type": "object", @@ -3423,6 +5312,50 @@ ], "title": "RoleDTO" }, + "RoleUpdate": { + "properties": { + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 64, + "minLength": 1 + }, + { + "type": "null" + } + ], + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Description" + }, + "permissions": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Permissions" + } + }, + "type": "object", + "title": "RoleUpdate" + }, "RoleWrite": { "properties": { "name": { @@ -3442,6 +5375,12 @@ }, "type": "array", "title": "Permissions" + }, + "scope": { + "type": "string", + "pattern": "^(org|team)$", + "title": "Scope", + "default": "team" } }, "type": "object", @@ -3450,6 +5389,121 @@ ], "title": "RoleWrite" }, + "SecurityConfigPublicDTO": { + "properties": { + "profile": { + "type": "string", + "title": "Profile" + }, + "detector_zones": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object", + "title": "Detector Zones" + }, + "available_detectors": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Available Detectors" + }, + "judge_endpoint": { + "type": "string", + "title": "Judge Endpoint" + }, + "judge_model": { + "type": "string", + "title": "Judge Model" + }, + "judge_api_key_masked": { + "type": "string", + "title": "Judge Api Key Masked" + }, + "judge_api_key_set": { + "type": "boolean", + "title": "Judge Api Key Set" + }, + "judge_timeout_seconds": { + "type": "number", + "title": "Judge Timeout Seconds" + } + }, + "type": "object", + "required": [ + "profile", + "detector_zones", + "available_detectors", + "judge_endpoint", + "judge_model", + "judge_api_key_masked", + "judge_api_key_set", + "judge_timeout_seconds" + ], + "title": "SecurityConfigPublicDTO" + }, + "SecurityConfigWrite": { + "properties": { + "profile": { + "type": "string", + "pattern": "^(lightweight|standard|strict|air_gapped)$", + "title": "Profile" + }, + "zone_overrides": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object", + "title": "Zone Overrides" + }, + "judge_endpoint": { + "type": "string", + "maxLength": 512, + "minLength": 1, + "title": "Judge Endpoint" + }, + "judge_model": { + "type": "string", + "maxLength": 128, + "minLength": 1, + "title": "Judge Model" + }, + "judge_api_key": { + "anyOf": [ + { + "type": "string", + "maxLength": 2048 + }, + { + "type": "null" + } + ], + "title": "Judge Api Key" + }, + "judge_timeout_seconds": { + "type": "number", + "maximum": 120.0, + "minimum": 1.0, + "title": "Judge Timeout Seconds", + "default": 20.0 + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "profile", + "judge_endpoint", + "judge_model" + ], + "title": "SecurityConfigWrite" + }, "SecurityEventDTO": { "properties": { "id": { @@ -3616,6 +5670,31 @@ ], "title": "SupplyScanRiskDTO" }, + "TeamMemberWrite": { + "properties": { + "user_id": { + "type": "integer", + "title": "User Id" + }, + "team_role": { + "type": "string", + "maxLength": 64, + "title": "Team Role", + "default": "member" + }, + "is_lead": { + "type": "boolean", + "title": "Is Lead", + "default": false + } + }, + "type": "object", + "required": [ + "user_id" + ], + "title": "TeamMemberWrite", + "description": "把某成员加入/更新到某团队(团队负责人或组织管理员可调)。" + }, "TempPasswordResponse": { "properties": { "user": { @@ -3730,10 +5809,12 @@ "properties": { "session_id": { "type": "string", + "maxLength": 256, "title": "Session Id" }, "tool_name": { "type": "string", + "maxLength": 128, "title": "Tool Name" }, "arguments": { @@ -3746,6 +5827,7 @@ "type": "string" }, "type": "array", + "maxItems": 64, "title": "Source Ids" } }, diff --git "a/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" "b/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" index 01aca7e..ff88895 100644 --- "a/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" +++ "b/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" @@ -200,3 +200,4 @@ | v1.64 | 2026-07-07 | **审计读热路径修 M14(评审报告):三条轮询路由消 N+1 冗余全量读 + sqlite 阻塞卸载线程**:`/overview/stats`、`/audit`、`/events` 此前每次请求对每个会话各自 `verify_chain`(每次=该会话全量重读+JSON 反序列化+重算整链)再叠 `all_events()`,且 `SqliteAuditSink` 的同步 sqlite 直接跑在事件循环上——前端轮询看板=每次 N+1 趟全量读并卡住全部并发请求(认证后 DoS 面)。两刀:①**sink 卸载**——`append/events/verify_chain/locate_break` 内部同步读写经 `asyncio.to_thread` 进工作线程,事件循环不再被审计 I/O 卡住(审计写在每次判定的 await 路径上,受益面=全部请求);②**路由消冗余**——三路由改单遍取全量(经 to_thread)、按会话分组后就地 `locate_break` 校验;`/audit` 每会话从两读(events+verify_chain 内部重读)降一读。**实测(20 会话)每请求 sqlite 连接数:/overview 21→1、/events 22→1、/audit 41→21(减半)**。**防篡改语义红线(设计取舍,回归锁死)**:**故意不缓存校验结果**——校验的意义正是发现落库后被篡改的留痕,缓存布尔值会把事后篡改掩盖到进程重启;哈希仍逐事件全量重算(新鲜度不降级),只消重复 I/O。评审建议的「聚合走 SQL」不在本 PR(需动响应聚合口径,收益小于以上两刀,如实排后)。`assistant/operations` 同模式但非轮询路径且属维护者活跃区,不越界。+3 HTTP 级回归(篡改库内事件→三路由**下一次请求立即**反映未校验;完好路径响应口径不变)。全门绿:ruff/format/pyright 0、import-linter 3 KEPT、pytest 859→862。基于 origin/dev 独立提(fork→上游 FPSZ/Fulcrum:dev),版本号撞栈由审核者重编号 | | v1.65 | 2026-07-07 | **前端处置元数据抽单一真源(评审报告 M29)**:Disposition 的「类型 + 展示顺序 + 徽标色调」此前在 events/gateway/audit/policies/tools/supply/eval **七处各写一份**,且已实际漂移——events 的 sanitize 色调独为 `info`,其余六页与总览硬编码均为 `med`(正是复制粘贴的后果)。新增 `console/src/lib/disposition.ts` 单一真源:`Disposition` 类型(与后端 core.domain.Disposition 值域一致,supply 的 `Rating` 别名同源)、`DISPOSITION_ORDER`、`DISPOSITION_TONE`、宽入口 `dispositionTone()`(未收窄字符串用,未知值回退 neutral,口径同 eval 页旧 `?? 'neutral'`)。七页删本地拷贝改导入;5 处类型定义(events/audit/gateway/policies/tools)与 supply `Rating` 改"import + re-export"保持既有导入面零波及。**唯一行为变化(有意)**:events 页 sanitize 徽标色 `info`→`med`,归一到全站既成口径(六页+总览一致)。**刻意不归一**:各页处置**文案**(i18n)按语境措辞是设计而非重复(gateway「转人工审核」/supply「需复核」/events「待审批」/其余「审批」),留在各页命名空间。前端门绿:tsc 0、vite build 通过;全仓 `type Disposition` 定义与 tone 映射各仅剩 lib 一处(grep 验证)。13 文件改 + 1 新增,纯前端零后端。基于 origin/dev 独立提(fork→上游 FPSZ/Fulcrum:dev),版本号撞栈由审核者重编号 | | v1.66 | 2026-07-07 | **助手流式对话可中止 + 错误不再覆盖已流出内容(评审报告 M25)**:此前 `assistant-page` 的流式发送①无 AbortController——网络挂起时该轮 `streaming` 永真、busy 锁死输入,只能刷新页面;②catch 里 `text` 被**整体替换**为错误文案——流到一半断线,已流出的回答全部丢失。三处修:①`sendChatStream` 加可选 `signal` 参数透传 fetch(连接与 reader.read() 均以 AbortError 解除);②页面按会话维护 `AbortController` Map(键=会话 id,切会话互不干扰;**组件卸载不中止**——后台续写模块 store 是既有有意设计,保留),catch 区分「用户主动停止」(已有内容原样保留,一字未出标「已停止生成」)与「真错误」(**错误文案追加在已流出内容之后**,绝不整体替换);③Composer 发送键在流式期间变为可点的「停止」(Square 图标,GPT/Kimi 惯例)——网络挂起也能一键解除 busy。i18n 补 `assistant.composer.stop`/`assistant.turn.stopped` 中英两 key(MessageKey 由 zh 词典派生,编译期锁定)。前端门绿:tsc 0、vite build 通过。**诚实边界**:未本地配真模型跑流式端到端,中止语义依赖标准 fetch AbortController 行为(连接中断/读取拒绝为平台保证);5 文件纯前端。基于 origin/dev 独立提(fork→上游 FPSZ/Fulcrum:dev),版本号撞栈由审核者重编号 | +| v1.71 | 2026-07-15 | **分级安全配置与控制台设置(PR #116)**:新增四类检测器的分级配置、预设与热更新机制;提供受 RBAC 约束的管理 API 和控制台设置页,使策略调整可在统一界面完成。 | diff --git "a/docs/plan/15-\345\274\200\346\224\276PR\347\233\230\347\202\271\344\270\216\345\220\216\347\273\255\345\256\236\346\226\275\350\256\241\345\210\222.md" "b/docs/plan/15-\345\274\200\346\224\276PR\347\233\230\347\202\271\344\270\216\345\220\216\347\273\255\345\256\236\346\226\275\350\256\241\345\210\222.md" new file mode 100644 index 0000000..038ca74 --- /dev/null +++ "b/docs/plan/15-\345\274\200\346\224\276PR\347\233\230\347\202\271\344\270\216\345\220\216\347\273\255\345\256\236\346\226\275\350\256\241\345\210\222.md" @@ -0,0 +1,88 @@ +# 15 · 开放 PR 盘点与后续实施计划 + +> 本文回答什么问题:截至 2026-07-15,7 条面向上游 `dev` 的开放 PR 分别改变了什么、应如何验证和合并,以及在它们稳定后应优先开发什么。 +> +> 状态:评审中 + +## 1. 盘点范围与证据 + +本文盘点 GitHub `FPSZ/Fulcrum` 的 #109 至 #115。结论来自 PR 说明、GitHub 当前检查状态、PR head 相对 `origin/dev` 的实际 Git diff 与现有路线文档。 + +- GitHub 显示 7 条 PR 当前检查均通过;这不替代 rebase 到最新 `dev` 后的本地复验。 +- PR 作者声明的性能数据、评测指标与测试数量尚未由本地环境独立重跑,本文不把它们当作已验证结论。 +- 所有 PR 尚未合入,既有 [03-进度看板](03-进度看板.md) 不应提前标记完成。 + +## 2. 开放 PR 改动 + +| PR | 实际变更范围 | 结论 | +|---|---|---| +| #109 | 6 文件,397 行新增、13 行删除:`pipeline.py`、助手 `agent.py`、装配 `app.py`、计划 03/14 与 `test_async_judge_bypass.py`。 | 助手路径的可选异步 judge,与模型规划并行,在写提案和最终回复前收口;核心管线改动,需完整回归。 | +| #110 | 3 文件,271 行新增、21 行删除:`keyword_rules.py`、进度看板、`test_intent_fpr_generalize.py`。 | 泛化良性意图抑制、降低输入误报;是 #112 的前置。 | +| #111 | 6 文件,461 行新增、2 行删除:新增 `render_exfil.py` 和测试,接入能力注册、`fulcrum.yml`、评测装配与进度看板。 | 覆盖渲染外泄与隐藏注入信道;与 #115 共享接入点。 | +| #112 | 相对 #110 的增量为 4 文件、333 行新增:`keyword_rules.py`、`normalize.py`、进度看板及 `test_decode_rescan_robust.py`。 | 覆盖空白 Base64、bidi 反转、解码后复扫和回环保护;已确认它是 stacked PR。 | +| #113 | 3 文件,102 行新增、3 行删除:`toolguard/argrisk.py`、进度看板、`test_argrisk.py`。 | 对路径围栏补 overlong UTF-8 编码分隔符规范化;独立、低冲突。 | +| #114 | 1 文件,18 行新增:`docs/arch/00-技术架构总览.md`。 | 补防旁路部署运维清单,明确产品能力、部署责任与未落地鉴权缺口;纯文档。 | +| #115 | 9 文件,423 行新增、1 行删除:新增 `false_authority.py` 和测试,接入注册、`fulcrum.yml`、评测装配;追加脱敏 corpus 样例和进度看板。 | 覆盖不可信来源伪造权威、诱导覆盖安全判断;与 #111 需串行集成。 | + +## 3. 合并队列与验收 + +建议合并顺序:#114 -> #113 -> #110 -> #112 -> #111 -> #115 -> #109。 + +1. #112 必须在 #110 合入后 rebase,只审其新增提交,避免重复审核和重复测试。 +2. #111 与 #115 都改能力注册、生产配置、评测装配、进度看板。先合入其中之一,另一个必须 rebase 并处理冲突后再复验。 +3. #109 最后合入,使用累计后的最新 `dev` 验证同步入口不变、异步失败降级、取消、幂等收口、提案拦截、流式与非流式路径。 +4. 所有检测器 PR 合入前都要重跑:静态检查、类型检查、分层契约检查、相关单测、冻结 corpus、held-out 良性集和非语料变换体;临时评测报告不入库。 +5. #113 额外覆盖多层 percent 编码、overlong `/`/`.`/`\\`、Windows 路径与工作区内合法路径。 +6. #114 核对部署端点、审计类型和“未落地能力”的表述,避免把计划写成既有事实。 + +## 4. 本地 TODO + +### 合并前 + +- [ ] 为 #114、#113、#110、#112、#111、#115、#109 逐条完成本地复验和代码审核,不根据历史 CI 直接批准。 +- [ ] 每次合入后更新下一个 PR 的基线、处理 rebase 冲突,并检查 PR base 始终为上游 `dev`。 +- [ ] 在检测器 PR 全部稳定后,重新生成 corpus 报告并同步 [03-进度看板](03-进度看板.md)、[07-功能实现路线图](07-功能实现路线图.md)、[08-攻击样例库与对标基准](08-攻击样例库与对标基准.md) 与 [评测指标体系](../eval/00-评测指标体系.md) 的版本、样例数和指标引用。 + +### 下一开发任务(待确认后实施) + +- [ ] **P_a:按区域配置 schema**。实现计划 14 定义的输入、输出、工具返回、助手工具治理四区域配置;保留扁平 `detectors` 的向后兼容,并完成配置校验、迁移与契约测试。 +- [ ] **P_e:预设档**。基于 P_a 提供轻量、标准、严格、合规 air-gapped 四档;每档声明检测器集合、judge 模式、默认处置、外联要求与性能预算。 +- [ ] **P_d:控制台设置页**。最后接入可编辑 UI 与后端 RBAC 校验,只显示真实可生效配置。 +- [ ] **更快 judge 后端评测**。网关保持同步判定;仅将实测达到 100–200ms 且 FPR、召回合格的候选写入生产配置。 + +P_a 是建议的首个新开发任务:它是 P_e/P_d 的前置,且可以把 #109 的助手异步 judge 与 #111/#115 的新增检测器纳入统一的按区域治理。它涉及配置契约与架构边界,开始编码前需维护者确认 schema 方案。 + +## 5. 代码实施计划表 + +本表只列尚未落地的代码能力。开放 PR 属于“待验证集成”,不计入新功能开发;效果数据须在 PR rebase 后重跑得出。 + +| 优先级 | 功能任务 | 可提交的最小范围 | 主要模块 | 前置依赖 | 完成定义 | +|---|---|---|---|---|---| +| 0 | 开放 PR 验证与集成 | 按 #114、#113、#110、#112、#111、#115、#109 队列复验、rebase 与 review。 | 对应 PR 已改文件、`docs/plan/03` | 维护者审核;#112 依赖 #110;#111/#115 串行。 | 每条基于最新 `dev` 通过相关测试和评测,冲突解决有记录,未把作者自述当验证结果。 | +| 1 | ✅ P_a-1 区域配置契约 | 四区域 `gateway_input`、`gateway_output`、`tool_return`、`assistant_intent` schema;扁平 `detectors` 自动映射为四区同配。 | `src/fulcrum/config/fulcrum.yml`、配置解析、`core/pipeline.py`、配置测试。 | 已完成 2026-07-15。 | 非法区域/检测器在构建期失败;旧配置保持兼容;新配置可独立指定各区检测器。 | +| 2 | ✅ P_a-2 管线按区调度与审计 | 四条检测入口按固定 zone 选择检测器;助手工具参数实际复扫但不污染既有来源归因;审计记录区域与非敏感配置摘要。 | `core/pipeline.py`、领域模型/审计适配器、检测与集成测试。 | 已完成 2026-07-15。 | 四区路由与审计摘要测试通过;正常资金审批语义保持 APPROVE,不被临时检测 span 升级为 BLOCK。 | +| 3 | ✅ P_e 预设档 | 轻量、标准、严格、合规 air-gapped 四档;区域覆盖、原子 JSON 持久化、候选构建与运行中热替换。 | 安全配置 store、管理 API、配置 profile、测试。 | 已完成 2026-07-15。 | 默认标准档;air-gapped 仅允许 loopback judge;候选失败不写盘/不切换;变更写入审计链且不记录密钥或端点明文。 | +| 4 | ✅ P_d 分级安全设置页 | `GET/PUT /admin/security-config`、RBAC、审计;前端安全策略页展示预设、四区开关和 Judge 配置。 | `adapters/api`、设置存储、`console/src/features/settings`、双语文案、测试。 | 已完成 2026-07-15。 | 未授权请求拒绝;重启恢复配置;前端不接收密钥明文;保存后热替换生效,前端 typecheck/build 通过。 | +| 5 | 更快 judge 后端基准与接入 | 为候选本地小模型/蒸馏分类器建立统一适配器、基准脚本与选择门槛;不改变网关同步语义。 | `capabilities/detectors`、`samples/eval/benchmarks`、配置与评测文档。 | 固定 corpus/held-out 口径。 | 报告包含 P50/P95、召回、FPR、失败降级;只有达成 100–200ms 与既定指标的候选可写入生产预设。 | +| 6 | 多轮 Agent 工具结果回填 | 让工具执行结果带 `tool_call_id` 回填模型,支持受治理的下一轮规划并设轮数/令牌/时间上限。 | 模型消息契约、`adapters/assistant`、`enterprise`、工具审计、测试。 | 区域治理稳定;模型适配器契约评审。 | 正常多轮完成;高危工具仍先过审批/策略;循环、超时、异常可审计且 fail-closed。 | +| 7 | 工具网关执行入口接控制台 | 将现有 `POST /tools/call` 接入受权限控制的控制台操作流,复用提案-确认与审计,不绕过助手/策略闸门。 | 工具 API、RBAC、`console/src/features/tools`、集成测试。 | 多轮/提案契约确认。 | 只读与高危操作分别按权限和审批执行;页面只显示真实调用结果;无直接执行旁路。 | +| 8 | 策略备份资源导入 | 将 policy 作为第二种备份资源纳入导入/导出与版本兼容校验。 | `console/src/lib/backup`、策略 API、测试。 | 策略 schema 稳定。 | 导出后可导入恢复;版本不兼容明确拒绝;不覆盖未确认的生产策略。 | +| 9 | 供应链扫描纳入评测 | 将 manifest/脚本样例接入统一评测,输出供应链召回、FPR、处置准确率与证据。 | `samples/supplychain`、`fulcrum.eval`、指标/报告测试。 | 评测口径确认。 | CLI 可复跑并产生分域报告;样例脱敏;不以离线扫描结果夸大为请求路径防护。 | +| 10 | 真进程/容器隔离沙箱 | 将受限执行器从线程超时提升为可终止的隔离进程/容器,定义挂载、网络、资源与审计边界。 | `capabilities/sandbox`、部署配置、隔离集成测试。 | 维护者确认部署模型与运行环境。 | 超时能终止副作用;默认无网络、最小挂载;逃逸与资源上限测试可复现。 | +| 11 | 低风险工程债 | `React.lazy`/`manualChunks`、备份 `dataVersion`、侧栏分组收起行为。 | `console/src`、备份模块、前端测试。 | 无。 | 构建产物和现有导航不回归;缓存升级行为可验证。 | + +下一代码任务建议转为优先级 5:建立更快 judge 后端的可复现基准和准入门槛。开放 PR 队列仍按优先级 0 单独复验与合并;优先级 6 至 10 不与其并发修改同一配置/管线边界,除非维护者明确指定。 + +## 6. Fork 与 PR 流程 + +- 本地 `origin` 是上游 `FPSZ/Fulcrum`;`waynejoon/Fulcrum` fork 已存在,但当前仅有 `main`,尚无 `dev`。 +- 开始实际开发时,将 fork 的 `dev` 对齐最新上游 `origin/dev`;开发、测试和提交均在 fork 的 `dev` 完成。 +- 创建 PR 时固定为 `waynejoon:dev` -> `FPSZ:dev`。不向上游 `dev` 或 `main` 直接推送,不执行合并。 +- 每项已确认开发任务使用两名子 agent:编码子 agent 实现最小变更;本地测试与代码审核子 agent 独立复查 diff、运行验收并报告问题;编排负责人决定范围、处理问题并创建 PR。 + +## 修订记录 + +| 版本 | 日期 | 变更 | +|---|---|---| +| v1 | 2026-07-15 | 初稿:盘点 #109–#115,记录合并队列、本地 TODO、建议首个开发任务与 fork PR 流程。 | +| v1.1 | 2026-07-15 | P_a-1、P_a-2、P_e、P_d 本地实现与验证完成:区域检测配置、预设档、热更新、审计留痕与控制台设置页已落地。 | diff --git a/src/fulcrum/adapters/api/app.py b/src/fulcrum/adapters/api/app.py index edf9f32..7a50c44 100644 --- a/src/fulcrum/adapters/api/app.py +++ b/src/fulcrum/adapters/api/app.py @@ -3,7 +3,8 @@ from __future__ import annotations import secrets -from typing import TYPE_CHECKING +from collections.abc import Callable +from typing import TYPE_CHECKING, Any from fastapi import FastAPI, HTTPException from fastapi.requests import Request @@ -34,6 +35,7 @@ from ..assistant.planner import ModelComplete from ..auth import AuthBundle from ..gateway import GatewayConfigStore, UpstreamForwarder + from ..security_config import SecurityConfigStore def _output_of(result: object | None) -> str | None: @@ -80,6 +82,9 @@ def build_api( scanner: SupplyChainScanner | None = None, assistant_complete: ModelComplete | None = None, assistant_model_turn: ModelTurn | None = None, + security_store: SecurityConfigStore | None = None, + capability_config: dict[str, Any] | None = None, + pipeline_factory: Callable[[dict[str, Any]], SecurityPipeline] | None = None, ) -> FastAPI: app = FastAPI(title="枢衡 Fulcrum API", version=__version__) @@ -136,6 +141,21 @@ async def _on_fulcrum_error(_: Request, exc: FulcrumError) -> JSONResponse: console_store = ConsoleSettingsStore(settings.console_settings_path) register_console_settings_routes(app, console_store, settings, deps) + if ( + security_store is not None + and capability_config is not None + and pipeline_factory is not None + ): + from .security_config_routes import register_security_config_routes + + register_security_config_routes( + app, + pipeline, + security_store, + capability_config, + pipeline_factory, + deps, + ) # AI 操作助手:模型后端默认从 .env(endpoint/key/name)装配,组装根可覆盖(测试注入假后端)。 complete = assistant_complete or make_model_backend( settings.model_endpoint, settings.model_api_key, settings.model_name diff --git a/src/fulcrum/adapters/api/schemas/admin.py b/src/fulcrum/adapters/api/schemas/admin.py index c83b538..39d9c67 100644 --- a/src/fulcrum/adapters/api/schemas/admin.py +++ b/src/fulcrum/adapters/api/schemas/admin.py @@ -8,6 +8,8 @@ "BackendModelInfo", "ConsoleSettingsWrite", "ConsoleSettingsPublic", + "SecurityConfigWrite", + "SecurityConfigPublicDTO", "LoginRequest", "RegisterRequest", "PrincipalResponse", @@ -53,6 +55,30 @@ class ConsoleSettingsPublic(ConsoleSettingsWrite): backend_model: BackendModelInfo +# ---- /admin/security-config(分级安全预设;密钥永不明文回传)---- +class SecurityConfigWrite(BaseModel): + model_config = ConfigDict(extra="forbid") + + profile: str = Field(pattern="^(lightweight|standard|strict|air_gapped)$") + zone_overrides: dict[str, list[str]] = Field(default_factory=dict) + judge_endpoint: str = Field(min_length=1, max_length=512) + judge_model: str = Field(min_length=1, max_length=128) + # null=保留,空串=清除;不在任何响应 DTO 中出现。 + judge_api_key: str | None = Field(default=None, max_length=2048) + judge_timeout_seconds: float = Field(default=20.0, ge=1, le=120) + + +class SecurityConfigPublicDTO(BaseModel): + profile: str + detector_zones: dict[str, list[str]] + available_detectors: list[str] + judge_endpoint: str + judge_model: str + judge_api_key_masked: str + judge_api_key_set: bool + judge_timeout_seconds: float + + # ---- /auth ---- class LoginRequest(BaseModel): username: str = Field(min_length=1, max_length=128) diff --git a/src/fulcrum/adapters/api/security_config_routes.py b/src/fulcrum/adapters/api/security_config_routes.py new file mode 100644 index 0000000..1181c08 --- /dev/null +++ b/src/fulcrum/adapters/api/security_config_routes.py @@ -0,0 +1,116 @@ +"""分级安全预设配置路由:RBAC、候选构建、原子持久化与运行时热替换。""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TYPE_CHECKING, Any + +from fastapi import Depends, FastAPI, HTTPException +from pydantic import ValidationError + +from ...core.domain import AuditEventType, Context +from ...core.errors import ConfigError +from ..auth import Principal +from ..security_config import ( + SecurityConfig, + SecurityConfigPublic, + SecurityConfigStore, + available_detector_names, +) +from .deps import AuthDeps +from .schemas import SecurityConfigPublicDTO, SecurityConfigWrite + +if TYPE_CHECKING: + from ...core.pipeline import SecurityPipeline + + +def register_security_config_routes( + app: FastAPI, + pipeline: SecurityPipeline, + store: SecurityConfigStore, + base_config: dict[str, Any], + pipeline_factory: Callable[[dict[str, Any]], SecurityPipeline], + deps: AuthDeps, +) -> None: + can_view = deps.require("settings.view") + can_manage = deps.require("settings.manage") + + def _public(cfg: SecurityConfig) -> SecurityConfigPublicDTO: + return SecurityConfigPublicDTO( + **SecurityConfigPublic.of(cfg).model_dump(), + available_detectors=available_detector_names(base_config), + ) + + @app.get("/admin/security-config", response_model=SecurityConfigPublicDTO) + async def get_security_config( + _: Principal = Depends(can_view), + ) -> SecurityConfigPublicDTO: + return _public(store.load()) + + @app.put("/admin/security-config", response_model=SecurityConfigPublicDTO) + async def put_security_config( + body: SecurityConfigWrite, principal: Principal = Depends(can_manage) + ) -> SecurityConfigPublicDTO: + current = store.load() + # null 保留已存密钥;空串明确清空。公开响应从不回传此字段。 + api_key = current.judge.api_key if body.judge_api_key is None else body.judge_api_key + try: + next_config = SecurityConfig.model_validate( + { + "profile": body.profile, + "zone_overrides": body.zone_overrides, + "judge": { + "endpoint": body.judge_endpoint, + "model": body.judge_model, + "api_key": api_key, + "timeout_seconds": body.judge_timeout_seconds, + }, + } + ) + # 预构建是事务的第一步:未知检测器或 options 错误必须不影响当前运行态和文件。 + candidate = pipeline_factory(next_config.apply_to(base_config)) + except (ValidationError, ValueError) as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + except ConfigError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + # save 采用临时文件 + replace;成功后才切换内存配置。candidate 已通过完整构建校验。 + previous_zones = pipeline.detector_zones + previous_names = { + zone: [getattr(detector, "name", detector.__class__.__name__) for detector in detectors] + for zone, detectors in previous_zones.items() + } + next_names = next_config.detector_zones() + changed_zones = [ + zone for zone, names in next_names.items() if previous_names.get(zone) != names + ] + store.save(next_config) + pipeline.replace_detector_zones(candidate.detector_zones) + try: + await pipeline.record( + Context(session_id=f"security-config:{principal.user_id}"), + AuditEventType.SECURITY_CONFIG_UPDATED, + subject_id=str(principal.user_id), + evidence={ + "actor": principal.username, + "previous_profile": current.profile, + "profile": next_config.profile, + "changed_zones": changed_zones, + "detector_zones": next_names, + "detector_revisions": { + zone: candidate.detector_zone_summary(zone)["revision"] + for zone in next_names + }, + # 只记录 judge 是否配置与是否满足隔离档,不记录 endpoint 或密钥。 + "judge_configured": bool(next_config.judge.api_key), + "air_gapped": next_config.profile == "air_gapped", + }, + ) + except Exception as exc: # noqa: BLE001 -- 配置生效必须与审计留痕同成败 + try: + store.save(current) + pipeline.replace_detector_zones(previous_zones) + except Exception: # noqa: BLE001 -- 返回通用错误,避免泄露配置内部细节 + pass + raise HTTPException(status_code=500, detail="安全配置审计失败,变更未生效") from exc + return _public(next_config) diff --git a/src/fulcrum/adapters/security_config.py b/src/fulcrum/adapters/security_config.py new file mode 100644 index 0000000..d80ad8f --- /dev/null +++ b/src/fulcrum/adapters/security_config.py @@ -0,0 +1,228 @@ +"""分级安全预设的持久化与展开。 + +本模块只保存安全检测配置,不保存模型主对话或网关接入配置。judge 密钥可以落盘,但 +公开 DTO 仅回传掩码;真正的运行时替换由 API 路由先构建候选管线后完成。 +""" + +from __future__ import annotations + +import copy +import ipaddress +import os +import tempfile +from pathlib import Path +from typing import Any, Literal +from urllib.parse import urlparse + +from pydantic import BaseModel, Field, field_validator, model_validator + +from ..config import DETECTOR_ZONES, normalize_detector_zones +from ..core.errors import ConfigError +from .net_guard import validate_endpoint + +SecurityProfile = Literal["lightweight", "standard", "strict", "air_gapped"] + +_RULE_DETECTORS = ( + "keyword_rules", + "secret_egress", + "manifest_guard", + "disclosure_egress", + "exfil_channel", +) +_CASCADE_DETECTORS = ( + "injection_cascade", + "secret_egress", + "manifest_guard", + "disclosure_egress", + "exfil_channel", +) +_FULL_JUDGE_DETECTORS = ( + "keyword_rules", + "llm_judge", + "secret_egress", + "manifest_guard", + "disclosure_egress", + "exfil_channel", +) + + +def _same_for_all(detectors: tuple[str, ...]) -> dict[str, list[str]]: + return {zone: list(detectors) for zone in DETECTOR_ZONES} + + +def profile_detector_zones(profile: SecurityProfile) -> dict[str, list[str]]: + """返回预设完整展开后的四区检测器集合。""" + if profile == "lightweight": + return _same_for_all(_RULE_DETECTORS) + if profile == "strict": + return _same_for_all(_FULL_JUDGE_DETECTORS) + # 标准与合规档都用级联,差异仅在合规档的 judge 端点只能是本机回环地址。 + return _same_for_all(_CASCADE_DETECTORS) + + +def available_detector_names(base_config: dict[str, Any]) -> list[str]: + """返回控制台可选检测器的稳定去重清单,不暴露实现 options。""" + names: list[str] = [] + seen: set[str] = set() + + def add(detector: str) -> None: + if detector not in seen: + seen.add(detector) + names.append(detector) + + baseline_zones = normalize_detector_zones(base_config["detectors"]) + for zone in DETECTOR_ZONES: + for detector in baseline_zones[zone]: + add(detector) + for profile in ("lightweight", "standard", "strict", "air_gapped"): + for zone in DETECTOR_ZONES: + for detector in profile_detector_zones(profile)[zone]: + add(detector) + return names + + +def _is_loopback_endpoint(endpoint: str) -> bool: + parsed = urlparse(endpoint) + host = (parsed.hostname or "").lower().rstrip(".") + if host == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +class JudgeConfig(BaseModel): + """语义 judge 的连接信息;仅本模块内部持有 api_key 明文。""" + + endpoint: str = Field(default="http://127.0.0.1:8123/v1", max_length=512) + model: str = Field(default="qwen3-8b", min_length=1, max_length=128) + api_key: str = Field(default="", max_length=2048) + timeout_seconds: float = Field(default=20.0, ge=1, le=120) + + @field_validator("endpoint") + @classmethod + def _validate_endpoint(cls, value: str) -> str: + return validate_endpoint(value.strip()) + + +class SecurityConfig(BaseModel): + """落盘安全配置:预设先展开,随后由 zone_overrides 覆盖指定区域。""" + + # 首启必须保持既有规则基线;Judge 级联由管理员显式切换预设后才启用。 + profile: SecurityProfile = "lightweight" + zone_overrides: dict[str, list[str]] = Field(default_factory=dict) + judge: JudgeConfig = Field(default_factory=JudgeConfig) + + @model_validator(mode="after") + def _validate_profile(self) -> SecurityConfig: + unknown = sorted(set(self.zone_overrides) - set(DETECTOR_ZONES)) + if unknown: + raise ValueError(f"未知检测区域:{unknown}") + for zone, names in self.zone_overrides.items(): + if any(not isinstance(name, str) or not name.strip() for name in names): + raise ValueError(f"区域 {zone} 的检测器名称不能为空") + if self.profile != "lightweight" and not self.judge.endpoint.strip(): + raise ValueError("启用 judge 的预设必须配置 judge endpoint") + if self.profile == "air_gapped" and not _is_loopback_endpoint(self.judge.endpoint): + raise ValueError("air_gapped 预设的 judge endpoint 仅允许 localhost 或 loopback 地址") + return self + + def detector_zones(self) -> dict[str, list[str]]: + zones = profile_detector_zones(self.profile) + for zone, names in self.zone_overrides.items(): + zones[zone] = list(names) + return zones + + def apply_to(self, base_config: dict[str, Any]) -> dict[str, Any]: + """生成可交给 build_pipeline 的完整候选配置,不改动静态基线。""" + cfg = copy.deepcopy(base_config) + cfg["detectors"] = self.detector_zones() + cfg.pop("detector_zones", None) + options = cfg.setdefault("options", {}) + judge = { + "endpoint": self.judge.endpoint, + "model": self.judge.model, + "api_key": self.judge.api_key, + "timeout": self.judge.timeout_seconds, + } + if self.profile != "lightweight": + options["llm_judge"] = dict(judge) + options["injection_cascade"] = { + "gray_low": 0.0, + "gray_high": 0.6, + "judge": dict(judge), + } + return cfg + + +def _mask(secret: str) -> str: + if not secret: + return "" + return ("*" * 6 + secret[-4:]) if len(secret) > 4 else "*" * len(secret) + + +class SecurityConfigPublic(BaseModel): + profile: SecurityProfile + detector_zones: dict[str, list[str]] + judge_endpoint: str + judge_model: str + judge_api_key_masked: str + judge_api_key_set: bool + judge_timeout_seconds: float + + @classmethod + def of(cls, cfg: SecurityConfig) -> SecurityConfigPublic: + return cls( + profile=cfg.profile, + detector_zones=cfg.detector_zones(), + judge_endpoint=cfg.judge.endpoint, + judge_model=cfg.judge.model, + judge_api_key_masked=_mask(cfg.judge.api_key), + judge_api_key_set=bool(cfg.judge.api_key), + judge_timeout_seconds=cfg.judge.timeout_seconds, + ) + + +class SecurityConfigStore: + """安全预设 JSON 存储;低频写使用临时文件 + replace 保证原子性。""" + + def __init__(self, path: str, seed: SecurityConfig | None = None) -> None: + self._path = Path(path) + self._seed = seed or SecurityConfig() + self._cache: SecurityConfig | None = None + + def load(self) -> SecurityConfig: + if self._cache is not None: + return self._cache + if self._path.is_file(): + try: + self._cache = SecurityConfig.model_validate_json( + self._path.read_text(encoding="utf-8") + ) + except (OSError, ValueError) as exc: + raise ConfigError(f"安全配置文件无法读取或校验:{self._path}") from exc + else: + self._cache = self._seed + self._write(self._cache) + return self._cache + + def save(self, cfg: SecurityConfig) -> SecurityConfig: + self._write(cfg) + self._cache = cfg + return cfg + + def _write(self, cfg: SecurityConfig) -> None: + self._path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=str(self._path.parent), suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(cfg.model_dump_json(indent=2)) + os.replace(tmp, self._path) + try: + os.chmod(self._path, 0o600) + except OSError: + pass + finally: + if os.path.exists(tmp): + os.unlink(tmp) diff --git a/src/fulcrum/app.py b/src/fulcrum/app.py index 19c14ef..7615cd8 100644 --- a/src/fulcrum/app.py +++ b/src/fulcrum/app.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any from .capabilities import load_builtin_capabilities -from .config import Settings, load_capability_config +from .config import Settings, load_capability_config, normalize_detector_zones from .core.pipeline import SecurityPipeline from .core.registry import registry from .observability import configure_logging @@ -34,13 +34,28 @@ def build_pipeline(config: dict[str, Any] | None = None) -> SecurityPipeline: # per-capability 参数注入:options.<注册名> → registry.create(kind, name, **那些参数)。 # 统一约定,避免各队友各自发明配置侧门(env/硬编码);无条目=无参构造,向后兼容。 opts: dict[str, Any] = cfg.get("options") or {} + # 直接调用 build_pipeline 的评测/集成代码也必须经过同一份 schema 校验;不能信任 + # 调用方可能预填的派生字段 detector_zones。 + detector_zones = normalize_detector_zones(cfg["detectors"]) def make(kind: str, name: str) -> Any: return registry.create(kind, name, **(opts.get(name) or {})) + # 分区配置中的每个名称都在构建期实例化,拼错的检测器不会等到某个流量路径才暴露。 + detector_names = dict.fromkeys(name for names in detector_zones.values() for name in names) + detectors_by_name = {name: make("detector", name) for name in detector_names} + return SecurityPipeline( labeler=make("labeler", cfg["labeler"]), - detectors=[make("detector", name) for name in cfg["detectors"]], + # P_a-2 前仍按旧的全局检测逻辑运行;这里保留扁平配置的调用顺序和重复项语义。 + detectors=[ + detectors_by_name[name] + for name in (cfg["detectors"] if isinstance(cfg["detectors"], list) else detector_names) + ], + detector_zones={ + zone: [detectors_by_name[name] for name in names] + for zone, names in detector_zones.items() + }, attributor=make("attributor", cfg["attributor"]), risk_scorer=make("risk_scorer", cfg["risk_scorer"]), chain_analyzer=make("chain_analyzer", cfg["chain_analyzer"]), @@ -64,6 +79,7 @@ def create_app(settings: Settings | None = None) -> FastAPI: from .adapters.api import build_api from .adapters.auth import build_auth_bundle from .adapters.gateway import GatewayConfig, GatewayConfigStore, UpstreamForwarder + from .adapters.security_config import SecurityConfigStore # 上游接入配置:首启以 .env 的 upstream_agent_endpoint 作默认地址, # 之后以落盘配置为准(设置页可改、热加载)。 @@ -71,10 +87,25 @@ def create_app(settings: Settings | None = None) -> FastAPI: store = GatewayConfigStore(settings.gateway_config_path, seed=seed) upstream = UpstreamForwarder(store) - pipeline = build_pipeline(cfg) # 触发 _load_builtins,注册表此后含 scanner + # 分级安全配置以静态能力清单为基线,首启默认标准档;以后从持久化配置恢复并热加载。 + security_store = SecurityConfigStore(settings.security_config_path) + security_config = security_store.load() + pipeline = build_pipeline( + security_config.apply_to(cfg) + ) # 触发 _load_builtins,注册表此后含 scanner # 供应链扫描器经组装根注入 API(不入管线装配 —— 离线关切;adapters 不依赖 capabilities)。 scanner = registry.create("scanner", "manifest") - app = build_api(pipeline, build_auth_bundle(settings), settings, upstream, store, scanner) + app = build_api( + pipeline, + build_auth_bundle(settings), + settings, + upstream, + store, + scanner, + security_store=security_store, + capability_config=cfg, + pipeline_factory=build_pipeline, + ) _maybe_start_live_feed(app, pipeline, settings, upstream) return app diff --git a/src/fulcrum/config/__init__.py b/src/fulcrum/config/__init__.py index fff0fdc..cc63e21 100644 --- a/src/fulcrum/config/__init__.py +++ b/src/fulcrum/config/__init__.py @@ -2,7 +2,7 @@ from __future__ import annotations -from .loader import load_capability_config +from .loader import DETECTOR_ZONES, load_capability_config, normalize_detector_zones from .settings import Settings -__all__ = ["Settings", "load_capability_config"] +__all__ = ["DETECTOR_ZONES", "Settings", "load_capability_config", "normalize_detector_zones"] diff --git a/src/fulcrum/config/fulcrum.yml b/src/fulcrum/config/fulcrum.yml index 5fb7e2a..aeb92e1 100644 --- a/src/fulcrum/config/fulcrum.yml +++ b/src/fulcrum/config/fulcrum.yml @@ -4,11 +4,16 @@ labeler: role_trust # 真·多源信任标注(角色归类 + 嵌入来源抽取);passthrough 为最小桩 detectors: - - keyword_rules # 多源规则检测器(六类风险 + 来源加权 + 分级) - - secret_egress # 出口凭据/系统提示泄露检测(连接串/云密钥/私钥/Bearer + LLM07) - - manifest_guard # 请求路径 manifest 哨兵:组件清单评估请求 → 抽取 → 扫描器分级处置 - - disclosure_egress # 出口自披露:策略原文 / 工具清单泄露(双条件高精度) - - exfil_channel # 出站外泄信道:带外汇点册 / 即时通讯 webhook / DNS 隧道(高精度) + # 四区显式同配以保持旧扁平清单的行为;后续可按区域独立调整。 + gateway_input: &default_detectors + - keyword_rules # 多源规则检测器(六类风险 + 来源加权 + 分级) + - secret_egress # 出口凭据/系统提示泄露检测(连接串/云密钥/私钥/Bearer + LLM07) + - manifest_guard # 请求路径 manifest 哨兵:组件清单评估请求 → 抽取 → 扫描器分级处置 + - disclosure_egress # 出口自披露:策略原文 / 工具清单泄露(双条件高精度) + - exfil_channel # 出站外泄信道:带外汇点册 / 即时通讯 webhook / DNS 隧道(高精度) + gateway_output: *default_detectors + tool_return: *default_detectors + assistant_intent: *default_detectors # 语义兜底(P6,可选,私有化合规推荐):抓无触发词的中文社工注入。二选一: # · injection_cascade —— keyword+judge 级联(**推荐**:规则已拦的不重判,judge 调用减半),启用时把上面 `- keyword_rules` 删掉(级联已内含),见 options.injection_cascade # · llm_judge —— 纯 judge 全量(每条都判),与 keyword_rules 并列,见 options.llm_judge diff --git a/src/fulcrum/config/loader.py b/src/fulcrum/config/loader.py index 3afe07d..3a8ff7f 100644 --- a/src/fulcrum/config/loader.py +++ b/src/fulcrum/config/loader.py @@ -27,6 +27,54 @@ "audit", ) +# 四道安全闸门是分区检测配置的固定契约。新增区域需要同步评审管线入口、审计口径和 +# 控制台展示,不能让 YAML 任意扩张后静默失效。 +DETECTOR_ZONES: tuple[str, ...] = ( + "gateway_input", + "gateway_output", + "tool_return", + "assistant_intent", +) + + +def normalize_detector_zones(detectors: Any) -> dict[str, list[str]]: + """把旧扁平 detectors 或四区映射规范化为按区域的检测器名称。 + + 扁平列表是历史配置,语义保持为四个区域使用完全相同的检测器集。新的映射格式 + 必须显式覆盖全部固定区域,避免漏配区域在运行期退化为无检测。 + """ + if isinstance(detectors, list): + names = _validate_detector_names(detectors, "detectors") + return {zone: list(names) for zone in DETECTOR_ZONES} + + if not isinstance(detectors, dict): + raise ConfigError("detectors 必须是检测器名称列表或按区域分组的映射") + + configured = set(detectors) + expected = set(DETECTOR_ZONES) + unknown = sorted(configured - expected) + missing = sorted(expected - configured) + if unknown or missing: + details: list[str] = [] + if unknown: + details.append(f"未知区域:{unknown}") + if missing: + details.append(f"缺少区域:{missing}") + raise ConfigError(f"detectors 分区配置无效({'; '.join(details)})") + + return { + zone: _validate_detector_names(detectors[zone], f"detectors.{zone}") + for zone in DETECTOR_ZONES + } + + +def _validate_detector_names(value: Any, field: str) -> list[str]: + if not isinstance(value, list): + raise ConfigError(f"{field} 必须是检测器名称列表") + if any(not isinstance(name, str) or not name.strip() for name in value): + raise ConfigError(f"{field} 只能包含非空检测器名称") + return [name.strip() for name in value] + def load_capability_config(path: str | None = None) -> dict[str, Any]: cfg_path = Path(path) if path else _DEFAULT_CONFIG @@ -37,4 +85,6 @@ def load_capability_config(path: str | None = None) -> dict[str, Any]: missing = [k for k in _REQUIRED_KEYS if k not in data] if missing: raise ConfigError(f"装配清单缺少字段:{missing}(文件:{cfg_path})") + # 保留原 detectors 字段,供旧调用方读取;规范化结果是新区域化契约的单一入口。 + data["detector_zones"] = normalize_detector_zones(data["detectors"]) return data diff --git a/src/fulcrum/config/settings.py b/src/fulcrum/config/settings.py index 135681a..4eba247 100644 --- a/src/fulcrum/config/settings.py +++ b/src/fulcrum/config/settings.py @@ -29,6 +29,8 @@ class Settings(BaseSettings): gateway_config_path: str = "data/runtime/gateway.json" # 控制台实例元信息落盘路径(JSON);同上挂卷即持久化。 console_settings_path: str = "data/runtime/console.json" + # 分级安全预设与按区覆盖落盘路径(JSON);保存后热替换运行中的检测器配置。 + security_config_path: str = "data/runtime/security.json" # 操作助手多轮对话记忆目录(一会话一文件);落盘故重启不丢,挂卷即持久化。 conversation_dir: str = "data/runtime/conversations" # 操作助手模型接入配置落盘路径(JSON;协议/端点/密钥/模型名);设置页可改、热加载。 diff --git a/src/fulcrum/core/domain/enums.py b/src/fulcrum/core/domain/enums.py index b1e229e..26fc846 100644 --- a/src/fulcrum/core/domain/enums.py +++ b/src/fulcrum/core/domain/enums.py @@ -56,3 +56,4 @@ class AuditEventType(StrEnum): ASSISTANT_CHAT = "assistant_chat" # AI 操作助手(真 Agent):一次会话(意图/入口判定/产出) ASSISTANT_ACTED = "assistant_acted" # 助手写提案被确认执行(tool/参数摘要/结果/undo 句柄) ASSISTANT_UNDONE = "assistant_undone" # 已执行写操作被一键撤销(tool/回滚前后) + SECURITY_CONFIG_UPDATED = "security_config_updated" # 分级安全配置已变更并生效 diff --git a/src/fulcrum/core/pipeline.py b/src/fulcrum/core/pipeline.py index e5cb748..7a84e6b 100644 --- a/src/fulcrum/core/pipeline.py +++ b/src/fulcrum/core/pipeline.py @@ -8,6 +8,7 @@ import hashlib import json +from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from typing import TYPE_CHECKING @@ -78,6 +79,9 @@ def _sanitize_args(arguments: dict) -> tuple[dict, list[str]]: # 来源最坏信任级归约:与 yaml_policy 共用 core.trust 单一真源(消除口径漂移,评审 M1)。 _intent_source_trust = intent_worst_trust +_DETECTOR_ZONE_NAMES = frozenset( + {"gateway_input", "gateway_output", "tool_return", "assistant_intent"} +) @dataclass(slots=True) @@ -103,6 +107,7 @@ def __init__( *, labeler: SourceLabeler, detectors: list[Detector], + detector_zones: dict[str, list[Detector]] | None = None, attributor: Attributor, risk_scorer: RiskScorer, chain_analyzer: ChainAnalyzer, @@ -114,6 +119,8 @@ def __init__( ) -> None: self._labeler = labeler self._detectors = detectors + # P_a-1 只承载已校验的区域配置契约;P_a-2 再让各闸门按该映射调度。 + self._detector_zones = detector_zones or {} self._attributor = attributor self._risk_scorer = risk_scorer self._chain_analyzer = chain_analyzer @@ -133,6 +140,41 @@ def policy(self) -> PolicyEngine: """只读访问策略引擎(供策略中心展示「当前装配的策略」)。""" return self._policy + @property + def detector_zones(self) -> dict[str, tuple[Detector, ...]]: + """按区域生效的检测器,只读暴露给编排和配置查询层。""" + return {zone: tuple(detectors) for zone, detectors in self._detector_zones.items()} + + def replace_detector_zones(self, detector_zones: Mapping[str, Sequence[Detector]]) -> None: + """原子切换已构建的四区检测器配置,供设置保存后的热加载使用。 + + 调用方须先在管线外构建候选配置;本方法只接受完整四区,拒绝半套配置造成某一 + 闸门静默失防。legacy 全局列表同步替换为按区域首次出现顺序去重后的并集。 + """ + if set(detector_zones) != _DETECTOR_ZONE_NAMES: + raise ValueError("检测器热更新必须提供完整四区配置") + zones = {zone: list(detector_zones[zone]) for zone in sorted(_DETECTOR_ZONE_NAMES)} + all_detectors: list[Detector] = [] + seen: set[int] = set() + for zone in ("gateway_input", "gateway_output", "tool_return", "assistant_intent"): + for detector in zones[zone]: + if id(detector) not in seen: + seen.add(id(detector)) + all_detectors.append(detector) + self._detectors = all_detectors + self._detector_zones = zones + + def detector_zone_summary(self, zone: str | None) -> dict[str, object]: + """返回可审计的区域配置摘要,不包含检测器 options 中的密钥或端点。""" + detectors = self._detectors_for_zone(zone) + names = [getattr(detector, "name", detector.__class__.__name__) for detector in detectors] + canonical = json.dumps({"zone": zone, "detectors": names}, ensure_ascii=False) + return { + "zone": zone or "legacy", + "detectors": names, + "revision": hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16], + } + def model_tool_schemas(self) -> list[dict]: """装配工具里声明了 model_schema 的 OpenAI function 规格列表。 @@ -156,7 +198,7 @@ async def handle_model_request(self, req: ModelRequest) -> PipelineResult: ctx, AuditEventType.SOURCE_LABELED, evidence={"span_count": len(ctx.spans)} ) - await self.detect_inputs(ctx, ctx.spans) + await self.detect_inputs(ctx, ctx.spans, zone="gateway_input") # 输入闸门:据检测结论决定是否转发给模型。此前 detect_inputs 的结果被**丢弃**、无条件转发, # 经此端点进来的高危注入照样喂模型;且多来源分片规避(gateway._effective_score)因唯一的多 @@ -230,7 +272,7 @@ async def screen_input( ctx, AuditEventType.SOURCE_LABELED, evidence={"span_count": len(ctx.spans)} ) - await self.detect_inputs(ctx, ctx.spans) + await self.detect_inputs(ctx, ctx.spans, zone="gateway_input") verdict = screen(ctx.findings) # 富化判定证据:把"这条输入凭什么这么判"的可展示依据落进审计 —— 供事件页逐事件 @@ -250,6 +292,7 @@ async def screen_input( "source_type": SourceType.USER.value, "trust_level": TrustLevel.UNTRUSTED.value, "stage": "input_gateway", + "detector_config": self.detector_zone_summary("gateway_input"), "team_id": team_id, # 团队级数据隔离(P2);None=无归属,对所有 events.view 可见 }, ) @@ -282,7 +325,7 @@ async def screen_output( content=text, # 检测看全文:载荷放在 600 字符后也不漏检 ) ] - await self.detect_inputs(ctx, ctx.spans) + await self.detect_inputs(ctx, ctx.spans, zone="gateway_output") verdict = screen_output(ctx.findings) await self._emit( @@ -299,6 +342,7 @@ async def screen_output( "source_type": SourceType.ASSISTANT.value, "trust_level": TrustLevel.UNTRUSTED.value, "stage": "output_gateway", + "detector_config": self.detector_zone_summary("gateway_output"), "team_id": team_id, # 团队级数据隔离(P2) }, ) @@ -327,7 +371,7 @@ async def screen_tool_return( content=text, # 检测看全文:载荷放在 600 字符后也不漏检 ) ] - await self.detect_inputs(ctx, ctx.spans) + await self.detect_inputs(ctx, ctx.spans, zone="tool_return") verdict = screen(ctx.findings) await self._emit( @@ -344,6 +388,7 @@ async def screen_tool_return( "source_type": SourceType.TOOL_RETURN.value, "trust_level": TrustLevel.UNTRUSTED.value, "stage": "tool_return_gateway", + "detector_config": self.detector_zone_summary("tool_return"), "team_id": team_id, # 团队级数据隔离(P2) }, ) @@ -375,6 +420,21 @@ async def evaluate_intent(self, intent: ToolIntent, ctx: Context) -> ToolOutcome spans / request_trace 能被归因与链分析看见。demo 与真实网关都经此单一真源—— fail-closed 等内核保证对它们一视同仁,适配器不再各自手撸评估链。 """ + # 模型规划出的参数同样是不可信输入面:它可能携带工具返回中的间接指令,或在 + # 规划阶段被污染。仅有审计 zone 而不实际检测会形成安全盲点,因此先按助手 + # 工具治理区域复扫,再进入既有的归因、评分和策略链。 + intent_text = json.dumps(intent.arguments, ensure_ascii=False, default=str) + assistant_span = SourceSpan( + source_type=SourceType.ASSISTANT, + trust_level=TrustLevel.UNTRUSTED, + content_hash=hashlib.sha256(intent_text.encode("utf-8")).hexdigest(), + excerpt=intent_text[:600], + content=intent_text, + ) + # 此 span 只供本次检测器扫描,不能写入 ctx.spans:后者是归因/策略的既有来源 + # 证据集合。把模型参数伪装成不可信来源放进去,会把正常的高风险业务动作从 + # APPROVE 错升为 BLOCK,破坏原有审批语义。 + await self.detect_inputs(ctx, [assistant_span], zone="assistant_intent") return await self._process_intent(intent, ctx) # ---- 共用:对单个工具意图做 归因 -> 评分 -> 策略 -> 处置 -> 审计 ---- @@ -420,6 +480,7 @@ async def _process_intent(self, intent: ToolIntent, ctx: Context) -> ToolOutcome "attribution_confidence": intent.attribution_confidence, "source_trust": _intent_source_trust(intent, ctx), "matched_policy": decision.matched_policy_id, + "detector_config": self.detector_zone_summary("assistant_intent"), }, ) @@ -525,20 +586,27 @@ async def _fail_closed( return ToolOutcome(intent=intent, decision=decision) # ---- 输入检测(供 agent 循环复用:用户输入 / 工具返回间接注入 走同一套检测器)---- - async def detect_inputs(self, ctx: Context, spans: list[SourceSpan]) -> list[Finding]: - """对一批新输入 span 跑全部检测器(逐个 fail-closed),累积进 ctx + 落审计,返回新增。""" - new = await self._run_detectors(ctx, spans) + async def detect_inputs( + self, ctx: Context, spans: list[SourceSpan], *, zone: str | None = None + ) -> list[Finding]: + """对一批新输入按区域跑检测器(逐个 fail-closed),累积进 ctx + 审计。""" + new = await self._run_detectors(ctx, spans, zone=zone) await self._emit( ctx, AuditEventType.INPUT_DETECTED, - evidence={"findings": [f.model_dump() for f in new]}, + evidence={ + "findings": [f.model_dump() for f in new], + "detector_config": self.detector_zone_summary(zone), + }, ) return new # ---- 检测:逐个检测器 fail-closed(某检测器崩溃 → 合成高危 Finding,绝不静默放行)---- - async def _run_detectors(self, ctx: Context, spans: list[SourceSpan]) -> list[Finding]: + async def _run_detectors( + self, ctx: Context, spans: list[SourceSpan], *, zone: str | None = None + ) -> list[Finding]: new: list[Finding] = [] - for detector in self._detectors: + for detector in self._detectors_for_zone(zone): try: new.extend(detector.detect(spans, ctx)) except Exception as exc: # noqa: BLE001 —— 检测器崩溃当作高危信号,不得 fail-open @@ -558,6 +626,15 @@ async def _run_detectors(self, ctx: Context, spans: list[SourceSpan]) -> list[Fi ctx.findings.extend(new) return new + def _detectors_for_zone(self, zone: str | None) -> list[Detector]: + """保留直接构造旧管线的全局列表兼容,分区配置缺失则 fail-closed。""" + if zone is None or not self._detector_zones: + return self._detectors + detectors = self._detector_zones.get(zone) + if detectors is None: + raise ValueError(f"未配置检测区域:{zone}") + return detectors + # ---- 审计 helper ---- async def _emit( self, diff --git a/tests/test_detector_zone_config.py b/tests/test_detector_zone_config.py new file mode 100644 index 0000000..243f924 --- /dev/null +++ b/tests/test_detector_zone_config.py @@ -0,0 +1,153 @@ +"""区域检测配置契约:新分区格式与旧扁平格式都须在构建期严格校验。""" + +from __future__ import annotations + +import asyncio +import copy + +import pytest + +from fulcrum.adapters.audit.memory_sink import InMemoryAuditSink +from fulcrum.adapters.model.fake_client import FakeModelClient +from fulcrum.app import build_pipeline +from fulcrum.capabilities import load_builtin_capabilities +from fulcrum.config import DETECTOR_ZONES, load_capability_config, normalize_detector_zones +from fulcrum.core.domain import Context, ToolIntent +from fulcrum.core.errors import ConfigError +from fulcrum.core.pipeline import SecurityPipeline +from fulcrum.core.registry import registry + + +class _RecordingDetector: + """不依赖规则内容,直接记录被哪个区域调用的测试替身。""" + + def __init__(self, name: str, calls: list[str]) -> None: + self.name = name + self._calls = calls + + def detect(self, _spans: object, _ctx: object) -> list: + self._calls.append(self.name) + return [] + + +def _base_config(detectors: object) -> dict: + return { + "labeler": "passthrough", + "detectors": detectors, + "attributor": "evidence", + "risk_scorer": "heuristic", + "chain_analyzer": "noop", + "policy": "allow_all", + "executor": "echo", + "tools": ["echo"], + "model": "fake", + "audit": "memory", + } + + +def test_flat_detector_list_maps_to_all_zones() -> None: + zones = normalize_detector_zones(["keyword_rules", "secret_egress"]) + + assert tuple(zones) == DETECTOR_ZONES + assert all(names == ["keyword_rules", "secret_egress"] for names in zones.values()) + + +def test_grouped_config_keeps_independent_detector_sets() -> None: + config = _base_config( + { + "gateway_input": ["keyword_rules"], + "gateway_output": ["secret_egress"], + "tool_return": ["keyword_rules", "secret_egress"], + "assistant_intent": [], + } + ) + pipeline = build_pipeline(config) + + assert [detector.name for detector in pipeline.detector_zones["gateway_input"]] == [ + "keyword_rules" + ] + assert [detector.name for detector in pipeline.detector_zones["gateway_output"]] == [ + "secret_egress" + ] + assert pipeline.detector_zones["assistant_intent"] == () + + +@pytest.mark.parametrize( + ("detectors", "message"), + [ + ({"gateway_input": []}, "缺少区域"), + ( + { + "gateway_input": [], + "gateway_output": [], + "tool_return": [], + "assistant_intent": [], + "typo_zone": [], + }, + "未知区域", + ), + ({zone: "keyword_rules" for zone in DETECTOR_ZONES}, "必须是检测器名称列表"), + ], +) +def test_invalid_zone_schema_rejected(detectors: object, message: str) -> None: + with pytest.raises(ConfigError, match=message): + build_pipeline(_base_config(detectors)) + + +def test_unknown_detector_rejected_during_pipeline_build() -> None: + config = _base_config({zone: ["does_not_exist"] for zone in DETECTOR_ZONES}) + + with pytest.raises(ConfigError, match="未找到能力实现"): + build_pipeline(config) + + +def test_default_config_declares_all_detector_zones() -> None: + config = load_capability_config() + + assert isinstance(config["detectors"], dict) + assert tuple(config["detector_zones"]) == DETECTOR_ZONES + # 复制后改动一个区域不应污染其他区域(即使 YAML 用 anchor 表示默认同配)。 + zones = copy.deepcopy(config["detector_zones"]) + zones["gateway_input"].pop() + assert zones["gateway_input"] != zones["gateway_output"] + + +def _zoned_pipeline(calls: list[str]) -> SecurityPipeline: + load_builtin_capabilities() + zones = {zone: [_RecordingDetector(zone, calls)] for zone in DETECTOR_ZONES} + return SecurityPipeline( + labeler=registry.create("labeler", "passthrough"), + detectors=[detector for detectors in zones.values() for detector in detectors], + detector_zones=zones, + attributor=registry.create("attributor", "zero"), + risk_scorer=registry.create("risk_scorer", "zero"), + chain_analyzer=registry.create("chain_analyzer", "noop"), + policy=registry.create("policy", "allow_all"), + executor=registry.create("executor", "echo"), + tools={"echo": registry.create("tool", "echo")}, + audit=InMemoryAuditSink(), + model_client=FakeModelClient(), + ) + + +def test_each_security_entry_uses_its_detector_zone_and_audits_summary() -> None: + calls: list[str] = [] + pipeline = _zoned_pipeline(calls) + + asyncio.run(pipeline.screen_input("zones", "正常输入")) + asyncio.run(pipeline.screen_output("zones", "正常回复")) + asyncio.run(pipeline.screen_tool_return("zones", "正常工具返回")) + asyncio.run( + pipeline.evaluate_intent( + ToolIntent(session_id="zones", tool_name="echo", arguments={"text": "正常参数"}), + Context(session_id="zones"), + ) + ) + + assert calls == list(DETECTOR_ZONES) + events = asyncio.run(pipeline.audit.events("zones")) + summaries = [event.evidence.get("detector_config") for event in events] + summaries = [summary for summary in summaries if summary] + assert {summary["zone"] for summary in summaries} >= set(DETECTOR_ZONES) + assert all(len(str(summary["revision"])) == 16 for summary in summaries) + assert all("options" not in summary for summary in summaries) diff --git a/tests/test_security_config.py b/tests/test_security_config.py new file mode 100644 index 0000000..0500aae --- /dev/null +++ b/tests/test_security_config.py @@ -0,0 +1,226 @@ +"""分级安全预设:展开、私有化边界、持久化与运行中管线热替换。""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient +from pydantic import ValidationError + +from fulcrum.adapters.api.security_config_routes import register_security_config_routes +from fulcrum.adapters.auth.models import Principal +from fulcrum.adapters.security_config import ( + SecurityConfig, + SecurityConfigStore, + available_detector_names, +) +from fulcrum.app import build_pipeline +from fulcrum.config import DETECTOR_ZONES +from fulcrum.core.domain import AuditEventType +from fulcrum.core.errors import ConfigError +from fulcrum.core.pipeline import SecurityPipeline + +_BASE_CONFIG = { + "labeler": "passthrough", + "detectors": ["keyword_rules"], + "attributor": "evidence", + "risk_scorer": "heuristic", + "chain_analyzer": "noop", + "policy": "allow_all", + "executor": "echo", + "tools": ["echo"], + "model": "fake", + "audit": "memory", +} + + +class _Deps: + def __init__(self, permissions: frozenset[str]) -> None: + self._principal = Principal( + user_id=1, + username="admin", + display_name="管理员", + role_key="admin", + role_name="管理员", + permissions=permissions, + ) + + def require(self, permission: str): # type: ignore[no-untyped-def] + def _guard() -> Principal: + if permission not in self._principal.permissions: + raise HTTPException(status_code=403, detail=f"无权限:需要 {permission}") + return self._principal + + return _guard + + +def _client( + tmp_path: Path, permissions: frozenset[str] +) -> tuple[TestClient, SecurityPipeline, SecurityConfigStore]: + store = SecurityConfigStore(str(tmp_path / "security.json")) + pipeline = build_pipeline(store.load().apply_to(_BASE_CONFIG)) + app = FastAPI() + register_security_config_routes( + app, + pipeline, + store, + _BASE_CONFIG, + build_pipeline, + _Deps(permissions), # type: ignore[arg-type] + ) + return TestClient(app), pipeline, store + + +@pytest.mark.parametrize("profile", ["lightweight", "standard", "strict", "air_gapped"]) +def test_profile_expands_to_all_detector_zones(profile: str) -> None: + config = SecurityConfig(profile=profile) # type: ignore[arg-type] + + zones = config.detector_zones() + assert tuple(zones) == DETECTOR_ZONES + assert all(isinstance(names, list) for names in zones.values()) + + +def test_default_profile_preserves_existing_rule_baseline() -> None: + config = SecurityConfig() + + assert config.profile == "lightweight" + assert all("injection_cascade" not in names for names in config.detector_zones().values()) + + +def test_zone_override_replaces_only_that_zone() -> None: + config = SecurityConfig( + profile="standard", zone_overrides={"gateway_output": ["secret_egress"]} + ) + + zones = config.detector_zones() + assert zones["gateway_output"] == ["secret_egress"] + assert "injection_cascade" in zones["gateway_input"] + + +def test_available_detectors_merges_static_baseline_and_all_profiles() -> None: + names = available_detector_names(_BASE_CONFIG) + + assert names[0] == "keyword_rules" + assert "injection_cascade" in names + assert "llm_judge" in names + assert len(names) == len(set(names)) + + +@pytest.mark.parametrize("endpoint", ["", "https://8.8.8.8/v1", "http://10.0.0.2/v1"]) +def test_air_gapped_rejects_missing_or_non_loopback_judge(endpoint: str) -> None: + with pytest.raises(ValidationError): + SecurityConfig(profile="air_gapped", judge={"endpoint": endpoint, "model": "local"}) + + +def test_store_persists_and_public_view_masks_judge_key(tmp_path: Path) -> None: + path = str(tmp_path / "security.json") + store = SecurityConfigStore(path) + store.save(SecurityConfig(judge={"api_key": "supersecret123"})) + + assert SecurityConfigStore(path).load().judge.api_key == "supersecret123" + + +def test_corrupt_security_config_refuses_to_lower_the_profile(tmp_path: Path) -> None: + path = tmp_path / "security.json" + path.write_text("{not-json", encoding="utf-8") + + with pytest.raises(ConfigError, match="安全配置文件无法读取或校验"): + SecurityConfigStore(str(path)).load() + + +def test_security_config_route_applies_candidate_and_never_returns_key(tmp_path: Path) -> None: + client, pipeline, store = _client(tmp_path, frozenset({"settings.view", "settings.manage"})) + + created = client.put( + "/admin/security-config", + json={ + "profile": "lightweight", + "zone_overrides": {"gateway_input": ["noop"]}, + "judge_endpoint": "http://127.0.0.1:8123/v1", + "judge_model": "qwen3-8b", + "judge_api_key": "supersecret123", + }, + ) + assert created.status_code == 200, created.text + assert "supersecret" not in created.text + assert created.json()["judge_api_key_set"] is True + assert {"keyword_rules", "injection_cascade", "llm_judge"} <= set( + created.json()["available_detectors"] + ) + assert [d.name for d in pipeline.detector_zones["gateway_input"]] == ["noop"] + assert store.load().profile == "lightweight" + events = asyncio.run(pipeline.audit.events("security-config:1")) + event = next( + event for event in events if event.event_type == AuditEventType.SECURITY_CONFIG_UPDATED + ) + assert event.evidence["actor"] == "admin" + assert event.evidence["profile"] == "lightweight" + assert "gateway_input" in event.evidence["changed_zones"] + assert "supersecret123" not in str(event.evidence) + assert "127.0.0.1" not in str(event.evidence) + + preserved = client.put( + "/admin/security-config", + json={ + "profile": "lightweight", + "zone_overrides": {"gateway_input": ["noop"]}, + "judge_endpoint": "http://127.0.0.1:8123/v1", + "judge_model": "qwen3-8b", + "judge_api_key": None, + }, + ) + assert preserved.status_code == 200 + assert store.load().judge.api_key == "supersecret123" + + cleared = client.put( + "/admin/security-config", + json={ + "profile": "lightweight", + "zone_overrides": {"gateway_input": ["noop"]}, + "judge_endpoint": "http://127.0.0.1:8123/v1", + "judge_model": "qwen3-8b", + "judge_api_key": "", + }, + ) + assert cleared.status_code == 200 + assert store.load().judge.api_key == "" + + +def test_invalid_candidate_keeps_file_and_running_pipeline(tmp_path: Path) -> None: + client, pipeline, store = _client(tmp_path, frozenset({"settings.view", "settings.manage"})) + before = store.load().model_dump_json() + names_before = [d.name for d in pipeline.detector_zones["gateway_input"]] + + response = client.put( + "/admin/security-config", + json={ + "profile": "lightweight", + "zone_overrides": {"gateway_input": ["does_not_exist"]}, + "judge_endpoint": "http://127.0.0.1:8123/v1", + "judge_model": "qwen3-8b", + }, + ) + + assert response.status_code == 400 + assert store.load().model_dump_json() == before + assert [d.name for d in pipeline.detector_zones["gateway_input"]] == names_before + + +def test_security_config_route_requires_settings_permissions(tmp_path: Path) -> None: + client, _, _ = _client(tmp_path, frozenset()) + + assert client.get("/admin/security-config").status_code == 403 + assert ( + client.put( + "/admin/security-config", + json={ + "profile": "lightweight", + "judge_endpoint": "http://127.0.0.1:8123/v1", + "judge_model": "qwen3-8b", + }, + ).status_code + == 403 + ) diff --git a/tests/test_walking_skeleton.py b/tests/test_walking_skeleton.py index e5d7c94..e0bbe3d 100644 --- a/tests/test_walking_skeleton.py +++ b/tests/test_walking_skeleton.py @@ -18,6 +18,7 @@ def _make_client(tmp_path: Path) -> TestClient: auth_db_path=str(tmp_path / "auth.sqlite"), bootstrap_admin_password=_ADMIN_PW, gateway_config_path=str(tmp_path / "gateway.json"), + security_config_path=str(tmp_path / "security.json"), audit_db_path=str(tmp_path / "audit.sqlite"), frontend_dir="", )