Compare commits
279 Commits
codex/fix-
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
3ad176b926 | |
|
|
41aea97735 | |
|
|
8e893960a3 | |
|
|
12b4bf638e | |
|
|
72ecf5aeab | |
|
|
7d209533fd | |
|
|
db61cfa342 | |
|
|
e7669f445d | |
|
|
5212870e9c | |
|
|
0677d5fa87 | |
|
|
f76fcdf407 | |
|
|
b501a91913 | |
|
|
a455e4025c | |
|
|
2f339ac4a9 | |
|
|
5e1922b40c | |
|
|
b98f6411bf | |
|
|
eaf1199cb2 | |
|
|
b2f9041589 | |
|
|
8e0694b594 | |
|
|
5ae0d91ba8 | |
|
|
2c107dc80a | |
|
|
0a0dcb51db | |
|
|
46a63b892e | |
|
|
f33afa6d93 | |
|
|
4e12a49f09 | |
|
|
aaa284586f | |
|
|
43aa4fe1eb | |
|
|
1c5c04362b | |
|
|
524ee29a84 | |
|
|
f4257cea3a | |
|
|
966836ef19 | |
|
|
b5f4ab9071 | |
|
|
b3a9ed7891 | |
|
|
1edfb9d3f4 | |
|
|
2863282250 | |
|
|
a8ed1ba946 | |
|
|
480f1ae7e2 | |
|
|
6e0a6854fb | |
|
|
0a7020f62a | |
|
|
550331e8e3 | |
|
|
1f6cf47e88 | |
|
|
a27c8c3fd1 | |
|
|
5cdb903320 | |
|
|
4fbf6f6d2f | |
|
|
85887a29ed | |
|
|
4c1436873d | |
|
|
5570c387a1 | |
|
|
a97f9b4b95 | |
|
|
2afe8c7075 | |
|
|
a897a9213b | |
|
|
ed82b78203 | |
|
|
614e5ff57f | |
|
|
5b81a98269 | |
|
|
3f2cea8f5b | |
|
|
603a6a666d | |
|
|
d6dbcb6dba | |
|
|
62151a6d01 | |
|
|
42d084de5f | |
|
|
ad57c85dd4 | |
|
|
8aef32ab00 | |
|
|
f757d2e60b | |
|
|
d49329857f | |
|
|
cac72a4821 | |
|
|
45d531b01b | |
|
|
986a6aca2b | |
|
|
52baa278cf | |
|
|
b718171a84 | |
|
|
f689e92678 | |
|
|
2fab8b7e11 | |
|
|
9c67d8c4bb | |
|
|
4f1ed1e650 | |
|
|
cb1507df6c | |
|
|
ca5057f8d9 | |
|
|
5129c3fe8a | |
|
|
cabc5546f3 | |
|
|
d685a5cd48 | |
|
|
33db868509 | |
|
|
883fb9105f | |
|
|
424fbf6bc3 | |
|
|
fbf632e4a3 | |
|
|
65e6a86c70 | |
|
|
229c83f64f | |
|
|
30894d2189 | |
|
|
f0b0bb5400 | |
|
|
1d1db56a04 | |
|
|
222398fdf7 | |
|
|
67007436a0 | |
|
|
8f49d91a88 | |
|
|
56691fa444 | |
|
|
aa620a2129 | |
|
|
e0153dc455 | |
|
|
af6cf7500c | |
|
|
85a81be890 | |
|
|
53e06773f0 | |
|
|
e3902005d8 | |
|
|
c34bd3a226 | |
|
|
87b41cd4b1 | |
|
|
33560def35 | |
|
|
02103fac9e | |
|
|
d7179957a6 | |
|
|
a3e4310e81 | |
|
|
1acb1597ea | |
|
|
aa1d569dd0 | |
|
|
e46ad04467 | |
|
|
d69cd7ca2c | |
|
|
6d96560acd | |
|
|
80be830b58 | |
|
|
7320cc608a | |
|
|
37aa7df7bb | |
|
|
db7373e5e1 | |
|
|
3090836143 | |
|
|
b0f6a07af0 | |
|
|
85da348093 | |
|
|
c6f352caa4 | |
|
|
f95d31d435 | |
|
|
b388c083a4 | |
|
|
f9ca96d647 | |
|
|
445744e2e7 | |
|
|
74e98c89a2 | |
|
|
f968f012c6 | |
|
|
4351c95000 | |
|
|
7df58533a6 | |
|
|
a4b7fdce9e | |
|
|
7b0e547316 | |
|
|
a6b5924794 | |
|
|
6815645a3f | |
|
|
c0b923fbe9 | |
|
|
f7cdf588ae | |
|
|
19142ba837 | |
|
|
def1038259 | |
|
|
9c63ff9874 | |
|
|
10a230343c | |
|
|
8addc2df2b | |
|
|
daa1c57556 | |
|
|
b345b708ca | |
|
|
9bdda0b392 | |
|
|
b6f755717b | |
|
|
8c2d815239 | |
|
|
04a70859b7 | |
|
|
e8ad42ac2c | |
|
|
15fbd1e001 | |
|
|
fcd7ee8061 | |
|
|
1dce196700 | |
|
|
faf21f6606 | |
|
|
8cbb7e42f8 | |
|
|
5b6be23ff0 | |
|
|
04ec3d11f8 | |
|
|
15c6a4bb1d | |
|
|
664de13eb8 | |
|
|
a598ffe8ee | |
|
|
697f2299fd | |
|
|
278885e3c8 | |
|
|
0811ac4a4d | |
|
|
ad6542a12c | |
|
|
ffc15f4402 | |
|
|
9927b93f25 | |
|
|
1978ab5e01 | |
|
|
dcdf05f75a | |
|
|
4fd613cf0f | |
|
|
d9a137d9c6 | |
|
|
7662038193 | |
|
|
1ab90f2f2f | |
|
|
bd03397be5 | |
|
|
715fef3e87 | |
|
|
9a59a5ad2e | |
|
|
42d8755a45 | |
|
|
1ccc1f53fb | |
|
|
91d3e3ac3f | |
|
|
a4eacf44b8 | |
|
|
4352433710 | |
|
|
24fad19a4b | |
|
|
6518bfe7d5 | |
|
|
0d65da6223 | |
|
|
5b2f87d205 | |
|
|
fbba8a20e3 | |
|
|
66fa4cfa54 | |
|
|
76caa2d081 | |
|
|
950f183056 | |
|
|
c0675ed082 | |
|
|
8b57d93f86 | |
|
|
7e96ce91db | |
|
|
c5f797c521 | |
|
|
1e4603f16b | |
|
|
e6f80618f3 | |
|
|
3097d5f9ff | |
|
|
9ffbf6d0e8 | |
|
|
1ebfac570c | |
|
|
1c0c6b9c91 | |
|
|
13259f49ef | |
|
|
cc05d0c028 | |
|
|
8bd86ba633 | |
|
|
310007fab3 | |
|
|
ed427505a8 | |
|
|
55647e1213 | |
|
|
6e6277d521 | |
|
|
51e4acacfe | |
|
|
e1c4551b64 | |
|
|
d0da169209 | |
|
|
f87245c575 | |
|
|
012a418b93 | |
|
|
e7ceffc184 | |
|
|
a17843c815 | |
|
|
b71e6e79bb | |
|
|
478858d36d | |
|
|
2836e1be33 | |
|
|
9c5dce5656 | |
|
|
5538829d4a | |
|
|
7072c1f2d3 | |
|
|
b77c8cda27 | |
|
|
76e9df9b0c | |
|
|
a125d749e7 | |
|
|
ab2ba8b9f8 | |
|
|
2e2ed49158 | |
|
|
63aa0a1307 | |
|
|
2c4364ad47 | |
|
|
9a0ea174b1 | |
|
|
72042749e3 | |
|
|
14c5422901 | |
|
|
ebc8425f38 | |
|
|
3646c1f38a | |
|
|
fcd54d6805 | |
|
|
6963344fe8 | |
|
|
4f2af3371b | |
|
|
e492a77182 | |
|
|
f2dcbc374d | |
|
|
b3ecf73a26 | |
|
|
aa7a533497 | |
|
|
18b4f82400 | |
|
|
335c985516 | |
|
|
0186cc64b4 | |
|
|
cfe3f82dd4 | |
|
|
49f326c269 | |
|
|
5d98f5d805 | |
|
|
f3997c48eb | |
|
|
ed4b86cee2 | |
|
|
a9a810f907 | |
|
|
42ce039ff6 | |
|
|
9ed4e19f5e | |
|
|
b30443387b | |
|
|
ecedd32c97 | |
|
|
4b4b623524 | |
|
|
1452c15f5f | |
|
|
4e76d922a4 | |
|
|
2196409964 | |
|
|
a66c6892a8 | |
|
|
7f723d1a95 | |
|
|
a04d113aea | |
|
|
b88e6229eb | |
|
|
fd10932de8 | |
|
|
0dd997ca01 | |
|
|
c07b6ac4ac | |
|
|
67683f4266 | |
|
|
43b5ac2da5 | |
|
|
f895a33eb1 | |
|
|
1ac81fe217 | |
|
|
8bfb840229 | |
|
|
cb77d0578c | |
|
|
6be4477e08 | |
|
|
5c6edff1dd | |
|
|
1931bf322a | |
|
|
261d2cd0ad | |
|
|
ef89d9e464 | |
|
|
ae4be163e0 | |
|
|
9a0d83c491 | |
|
|
900b21a99b | |
|
|
07864b355f | |
|
|
1609ac21bf | |
|
|
3afff5ed8a | |
|
|
cc37959e14 | |
|
|
cb15de1760 | |
|
|
d8530439e6 | |
|
|
5d7cb1ff5d | |
|
|
8b74b33eee | |
|
|
da0cb2a106 | |
|
|
77711616b2 | |
|
|
0d97169d07 | |
|
|
0be25994a3 | |
|
|
3964f325bd | |
|
|
d7e8a29dfe |
|
|
@ -0,0 +1,26 @@
|
|||
name: Deep assessments
|
||||
on:
|
||||
push:
|
||||
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/frontend/**', '.github/workflows/deep-assessments.yml']
|
||||
pull_request:
|
||||
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/frontend/**', '.github/workflows/deep-assessments.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
isolated-regression:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22.19.0'
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- run: npm ci --ignore-scripts && npm run build && npm test
|
||||
working-directory: runtime/pi
|
||||
- run: go test -race ./internal/database -run 'TestAssessment|TestSharedAssetGraph'
|
||||
- run: go test ./internal/app -run TestRecordVulnerabilityAssessmentEvidence
|
||||
- run: go test -race ./internal/deepassessment
|
||||
- run: go test -race ./internal/handler -run TestDeepAssessment
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
name: Frontend build
|
||||
|
||||
on:
|
||||
push:
|
||||
paths: ['web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'internal/app/app.go', 'internal/app/spa_test.go', '.github/workflows/frontend-build.yml']
|
||||
pull_request:
|
||||
paths: ['web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'internal/app/app.go', 'internal/app/spa_test.go', '.github/workflows/frontend-build.yml']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: Build React + Semi Design bundle
|
||||
run: |
|
||||
npm ci --prefix web/frontend
|
||||
npm run --prefix web/frontend build
|
||||
- name: Committed bundle matches sources
|
||||
run: |
|
||||
if [ -n "$(git status --porcelain web/static/app)" ]; then
|
||||
echo "web/static/app is out of date; run: npm run --prefix web/frontend build" >&2
|
||||
git status --porcelain web/static/app >&2
|
||||
exit 1
|
||||
fi
|
||||
- name: SPA entry and build artifacts
|
||||
run: go test ./internal/app -run TestSPA -count=1
|
||||
- run: node --test web/frontend/tests/*.test.mjs
|
||||
- name: Install Chromium for isolated UI tests
|
||||
working-directory: web/frontend
|
||||
run: npx playwright install --with-deps chromium
|
||||
- name: Browser regression tests
|
||||
run: npm run --prefix web/frontend test:ui -- --reporter=line
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
name: HTTP proxy pool
|
||||
on:
|
||||
push:
|
||||
paths: ['tools/http-framework-test.yaml', 'scripts/test_http_proxy_pool.py', 'requirements.txt', '.github/workflows/http-proxy-pool.yml']
|
||||
pull_request:
|
||||
paths: ['tools/http-framework-test.yaml', 'scripts/test_http_proxy_pool.py', 'requirements.txt', '.github/workflows/http-proxy-pool.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
proxy-pool:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
httpx: ['0.27.0', '0.28.1']
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
- run: python -m pip install 'httpx[http2,socks]==${{ matrix.httpx }}' PyYAML
|
||||
- run: python -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
name: Self-update
|
||||
on:
|
||||
push:
|
||||
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
pull_request:
|
||||
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
|
|
@ -27,9 +27,12 @@ jobs:
|
|||
- name: Authentication and update session handoff
|
||||
run: go test -race ./internal/security -run '^(TestAuthManager|TestAttachRBACStore|TestRevokeRoleSessions|TestPublishSession|TestRestartHandoff)'
|
||||
- run: go build ./...
|
||||
- name: Frontend regression tests
|
||||
- name: Frontend build and SPA artifacts
|
||||
shell: bash
|
||||
run: node --test web/static/js/*.test.cjs
|
||||
run: |
|
||||
npm ci --prefix web/frontend
|
||||
npm run --prefix web/frontend build
|
||||
go test ./internal/app -run TestSPA -count=1
|
||||
- name: Shell syntax
|
||||
shell: bash
|
||||
run: bash -n run.sh upgrade.sh
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ chat_uploads/
|
|||
*.db-shm
|
||||
*.db-wal
|
||||
*.db-journal
|
||||
*.instance.lock
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
|
|
@ -72,6 +73,8 @@ __pycache__/
|
|||
|
||||
# Node / browser extension
|
||||
node_modules/
|
||||
/web/frontend/test-results/
|
||||
/web/frontend/playwright-report/
|
||||
|
||||
# macOS / Windows / editors
|
||||
.DS_Store
|
||||
|
|
|
|||
112
CHANGELOG.md
|
|
@ -1,13 +1,123 @@
|
|||
# Changelog
|
||||
|
||||
## 2026-11-27 · v1.8.2 全局安全底座融合与深度测评增强
|
||||
|
||||
- **全局非受信数据隔离与扫描面收敛**:新增 `internal/promptguard` 随机 16 字节(32 位十六进制)Nonce 包络(`[[CSAI_DATA nonce=... field=...]]`),自动中性化目标可控标记词干并支持可选工具回执隔离(`multi_agent.runtime.prompt_guard_tool_results`);新增 `internal/surfaceingest` 结构化解析 `nmap`、`nuclei`、`httpx`、`ffuf` 输出,剥离 URL 凭据、过滤排除范围并通过 `Claim(executionID)` 跨普通 MCP 与深度测评幂等去重入库。
|
||||
- **确定性漏洞指纹去重与五维对抗复核**:`record_vulnerability`、状态流转、一键复测与深度测评独立复核共享同一套确定性三轴指纹(规范化位置 + 漏洞机制类 + 参数/组件锚点,按 `project_id` / `assessment_id` / `conversation_id` 作用域合并并保留 `force_distinct_reason` 显式拆分)与五维质量校验(可达性、前置条件、可复现性、授权范围、真实影响,区分控制有效拦截与机制不成立),漏洞详情抽屉同步展示结构化复核字段。
|
||||
- **项目级结构化约束、扫描噪声档位与经验沉淀**:项目 `scope_json` 扩展结构化 `constraints`(`allow` / `deny`)与 `noise_profile`(`off` / `quiet` / `balanced` / `aggressive`),为常用扫描器提供具体速率/并发参数及 `429`/`503` `Retry-After` 退避指引;新增基于回执证据的项目级经验库(`off` / `shadow` / `inject` 三态切换,规则失败时自动撤回淘汰,`inject` 模式下按 `CSAI_DATA` 包络安全注入)。
|
||||
- **离线安全分类标准与 Pi 提示词缓存前缀拆分**:内置离线 `lookup_security_taxonomy` 工具(打包 OWASP WSTG v4.2、核心 CWE 与 MITRE ATT&CK 技术摘要及来源许可说明);Pi 运行时支持紧凑排序技能索引与 `prompt_cache_prefix_split` 静态角色前缀 / 动态上下文拆分。
|
||||
- **深度测评目标拆解、覆盖率账本与分段优雅收尾**:新增规划前 `set_goals` / `set_constraints` 控制会话(拦截过程性伪目标、消解指代目标,弱模型解析失败自动单次重试并平滑回退,支持任务级噪声档位覆盖);新增持久化覆盖率账本与计划笔记工具(`record_coverage`、`assessment_coverage_ledger`、`assessment_plan_notes`),识别四类覆盖缺口并在验收门禁(`AcceptanceGate`)阻断未覆盖必测风险类的过早结项(历史无目标任务完全兼容);Pi 执行分段耗尽前提供只读优雅收尾轮次(`WrapupPrompt`),服务端 `BeforeTool` 同步拦截收尾期新扫描与外部命令。
|
||||
|
||||
## 2026-11-19 · 前端整体迁移到 React + Semi Design
|
||||
|
||||
- Web 界面重写为 Vite 构建的 React 19 单页应用,组件统一使用 Semi Design;页面按 `#/<页面 id>` 路由,
|
||||
深链接(会话、漏洞、项目、测评、设置分区、MCP 执行、HITL 审批)保持可分享。
|
||||
- 服务端不再渲染业务模板:`GET /` 直接返回 `web/static/app/index.html`,`/api-docs` 302 到 `/#/api-docs`,
|
||||
API 文档改为应用内 OpenAPI 浏览器(含在线调试)。
|
||||
- 复用既有 REST 接口、`cyberstrike-auth` 会话令牌、`cyberstrike-theme` 主题偏好与 `web/static/i18n` 词条;
|
||||
新增 `src/lib/http.js` 统一注入令牌、错误与 SSE 解析,`components/ui.jsx` 统一页面骨架、表格、指标卡、
|
||||
Markdown/JSON 视图与抽屉。
|
||||
- 30 个业务页面 + API 文档全部由 React 组件实现,覆盖对话流式回复与内联审批、深度测评图谱与验收、
|
||||
资产/漏洞/项目/任务/工作流、WebShell 与 C2、MCP 与 HITL、知识与技能、角色与平台权限、系统设置。
|
||||
- 新增 `internal/app/spa_test.go` 校验构建产物与入口路由;CI 增加 `frontend-build.yml`,
|
||||
`self-update.yml` 的前端回归改为构建校验,移除依赖旧模板的 `task-ui.yml` 与浏览器夹具测试。
|
||||
|
||||
## 2026-11-15 · 深度测评工作台与完整链路
|
||||
|
||||
- 探索图增加主链路/执行记录两种视图,跨页引用和原始上下游分页导航;归档按真实分支分组,重新引用后重新计冷却轮次,漏洞与人工线索保持可见,旧归档链接继续可读。
|
||||
- 详情默认展示运行概览:规划/验收阶段、活跃意图、工具活动、Pi 原生会话状态、队列数量、最近进展和下次唤醒;无变化时不重建正文,保留定向补充草稿和阅读位置。
|
||||
- 增加单条意图暂停、继续、优先级和定向补充。独立取消执行上下文,补充持久化后通过 Pi 原生 steer 只发送到目标会话;手动暂停不会被整任务继续或规划器绕过。
|
||||
- 测评报告补齐当前账号可读的关联漏洞、全部独立复核记录、已保存回执摘录和来源链接;原有批量任务行为保持不变。
|
||||
|
||||
## 2026-11-15 · 深度测评开始与整任务暂停
|
||||
|
||||
- 开始/继续统一续接原 Pi 会话;暂停同时取消本测评的规划与执行步骤、清除自动重试安排,阻止晚到重试及后台恢复队列覆盖手动暂停。
|
||||
- 修复正常取消被一律记为结果不明的问题:资源清理后或手动开始时,按同任务、步骤、会话和工具的终态执行回执自动核对。已取消调用保留为错误回执,不计作成功证据;远端未确认和无可靠回执的调用仍需核对。
|
||||
- 列表与详情保留开始、暂停入口,待核对状态可直接查看相关步骤及回执;概览展示实际状态和重启恢复设置,避免将历史路线误认为正在执行。原批量任务保持不变。
|
||||
|
||||
## 2026-11-15 · 大规模探索链路与节点阅读修复
|
||||
|
||||
- 修复循环引用将整组节点排成单列的问题;布局只避开回边的层级计算,原始节点、连线和证据保持完整,同层大量节点采用紧凑排列。
|
||||
- 新增可定位的图缩略导航和关系着色;选中画布外或过小的节点时定位到可读尺度,自动刷新继续保留用户视图。
|
||||
- 将多个目标资产链接放入详情正文的折叠区,避免固定操作区挤压正文;切换双图时不再继承空白详情栏。
|
||||
|
||||
## 2026-11-15 · 深度测评图阅读体验
|
||||
|
||||
- 整理任务标题、图工具栏及搜索间距,修复资产搜索焦点边框被裁切和控件挤靠,补充空资产提示。
|
||||
- 扩大节点详情栏,支持拖动调整和页面内展开阅读;按摘要、执行说明、回执及来源组织内容,刷新保留滚动位置与展开状态。
|
||||
- 资产节点使用字段式详情,保留原始记录及意图、证据和漏洞跳转;原批量任务逻辑不变。
|
||||
|
||||
## 2026-11-15 · 深度测评工作区与归档
|
||||
|
||||
- 测评详情改为主内容区的完整工作区,保留深链、漏洞返回及列表筛选;扩大图画布,支持收起节点详情,保持刷新和视图切换后的缩放位置。
|
||||
- 行尾提供开始/继续、暂停、详情及归档操作;归档保留证据和关联,可筛选、恢复,恢复不自动执行。
|
||||
- 执行中或结果不明的任务不能归档,归档任务不参与自动恢复;原批量任务逻辑保持不变。
|
||||
|
||||
## 2026-11-15 · 简化新建深度测评
|
||||
|
||||
- 将允许范围调整为「补充限制与排除项(选填)」,验收条件也标记选填,提供简短说明和示例。
|
||||
- 两项留空时沿用完整目标,显式填写的内容保持独立;保存草稿与原批量任务行为不变。
|
||||
|
||||
## 2026-11-15 · 深度测评关联跳转实机修复
|
||||
|
||||
- 定时刷新保留已展开的独立复核记录和探索图来源引用,避免返回链接在阅读时消失。
|
||||
- 会话失效后重新登录,恢复测评深链定位及当前账号的新建入口;批量任务逻辑保持不变。
|
||||
|
||||
## 2026-11-15 · 深度测评双图与意图队列
|
||||
|
||||
- 复用现有资产库建立共享资产图,关联测评资产、服务端点及首次执行快照;探索图增加事实、漏洞和来源关系。
|
||||
- 步骤扩展为持久意图队列,支持资产锚定、优先级、依赖和状态筛选;规划/验收每轮使用新的 Pi 原生会话,worker 继续使用原生恢复与压缩。
|
||||
- 事实、漏洞和资产变更按持久版本触发重规划,拒绝过时计划与完成结论;新变化可唤醒等待任务,手动暂停保持暂停。
|
||||
- 测评漏洞登记绑定本意图原始回执,独立复核来自另一意图,追加记录并同步漏洞状态;保留旧漏洞链接和原批量任务行为。
|
||||
|
||||
## 2026-11-14 · 深度测评漏洞关联
|
||||
|
||||
- 已登记漏洞自动绑定来源测评与步骤,漏洞管理按测评名称分组,支持测评名称搜索及测评 ID 筛选;批量任务的 ID、队列和分组语义保持不变。
|
||||
- 测评详情新增关联漏洞入口;漏洞详情可跳回具体步骤及复现证据,支持跨分页和刷新定位。
|
||||
- 补建已有记录的可信来源关联,分别校验漏洞与测评权限;删除测评后保留漏洞及来源快照。
|
||||
|
||||
## 2026-11-14 · 持续探索与图记忆
|
||||
|
||||
- 深度测评取消任务时间、累计 Token、规划轮数、总步骤及累计分段次数上限;保留用量统计和手动暂停/停止。旧预算耗尽记录迁移为暂停,可直接继续。
|
||||
- 新增可交互探索图,持久化步骤、观察、执行回执、人工线索和 Pi 原生压缩摘要;冷历史按引用折叠,活跃依赖重新展开,支持按节点检索原文。
|
||||
- 暂无新进展时保存状态并定时重评,临时模型故障退避后继续;现有任务管理保持不变。
|
||||
|
||||
## 2026-11-14 · 深度测评界面统一
|
||||
|
||||
- 将深度测评入口移到对话下方,主页面采用整行列表,详情、新建和预算调整统一为右侧抽屉。
|
||||
- 支持点击遮罩、Esc 与关闭按钮退出当前抽屉,保留原批量任务行为。
|
||||
|
||||
## 2026-11-14 · 独立深度测评
|
||||
|
||||
- 新增独立深度测评栏目,默认 48 小时任务窗口,持久计划、证据回执、分段续跑、模型故障退避和重启恢复;现有批量任务管理保持不变。
|
||||
- 复用 Pi 原生会话、压缩、Skills、工具搜索、结构化工具和生命周期接口;工具结果不明时等待核对,阶段结束及预算耗尽不报告为完成。
|
||||
- 增加隔离恢复测试、真实 Pi SDK 模拟模型集成及独立页面浏览器回归。真实目标的 48 小时效果尚待验收,详见 [深度测评](docs/zh-CN/deep-assessments.md)。
|
||||
|
||||
## 2026-11-14 · 恢复批量任务管理
|
||||
|
||||
- 按 v1.8.0 恢复批量队列、创建窗口和详情操作,撤回目标任务及后续统一列表与布局改造。
|
||||
- 保留深度测评移除和 PR #383 关闭状态;不删除已有任务、会话及历史数据,不回退其他模块的修复。
|
||||
|
||||
## 2026-11-13 · 任务管理
|
||||
|
||||
- 移除深度测评模块;关闭上游 PR #383,保留通用授权及资产归属修复。
|
||||
- 任务管理新增目标任务:持久计划与依赖、完整 Pi Agent 步骤、有限并发、结果触发再规划、任务内过程检索、独立验收、暂停恢复和补充方向。
|
||||
- 保留批量队列;目标任务创建为草稿,中断/受阻/预算耗尽与完成分别显示。
|
||||
|
||||
## Unreleased
|
||||
|
||||
- 当前任务管理恢复批量队列逻辑,见 `docs/zh-CN/task-management.md`。
|
||||
|
||||
### Added
|
||||
|
||||
- 默认 Agent 运行时迁移为 Pi 1.5.2:Go 工具网关继续处理角色、审批、监控与证据;聊天与子代理的模型提案接入 Pi。新增按源码指纹发布的 Node Worker、流式协议、会话恢复和原生工具检索。部署需 Node.js >=22.19;已删除 Eino 内核、模型适配、桥接和全部依赖,运行时仅支持 Pi。
|
||||
- 个人版上下文优化统一采用 #399 的 Pi 自动策略,清理 #367 遗留的摘要、消息和工具输出预算覆盖及辅助请求适配。DeepSeek 输入节省、本地服务窗口检测和已有通道配置兼容继续由自动策略处理。
|
||||
|
||||
- 默认 Agent 运行时迁移为 Pi 1.5.2:Go 工具网关继续处理角色、审批、监控与证据;聊天及子代理接入 Pi。新增按源码指纹发布的 Node Worker、流式协议、会话恢复和原生工具检索。部署需 Node.js >=22.19;已删除 Eino 内核、模型适配、桥接和全部依赖,运行时仅支持 Pi。
|
||||
- Workflow 改用原生 DAG 与版本化检查点,知识库改用自身文档、切分、Embedding 和检索组件。旧 Eino Workflow 检查点无法由新版直接恢复,升级前需完成或导出旧任务,详见 [Pi 迁移说明](docs/zh-CN/pi-runtime.md)。
|
||||
- 个人仓库正式命名为 `Sycun/CyberStrikeAI`,原上游贡献 fork 改为 `Sycun/CyberStrikeAI-upstream-fork`。新增任务接单、阶段汇报与主动请示的设计调研文档(尚未作为产品功能上线)。
|
||||
|
||||
- AI 渠道支持自定义 HTTP 请求头、环境变量和会话 ID 占位符;保存后的鉴权头可安全用于连接测试,独立审计身份隔离主渠道请求头,自定义头不会跟随跨源重定向。
|
||||
- 系统设置新增代理二级菜单,提供固定出口、代理池、最短切换间隔及凭证脱敏;配置仅注入后续 HTTP 工具进程,不影响 Kali 其他工具和模型 API。`http-framework-test` 新增可选代理池:支持静态/结构化代理列表与供应商接口、粘性/轮询策略、供应商故障静态回退、失败冷却及有界切换;仅自动重放 GET/HEAD/OPTIONS,遵守 429 Retry-After,切换失败时返回响应或错误且不回退直连。附中英文指南与本地 HTTP/HTTPS/SOCKS5 回归测试(#357)。
|
||||
|
||||
- 支持通过 `agent.task_timeout_minutes` 配置单代理、多代理、工作流及异步任务执行超时:未配置默认 600 分钟,`0` 表示不限时,负数拒绝加载;续跑保留重新计时行为,单次工具超时仍独立生效。
|
||||
|
||||
|
|
|
|||
513
README.md
|
|
@ -1,429 +1,202 @@
|
|||
<div align="center">
|
||||
<img src="images/logo.png" alt="CyberStrikeAI Logo" width="200" >
|
||||
<img src="images/logo.png" alt="CyberStrikeAI" width="144">
|
||||
<h1>CyberStrikeAI</h1>
|
||||
<p><strong>Describe goals or tasks, run tool-calling security agents, and record verifiable execution evidence.</strong></p>
|
||||
<p><a href="README_CN.md">中文</a> · <strong>English</strong></p>
|
||||
<p>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/pi-runtime.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/pi-runtime.yml/badge.svg?branch=main" alt="Pi runtime CI"></a>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/deep-assessments.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/deep-assessments.yml/badge.svg?branch=main" alt="Deep assessments CI"></a>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/frontend-build.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/frontend-build.yml/badge.svg?branch=main" alt="Frontend build CI"></a>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/self-update.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/self-update.yml/badge.svg?branch=main" alt="Self-update CI"></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
# CyberStrikeAI
|
||||
CyberStrikeAI is an open-source cybersecurity agent workbench built with **Go + Pi** (Go backend + React / Semi Design frontend). It unifies interactive security chat, goal-driven **Deep Assessments**, and list-driven **Batch Tasks**, enabling security agents to orchestrate tools and record structured execution evidence.
|
||||
|
||||
> This repository ([Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI)) is forked from the original open-source [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) repository with its full commit history, copyright notices, and [Apache-2.0 License](LICENSE) preserved. Following the upstream project's transition to closed source, this repository is independently maintained and developed as an open-source branch by **[Sycun](https://github.com/Sycun)**, former core maintainer of the official project.
|
||||
|
||||
[中文](README_CN.md) | [English](README.md)
|
||||
[Key highlights](#highlights) · [Preview](#screenshots) · [Quick start](#quick-start) · [Execution modes](#delegation) · [Capabilities](#capabilities) · [Architecture](#architecture) · [Documentation](#documentation) · [Feedback](#contributing)
|
||||
|
||||
**The system of action for AI-native cybersecurity—where intent becomes governed execution, evidence becomes operational memory, and every operation improves the next.**
|
||||
<a id="highlights"></a>
|
||||
|
||||
CyberStrikeAI connects planning, execution, human oversight, evidence, and replay in one auditable workspace. Built in Go, it combines Pi-powered agents, MCP-native tools, RAG knowledge, visual workflows, and attack-chain modeling and analysis for authorized security operations.
|
||||
## Key highlights
|
||||
|
||||
**Start here:** [Quick start](#quick-start-one-command-deployment) · [Documentation](docs/en-US/README.md) · [Security hardening](docs/en-US/security-hardening.md)
|
||||
- **Native Pi 1.7.0 agent runtime**: Powered by native Pi session persistence, automatic context compaction, live mid-run steering (**Interrupt & continue**), and configurable reasoning-effort controls, with legacy Eino engine dependencies completely removed.
|
||||
- **Goal-driven Deep Assessments workbench**: Long-running autonomous assessments backed by a shared project **Attack-Surface Graph**, hot/cold archived **Exploration Graph**, prioritized **Intent Queue**, and receipt-backed **Facts & Acceptance Evidence Matrix**.
|
||||
- **React 19 + Semi Design workbench**: Modern single-page interface featuring unified detail drawers, project-grouped conversations, compact model/role pickers, domain/host/task vulnerability views, and **one-click vulnerability retesting**.
|
||||
- **Multi-gateway compatibility & adaptive context**: Supports custom per-channel auth headers (same-origin guarded for third-party gateways), automatic runtime context-window probing, `local_auto` profiles for local inference servers (oMLX, Ollama, etc.), DeepSeek economy profiles, and dedicated HITL review model testing.
|
||||
- **Isolated HTTP proxy pool & self-hosted operations**: Provides an [HTTP testing proxy pool with failover](docs/en-US/http-proxy-pool.md) isolated from model API traffic, supervisor-free **One-Click Update** preserving self-signed TLS certs and active sessions, plus previewable **Storage Cleanup**.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Use CyberStrikeAI only on systems you own or are explicitly authorized to test. For shared or production environments, review the [security model](docs/en-US/security-model.md) and [hardening guide](docs/en-US/security-hardening.md) before enabling high-risk tools, WebShell, or C2 capabilities.
|
||||
<a id="screenshots"></a>
|
||||
|
||||
## Interface & Integration Preview
|
||||
## Workbench preview
|
||||
|
||||
<div align="center">
|
||||
| Dashboard (Risk distribution & live metrics) | Deep Assessments (Dark theme · Goals & progress) |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
### System Dashboard Overview
|
||||
| Deep Assessments · Exploration Graph (Intents, facts, findings & archive) | Chat Console (Project groups, tool receipts & summary) |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<strong>Light Mode</strong><br/>
|
||||
<img src="./images/dashboard.png" alt="System Dashboard (Light)" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>Dark Mode</strong><br/>
|
||||
<img src="./images/dark.png" alt="System Dashboard (Dark)" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
| Vulnerability Management (Domain/host tree & severity overview) | MCP & Tool Management (External MCP status & built-in tools) |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
*The dashboard provides a comprehensive overview of system runtime status, security vulnerabilities, tool usage, and knowledge base, helping users quickly understand the platform's core features and current state.*
|
||||
<a id="quick-start"></a>
|
||||
|
||||
<details>
|
||||
<summary><strong>More interface screenshots</strong></summary>
|
||||
## Quick start
|
||||
|
||||
### Core Features Overview
|
||||
### 1. Prepare the environment
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Web Console</strong><br/>
|
||||
<img src="./images/web-console.png" alt="Web Console" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Task Management</strong><br/>
|
||||
<img src="./images/task-management.png" alt="Task Management" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Vulnerability Management</strong><br/>
|
||||
<img src="./images/vulnerability-management.png" alt="Vulnerability Management" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>WebShell Management</strong><br/>
|
||||
<img src="./images/webshell-management.png" alt="WebShell Management" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP Management</strong><br/>
|
||||
<img src="./images/mcp-management.png" alt="MCP management" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Knowledge Base</strong><br/>
|
||||
<img src="./images/knowledge-base.png" alt="Knowledge Base" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Skills Management</strong><br/>
|
||||
<img src="./images/skills.png" alt="Skills Management" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Agent Management</strong><br/>
|
||||
<img src="./images/agent-management.png" alt="Agent Management" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Role Management</strong><br/>
|
||||
<img src="./images/role-management.png" alt="Role Management" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>System Settings</strong><br/>
|
||||
<img src="./images/settings.png" alt="System settings" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP stdio Mode</strong><br/>
|
||||
<img src="./images/mcp-stdio2.png" alt="MCP stdio mode" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Burp Suite Plugin</strong><br/>
|
||||
<img src="./images/plugins.png" alt="Burp Suite plugin" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
| Dependency | Requirement | Purpose |
|
||||
| --- | --- | --- |
|
||||
| Go | 1.25+; see [go.mod](go.mod) | Build the backend server and runtime builder |
|
||||
| Node.js and npm | Node.js 22.19+ | Build and run the Pi worker (and optional frontend rebuilds) |
|
||||
| Python | 3.10+, with `venv` support | Launcher and Python tool dependencies |
|
||||
| Git | Available on `PATH` | Clone source and run Web one-click updates |
|
||||
|
||||
</details>
|
||||
You also need a model channel that supports tool calling, plus the local security tools or external MCP servers required by your tasks. The repository includes tool recipes, **not preinstalled third-party security binaries**. By default, `run.sh` configures temporary Go and PyPI mirrors for faster setup; set `GOPROXY` and `PIP_INDEX_URL` in your environment to override them.
|
||||
|
||||
</div>
|
||||
### 2. Clone and start
|
||||
|
||||
## Highlights
|
||||
Run the following commands in Bash on macOS or Linux:
|
||||
|
||||
### Agents and orchestration
|
||||
|
||||
- 🤖 **Agentic execution** translates natural-language intent into governed, auditable security actions.
|
||||
- 🧩 **Pi orchestration** supports single-agent execution plus Deep, Plan-Execute, and Supervisor multi-agent modes.
|
||||
- 🔀 **Graph workflows** combine Agents, tools, conditions, approvals, and outputs into reusable flows.
|
||||
- 🎭 **Role-based testing** provides focused prompts and tool policies for common security scenarios.
|
||||
|
||||
### Tools and knowledge
|
||||
|
||||
- 🧰 **Security tools** include 100+ curated YAML recipes with custom extensions and role-scoped access.
|
||||
- 🔌 **MCP integration** supports HTTP, stdio, SSE, external federation, and dynamic tool discovery.
|
||||
- ⏱️ **Resilient tool execution** runs blocking MCP/tool calls in workers with bounded agent waits, resumable `execution_id` polling, cancellation, per-server circuit breakers, concurrency limits, and unified output caps.
|
||||
- 🎯 **Agent Skills** follow the standard Skill layout and support progressive, on-demand loading.
|
||||
- 📚 **Knowledge base** combines query rewriting, vector retrieval, reranking, and result post-processing.
|
||||
- 🖼️ **Vision analysis** uses a separate vision model for screenshots, captchas, and UI while retaining text summaries only.
|
||||
|
||||
### Governance and audit
|
||||
|
||||
- 🧑⚖️ **Human in the loop** provides approval modes, tool allowlists, audit-agent review, and traceable decisions.
|
||||
- 🛡️ **Call blocking** under Security adds configurable regex checks before MCP execution, reminder templates, and dry runs, with government-domain protection enabled by default. See [Tool call blocking](docs/en-US/tool-call-guard.md).
|
||||
- 🔐 **Platform RBAC** supports multiple users, system and custom roles, scoped permissions, ownership, and explicit assignments.
|
||||
- 🔒 **Security and audit** provide authenticated access, audit logs, SQLite persistence, and operational evidence retention.
|
||||
- 📄 **Result governance** stores the same capped tool result seen by the agent, protects resume paths from oversized historical output, and adds UI safeguards for large detail views. See [Tool Execution Governance](docs/en-US/tool-execution-governance.md).
|
||||
|
||||
### Security operations
|
||||
|
||||
- 📁 **Conversation management** provides pinning, renaming, and batch organization.
|
||||
- 📂 **Projects and attack chains** connect cross-session facts, risk scoring, graph views, and step-by-step replay.
|
||||
- 🗂️ **Asset management** normalizes and deduplicates domains, IP addresses, ports, and services; supports XLSX/CSV import and export, advanced filters and saved views, ownership and business metadata, cross-page bulk maintenance, and duplicate merging; and tracks scan coverage, linked vulnerabilities, and risk state. See the [Asset Management guide](docs/en-US/asset-management.md).
|
||||
- 🛡️ **Vulnerability management** provides severity classification, lifecycle tracking, filtering, and statistics.
|
||||
- 📋 **Batch tasks** provide queued execution, editing, status tracking, and retained results.
|
||||
- 📱 **Chatbots** connect Personal WeChat, WeCom, DingTalk, Lark, Telegram, Slack, Discord, and QQ Bot.
|
||||
|
||||
### Authorized security operations
|
||||
|
||||
- 🐚 **WebShell management** provides connection management, a virtual terminal, file operations, and AI-assisted workflows.
|
||||
- 📡 **Built-in C2** provides listeners, encrypted beacons, sessions, task queues, payload helpers, and live events.
|
||||
|
||||
> WebShell, C2, and other high-risk capabilities are for systems you own or are explicitly authorized to test. See the [security model](docs/en-US/security-model.md) and [hardening guide](docs/en-US/security-hardening.md).
|
||||
|
||||
## Plugins
|
||||
|
||||
CyberStrikeAI includes optional integrations under `plugins/`.
|
||||
|
||||
- **Burp Suite extension**: `plugins/burp-suite/cyberstrikeai-burp-extension/`
|
||||
Build output: `plugins/burp-suite/cyberstrikeai-burp-extension/dist/cyberstrikeai-burp-extension.jar`
|
||||
Docs: `plugins/burp-suite/cyberstrikeai-burp-extension/README.md`
|
||||
- **Browser extension (Chrome / Edge)**: `plugins/browser-extension/cyberstrikeai-browser-extension/`
|
||||
Capture Network traffic in DevTools and send it to CyberStrikeAI for AI-assisted security testing—aligned with the Burp plugin.
|
||||
Install: `chrome://extensions/` → Load unpacked → F12 → **CyberStrikeAI** tab
|
||||
Package output: `plugins/browser-extension/cyberstrikeai-browser-extension/dist/cyberstrikeai-browser-extension.zip`
|
||||
Docs: `plugins/browser-extension/cyberstrikeai-browser-extension/README.md` / `README.zh-CN.md`
|
||||
|
||||
## Tool Overview
|
||||
|
||||
CyberStrikeAI ships with 100+ curated tools covering the whole kill chain:
|
||||
|
||||
<details>
|
||||
<summary><strong>View the complete tool categories</strong></summary>
|
||||
|
||||
- **Network Scanners** – nmap, masscan, rustscan, arp-scan, nbtscan
|
||||
- **Web & App Scanners** – sqlmap, nikto, dirb, gobuster, feroxbuster, ffuf, httpx
|
||||
- **Vulnerability Scanners** – nuclei, wpscan, wafw00f, dalfox, xsser
|
||||
- **Subdomain Enumeration** – subfinder, amass, findomain, dnsenum, fierce
|
||||
- **Network Space Search Engines** – fofa_search, zoomeye_search, quake_search, shodan_search
|
||||
- **API Security** – graphql-scanner, arjun, api-fuzzer, api-schema-analyzer
|
||||
- **Container Security** – trivy, clair, docker-bench-security, kube-bench, kube-hunter
|
||||
- **Cloud Security** – prowler, scout-suite, cloudmapper, pacu, terrascan, checkov
|
||||
- **Binary Analysis** – gdb, radare2, ghidra, objdump, strings, binwalk
|
||||
- **Exploitation** – metasploit, msfvenom, pwntools, ropper, ropgadget
|
||||
- **Password Cracking** – hashcat, john, hashpump
|
||||
- **Forensics** – volatility, volatility3, foremost, steghide, exiftool
|
||||
- **Post-Exploitation** – linpeas, winpeas, mimikatz, bloodhound, impacket, responder
|
||||
- **CTF Utilities** – stegsolve, zsteg, hash-identifier, fcrackzip, pdfcrack, cyberchef
|
||||
- **System Helpers** – exec, create-file, delete-file, list-files, modify-file
|
||||
|
||||
</details>
|
||||
|
||||
See [tools/README_EN.md](tools/README_EN.md) for tool definitions, customization, and usage notes.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Quick Start (One-Command Deployment)
|
||||
|
||||
**Prerequisites:**
|
||||
- Go 1.25+ ([Install](https://go.dev/dl/); required by `go.mod`)
|
||||
- Python 3.10+ ([Install](https://www.python.org/downloads/))
|
||||
|
||||
**One-Command Deployment:**
|
||||
```bash
|
||||
git clone https://github.com/Ed1s0nZ/CyberStrikeAI.git
|
||||
git clone --branch main https://github.com/Sycun/CyberStrikeAI.git
|
||||
cd CyberStrikeAI
|
||||
chmod +x run.sh && ./run.sh
|
||||
cp config.example.yaml config.yaml
|
||||
```
|
||||
|
||||
The `run.sh` script will automatically:
|
||||
- ✅ Check and validate Go & Python environments
|
||||
- ✅ Create Python virtual environment
|
||||
- ✅ Install Python dependencies
|
||||
- ✅ Download Go dependencies
|
||||
- ✅ Build the project
|
||||
- ✅ Start the server
|
||||
For local trials, set `server.host` in `config.yaml` to `127.0.0.1`, then start the server:
|
||||
|
||||
**Verify the startup:**
|
||||
|
||||
1. Confirm the terminal displays `● ONLINE` followed by the actual Web UI URL.
|
||||
2. Open that URL; the default HTTPS mode uses a local self-signed certificate, so accept the browser warning once.
|
||||
3. On a new installation, store the one-time `admin` password shown under `ADMIN SETUP REQUIRED`, sign in, and change it immediately.
|
||||
|
||||
**Networking defaults:** `run.sh` starts the server with **`--https`** and the repo **`config.yaml`** (local self-signed TLS; better for many concurrent streams). Use **`./run.sh --http`** for plain HTTP. In production, set **`server.tls_cert_path`** / **`server.tls_key_path`** in **`config.yaml`** (see comments there). For manual runs, add **`--https`** or **`CYBERSTRIKE_HTTPS=1`**; if **`-config`** is wrong, the binary prints a short usage hint on stderr.
|
||||
|
||||
**First-Time Configuration:**
|
||||
1. **Configure AI channels** (required before first use)
|
||||
- After launch, open **`https://127.0.0.1:8080/`** (or **`https://localhost:8080/`**; replace **8080** with `server.port` in `config.yaml`) and accept the self-signed certificate warning once. If you used `./run.sh --http`, use **`http://`** instead.
|
||||
- Go to `System Settings` → `Basic Settings` → `AI Channel Configuration`, add or edit a channel, then fill in provider, Base URL, API key, model, and token limits. Click **Save changes**. The left channel list supports setting a default, copy, delete, and bulk probe.
|
||||
```yaml
|
||||
ai:
|
||||
default_channel: openai-main
|
||||
channels:
|
||||
openai-main:
|
||||
name: OpenAI Main
|
||||
provider: openai_compatible
|
||||
api_key: "${OPENAI_API_KEY}"
|
||||
base_url: "https://api.openai.com/v1" # or https://api.deepseek.com/v1
|
||||
model: "gpt-4o" # or deepseek-chat, qwen3-max, etc.
|
||||
max_total_tokens: 120000
|
||||
max_completion_tokens: 16384
|
||||
```
|
||||
- Or edit `config.yaml` directly before launching. `ai.default_channel` is used for new conversations and tasks that do not explicitly select a channel; the chat page can also select any saved channel per session.
|
||||
2. **Login** - On first startup the console prints an auto-generated initial `admin` password; create accounts from **Platform permissions → User management**
|
||||
3. **Install security tools (optional)** - Install tools from `tools/` as needed; missing tools are skipped or substituted at runtime. Common examples:
|
||||
|
||||
**macOS (Homebrew):**
|
||||
```bash
|
||||
brew install nmap masscan sqlmap nikto gobuster ffuf hydra hashcat nuclei subfinder
|
||||
```
|
||||
|
||||
**Linux (Kali / Debian / Ubuntu):**
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y nmap masscan sqlmap nikto gobuster hydra hashcat john binwalk
|
||||
# On some distros, install ffuf/nuclei/subfinder via go install or upstream docs
|
||||
```
|
||||
|
||||
See the `tools/` directory for the full list; refer to each tool's official docs for install details.
|
||||
|
||||
**Alternative Launch Methods:**
|
||||
```bash
|
||||
# Direct Go run (set up env yourself); add --https to match run.sh defaults
|
||||
go run ./cmd/server --https
|
||||
|
||||
# Manual build
|
||||
go build -o cyberstrike-ai ./cmd/server
|
||||
./cyberstrike-ai --https
|
||||
bash run.sh --http
|
||||
```
|
||||
|
||||
If server logs show `client sent an HTTP request to an HTTPS server`, a client is still using **`http://`** on a TLS-only port—switch the URL to **`https://`**.
|
||||
The script builds the Pi worker, creates a Python virtual environment, installs dependencies, and compiles the Go server (prebuilt frontend assets are already included under `web/static/app/`). Open [http://127.0.0.1:8080/](http://127.0.0.1:8080/) by default, or check your terminal output for the active port.
|
||||
|
||||
**Note:** The Python virtual environment (`venv/`) is automatically created and managed by `run.sh`. Tools that require Python (like `api-fuzzer`, `http-framework-test`, etc.) will automatically use this environment.
|
||||
Without `--http`, `run.sh` starts with HTTPS + HTTP/2 and generates a reusable local self-signed certificate when none is configured. For shared team deployments, see the [deployment guide](docs/en-US/deployment.md) for bind addresses, TLS certificates, and access controls.
|
||||
|
||||
### Upgrade and Compatibility
|
||||
### 3. Complete the initial setup
|
||||
|
||||
**Prefer the platform's own one-click update** (console System settings -> One-click update, or
|
||||
`./cyberstrike-ai -update` / `-check-update` / `-update-rollback`): it pulls the newest commit of the
|
||||
**update source repository**'s default branch (the official repository by default; one setting points
|
||||
it at your own fork or a mirror), fast-forwards, rebuilds and swaps the binary atomically, keeps your
|
||||
`roles/skills/tools/agents/data/config.yaml` untouched (the result names every file it kept; only
|
||||
`config.yaml`'s `version` field is synced to the new code, so the header badge matches it), and
|
||||
refuses - rather than overwrites - when source is modified locally or the local history has diverged.
|
||||
See the [deployment guide](docs/en-US/deployment.md).
|
||||
1. Sign in with the initial `admin` password printed under `ADMIN SETUP REQUIRED` in the terminal, then change it.
|
||||
2. Go to **System settings → Basic → AI channel config**, enter your provider, Base URL, API key, and model, then save it as the default channel (values in `config.example.yaml` are placeholders).
|
||||
3. Install the local tools needed for your engagement or connect external MCP servers, and verify each tool before assigning it to an agent role.
|
||||
4. For multi-user deployments, create separate member accounts, roles, and project scopes under **Platform Access → Add Member**.
|
||||
|
||||
`upgrade.sh` still works: when this directory is a git work tree it is a thin shell over the command
|
||||
above; only a non-git (tarball) installation falls back to the old "download a GitHub Release and
|
||||
rsync it in" path, where the source repository comes from `--repo owner/name` or `GITHUB_REPO` and the
|
||||
built-in default applies only when neither is given (with a warning naming the repository).
|
||||
Use [config.example.yaml](config.example.yaml) as the full reference. See [configuration](docs/en-US/configuration.md) and [configuration profiles](docs/en-US/configuration-profiles.md) for model channels, local models, and context sizing.
|
||||
|
||||
The update source is one setting, a repository address in the `update` section of `config.yaml` or
|
||||
right on the console page - the official repository, your own fork, or somebody else's fork. An
|
||||
installation unpacked from a Release archive (no git) can be previewed and connected from the same
|
||||
page and updates in one click from then on.
|
||||
<details>
|
||||
<summary><strong>Manual build and frontend customization</strong></summary>
|
||||
|
||||
**CyberStrikeAI upgrade script:**
|
||||
1. (First time) enable the script: `chmod +x upgrade.sh`
|
||||
2. Upgrade with: `./upgrade.sh` (optional flags: `--check`, `--tag vX.Y.Z`, `--repo owner/name`, `--no-venv`, `--yes`). Local `tools/`, `roles/`, `skills/` and `agents/` are always preserved.
|
||||
3. The script will back up your `config.yaml` and `data/`, upgrade the code, update `config.yaml`'s `version`, then restart the server.
|
||||
After preparing `config.yaml`, you can build the Pi worker and Go server step by step:
|
||||
|
||||
Recommended one-liner:
|
||||
`chmod +x upgrade.sh && ./upgrade.sh --yes`
|
||||
```bash
|
||||
bash scripts/build-pi-runtime.sh
|
||||
go build -o cyberstrike-ai ./cmd/server
|
||||
./cyberstrike-ai -config config.yaml --http
|
||||
```
|
||||
|
||||
If something goes wrong: inside a git work tree just run `./cyberstrike-ai -update-rollback` (back to
|
||||
the commit and binary kept before that update); for a tarball installation restore from
|
||||
`.upgrade-backup/` (or manually copy `data/` and `config.yaml` back) and run `./run.sh` again.
|
||||
If you modify frontend source files under `web/frontend/`, rebuild the static bundle before starting the server:
|
||||
|
||||
Requirements / tips (tarball path only):
|
||||
* You need `curl` or `wget` for downloading Release packages.
|
||||
* `rsync` is recommended/required for the safe code sync.
|
||||
* If GitHub API rate-limits you, set `export GITHUB_TOKEN="..."` before running `./upgrade.sh`.
|
||||
```bash
|
||||
cd web/frontend && npm ci && npm run build
|
||||
```
|
||||
|
||||
⚠️ **Before upgrading:** review the target release notes for configuration, database, and API changes. Backups are required even for patch upgrades; a version number alone is not a compatibility guarantee.
|
||||
Deployments require the runtime directory, `web/static/`, and a matching Pi worker bundle (or a fresh build on the target host); copying the Go binary alone is not sufficient to run agents. Prepare Python tool dependencies separately. See the [Pi runtime guide](docs/en-US/pi-runtime.md).
|
||||
|
||||
</details>
|
||||
|
||||
## Configuration
|
||||
<a id="delegation"></a>
|
||||
|
||||
Use [`config.example.yaml`](config.example.yaml) as the authoritative configuration template and copy only the values required for your environment. At minimum, configure the server and one AI channel:
|
||||
## Execution modes
|
||||
|
||||
CyberStrikeAI provides three complementary ways to run security work over a shared project asset library, tool permissions, and vulnerability records:
|
||||
|
||||
- **Chat**: Interactive investigation and ad-hoc tool execution across single-agent, Deep, Plan-Execute, and Supervisor modes, with project-grouped conversations and live mid-run steering via **Interrupt & continue**.
|
||||
- **Deep Assessments**: Goal-driven persistent assessment workbench powered by native Pi sessions. Maintains attack-surface graphs, exploration graphs, prioritized intent queues, in-task operator Q&A, and receipt-backed acceptance criteria across pause/resume cycles. See the [deep assessments guide (zh-CN)](docs/zh-CN/deep-assessments.md).
|
||||
- **Tasks (Task Management)**: Queue-based batch execution for explicit task lists. Open **Tasks → New task** (`Task Management`), enter one task per line, and configure project scope, role, agent mode, tool approval, concurrency, and optional Cron schedules. Inspect per-subtask results and conversations, or pause, resume, and edit subtasks from the queue detail view. See [batch task management (zh-CN)](docs/zh-CN/task-management.md).
|
||||
|
||||
<a id="capabilities"></a>
|
||||
|
||||
## Capabilities
|
||||
|
||||
| Capability | What it provides | Details |
|
||||
| --- | --- | --- |
|
||||
| Pi agent orchestration | Single-agent, Deep, Plan-Execute, and Supervisor modes with live steering and reasoning controls | [Agents and roles](docs/en-US/agent-and-role-guide.md) |
|
||||
| Deep assessments | Goal-driven planning, shared attack-surface graph, hot/cold exploration graph, intent queues, and acceptance matrix | [Deep assessments (zh-CN)](docs/zh-CN/deep-assessments.md) |
|
||||
| Batch task queues | Concurrent task lists, Cron schedules, pause/resume, and subtask conversation logs | [Task management (zh-CN)](docs/zh-CN/task-management.md) |
|
||||
| Tools, skills, and proxy pool | YAML tool recipes, MCP connections, on-demand skills, and isolated HTTP egress proxy pool | [Tools](tools/README_EN.md) · [Skills](skills/README.md) · [Proxy pool](docs/en-US/http-proxy-pool.md) |
|
||||
| Visual workflows | Compose agent, tool, conditional, and human-approval nodes | [Workflows](docs/en-US/workflow-graph.md) |
|
||||
| Knowledge, evidence, and reports | RAG retrieval, project facts, raw tool receipts, attack-chain analysis, and Word / Markdown reports | [Knowledge base](docs/en-US/knowledge-base.md) · [Reports](docs/en-US/word-reports.md) |
|
||||
| Project & vulnerability workspace | Project-scoped asset library, domain/host/task vulnerability views, and one-click retesting | [Asset management](docs/en-US/asset-management.md) |
|
||||
| Human oversight & governance | RBAC, human-in-the-loop (HITL) approvals, call guards, audit logs, and token monitoring | [Security model](docs/en-US/security-model.md) · [HITL](docs/en-US/hitl-best-practices.md) · [Token usage](docs/en-US/token-usage-monitoring.md) |
|
||||
| Integrations | Burp Suite extension, browser DevTools extension, chat bots, and MCP federation | [Plugins](#integrations) · [Bots](docs/en-US/robot.md) · [MCP](docs/en-US/mcp-federation.md) |
|
||||
|
||||
Specialized operations also include [WebShell management](docs/en-US/webshell.md) and [C2](docs/en-US/c2.md). Enable only the capabilities required for your authorized scope; a bundled tool recipe does not imply the underlying binary is installed or validated in your environment.
|
||||
|
||||
<a id="architecture"></a>
|
||||
|
||||
## Architecture
|
||||
|
||||
| Component | Responsibility |
|
||||
| --- | --- |
|
||||
| **Go server and schedulers** | HTTP/SSE APIs, deep-assessment and batch-queue scheduling, tool governance, storage cleanup, and evidence persistence |
|
||||
| **Pi runtime** | **Pi 1.7.0** model interaction, agent tool loops, native session persistence, compaction, steering, and tool discovery |
|
||||
| **Tool gateway** | Dispatches local tools and MCP calls under role boundaries, permissions, HITL approvals, and output/timeout guards |
|
||||
| **SQLite and Pi sessions** | Business state, graph nodes, and raw tool receipts in SQLite; model transcripts and compaction entries in Pi sessions |
|
||||
| **Web workbench** | React 19 + Semi Design + Cytoscape frontend unifying chat, assessment graphs, task traces, and project assets |
|
||||
|
||||
<a id="integrations"></a>
|
||||
|
||||
## Browser and proxy plugins
|
||||
|
||||
| Integration | Usage | Documentation and package |
|
||||
| --- | --- | --- |
|
||||
| Burp Suite | Send selected HTTP requests to CyberStrikeAI for analysis | [Setup](plugins/burp-suite/cyberstrikeai-burp-extension/README.md) · [JAR](plugins/burp-suite/cyberstrikeai-burp-extension/dist/cyberstrikeai-burp-extension.jar) |
|
||||
| Chrome / Edge | Capture and forward requests from the CyberStrikeAI DevTools panel | [Setup](plugins/browser-extension/cyberstrikeai-browser-extension/README.md) · [ZIP](plugins/browser-extension/cyberstrikeai-browser-extension/dist/cyberstrikeai-browser-extension.zip) |
|
||||
|
||||
## Updates and version migration
|
||||
|
||||
Fresh installations using [config.example.yaml](config.example.yaml) point updates to this repository by default:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
host: "127.0.0.1"
|
||||
port: 8080
|
||||
ai:
|
||||
default_channel: openai-main
|
||||
channels:
|
||||
openai-main:
|
||||
provider: openai_compatible
|
||||
api_key: "${OPENAI_API_KEY}"
|
||||
base_url: "https://api.openai.com/v1"
|
||||
model: "your-model"
|
||||
update:
|
||||
repo: https://github.com/Sycun/CyberStrikeAI
|
||||
```
|
||||
|
||||
`openai` is a backward-compatible runtime field; maintain new model settings in `ai.channels`. Do not commit real credentials. Review the [configuration reference](docs/en-US/configuration.md), [recommended profiles](docs/en-US/configuration-profiles.md), and [security hardening guide](docs/en-US/security-hardening.md) before exposing the service beyond localhost.
|
||||
When migrating an older installation, ensure `update.repo` is set to `https://github.com/Sycun/CyberStrikeAI` in `config.yaml` or under **System settings → One-Click Update** (leaving `update.repo` empty still points to the historical upstream URL, which no longer publishes open-source updates). One-click update pulls the latest source, rebuilds a matching Pi worker and server binary, and preserves existing self-signed TLS certificates and active sessions; see [deployment](docs/en-US/deployment.md) for details.
|
||||
|
||||
## Related documentation
|
||||
Before upgrading from an older Eino-based release, back up your configuration and database and finish or export active workflow runs: **legacy Eino binary workflow checkpoints cannot be resumed in this version**. Historical records, configuration keys, and compatibility routes remain readable, with no legacy-engine fallback switch. See the [Pi runtime and migration guide](docs/en-US/pi-runtime.md).
|
||||
|
||||
- **New users:** [Deployment](docs/en-US/deployment.md) → [Configuration](docs/en-US/configuration.md) → [Troubleshooting](docs/en-US/troubleshooting.md)
|
||||
- **Operators:** [Configuration profiles](docs/en-US/configuration-profiles.md) → [Security hardening](docs/en-US/security-hardening.md) → [Runbooks](docs/en-US/runbooks.md)
|
||||
- **Integrators:** [API reference](docs/en-US/api-reference.md) → [API recipes](docs/en-US/api-recipes.md) → [MCP federation](docs/en-US/mcp-federation.md)
|
||||
- **Contributors:** [Developer guide](docs/en-US/developer-guide.md) → [Testing](docs/en-US/testing.md) → [Contributing](docs/en-US/contributing-guide.md)
|
||||
- **All topics:** [English documentation](docs/en-US/README.md) · [Bilingual documentation index](docs/README.md)
|
||||
## Validation and scope
|
||||
|
||||
## Project Layout
|
||||
Continuous integration covers Go backend tests, Pi runtime protocol checks, frontend builds, process isolation, HTTP proxy pool tests, and isolated regressions for deep assessments and batch queues; check [GitHub Actions](https://github.com/Sycun/CyberStrikeAI/actions) for current status. Automated checks do not replace live evaluation—model compatibility, token cost, and effectiveness on real targets depend on your configured model channel and environment.
|
||||
|
||||
```
|
||||
CyberStrikeAI/
|
||||
├── cmd/ # Server, MCP stdio entrypoints, tooling
|
||||
├── internal/ # Agent, MCP core, handlers, C2 (`internal/c2`), security executor
|
||||
├── web/ # Static SPA + templates
|
||||
├── tools/ # YAML tool recipes (100+ examples provided)
|
||||
├── roles/ # Role configurations (12+ predefined security testing roles)
|
||||
├── skills/ # Agent Skills dirs (SKILL.md + optional files; demo: cyberstrike-pi-demo)
|
||||
├── agents/ # Multi-agent Markdown (orchestrator.md + sub-agent *.md)
|
||||
├── docs/ # Topic docs (deployment, config, security, API, knowledge base, C2, WebShell, etc.)
|
||||
├── images/ # Docs screenshots & diagrams
|
||||
├── config.yaml # Runtime configuration
|
||||
├── run.sh # Convenience launcher
|
||||
└── README*.md
|
||||
```
|
||||
<a id="documentation"></a>
|
||||
|
||||
## Basic Usage Examples
|
||||
## Documentation
|
||||
|
||||
```
|
||||
Scan open ports on 192.168.1.1
|
||||
Perform a comprehensive port scan on 192.168.1.1 focusing on 80,443,22
|
||||
Check if https://example.com/page?id=1 is vulnerable to SQL injection
|
||||
Scan https://example.com for hidden directories and outdated software
|
||||
Enumerate subdomains for example.com, then run nuclei against the results
|
||||
```
|
||||
| What you want to do | Start here |
|
||||
| --- | --- |
|
||||
| Deploy and configure models | [Deployment](docs/en-US/deployment.md) · [Configuration](docs/en-US/configuration.md) · [Config profiles](docs/en-US/configuration-profiles.md) · [Troubleshooting](docs/en-US/troubleshooting.md) |
|
||||
| Run assessments and batch queues | [Deep assessments (zh-CN)](docs/zh-CN/deep-assessments.md) · [Task management (zh-CN)](docs/zh-CN/task-management.md) |
|
||||
| Customize agents, tools, and proxies | [Pi runtime](docs/en-US/pi-runtime.md) · [Agents and roles](docs/en-US/agent-and-role-guide.md) · [Tool recipes](tools/README_EN.md) · [HTTP proxy pool](docs/en-US/http-proxy-pool.md) |
|
||||
| Integrate external systems | [API reference](docs/en-US/api-reference.md) · [API examples](docs/en-US/api-recipes.md) · [MCP federation](docs/en-US/mcp-federation.md) |
|
||||
| Operate a team service | [Security hardening](docs/en-US/security-hardening.md) · [Tool governance](docs/en-US/tool-execution-governance.md) · [Runbooks](docs/en-US/runbooks.md) |
|
||||
| Contribute and explore the repo | [Developer guide](docs/en-US/developer-guide.md) · [Testing](docs/en-US/testing.md) · [Repository guide](docs/REPOSITORY_GUIDE.md) |
|
||||
|
||||
## Advanced Playbooks
|
||||
Browse all topics in the [English documentation](docs/en-US/README.md) or the [bilingual index](docs/README.md).
|
||||
|
||||
```
|
||||
Load the recon-engagement template, run amass/subfinder, then brute-force dirs on every live host.
|
||||
Use external Burp-based MCP server for authenticated traffic replay, then pass findings back for graphing.
|
||||
Compress the 5 MB nuclei report, summarize critical CVEs, and attach the artifact to the conversation.
|
||||
Build an attack chain for the latest engagement and export the node list with severity >= high.
|
||||
```
|
||||
<a id="contributing"></a>
|
||||
|
||||
## 404Starlink
|
||||
## Feedback and contributions
|
||||
|
||||
<img src="./images/404StarLinkLogo.png" width="30%">
|
||||
As an independently maintained open-source branch, community bug reports, feature requests, and pull requests (including tool recipes, UX refinements, and regression tests) are welcome in [Issues](https://github.com/Sycun/CyberStrikeAI/issues) and Pull Requests. When reporting issues, please include the commit hash, OS, model protocol/channel type, reproduction steps, and redacted logs—never upload live API keys, credentials, or sensitive engagement data.
|
||||
|
||||
CyberStrikeAI has joined [404Starlink](https://github.com/knownsec/404StarLink)
|
||||
Thanks to the original authors and past contributors of the earlier open-source [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) project, as well as the Pi, MCP, and broader open-source communities.
|
||||
|
||||
## TCH Top-Ranked Intelligent Pentest Project
|
||||
<div align="left">
|
||||
<a href="https://zc.tencent.com/competition/competitionHackathon?code=cha004" target="_blank">
|
||||
<img src="./images/tch.png" alt="TCH Top-Ranked Intelligent Pentest Project" width="30%">
|
||||
</a>
|
||||
</div>
|
||||
## License and intended use
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Community and Support
|
||||
|
||||
- Join the community on [Discord](https://discord.gg/8PjVCMu8Zw).
|
||||
|
||||
<details>
|
||||
<summary><strong>WeCom group</strong></summary>
|
||||
|
||||
<img src="./images/wecom-group-cyberstrikeai-qr.png" alt="CyberStrikeAI WeCom group QR code" width="280">
|
||||
|
||||
</details>
|
||||
|
||||
## License
|
||||
|
||||
CyberStrikeAI is licensed under the Apache License 2.0.
|
||||
See the [LICENSE](LICENSE) file for details.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Disclaimer
|
||||
|
||||
**This tool is for educational and authorized testing purposes only!**
|
||||
|
||||
CyberStrikeAI is a professional security testing platform designed to assist security researchers, penetration testers, and IT professionals in conducting security assessments and vulnerability research **with explicit authorization**.
|
||||
|
||||
**By using this tool, you agree to:**
|
||||
- Use this tool only on systems where you have clear written authorization
|
||||
- Comply with all applicable laws, regulations, and ethical standards
|
||||
- Take full responsibility for any unauthorized use or misuse
|
||||
- Not use this tool for any illegal or malicious purposes
|
||||
|
||||
**The developers are not responsible for any misuse!** Please ensure your usage complies with local laws and regulations, and that you have obtained explicit authorization from the target system owner.
|
||||
|
||||
For vulnerability reporting and deployment hardening guidance, see [SECURITY.md](SECURITY.md).
|
||||
|
||||
---
|
||||
|
||||
Need help or want to contribute? Open an issue or PR—community tooling additions are welcome!
|
||||
Licensed under the [Apache License 2.0](LICENSE) with the original commit history and copyright notices preserved; third-party components retain their respective licenses and notices. Use this software only on systems you own or have explicit written authorization to test, in compliance with your agreed scope and applicable law. See [SECURITY.md](SECURITY.md) for vulnerability reporting.
|
||||
|
|
|
|||
504
README_CN.md
|
|
@ -1,420 +1,202 @@
|
|||
<div align="center">
|
||||
<img src="images/logo.png" alt="CyberStrikeAI Logo" width="200">
|
||||
<img src="images/logo.png" alt="CyberStrikeAI" width="144">
|
||||
<h1>CyberStrikeAI</h1>
|
||||
<p><strong>描述目标或任务,驱动安全智能体调用工具并沉淀可核查的执行证据。</strong></p>
|
||||
<p><strong>中文</strong> · <a href="README.md">English</a></p>
|
||||
<p>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/pi-runtime.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/pi-runtime.yml/badge.svg?branch=main" alt="Pi runtime CI"></a>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/deep-assessments.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/deep-assessments.yml/badge.svg?branch=main" alt="Deep assessments CI"></a>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/frontend-build.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/frontend-build.yml/badge.svg?branch=main" alt="Frontend build CI"></a>
|
||||
<a href="https://github.com/Sycun/CyberStrikeAI/actions/workflows/self-update.yml"><img src="https://github.com/Sycun/CyberStrikeAI/actions/workflows/self-update.yml/badge.svg?branch=main" alt="Self-update CI"></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
# CyberStrikeAI
|
||||
CyberStrikeAI 是基于 **Go + Pi** 构建的开源网络安全智能体工作台(Go 后端 + React / Semi Design 前端),统一承载交互式安全对话、目标驱动的**深度测评**与清单驱动的**批量任务**,由智能体编排调用安全工具并沉淀结构化执行证据。
|
||||
|
||||
[中文](README_CN.md) | [English](README.md)
|
||||
> 本仓库([Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI))Fork 自原开源仓库 [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI),完整保留原始提交历史、版权声明与 [Apache-2.0 许可证](LICENSE)。在原官方项目转向闭源后,本仓库由原官方核心维护者 **[Sycun](https://github.com/Sycun)** 作为独立开源分支继续维护与演进。
|
||||
|
||||
**CyberStrikeAI 是 AI 原生网络安全的智能执行中枢——让意图转化为受治理的行动,让证据沉淀为运营记忆,并让每次行动优化下一次行动。**
|
||||
[核心特性](#highlights) · [界面预览](#screenshots) · [快速上手](#quick-start) · [任务与测评模式](#delegation) · [主要能力](#capabilities) · [架构](#architecture) · [文档](#documentation) · [反馈与贡献](#contributing)
|
||||
|
||||
CyberStrikeAI 将规划、执行、人工监督、证据与复盘连接在同一个可审计工作空间中。项目基于 Go 构建,使用 Pi 智能体,融合 MCP 原生工具、RAG 知识、可视化工作流以及攻击链建模与分析能力,面向已获得明确授权的安全任务。
|
||||
<a id="highlights"></a>
|
||||
|
||||
**从这里开始:** [快速上手](#快速上手一条命令部署) · [中文文档](docs/zh-CN/README.md) · [安全加固](docs/zh-CN/security-hardening.md)
|
||||
## 核心特性
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 仅可对自有系统或已获得明确授权的目标使用 CyberStrikeAI。在共享或生产环境启用高风险工具、WebShell 或 C2 前,请先阅读[安全模型](docs/zh-CN/security-model.md)和[安全加固指南](docs/zh-CN/security-hardening.md)。
|
||||
- **Pi 1.7.0 原生智能体运行时**:全面采用原生 Pi 会话持久化、自动上下文压缩(Compaction)、执行中实时「中断并继续(Steering)」以及推理强度(Reasoning Effort)档位调节,已彻底移除早期 Eino 引擎依赖。
|
||||
- **目标驱动的「深度测评」持久工作台**:围绕测评目标与验收条件长周期推进,内置项目级共享**攻击面图**、支持冷热分支归档的**探索图谱**、优先级**意图队列**,以及强制绑定真实工具回执的**事实记录与验收证据矩阵**。
|
||||
- **React 19 + Semi Design 统一工作台**:采用现代化单页架构,支持抽屉式详情查阅、按项目分组管理对话、紧凑模型与角色切换,以及按域名、主机、任务多维聚合的漏洞管理与**一键复测**。
|
||||
- **多网关兼容与上下文自适应**:支持渠道自定义鉴权请求头(适配各类第三方聚合网关,限制同源重定向防泄露)、运行时上下文窗口自动探测、本地推理服务(oMLX / Ollama 等)`local_auto` 画像、DeepSeek 经济上下文画像及独立 HITL 审计模型配置。
|
||||
- **独立出站代理池与自托管运维**:提供与模型 API 流量隔离的 [HTTP 测试代理池与故障切换](docs/zh-CN/http-proxy-pool.md);内置保留自签证书与登录态的 Web 端**一键自更新**,以及可预览的运行空间**存储清理**。
|
||||
|
||||
## 界面与集成预览
|
||||
<a id="screenshots"></a>
|
||||
|
||||
<div align="center">
|
||||
## 界面预览
|
||||
|
||||
### 系统仪表盘概览
|
||||
| 系统仪表盘(风险分布与运行态概览) | 深度测评工作台(深色主题 · 目标与进度) |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<strong>浅色模式</strong><br/>
|
||||
<img src="./images/dashboard.png" alt="系统仪表盘(浅色)" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>深色模式</strong><br/>
|
||||
<img src="./images/dark.png" alt="系统仪表盘(深色)" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
| 深度测评 · 探索图谱(意图、事实、漏洞与冷归档) | 对话控制台(项目分组、工具回执与任务总结) |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
*仪表盘提供系统运行状态、安全漏洞、工具使用情况和知识库的全面概览,帮助用户快速了解平台核心功能和当前状态。*
|
||||
| 漏洞管理(按域名/主机树状聚合与严重度统计) | MCP 与工具管理(外部 MCP 连接与内置工具配置) |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
<details>
|
||||
<summary><strong>查看更多界面截图</strong></summary>
|
||||
<a id="quick-start"></a>
|
||||
|
||||
### 核心功能概览
|
||||
## 快速上手
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Web 控制台</strong><br/>
|
||||
<img src="./images/web-console.png" alt="Web 控制台" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>任务管理</strong><br/>
|
||||
<img src="./images/task-management.png" alt="任务管理" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>漏洞管理</strong><br/>
|
||||
<img src="./images/vulnerability-management.png" alt="漏洞管理" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>WebShell 管理</strong><br/>
|
||||
<img src="./images/webshell-management.png" alt="WebShell 管理" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP 管理</strong><br/>
|
||||
<img src="./images/mcp-management.png" alt="MCP 管理" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>知识库</strong><br/>
|
||||
<img src="./images/knowledge-base.png" alt="知识库" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Skills 管理</strong><br/>
|
||||
<img src="./images/skills.png" alt="Skills 管理" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Agent 管理</strong><br/>
|
||||
<img src="./images/agent-management.png" alt="Agent 管理" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>角色管理</strong><br/>
|
||||
<img src="./images/role-management.png" alt="角色管理" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>系统设置</strong><br/>
|
||||
<img src="./images/settings.png" alt="系统设置" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP stdio 模式</strong><br/>
|
||||
<img src="./images/mcp-stdio2.png" alt="MCP stdio 模式" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Burp Suite 插件</strong><br/>
|
||||
<img src="./images/plugins.png" alt="Burp Suite 插件" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
### 1. 准备环境
|
||||
|
||||
</details>
|
||||
| 依赖 | 要求 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| Go | 1.25+,以 [go.mod](go.mod) 为准 | 编译后端服务与运行时构建器 |
|
||||
| Node.js 与 npm | Node.js 22.19+ | 构建与运行 Pi Worker(及可选前端二次构建) |
|
||||
| Python | 3.10+,支持 `venv` | 启动脚本及 Python 工具依赖 |
|
||||
| Git | 已加入 `PATH` | 克隆源码与 Web 端一键更新 |
|
||||
|
||||
</div>
|
||||
运行前还需准备支持工具调用(Tool Calling)的模型渠道,以及任务实际所需的本地安全工具或外部 MCP 服务。仓库内置工具配方,但**不会自动安装所有第三方安全工具**。`run.sh` 默认使用国内临时镜像加速 Go 与 pip 依赖下载,也可通过环境变量 `GOPROXY`、`PIP_INDEX_URL` 自定义。
|
||||
|
||||
## 特性速览
|
||||
### 2. 获取源码并启动
|
||||
|
||||
### 智能体与编排
|
||||
以下命令适用于 macOS / Linux 的 Bash 环境:
|
||||
|
||||
- 🤖 **智能体执行层**:将自然语言意图转化为受控、可审计的安全行动。
|
||||
- 🧩 **Pi 编排**:支持单智能体及 Deep、Plan-Execute、Supervisor 多智能体模式。
|
||||
- 🔀 **工作流**:通过 Agent、工具、条件、审批和输出节点构建可复用流程。
|
||||
- 🎭 **角色化测试**:为常见安全场景提供聚焦的提示词和工具策略。
|
||||
|
||||
### 工具与知识扩展
|
||||
|
||||
- 🧰 **安全工具**:提供 100+ 精选 YAML 工具配方,支持自定义扩展和按角色控制。
|
||||
- 🔌 **MCP 集成**:支持 HTTP、stdio、SSE、外部 MCP 联邦和动态工具发现。
|
||||
- ⏱️ **弹性工具执行**:阻塞型 MCP/工具调用交给 worker 执行,Agent 只有限等待;支持 `execution_id` 多轮等待、主动取消、单 server 熔断、并发限制和统一输出兜底。
|
||||
- 🎯 **Agent Skills**:遵循标准 Skill 目录结构,支持渐进式按需加载。
|
||||
- 📚 **知识库**:组合查询改写、向量检索、精排和结果后处理能力。
|
||||
- 🖼️ **视觉分析**:使用独立视觉模型分析截图、验证码和 UI,对话中仅保留文字摘要。
|
||||
|
||||
### 安全治理与审计
|
||||
|
||||
- 🧑⚖️ **人机协同**:支持审批模式、工具白名单、审计 Agent 复核和决策追踪。
|
||||
- 🛡️ **调用拦截**:「安全防护」下配置 MCP 执行前正则拦截、提醒模板和试匹配,默认启用政府域名保护。详见[调用拦截](docs/zh-CN/tool-call-guard.md)。
|
||||
- 🔐 **平台 RBAC**:支持多用户、系统及自定义角色、权限 Scope、资源归属和显式授权。
|
||||
- 🔒 **安全与审计**:提供登录保护、审计日志、SQLite 持久化和行动证据留存。
|
||||
- 📄 **结果治理**:数据库保存与 Agent 实际看到的同一份兜底后工具结果,恢复路径会再次防御历史超大输出,前端详情也有展示保护。详见[工具执行治理](docs/zh-CN/tool-execution-governance.md)。
|
||||
|
||||
### 安全运营管理
|
||||
|
||||
- 📁 **对话管理**:支持分组、置顶、重命名和批量管理。
|
||||
- 📂 **项目与攻击链**:关联跨会话事实、风险评分、图谱视图和步骤回放。
|
||||
- 🗂️ **资产管理**:统一归档和去重域名、IP、端口与服务,支持 XLSX/CSV 导入导出、高级筛选与保存视图、责任和业务属性、跨页批量维护、重复资产合并,并跟踪扫描覆盖、关联漏洞和风险状态。详见[资产管理指南](docs/zh-CN/asset-management.md)。
|
||||
- 🛡️ **漏洞管理**:支持严重程度分级、状态流转、过滤和统计看板。
|
||||
- 📋 **批量任务**:支持任务队列、编辑、状态跟踪和结果留存。
|
||||
- 📱 **机器人接入**:支持个人微信、企业微信、钉钉、飞书、Telegram、Slack、Discord 和 QQ。
|
||||
|
||||
### 授权安全操作
|
||||
|
||||
- 🐚 **WebShell 管理**:提供连接管理、虚拟终端、文件操作和 AI 辅助工作流。
|
||||
- 📡 **内置 C2**:提供监听器、加密 Beacon、会话、任务队列、Payload 辅助和实时事件。
|
||||
|
||||
> WebShell、C2 及其他高风险能力仅限自有系统或已获得明确授权的测试环境。使用前请阅读[安全模型](docs/zh-CN/security-model.md)和[安全加固指南](docs/zh-CN/security-hardening.md)。
|
||||
|
||||
## 插件(Plugins)
|
||||
|
||||
可选集成在 `plugins/` 目录下。
|
||||
|
||||
- **Burp Suite 插件**:`plugins/burp-suite/cyberstrikeai-burp-extension/`
|
||||
构建产物:`plugins/burp-suite/cyberstrikeai-burp-extension/dist/cyberstrikeai-burp-extension.jar`
|
||||
说明文档:`plugins/burp-suite/cyberstrikeai-burp-extension/README.zh-CN.md`
|
||||
- **浏览器扩展(Chrome / Edge)**:`plugins/browser-extension/cyberstrikeai-browser-extension/`
|
||||
在 DevTools 中捕获 Network 流量并发送到 CyberStrikeAI 进行 AI 辅助安全测试,能力与 Burp 插件对齐。
|
||||
安装:`chrome://extensions/` → 加载已解压 → F12 → **CyberStrikeAI** 标签页
|
||||
打包产物:`plugins/browser-extension/cyberstrikeai-browser-extension/dist/cyberstrikeai-browser-extension.zip`
|
||||
说明文档:`plugins/browser-extension/cyberstrikeai-browser-extension/README.zh-CN.md`
|
||||
|
||||
## 工具概览
|
||||
|
||||
系统预置 100+ 渗透/攻防工具,覆盖完整攻击链:
|
||||
|
||||
<details>
|
||||
<summary><strong>查看完整工具分类</strong></summary>
|
||||
|
||||
- **网络扫描**:nmap、masscan、rustscan、arp-scan、nbtscan
|
||||
- **Web 应用扫描**:sqlmap、nikto、dirb、gobuster、feroxbuster、ffuf、httpx
|
||||
- **漏洞扫描**:nuclei、wpscan、wafw00f、dalfox、xsser
|
||||
- **子域名枚举**:subfinder、amass、findomain、dnsenum、fierce
|
||||
- **网络空间搜索引擎**:fofa_search、zoomeye_search、quake_search、shodan_search
|
||||
- **API 安全**:graphql-scanner、arjun、api-fuzzer、api-schema-analyzer
|
||||
- **容器安全**:trivy、clair、docker-bench-security、kube-bench、kube-hunter
|
||||
- **云安全**:prowler、scout-suite、cloudmapper、pacu、terrascan、checkov
|
||||
- **二进制分析**:gdb、radare2、ghidra、objdump、strings、binwalk
|
||||
- **漏洞利用**:metasploit、msfvenom、pwntools、ropper、ropgadget
|
||||
- **密码破解**:hashcat、john、hashpump
|
||||
- **取证分析**:volatility、volatility3、foremost、steghide、exiftool
|
||||
- **后渗透**:linpeas、winpeas、mimikatz、bloodhound、impacket、responder
|
||||
- **CTF 实用工具**:stegsolve、zsteg、hash-identifier、fcrackzip、pdfcrack、cyberchef
|
||||
- **系统辅助**:exec、create-file、delete-file、list-files、modify-file
|
||||
|
||||
</details>
|
||||
|
||||
工具定义、自定义方式与使用说明见 [tools/README.md](tools/README.md)。
|
||||
|
||||
## 基础使用
|
||||
|
||||
### 快速上手(一条命令部署)
|
||||
|
||||
**环境要求:**
|
||||
- Go 1.25+([下载安装](https://go.dev/dl/),以 `go.mod` 为准)
|
||||
- Python 3.10+ ([下载安装](https://www.python.org/downloads/))
|
||||
|
||||
**一条命令部署:**
|
||||
```bash
|
||||
git clone https://github.com/Ed1s0nZ/CyberStrikeAI.git
|
||||
git clone --branch main https://github.com/Sycun/CyberStrikeAI.git
|
||||
cd CyberStrikeAI
|
||||
chmod +x run.sh && ./run.sh
|
||||
cp config.example.yaml config.yaml
|
||||
```
|
||||
|
||||
`run.sh` 脚本会自动完成:
|
||||
- ✅ 检查并验证 Go 和 Python 环境
|
||||
- ✅ 创建 Python 虚拟环境
|
||||
- ✅ 安装 Python 依赖包
|
||||
- ✅ 下载 Go 依赖模块
|
||||
- ✅ 编译构建项目
|
||||
- ✅ 启动服务器
|
||||
本机试用建议先将 `config.yaml` 中的 `server.host` 改为 `127.0.0.1`,然后启动服务:
|
||||
|
||||
**验证是否启动成功:**
|
||||
|
||||
1. 确认终端显示 `● ONLINE`,并在其后给出实际 Web UI 地址。
|
||||
2. 打开该地址;默认 HTTPS 使用本地自签证书,首次访问需接受一次浏览器证书提示。
|
||||
3. 全新安装时,妥善保存 `ADMIN SETUP REQUIRED` 下仅展示一次的 `admin` 密码,登录后立即修改。
|
||||
|
||||
**网络默认:** `run.sh` 会以 **`--https`** 并传入项目根 **`config.yaml`** 启动(本机自签证书,多路流式场景更稳)。只要明文 HTTP 用 **`./run.sh --http`**。生产环境在 **`config.yaml`** 的 **`server.tls_cert_path` / `server.tls_key_path`** 配正式证书(见文件内注释)。手动启动可加 **`--https`** 或环境变量 **`CYBERSTRIKE_HTTPS=1`**;`-config` 写错时程序会在终端提示正确写法。
|
||||
|
||||
**首次配置:**
|
||||
1. **配置 AI 通道**(首次使用前必填)
|
||||
- 启动后在浏览器打开 **`https://127.0.0.1:8080/`**(或 **`https://localhost:8080/`**;端口以 `config.yaml` 中 **`server.port`** 为准,默认 8080),并按提示信任自签证书。若使用 **`./run.sh --http`**,则改用 **`http://`** 访问。
|
||||
- 进入 `系统设置` → `基本设置` → `AI 通道配置`,新增或编辑通道,填写 API 提供商、Base URL、API Key、模型和 Token 上限,点击 **保存更改**。左侧通道列表支持设为默认、复制、删除和批量探活。
|
||||
```yaml
|
||||
ai:
|
||||
default_channel: openai-main
|
||||
channels:
|
||||
openai-main:
|
||||
name: OpenAI Main
|
||||
provider: openai_compatible
|
||||
api_key: "${OPENAI_API_KEY}"
|
||||
base_url: "https://api.openai.com/v1" # 或 https://api.deepseek.com/v1
|
||||
model: "gpt-4o" # 或 deepseek-chat, qwen3-max 等
|
||||
max_total_tokens: 120000
|
||||
max_completion_tokens: 16384
|
||||
```
|
||||
- 或启动前直接编辑 `config.yaml` 文件。`ai.default_channel` 会作为新对话和未显式选择通道任务的默认模型;对话页也可以在会话设置里选择某个已保存通道。
|
||||
2. **登录系统** - 首次启动时控制台会显示自动生成的 `admin` 初始密码;也可在「平台权限 → 用户管理」中创建账号
|
||||
3. **安装安全工具(可选)** - 按需安装 `tools/` 目录中的工具;未安装的工具在执行时会自动跳过或改用替代方案。常用示例:
|
||||
|
||||
**macOS(Homebrew):**
|
||||
```bash
|
||||
brew install nmap masscan sqlmap nikto gobuster ffuf hydra hashcat nuclei subfinder
|
||||
```
|
||||
|
||||
**Linux(Kali / Debian / Ubuntu):**
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y nmap masscan sqlmap nikto gobuster hydra hashcat john binwalk
|
||||
# 部分发行版需自行安装:ffuf、nuclei、subfinder 等可用 go install 或见各工具官网
|
||||
```
|
||||
|
||||
完整工具列表见 `tools/` 目录;各工具安装方式以官方文档为准。
|
||||
|
||||
**其他启动方式:**
|
||||
```bash
|
||||
# 直接运行(需自行配环境);与 run.sh 默认一致可加 --https
|
||||
go run ./cmd/server --https
|
||||
|
||||
# 手动编译
|
||||
go build -o cyberstrike-ai ./cmd/server
|
||||
./cyberstrike-ai --https
|
||||
bash run.sh --http
|
||||
```
|
||||
|
||||
若日志出现 `client sent an HTTP request to an HTTPS server`,说明仍有客户端用 **`http://`** 访问只提供 HTTPS 的端口,请改为 **`https://`**。
|
||||
脚本会自动构建 Pi Worker、创建 Python 虚拟环境、安装依赖并编译启动服务(前端静态产物已预构建在 `web/static/app/` 中,开箱即用)。默认监听 [http://127.0.0.1:8080/](http://127.0.0.1:8080/),实际端口以配置和终端输出为准。
|
||||
|
||||
**说明:** Python 虚拟环境(`venv/`)由 `run.sh` 自动创建和管理。需要 Python 的工具(如 `api-fuzzer`、`http-framework-test` 等)会自动使用该环境。
|
||||
不带 `--http` 时,`run.sh` 默认启用 HTTPS + HTTP/2(未配置证书时自动生成并复用本地自签证书)。团队共享部署的监听地址、TLS 证书与访问控制请参考[部署指南](docs/zh-CN/deployment.md)。
|
||||
|
||||
### 版本升级与兼容性
|
||||
### 3. 完成首次配置
|
||||
|
||||
**优先用平台自带的「一键更新」**(控制台「系统设置 → 一键更新」,或 `./cyberstrike-ai -update` /
|
||||
`-check-update` / `-update-rollback`):它从**更新源仓库**(默认官方仓库,可一处配置改成自己的二开或镜像)
|
||||
拉取默认分支的最新代码,快进后重编译并原子换二进制,你的 `roles/skills/tools/agents/data/config.yaml`
|
||||
会被原样保留(结果里逐个点名保留了什么,只有 `config.yaml` 的 `version` 字段会随新代码同步,让页头版本号与代码对上),
|
||||
本地源码有改动或本地历史与更新源分叉时它会拒绝而不是覆盖。
|
||||
详见 [部署指南](docs/zh-CN/deployment.md)。
|
||||
1. 使用终端 `ADMIN SETUP REQUIRED` 输出的初始 `admin` 密码登录,并按提示修改密码。
|
||||
2. 在 **系统设置 → 基本设置 → AI 通道配置** 中填写提供商、Base URL、API Key 和模型,保存后设为默认通道(示例配置中的凭据仅为占位符)。
|
||||
3. 按需安装本地安全工具或接入外部 MCP 服务,确认工具可用后再分配给对应角色或智能体。
|
||||
4. 多人协作时,可在 **平台权限 → 添加成员** 中为团队成员分配独立账号、角色与数据范围。
|
||||
|
||||
`upgrade.sh` 仍然可用:本目录是 git 工作树时它就是上面那条命令的薄壳;不是 git 工作树(tarball 安装)时
|
||||
才回落到"下载 GitHub Release 包 + rsync"的老路径,此时源码仓库由 `--repo owner/name` 或 `GITHUB_REPO`
|
||||
决定(都不给才用内置默认值,并会警告说明代码来自哪个仓库)。
|
||||
完整配置项以 [config.example.yaml](config.example.yaml) 为准;模型通道、本地模型与上下文策略详见[配置参考](docs/zh-CN/configuration.md)与[配置画像](docs/zh-CN/configuration-profiles.md)。
|
||||
|
||||
更新源是 `config.yaml` `update` 段里的一个仓库地址(`repo`),也可以在控制台「一键更新」页填写保存
|
||||
(跟随官方仓库、自己的二开、别人的二开或镜像都只是这一处;不写就是官方仓库);解压安装(目录里没有 git)
|
||||
也能在同一页「预览并接入」后进入一键更新。
|
||||
<details>
|
||||
<summary><strong>手动构建与前端二次开发</strong></summary>
|
||||
|
||||
1. (首次使用)启用脚本:`chmod +x upgrade.sh`
|
||||
2. 升级:`./upgrade.sh`(可选参数:`--check`、`--tag vX.Y.Z`、`--repo owner/name`、`--no-venv`、`--yes`)。本地的 `tools/`、`roles/`、`skills/`、`agents/` 会始终保留不被覆盖。
|
||||
3. 脚本会备份你的 `config.yaml` 和 `data/`,升级代码,更新 `config.yaml` 的 `version` 字段后重启服务。
|
||||
完成 `config.yaml` 配置后,可分步构建 Pi Worker 与 Go 服务:
|
||||
|
||||
推荐的一键指令:
|
||||
`chmod +x upgrade.sh && ./upgrade.sh --yes`
|
||||
```bash
|
||||
bash scripts/build-pi-runtime.sh
|
||||
go build -o cyberstrike-ai ./cmd/server
|
||||
./cyberstrike-ai -config config.yaml --http
|
||||
```
|
||||
|
||||
如果升级失败:git 工作树里直接 `./cyberstrike-ai -update-rollback`(回到那次更新前的提交与二进制);
|
||||
tarball 安装则从 `.upgrade-backup/` 恢复,或手动拷回 `data/` 和 `config.yaml` 后再运行 `./run.sh`。
|
||||
若修改了 `web/frontend/` 下的前端源码,重新构建静态产物后再启动服务即可:
|
||||
|
||||
依赖/提示(只有 tarball 路径用得到):
|
||||
* 需要 `curl` 或 `wget` 用于下载 GitHub Release 包。
|
||||
* 建议/需要 `rsync` 用于安全同步代码。
|
||||
* 如果遇到 GitHub API 限流,运行前设置 `export GITHUB_TOKEN="..."` 再执行 `./upgrade.sh`。
|
||||
```bash
|
||||
cd web/frontend && npm ci && npm run build
|
||||
```
|
||||
|
||||
⚠️ **升级前必读:** 请查看目标版本的 Release Notes,确认配置、数据库和 API 是否变化。即使只是补丁版本也应先备份,不能仅凭版本号判断兼容性。
|
||||
部署时需同时保留运行时目录、`web/static/` 与匹配的 Pi Worker 构建产物(或在目标机器重新执行构建),仅复制单个 Go 二进制无法运行智能体;Python 工具依赖需另行准备。详见 [Pi 运行时说明](docs/zh-CN/pi-runtime.md)。
|
||||
|
||||
</details>
|
||||
|
||||
## 配置
|
||||
<a id="delegation"></a>
|
||||
|
||||
请以 [`config.example.yaml`](config.example.yaml) 作为权威配置模板,只复制当前环境需要的配置。最少需要配置服务监听地址和一个 AI 通道:
|
||||
## 任务与测评模式
|
||||
|
||||
平台提供三种互补的执行入口,共享同一套项目资产库、工具权限与漏洞记录:
|
||||
|
||||
- **对话(Chat)**:面向交互式研判与即时操作,支持单智能体、Deep、Plan-Execute、Supervisor 模式,支持按项目分组管理会话,并可在执行中通过「中断并继续」实时补充人工指令。
|
||||
- **深度测评(Deep Assessments)**:面向目标驱动的持续安全测评。围绕测评目标与验收条件,基于 Pi 原生会话维护攻击面图、探索图、优先级意图队列与原始执行回执,支持长周期暂停、恢复、任务内追问与验收证据核对。详见[深度测评说明](docs/zh-CN/deep-assessments.md)。
|
||||
- **任务管理(Batch Tasks)**:面向清单驱动的批量队列执行。在 **任务管理 → 新建任务** 中每行填写一项任务,配置项目、角色、代理模式、工具审批、并发数与可选 Cron 定时规则,在队列详情中查看子任务结果与执行会话,并按状态暂停、继续或编辑子任务。详见[批量任务管理](docs/zh-CN/task-management.md)。
|
||||
|
||||
<a id="capabilities"></a>
|
||||
|
||||
## 主要能力
|
||||
|
||||
| 能力 | 功能概述 | 参考文档 |
|
||||
| --- | --- | --- |
|
||||
| Pi 智能体编排 | 单智能体、Deep、Plan-Execute、Supervisor 多模式执行、中途引导与推理档位控制 | [智能体与角色](docs/zh-CN/agent-and-role-guide.md) |
|
||||
| 深度测评 | 目标驱动规划、共享攻击面图、探索图冷热记忆、意图队列与验收证据矩阵 | [深度测评](docs/zh-CN/deep-assessments.md) |
|
||||
| 批量任务队列 | 清单并发执行、Cron 定时调度、暂停/继续与子任务会话追溯 | [批量任务管理](docs/zh-CN/task-management.md) |
|
||||
| 工具、Skills 与代理池 | YAML 工具配方、外部 MCP 接入、按需技能加载与独立 HTTP 出站代理池 | [工具](tools/README.md) · [Skills](skills/README.md) · [代理池](docs/zh-CN/http-proxy-pool.md) |
|
||||
| 可视化工作流 | 编排智能体、工具、条件分支与人工审批节点 | [工作流](docs/zh-CN/workflow-graph.md) |
|
||||
| 知识、证据与报告 | RAG 检索、项目事实沉淀、原始工具回执、攻击链分析与 Word / Markdown 报告导出 | [知识库](docs/zh-CN/knowledge-base.md) · [报告导出](docs/zh-CN/word-reports.md) |
|
||||
| 项目与漏洞工作台 | 项目级资产库、域名/主机/任务多维漏洞视图、详情抽屉一键复测 | [资产管理](docs/zh-CN/asset-management.md) |
|
||||
| 人工监督与治理 | RBAC 权限控制、高风险工具审批(HITL)、调用拦截、操作审计与 Token 监控 | [安全模型](docs/zh-CN/security-model.md) · [HITL](docs/zh-CN/hitl-best-practices.md) · [Token 监控](docs/zh-CN/token-usage-monitoring.md) |
|
||||
| 外部生态集成 | Burp Suite 插件、浏览器 DevTools 扩展、IM 机器人与外部 MCP 联邦 | [插件](#integrations) · [机器人](docs/zh-CN/robot.md) · [MCP](docs/zh-CN/mcp-federation.md) |
|
||||
|
||||
专项能力还包括 [WebShell 管理](docs/zh-CN/webshell.md) 与 [C2 协同](docs/zh-CN/c2.md)。请按授权任务范围启用所需模块;仓库包含工具配方不代表对应二进制已在本地安装或完成环境校验。
|
||||
|
||||
<a id="architecture"></a>
|
||||
|
||||
## 架构概览
|
||||
|
||||
| 组件 | 核心职责 |
|
||||
| --- | --- |
|
||||
| **Go 服务与调度引擎** | 承载 HTTP/SSE 接口、深度测评与批量队列调度、工具执行管控、存储清理及证据落盘 |
|
||||
| **Pi 运行时** | 基于 **Pi 1.7.0** 处理模型交互、工具调用循环、原生会话持久化、上下文压缩与中途引导(Steering) |
|
||||
| **工具网关** | 统一分发本地工具与 MCP 调用,执行角色边界、权限校验、人工审批与超时/输出截断治理 |
|
||||
| **SQLite 与 Pi 会话存储** | SQLite 保存业务状态、图谱节点与执行回执;Pi 会话记录模型上下文与压缩摘要 |
|
||||
| **Web 工作台** | 基于 React 19 + Semi Design + Cytoscape 构建的前端界面,统一呈现对话、测评图谱、任务轨迹与项目资产 |
|
||||
|
||||
<a id="integrations"></a>
|
||||
|
||||
## 浏览器与抓包插件
|
||||
|
||||
| 集成组件 | 用途 | 文档与构建包 |
|
||||
| --- | --- | --- |
|
||||
| Burp Suite 插件 | 将选中的 HTTP 请求一键发送至 CyberStrikeAI 进行安全分析 | [安装说明](plugins/burp-suite/cyberstrikeai-burp-extension/README.zh-CN.md) · [JAR](plugins/burp-suite/cyberstrikeai-burp-extension/dist/cyberstrikeai-burp-extension.jar) |
|
||||
| Chrome / Edge 扩展 | 在浏览器 DevTools 的 CyberStrikeAI 面板捕获并提交请求 | [安装说明](plugins/browser-extension/cyberstrikeai-browser-extension/README.zh-CN.md) · [ZIP](plugins/browser-extension/cyberstrikeai-browser-extension/dist/cyberstrikeai-browser-extension.zip) |
|
||||
|
||||
## 更新与版本迁移
|
||||
|
||||
新安装的 [config.example.yaml](config.example.yaml) 默认将更新源指向本仓库:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
host: "127.0.0.1"
|
||||
port: 8080
|
||||
ai:
|
||||
default_channel: openai-main
|
||||
channels:
|
||||
openai-main:
|
||||
provider: openai_compatible
|
||||
api_key: "${OPENAI_API_KEY}"
|
||||
base_url: "https://api.openai.com/v1"
|
||||
model: "your-model"
|
||||
update:
|
||||
repo: https://github.com/Sycun/CyberStrikeAI
|
||||
```
|
||||
|
||||
`openai` 是兼容旧版本的运行时字段,新配置优先维护 `ai.channels`。不要提交真实凭证。将服务暴露到 localhost 之外前,请阅读[配置参考](docs/zh-CN/configuration.md)、[推荐配置画像](docs/zh-CN/configuration-profiles.md)和[安全加固指南](docs/zh-CN/security-hardening.md)。
|
||||
若从旧版安装迁移而来,请在 `config.yaml` 或 **系统设置 → 一键更新** 中确认更新源已设为 `https://github.com/Sycun/CyberStrikeAI`(`update.repo` 留空仍指向已停止开源更新的旧仓库地址)。一键更新会自动拉取源码、重新构建匹配的 Pi Worker 与服务二进制,并保留现有自签 TLS 证书与登录会话;详细步骤见[部署指南](docs/zh-CN/deployment.md)。
|
||||
|
||||
## 相关文档
|
||||
若从早期 Eino 版本升级,请先备份运行配置与数据库,并结束或导出旧工作流任务:**旧版 Eino 二进制工作流检查点无法在当前版本直接续跑**。历史数据记录、常用配置键与兼容路由仍保持可读,但不提供旧引擎切换开关。详见 [Pi 运行时与迁移说明](docs/zh-CN/pi-runtime.md)。
|
||||
|
||||
- **新用户:** [部署指南](docs/zh-CN/deployment.md) → [配置参考](docs/zh-CN/configuration.md) → [排错指南](docs/zh-CN/troubleshooting.md)
|
||||
- **运维人员:** [配置画像](docs/zh-CN/configuration-profiles.md) → [安全加固](docs/zh-CN/security-hardening.md) → [运维 Runbooks](docs/zh-CN/runbooks.md)
|
||||
- **集成开发:** [API 参考](docs/zh-CN/api-reference.md) → [API Recipes](docs/zh-CN/api-recipes.md) → [MCP 联邦](docs/zh-CN/mcp-federation.md)
|
||||
- **项目贡献:** [开发者指南](docs/zh-CN/developer-guide.md) → [测试指南](docs/zh-CN/testing.md) → [贡献规范](docs/zh-CN/contributing-guide.md)
|
||||
- **全部专题:** [中文文档](docs/zh-CN/README.md) · [双语文档索引](docs/README.md)
|
||||
## 验证与质量边界
|
||||
|
||||
## 项目结构
|
||||
持续集成覆盖 Go 后端测试、Pi 运行时协议校验、前端构建、进程隔离、代理池以及深度测评与批量队列的隔离回归检查,最新状态见 [GitHub Actions](https://github.com/Sycun/CyberStrikeAI/actions)。自动化回归不替代真实环境验收;具体模型渠道的兼容性、Token 成本与真实目标测试效果需结合实际环境评估。
|
||||
|
||||
```
|
||||
CyberStrikeAI/
|
||||
├── cmd/ # Web 服务、MCP stdio 入口及辅助工具
|
||||
├── internal/ # Agent、MCP 核心、路由、C2(`internal/c2`)与执行器
|
||||
├── web/ # 前端静态资源与模板
|
||||
├── tools/ # YAML 工具目录(含 100+ 示例)
|
||||
├── roles/ # 角色配置文件目录(含 12+ 预设安全测试角色)
|
||||
├── skills/ # Agent Skills 目录(SKILL.md + 可选文件;示例 cyberstrike-pi-demo)
|
||||
├── agents/ # 多代理 Markdown(orchestrator.md + 子代理 *.md)
|
||||
├── docs/ # 专题文档(部署、配置、安全、API、知识库、C2、WebShell 等)
|
||||
├── images/ # 文档配图
|
||||
├── config.yaml # 运行配置
|
||||
├── run.sh # 启动脚本
|
||||
└── README*.md
|
||||
```
|
||||
<a id="documentation"></a>
|
||||
|
||||
## 基础体验示例
|
||||
## 文档导航
|
||||
|
||||
```
|
||||
扫描 192.168.1.1 的开放端口
|
||||
对 192.168.1.1 做 80/443/22 重点扫描
|
||||
检查 https://example.com/page?id=1 是否存在 SQL 注入
|
||||
枚举 https://example.com 的隐藏目录与组件漏洞
|
||||
获取 example.com 的子域并批量执行 nuclei
|
||||
```
|
||||
| 使用场景 | 推荐入口 |
|
||||
| --- | --- |
|
||||
| 部署服务与配置模型 | [部署指南](docs/zh-CN/deployment.md) · [配置参考](docs/zh-CN/configuration.md) · [配置画像](docs/zh-CN/configuration-profiles.md) · [故障排查](docs/zh-CN/troubleshooting.md) |
|
||||
| 运行深度测评与批量任务 | [深度测评](docs/zh-CN/deep-assessments.md) · [批量任务管理](docs/zh-CN/task-management.md) |
|
||||
| 定制智能体、工具与代理 | [Pi 运行时](docs/zh-CN/pi-runtime.md) · [智能体与角色](docs/zh-CN/agent-and-role-guide.md) · [工具配方](tools/README.md) · [HTTP 代理池](docs/zh-CN/http-proxy-pool.md) |
|
||||
| 对接外部系统与自动化 | [API 参考](docs/zh-CN/api-reference.md) · [API 示例](docs/zh-CN/api-recipes.md) · [MCP 联邦](docs/zh-CN/mcp-federation.md) |
|
||||
| 团队运维与安全加固 | [安全加固](docs/zh-CN/security-hardening.md) · [工具执行治理](docs/zh-CN/tool-execution-governance.md) · [运维手册](docs/zh-CN/runbooks.md) |
|
||||
| 参与开发与了解仓库结构 | [开发者指南](docs/zh-CN/developer-guide.md) · [测试说明](docs/zh-CN/testing.md) · [仓库说明](docs/REPOSITORY_GUIDE.md) |
|
||||
|
||||
## 进阶剧本示例
|
||||
完整目录请浏览[中文文档索引](docs/zh-CN/README.md)或[中英双语索引](docs/README.md)。
|
||||
|
||||
```
|
||||
加载侦察剧本:先 amass/subfinder,再对存活主机进行目录爆破。
|
||||
挂载基于 Burp 的外部 MCP,完成认证流量回放并回传到攻击链。
|
||||
将 5MB nuclei 报告压缩并生成摘要,附加到对话记录。
|
||||
构建最新一次测试的攻击链,只导出风险 >= 高的节点列表。
|
||||
```
|
||||
<a id="contributing"></a>
|
||||
|
||||
## 404星链计划
|
||||
<img src="./images/404StarLinkLogo.png" width="30%">
|
||||
## 反馈与贡献
|
||||
|
||||
CyberStrikeAI 现已加入 [404星链计划](https://github.com/knownsec/404StarLink)
|
||||
本仓库作为独立开源分支持续演进,欢迎在 [Issues](https://github.com/Sycun/CyberStrikeAI/issues) 提交问题反馈与功能建议,也欢迎围绕工具配方适配、交互体验优化与回归测试提交 Pull Request。反馈问题时请附上 Commit 版本、操作系统、模型协议类型、复现步骤与脱敏日志,切勿上传真实 API Key、登录凭据或敏感目标数据。
|
||||
|
||||
## TCH Top-Ranked Intelligent Pentest Project
|
||||
<div align="left">
|
||||
<a href="https://zc.tencent.com/competition/competitionHackathon?code=cha004" target="_blank">
|
||||
<img src="./images/tch.png" alt="TCH Top-Ranked Intelligent Pentest Project" width="30%">
|
||||
</a>
|
||||
</div>
|
||||
感谢早期开源阶段 [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) 的原作者与历任贡献者,以及 Pi、MCP 等开源社区项目。
|
||||
|
||||
## 许可证与使用声明
|
||||
|
||||
---
|
||||
|
||||
## 社区与支持
|
||||
|
||||
- 在 [Discord](https://discord.gg/8PjVCMu8Zw) 加入社区。
|
||||
|
||||
<details>
|
||||
<summary><strong>企业微信群</strong></summary>
|
||||
|
||||
<img src="./images/wecom-group-cyberstrikeai-qr.png" alt="CyberStrikeAI 企业微信群二维码" width="280">
|
||||
|
||||
</details>
|
||||
|
||||
## 许可证
|
||||
|
||||
CyberStrikeAI 采用 **Apache License 2.0** 开源许可。
|
||||
完整条款见仓库根目录 [LICENSE](LICENSE) 文件。
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 免责声明
|
||||
|
||||
**本工具仅供教育和授权测试使用!**
|
||||
|
||||
CyberStrikeAI 是一个专业的安全测试平台,旨在帮助安全研究人员、渗透测试人员和IT专业人员在**获得明确授权**的情况下进行安全评估和漏洞研究。
|
||||
|
||||
**使用本工具即表示您同意:**
|
||||
- 仅在您拥有明确书面授权的系统上使用此工具
|
||||
- 遵守所有适用的法律法规和道德准则
|
||||
- 对任何未经授权的使用或滥用行为承担全部责任
|
||||
- 不会将本工具用于任何非法或恶意目的
|
||||
|
||||
**开发者不对任何滥用行为负责!** 请确保您的使用符合当地法律法规,并获得目标系统所有者的明确授权。
|
||||
|
||||
安全问题报告与部署加固建议见 [SECURITY.md](SECURITY.md)。
|
||||
|
||||
---
|
||||
|
||||
欢迎提交 Issue/PR 贡献新的工具模版或优化建议!
|
||||
本项目遵循 [Apache License 2.0](LICENSE) 开源许可证,完整保留原始提交历史与版权声明;第三方组件遵循其各自许可证与声明。本项目仅限用于自有系统或已获得明确书面授权的安全测试与研究,使用者须严格遵守授权范围及所在地法律法规。安全漏洞报告方式请参阅 [SECURITY.md](SECURITY.md)。
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ description: plan_execute 模式下的规划/重规划侧主代理:拆解目
|
|||
|
||||
## Pi 执行协议
|
||||
|
||||
使用可用的 write_todos 或 TaskCreate/TaskUpdate 维护计划。每一步通过 task 调用 `subagent_type=executor`,在 description 中写清目标、范围、动作和成功标准。根据执行器返回的真实证据再决定继续、调整或结束。不要只输出计划 JSON 就把任务标为完成;最终交付通过 exit 提交,仍需经过宿主验收。
|
||||
使用可用的 write_todos 或 TaskCreate/TaskUpdate 维护计划。每一步通过 task 调用 `subagent_type=executor`,在 description 中写清目标、范围、动作和成功标准。根据执行器返回的真实证据再决定继续、调整或结束。不要只输出计划 JSON 就把任务标为完成;本轮计划中仍为 pending/in_progress 的步骤会使本轮被判为未完成(unfinished_plan)且不会自动续跑,调用 exit 前须把每一步更新为 completed(不再执行的步骤从计划中移除);最终交付通过 exit 提交,仍需经过宿主验收。
|
||||
|
||||
## 计划与执行器上下文(强制)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
# Fresh installations follow this independent repository. Existing deployments
|
||||
# retain their own update.repo; adopting this version does not modify a running service.
|
||||
update:
|
||||
repo: https://github.com/Sycun/CyberStrikeAI
|
||||
|
||||
# ============================================
|
||||
# CyberStrikeAI 配置文件
|
||||
# ============================================
|
||||
|
|
@ -11,7 +16,7 @@
|
|||
|
||||
# 前端显示的版本号(可选,不填则显示默认版本)。一键更新完成后,会用新代码里这个文件的值
|
||||
# 同步更新你的 config.yaml 的 version 字段(页头版本号与静态资源缓存随代码走)。
|
||||
version: "v1.8.0"
|
||||
version: "v1.8.2"
|
||||
# 服务器配置
|
||||
server:
|
||||
host: 0.0.0.0 # 监听地址,0.0.0.0 表示监听所有网络接口
|
||||
|
|
@ -30,6 +35,36 @@ server:
|
|||
# tls_key_path: /path/to/privkey.pem
|
||||
# 方式 B(仅本地/测试):在配置目录的 data/tls/self-signed.pem 保存并复用自签证书和私钥(SAN 含 localhost / 127.0.0.1)。
|
||||
tls_auto_self_sign: true
|
||||
# 插件平台。默认每个 WebUI 使用独立端口并复用主站 TLS 策略。
|
||||
# 默认端口模式每个已安装插件占用一个代理端口,并复用主站的 TLS 配置。
|
||||
# VPS、防火墙或容器端口映射可预先放行这个闭区间。插件后端端口保持在私网。
|
||||
# plugins:
|
||||
# directory: data/plugins # 相对配置文件目录
|
||||
# egress:
|
||||
# proxy_mode: system # system / direct / fixed
|
||||
# # proxy_url: http://proxy.example.com:3128
|
||||
# # github_token_env: CSAI_PLUGINS_GITHUB_TOKEN
|
||||
# approval_policy: admin_confirm # 默认:全局插件管理员确认锁定计划,批准记录保存在 SQLite
|
||||
# # 改为 host_config_only 时,由下方声明摘要与制品摘要列表授权执行。
|
||||
# # approved_artifacts:
|
||||
# # "<manifest SHA-256>": ["<artifact SHA-256>"]
|
||||
# proxy:
|
||||
# mode: port
|
||||
# port_pool:
|
||||
# start: 43100
|
||||
# end: 43131
|
||||
# # host_suffix: plugins.localhost # mode: host 使用
|
||||
# # bind_host: 127.0.0.1 # 端口模式,缺省继承主站监听 IP
|
||||
# # public_origin: https://csai.example.com
|
||||
# # external_ports: {43100: 44310}
|
||||
# llm_gateway:
|
||||
# listen_host: 127.0.0.1 # 也可绑定明确的私有 bridge IP
|
||||
# listen_port: 0 # 0 表示分配可用端口
|
||||
# # container_host: host.docker.internal
|
||||
# concurrency: 4
|
||||
# rpm: 30
|
||||
# token_budget: 200000 # 每实例每日 UTC 计费额度
|
||||
|
||||
# 认证配置
|
||||
auth:
|
||||
session_duration_hours: 12 # 登录有效期(小时),超时后需重新登录
|
||||
|
|
@ -106,6 +141,7 @@ ai:
|
|||
base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
|
||||
api_key: sk-xxxxxxx
|
||||
model: qwen3-max
|
||||
# 图片输入默认按模型能力自动判断。自定义网关可在「测试图片」通过后启用,或设置 image_input: enabled。
|
||||
max_total_tokens: 120000
|
||||
max_completion_tokens: 32768
|
||||
# headers: 可选。追加或覆盖发给模型网关的 HTTP 请求头,值支持 ${ENV_VAR} 与 ${ENV_VAR:-默认值}。
|
||||
|
|
@ -139,7 +175,7 @@ ai:
|
|||
# model: qwen-plus
|
||||
# max_total_tokens: 120000
|
||||
# max_completion_tokens: 32768
|
||||
# 视觉分析(analyze_image MCP 工具;图片仅在单次 VL 调用中出现,Agent 上下文只保留文字摘要)
|
||||
# 可选的独立 analyze_image 工具配置。聊天图片可通过支持图片输入的模型通道发送。
|
||||
vision:
|
||||
enabled: false # true 且 model 非空时注册 analyze_image
|
||||
model: qwen-vl # VL 模型名(enabled 时必填)
|
||||
|
|
@ -348,7 +384,7 @@ multi_agent:
|
|||
enabled: true
|
||||
robot_default_agent_mode: single # 企微/钉钉/飞书机器人默认:single | deep | plan_execute | supervisor
|
||||
batch_use_multi_agent: false # true 时「批量任务」队列中每个子任务也走 Pi 多代理(成本更高)
|
||||
# plan_execute 专用:execute↔replan 外层循环上限,0 表示 原生默认 10。主/子代理 ReAct 轮次见 agent.max_iterations。
|
||||
# plan_execute 专用:向 executor 委派的外层步数预算上限;0 表示不单独限制(主/子代理 ReAct 轮次统一由 agent.max_iterations 控制)。
|
||||
plan_execute_loop_max_iterations: 0
|
||||
sub_agent_user_context_max_runes: 0 # 子代理 task 描述中注入用户原文;0=不截断(默认),>0=总字符上限,负数=禁用
|
||||
without_general_sub_agent: false # false 时保留 Deep 内置 general-purpose 子代理
|
||||
|
|
@ -364,11 +400,15 @@ multi_agent:
|
|||
# Pi 原生 中间件与 Deep/Supervisor/plan_execute Executor 调参(结构体见 internal/config/config.go → MultiAgentPiMiddlewareConfig)
|
||||
# plan_execute:下列 patch/reduction/tool_search/plantask 等同样作用于 Executor(经 ExecPreMiddlewares);Planner/Replanner 不挂 MCP 前置中间件。
|
||||
runtime:
|
||||
prompt_cache_prefix_split: false # keep the Pi role prompt separate from per-run context
|
||||
tool_search_enable: true
|
||||
tool_search_min_tools: 20
|
||||
tool_search_always_visible: 12
|
||||
tool_search_always_visible_tools: [get_tool_execution, wait_tool_execution, cancel_tool_execution, search_knowledge_base]
|
||||
tool_search_include_builtins: true # true:后端内置工具始终常驻,绕过 tool_search
|
||||
codemode_enable: false # true:启用 Pi 原生 QuickJS-WASI codemode 沙箱,模型可用一段 JS 批量编排/过滤多步工具调用
|
||||
codemode_mode: on # codemode 工具面板形态:留空/on(默认,常规工具并存)或 only(脚本优先);其他值拒绝加载
|
||||
codemode_inline_budget: 0 # >0 时限制 codemode 描述中内联工具声明的估算 token 预算;0 用 Pi 默认
|
||||
plantask_enable: true
|
||||
plantask_rel_dir: .pi/plantask
|
||||
reduction_enable: true
|
||||
|
|
@ -599,3 +639,15 @@ project:
|
|||
# 把目录变成跟踪该仓库的 git 工作树,此后按正常安装一键更新。
|
||||
# update:
|
||||
# repo: https://github.com/AIPentest/CyberStrikeAI.git # 一个仓库地址;留空/不写 = 官方仓库
|
||||
|
||||
# HTTP 测试工具的受管出口;不影响 Kali 其他工具、外部 MCP 或大模型 API。
|
||||
# 固定 URL 是否固定公网 IP 取决于供应商。运行中的工具使用启动时快照。
|
||||
proxy:
|
||||
mode: manual # manual=沿用工具参数,fixed=固定代理,pool=显式启用代理池
|
||||
proxy_url: "" # fixed 模式必填,支持 http(s)/socks5://host:port
|
||||
proxy_pool: "" # pool 模式:每行一个代理 URL;与供应商至少配置一项
|
||||
proxy_source: "" # 可选供应商 HTTP(S) 地址
|
||||
strategy: sticky # sticky 或 round_robin
|
||||
max_attempts: 3
|
||||
cooldown: 60
|
||||
min_switch_interval: 60 # 间隔内即使失败也不提前切换;0 表示不限制
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ CyberStrikeAI documentation is organized by user journey. Start with deployment,
|
|||
- [资产管理](zh-CN/asset-management.md)
|
||||
- [项目任务续接](zh-CN/project-resume.md)
|
||||
- [Token 用量分析](zh-CN/token-usage-monitoring.md)
|
||||
- [HTTP 测试工具代理池](zh-CN/http-proxy-pool.md)
|
||||
- [知识库](zh-CN/knowledge-base.md)
|
||||
- [RBAC 权限管理](zh-CN/rbac.md)
|
||||
- [机器人接入](zh-CN/robot.md)
|
||||
|
|
@ -76,6 +77,7 @@ CyberStrikeAI documentation is organized by user journey. Start with deployment,
|
|||
- [Asset Management](en-US/asset-management.md)
|
||||
- [Resuming Project Tasks](en-US/project-resume.md)
|
||||
- [Token Usage Analysis](en-US/token-usage-monitoring.md)
|
||||
- [HTTP Test Tool Proxy Pool](en-US/http-proxy-pool.md)
|
||||
- [Knowledge Base](en-US/knowledge-base.md)
|
||||
- [RBAC Administration](en-US/rbac.md)
|
||||
- [Robot / Chatbot](en-US/robot.md)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,43 @@
|
|||
# 仓库与分支说明 / Repository and branch guide
|
||||
|
||||
2026-11-11:个人仓库已由 `CyberStrikeAI-personal` 改名为 `CyberStrikeAI`。2026-11-25 起本项目仅在个人独立仓库维护发布,不再向官方上游提交 PR。
|
||||
|
||||
## 仓库职责
|
||||
|
||||
| 仓库 | 职责 |
|
||||
| --- | --- |
|
||||
| [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI) | 个人维护主线。日常修复、优化和文档均在这里保存、使用与验证。 |
|
||||
| [Sycun/csai-decouple-refactor](https://github.com/Sycun/csai-decouple-refactor) | 独立架构实验线,探索分层解耦与插件化;完成度以该仓库代码和验证记录为准。 |
|
||||
| [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) | 官方上游。个人维护线与重构线均保留原始历史、许可证与版权说明。 |
|
||||
|
||||
个人主线与架构实验线分别演进,不把全部分支自动合入一个版本。
|
||||
|
||||
## 分支状态(2026-11-03 整理时核对)
|
||||
|
||||
| 分支 | 当前定位 | 上游状态与后续处理 |
|
||||
| --- | --- | --- |
|
||||
| `main` | 个人维护默认分支 | 初始快照来自 `codex/deep-assessment`,后续日常改动以本分支为基线。 |
|
||||
| `codex/deep-assessment` | 深度测评功能与官方 PR 来源 | [上游 PR #383](https://github.com/AIPentest/CyberStrikeAI/pull/383) 已于 2026-11-13 关闭;个人版已移除该模块,来源分支仅保留历史。 |
|
||||
| `codex/issue-365-word-reports` | 单条漏洞 Markdown / Word 下载的历史分支 | [上游 PR #378](https://github.com/AIPentest/CyberStrikeAI/pull/378) 已合并,分支尖端已包含在个人主线历史中;保留存档。 |
|
||||
| `codex/issue-357-proxy-pool` | 代理池功能开发分支 | 已整合进个人主线;[上游 PR #381](https://github.com/AIPentest/CyberStrikeAI/pull/381) 待合并,整理时存在合并冲突。个人版已完成兼容整合;官方 PR 的冲突另行处理。 |
|
||||
| `feat/local-model-context-profile` | 本地模型上下文优化分支 | 已整合进个人主线;[上游 PR #367](https://github.com/AIPentest/CyberStrikeAI/pull/367) 待合并,整理时存在合并冲突。个人版已完成兼容整合;官方 PR 的冲突另行处理。 |
|
||||
| `archive/local-main-20261103` | 调整个人维护流程前的本地 `main` | 历史存档,不作为日常开发或部署来源。 |
|
||||
|
||||
上表是带日期的状态快照,PR 后续状态以对应 GitHub 页面为准。保留分支与标签用于追溯,不据此宣称功能已集成或验收通过。
|
||||
|
||||
## 本次个人版整合(2026-11-03)
|
||||
|
||||
代理池与本地模型上下文分支已合入个人版 `main`,并保留各自提交历史。当时合并保留自定义请求头、深度测评与 Word 下载功能(深度测评已于 2026-11-13 移除);上下文探测复用渠道鉴权头,禁止跟随重定向。此记录表示代码整合,真实模型与真实目标的运行验收仍单独记录。
|
||||
|
||||
## 验证与安装
|
||||
|
||||
- 任务管理已恢复 v1.8.0 的批量队列逻辑;入口、兼容性与验证边界见 [任务管理](zh-CN/task-management.md)。
|
||||
- 现有自动化与夹具验证不代表完成真实模型、真实目标的长时验收,也不构成漏洞发现率或成本优势的证明。
|
||||
- 安装个人维护版时使用本仓库 README 的克隆地址。官方仓库与个人仓库的更新来源应明确选择;采用个人仓库默认分支更新时,应先评估对应提交与运行数据迁移。
|
||||
- 仓库整理与默认分支调整不等于部署。已有安装的更新配置和运行状态由各自环境管理。
|
||||
|
||||
## Development workflow (English)
|
||||
|
||||
`CyberStrikeAI/main` is the personal maintenance baseline. `csai-decouple-refactor` is a separate architecture experiment. This repository is maintained independently and no longer submits PRs to upstream.
|
||||
|
||||
The dated table above distinguishes integrated work, pending branches, and historical snapshots. Proxy-pool and local-model changes are integrated into the personal main line; upstream PR integration is tracked separately. Keep existing PR branches and archival refs. Automated checks and fixtures do not establish real-model or real-target acceptance; installation and deployment sources must be selected explicitly.
|
||||
|
|
@ -20,6 +20,7 @@
|
|||
## Feature guides
|
||||
|
||||
- [Resuming Project Tasks](project-resume.md) · [Token Usage Analysis](token-usage-monitoring.md)
|
||||
- [HTTP Test Tool Proxy Pool](http-proxy-pool.md)
|
||||
- [Asset Management](asset-management.md) · [Knowledge Base](knowledge-base.md) · [Robot / Chatbot](robot.md) · [Vision](VISION.md)
|
||||
- [WebShell](webshell.md) · [C2](c2.md) · [MCP Federation](mcp-federation.md)
|
||||
|
||||
|
|
@ -35,3 +36,5 @@
|
|||
- [Testing](testing.md) · [Contributing](contributing-guide.md) · [Release Process](release-process.md)
|
||||
|
||||
- [Pi runtime and migration](pi-runtime.md)
|
||||
|
||||
- [Batch task management (Chinese)](../zh-CN/task-management.md)
|
||||
|
|
|
|||
|
|
@ -4,4 +4,6 @@ Pi `agent_settled` ends automatic model work for the current run. Go still decid
|
|||
|
||||
`internal/agentfinalizer` keeps runtime failure, cancellation and iteration-limit outcomes separate from candidate assistant text. Pending tool executions, empty responses and missing required execution evidence prevent completion. Specialist output must be checked against execution receipts; `exit.final_result` does not bypass finalization.
|
||||
|
||||
Implementation: `internal/agentfinalizer/decision.go` and `internal/multiagent/pi_runner.go`. See [Pi SDK lifecycle](https://github.com/earendil-works/pi/blob/v1.5.2/packages/coding-agent/docs/sdk.md).
|
||||
A completed model run is distinct from a completed long-running objective.
|
||||
|
||||
Implementation: `internal/agentfinalizer/decision.go` and `internal/multiagent/pi_runner.go`.
|
||||
|
|
|
|||
|
|
@ -91,9 +91,10 @@ instead of forcing. See [the developer guide](developer-guide.md) for the full s
|
|||
|
||||
On macOS and Linux, when started from the `cyberstrike-ai` binary alongside its config, the console
|
||||
defaults to switching to the new binary after a successful build. The old service remains available
|
||||
during the build. Connections briefly drop at the switch and the page reloads when the new service
|
||||
answers. Sign in again afterward because sessions live in memory. A supervisor is still useful for
|
||||
starting at boot and recovering from crashes. If you defer the switch or replace the binary from the
|
||||
during the build. Connections briefly drop at the switch. When the new service answers, the page
|
||||
reloads and reuses the current login session if it is still valid. Under **One-click update**, the
|
||||
**Running build** field shows the commit of the binary serving requests. A supervisor is still useful
|
||||
for starting at boot and recovering from crashes. If you defer the switch or replace the binary from the
|
||||
CLI, the console offers **Restart now** on installations that support the switch.
|
||||
|
||||
The update source is a single repository address in the `update` section of `config.yaml` (`repo`),
|
||||
|
|
|
|||
|
|
@ -2,53 +2,38 @@
|
|||
|
||||
[中文](../zh-CN/frontend-i18n.md)
|
||||
|
||||
CyberStrikeAI frontend i18n is static and lightweight. Text is organized in JSON files and applied through `data-i18n` attributes plus JavaScript helper functions.
|
||||
The web UI is a React + Semi Design single-page app. Translations come from
|
||||
`web/frontend/src/lib/i18n.jsx`, backed by the same JSON files the backend ships.
|
||||
|
||||
## Files
|
||||
|
||||
```text
|
||||
web/static/i18n/zh-CN.json
|
||||
web/static/i18n/en-US.json
|
||||
web/static/js/i18n.js
|
||||
web/static/i18n/ru-RU.json
|
||||
web/static/i18n/ar-SA.json
|
||||
web/frontend/src/lib/i18n.jsx
|
||||
```
|
||||
|
||||
## Key Principles
|
||||
## Runtime behavior
|
||||
|
||||
- Keep keys stable and semantic.
|
||||
- Update Chinese and English together.
|
||||
- Do not hardcode new visible text in JS when it should be localized.
|
||||
- Preserve default HTML text as fallback before JS initialization.
|
||||
- Preference is stored in `localStorage['csai_lang']`; otherwise it follows `navigator.language`, defaulting to `zh-CN`.
|
||||
- The provider loads the active language plus `zh-CN` and `en-US` fallbacks; lookups fall back `active → zh-CN → en-US → caller default`.
|
||||
- Switching language updates `<html lang>`, sets `dir="rtl"` for Arabic, and swaps Semi's `ConfigProvider` locale.
|
||||
- No page reload is required; `useT()` re-renders consumers.
|
||||
|
||||
## HTML Usage
|
||||
## Usage
|
||||
|
||||
```html
|
||||
<button data-i18n="common.save">保存</button>
|
||||
```jsx
|
||||
const t = useT();
|
||||
t('vulnerability.title');
|
||||
t('common.minutesAgo', { n: 5 }); // {{n}} interpolation
|
||||
t('chat.unknownKey', null, '中文兜底'); // explicit Chinese fallback
|
||||
```
|
||||
|
||||
For attributes, follow the existing `i18n.js` conventions.
|
||||
Rules:
|
||||
|
||||
## JavaScript Usage
|
||||
|
||||
Use the global translation helper where available:
|
||||
|
||||
```javascript
|
||||
const label = t('common.save');
|
||||
```
|
||||
|
||||
When adding dynamic UI, make sure language switching refreshes the text or re-renders the component.
|
||||
|
||||
## Migration Workflow
|
||||
|
||||
1. Add or update UI text.
|
||||
2. Add keys to `zh-CN.json`.
|
||||
3. Add matching keys to `en-US.json`.
|
||||
4. Replace hardcoded text with `data-i18n` or `t()`.
|
||||
5. Test both languages and browser console.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- Missing keys only in one language.
|
||||
- Dynamic text built from hardcoded fragments.
|
||||
- Button labels too long in English.
|
||||
- HTML fallback text diverges from JSON text.
|
||||
- Adding new page text without updating language switch behavior.
|
||||
1. Every visible string goes through `t(...)` with a Chinese fallback as the third argument.
|
||||
2. Add new keys to `zh-CN.json` and `en-US.json` together; `ru-RU`/`ar-SA` may lag and rely on the fallback chain.
|
||||
3. Format dates with `formatDateTime`/`relativeTime` from `src/lib/format.js`.
|
||||
4. Keep keys two levels deep (`<domain>.<key>`) and stable across releases.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,99 @@
|
|||
# HTTP test tool proxy pool
|
||||
|
||||
[中文](../zh-CN/http-proxy-pool.md) | [Documentation home](README.md)
|
||||
|
||||
`http-framework-test` accepts a user-supplied proxy list and/or provider endpoint. It switches proxies within a bounded attempt budget on transport failures or configured HTTP status codes, and reuses a successful proxy. Settings → Proxy settings can manage egress for this HTTP tool; the default remains per-call arguments.
|
||||
|
||||
## Usage
|
||||
|
||||
After updating the tool file, apply configuration in settings or restart the service to reload its parameters. The proxy submenu also supports persistent settings that apply to subsequent invocations without restarting active processes.
|
||||
|
||||
Example MCP tool arguments:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"method": "GET",
|
||||
"proxy_pool": "[\"http://127.0.0.1:8081\",\"http://127.0.0.1:8082\"]",
|
||||
"proxy_max_attempts": 3,
|
||||
"proxy_cooldown": "60",
|
||||
"proxy_fail_status": "403,429",
|
||||
"response_max_bytes": 8192
|
||||
}
|
||||
```
|
||||
|
||||
`proxy_pool` also accepts newline-separated endpoints. Supported forms are `http://host:port`, `https://host:port`, `socks5://host:port`, and bare `host:port` (HTTP). An explicit port is required. IPv6 brackets and URL-encoded `user:password@host:port` credentials are supported. SOCKS support is included in the `httpx[http2,socks]` requirement.
|
||||
|
||||
To fetch proxies automatically, add or use `proxy_source` alone:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"proxy_source": "https://your-proxy-provider.example/api/proxies"
|
||||
}
|
||||
```
|
||||
|
||||
The endpoint must return UTF-8 newline-separated endpoints, a JSON array of endpoint strings, or an object containing a `proxies` or `data` array:
|
||||
|
||||
```json
|
||||
{"proxies": ["http://127.0.0.1:8081", "127.0.0.1:8082"]}
|
||||
```
|
||||
|
||||
Entries may also be objects such as `{"host":"127.0.0.1","port":8081,"scheme":"http","username":"user","password":"pass"}` (`ip` aliases `host`) or `{"url":"http://127.0.0.1:8081"}`. Scheme defaults to HTTP, credentials are optional and automatically URL-encoded. Other provider formats require an adapter. No public free-proxy sources are built in. The source is fetched at startup and at most once more per request/redirect hop when available candidates run out. New endpoints are deduplicated and merged without clearing cooldowns. Fetches have 10-second connect/read timeouts, do not follow redirects, accept at most 1 MiB, and the pool holds at most 256 endpoints. An initial fetch failure warns and uses static endpoints when available; source-only calls fail. A refresh failure preserves the last HTTP failure response, or reports an error if no response exists.
|
||||
|
||||
## Behavior
|
||||
|
||||
| Parameter | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `proxy_pool` | Empty | JSON string array or newline-separated list |
|
||||
| `proxy_strategy` | `"sticky"` | `sticky` reuses successful proxies; `round_robin` rotates and skips cooldowns |
|
||||
| `proxy_source` | Empty | User-configured HTTP(S) provider endpoint, optionally combined with a list |
|
||||
| `proxy_max_attempts` | `3` | 1–10 distinct proxy attempts per request/redirect hop |
|
||||
| `proxy_cooldown` | `"60"` | 0–86400 seconds before a failed proxy is eligible again |
|
||||
| `proxy_fail_status` | `"403,429"` | Comma-separated status codes from 400–599; `"none"` disables status-based switching |
|
||||
|
||||
- Successful proxies stay selected by default. With `proxy_strategy="round_robin"`, each request/redirect hop rotates through eligible proxies. Failed proxies enter cooldown. Each proxy is tried at most once per request/redirect hop.
|
||||
- Only GET, HEAD and OPTIONS are replayed automatically. POST, PUT, DELETE and other methods retain the first result. An explicit `repeat` still requests additional executions.
|
||||
- Transport failures before response headers can trigger switching. Failures while reading a response body are reported without replaying a partial response.
|
||||
- A 429 with a valid future `Retry-After` stops automatic replay and reports that the caller should retry later. Further requests to that origin within the same tool invocation are blocked until the wait expires; waits are recorded for at most 24 hours.
|
||||
- If the final attempt returns an HTTP failure response, it is preserved with a nonzero exit code. A network failure or a pool with all endpoints cooling down reports an error. There is no direct fallback or extra direct DNS/TCP/TLS target probe.
|
||||
- Pool diagnostics show attempt numbers, proxy numbers and failure types. They omit proxy credentials and provider URLs. The platform's existing argument traces, audit records and logs still apply; treat arguments containing credentials as sensitive configuration.
|
||||
|
||||
## Scope and design
|
||||
|
||||
[#357](https://github.com/AIPentest/CyberStrikeAI/issues/357) requests automatic proxy acquisition and switching after a ban, without specifying providers, detection or tool scope. This implementation starts with `http-framework-test`, where both HTTP and decrypted HTTPS responses can be inspected. A standalone forwarding proxy cannot read HTTPS responses inside a CONNECT tunnel. See the [HTTPX proxy](https://www.python-httpx.org/advanced/proxies/) and [transport](https://www.python-httpx.org/advanced/transports/) documentation.
|
||||
|
||||
A 403 can be an application authorization failure; a 429 can apply to an account or other scope. Status matching is a configurable policy, not proof of an IP ban. CAPTCHA or HTTP 200 block pages remain unchanged. Replay and waiting rules are informed by [RFC 9110 §9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) and [RFC 6585 §4](https://www.rfc-editor.org/rfc/rfc6585.html#section-4).
|
||||
|
||||
Pool state lasts for one tool invocation. Other scanners, `exec`, Pi `execute`, external MCP servers and LLM API connections are outside this pool; the settings submenu manages only this HTTP tool. Provider fetching uses a separate client with TLS verification and no target cookies, target Authorization, environment proxies or inherited `allow_insecure`. Use HTTPS for production provider endpoints.
|
||||
|
||||
## Troubleshooting and source
|
||||
|
||||
| Message | Action |
|
||||
| --- | --- |
|
||||
| `Proxy pool exhausted` | Check endpoint connectivity, wait for cooldown, or replace the list/provider results |
|
||||
| `failure policy still matched` | Inspect the preserved response and distinguish IP restrictions from normal authorization/rate limits; adjust `proxy_fail_status` if needed |
|
||||
| `Retry-After is still active` | Wait for the target's requested delay before another call |
|
||||
| `Could not fetch proxy source` | Check provider connectivity, authentication and TLS; target `allow_insecure` does not affect provider connections |
|
||||
| `SOCKS support requires ...` | Install `httpx[socks]` in the tool's Python environment or update its requirements |
|
||||
|
||||
The implementation and MCP parameter definitions are in [tools/http-framework-test.yaml](../../tools/http-framework-test.yaml); regression scenarios are in [scripts/test_http_proxy_pool.py](../../scripts/test_http_proxy_pool.py).
|
||||
|
||||
## Local verification
|
||||
|
||||
```sh
|
||||
python3 -m pip install 'httpx[http2,socks]>=0.27.0' PyYAML
|
||||
python3 -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
|
||||
```
|
||||
|
||||
Tests execute the code read from the tool YAML against local HTTP proxies, CONNECT tunnels and TLS servers. No external targets or real providers are contacted. The HTTPS fixture requires `openssl`.
|
||||
|
||||
## Managed settings and stable egress
|
||||
|
||||
Settings → Proxy settings offers manual arguments, a fixed proxy, or a pool. Fixed mode keeps the configured endpoint across calls and does not fail over. Pool mode offers sticky or round-robin selection with a minimum switch interval (60 seconds in the settings form). The interval also prevents early failover: return the failure response/error instead. Timing is invocation-local; use fixed mode and a provider with fixed egress for stability across calls. A fixed URL alone cannot guarantee the provider's public IP.
|
||||
|
||||
`PUT /api/config` persists the `proxy` object and applies it to future HTTP tool invocations. GET masks `proxy_url`, `proxy_pool`, and `proxy_source`; preserve `********` to keep a saved value or send an empty string to clear it. The settings list accepts one URL per line; provider responses may still use structured entries. See `config.example.yaml`. Managed values override model-supplied proxy arguments through a process-local environment snapshot, never global HTTP_PROXY or command arguments. This is not a network sandbox for arbitrary shell commands.
|
||||
|
||||
Design references: [Zyte sessions](https://docs.zyte.com/zyte-api/usage/features.html#sessions) motivate stable IP/cookie conditions; [HTTPX clients](https://www.python-httpx.org/advanced/clients/) motivate connection reuse; [Nuclei](https://docs.projectdiscovery.io/opensource/nuclei/running) exposes distinct proxy/rate controls; [Nmap](https://nmap.org/book/man-bypass-firewalls-ids.html) documents limits on which scan phases support proxies. Other Kali tools retain native routing, proxy and rate settings. No output-based ban guessing or process restarts are introduced.
|
||||
|
||||
LLM API transports, streams and retry/backoff remain separate from the scan pool. Account/token rate limits are handled by existing provider retry policies. Stable public-IP requirements depend on the provider; this feature never rotates model API egress.
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Pi runtime
|
||||
|
||||
CyberStrikeAI uses Pi 1.5.2 as its only runtime. Go owns business state, permissions, MCP execution, evidence, and delivery checks; an isolated Node worker hosts the Pi SDK.
|
||||
CyberStrikeAI uses Pi 1.7.0 as its only runtime. Go owns business state, permissions, MCP execution, evidence, and delivery checks; an isolated Node worker hosts the Pi SDK. The source repository is [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI).
|
||||
|
||||
Prefer public APIs from the pinned Pi SDK. Add host or worker logic where project permissions, business records, or compatibility require it.
|
||||
|
||||
|
|
@ -17,9 +17,11 @@ The launcher and self-update build prepare the worker. The new server also prepa
|
|||
|
||||
After pulling a worker fix into a source installation, run `bash scripts/build-pi-runtime.sh` in that installation before restarting the service. If `agent_runtime.worker_path` is set, make sure it points to the rebuilt worker. Keep existing session files: the worker corrects interrupted OpenAI-compatible tool batches when preparing model requests.
|
||||
|
||||
Chat Completions channels outside the native OpenAI service send instructions with the `system` role. This prevents Pi from switching to an unsupported `developer` role when thinking is enabled, while preserving the configured reasoning options. Primary models, fallback models and background generation share this setting. Native OpenAI channels and the Responses/Anthropic protocols keep the SDK's role handling.
|
||||
|
||||
## Configuration
|
||||
|
||||
`agent_runtime.engine` accepts only `pi` (also the default). The former engine and dependencies have been removed. Optional `node_path`, `worker_path`, and `session_dir` control deployment.
|
||||
`agent_runtime.engine` accepts only `pi` (also the default). The former engine and dependencies have been removed. Optional `node_path`, `worker_path`, and `session_dir` control deployment. The retired `agent_runtime.purge` key is ignored on load and removed when system settings are saved.
|
||||
|
||||
The model worker uses HTTP/1.1 and respects the service's `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` environment variables. Model redirects stay on the original origin to protect credentials.
|
||||
|
||||
|
|
@ -27,8 +29,10 @@ Deleting a conversation turn removes all of its persisted Pi mode/child sessions
|
|||
|
||||
Pi's `SessionManager` opens `session.jsonl` directly for new conversations. Existing conversations keep using the file referenced by their `current-session` pointer, preserving saved evidence paths. If rolled back to an older worker, it rebuilds the context for new-format sessions from the history supplied by the host without loading their Pi compaction records.
|
||||
|
||||
Chat agents, specialists and workflow Agent nodes use Pi. User steering goes through Pi's native queue. Large catalogs can use native tool search. Conversation task boards remain compatible with the existing UI.
|
||||
Chat agents, specialists and workflow Agent nodes use Pi. User steering goes through Pi's native queue.
|
||||
|
||||
Workflow now uses a native DAG and versioned JSON checkpoints. Old Eino Workflow binary checkpoints cannot be resumed by this version; finish those runs before upgrading, or export their material and start new Pi tasks. Knowledge retrieval and indexing use native domain types and HTTP embeddings. Old configuration keys are read as data migration only; saving emits the native skills/runtime keys. Legacy URL aliases call the same Pi handlers and cannot select a different engine.
|
||||
|
||||
See the [Chinese implementation and validation guide](../zh-CN/pi-runtime.md) for protocol, recovery and test details. Local fixtures establish functional behavior, not live-provider reliability, refusal-rate improvements or production acceptance.
|
||||
|
||||
The example configuration follows Sycun/CyberStrikeAI. Existing installations retain their own update source, which must be checked separately; this source migration does not deploy or change a running production configuration.
|
||||
|
|
|
|||
|
|
@ -117,4 +117,4 @@ Plugins should not bypass platform controls:
|
|||
- Capture: `devtools.js`, `background/service-worker.js`
|
||||
- OpenAPI: `internal/handler/openapi.go`
|
||||
- External MCP: `internal/handler/external_mcp.go`
|
||||
- Web auth reference: `web/static/js/auth.js`
|
||||
- Web auth reference: `web/frontend/src/lib/auth.jsx`
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ Expand testing when changing:
|
|||
- `internal/multiagent/`: streaming, tool calls, summarization, retry, HITL;
|
||||
- `internal/security/`: auth, shell, timeout, no-output;
|
||||
- `internal/database/`: old data compatibility;
|
||||
- `web/static/js/chat.js`: chat, process details, attack chain, groups.
|
||||
- `web/frontend/src/pages/chat/`: chat, process details, attack chain, groups.
|
||||
|
||||
## Test Data
|
||||
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@
|
|||
|
||||
Pi reports usage; Go accumulates completed model turns and emits `agent_usage_summary` into the existing database and timeline. Local statistics are not a provider billing statement and may not cover every auxiliary HTTP request.
|
||||
|
||||
Prompt tokens are Pi input + cacheRead + cacheWrite. Completion tokens are output, and total is prompt + completion. Cache details are already included and must not be added again. The usage view shows provider-reported reasoning tokens as a subset of completion tokens. Model-call counts reflect observed turns. Missing reasoning/cache details mean unreported data, not proven zero use. Durable assessments retain their own conservative budget ledger.
|
||||
Prompt tokens are Pi input + cacheRead + cacheWrite. Completion tokens are output, and total is prompt + completion. Cache details are already included and must not be added again. The usage view shows provider-reported reasoning tokens as a subset of completion tokens. Model-call counts reflect observed turns. Missing reasoning/cache details mean unreported data, not proven zero use.
|
||||
|
||||
The dashboard and Settings usage view retain period, model and project filters. APIs are `GET /api/usage/tokens` and `GET /api/conversations/:id/token-usage`. Existing usage rows and historical timeline backfill remain compatible.
|
||||
|
||||
Streaming updates carry deltas; complete messages are committed at message end. Implementation: `internal/multiagent/pi_runner.go` and `internal/database/model_token_usage.go`. See [Pi AI](https://github.com/earendil-works/pi/tree/v1.5.2/packages/ai).
|
||||
Streaming updates carry deltas; complete messages are committed at message end. Implementation: `internal/multiagent/pi_runner.go` and `internal/database/model_token_usage.go`. See [Pi AI](https://github.com/earendil-works/pi/tree/v1.7.0/packages/ai).
|
||||
|
||||
## DeepSeek
|
||||
|
||||
|
|
|
|||
|
|
@ -224,6 +224,10 @@ Expected behavior:
|
|||
|
||||
Each task has a distinct `runId`. Local commands and detached MCP workers retain ownership through context values. Managed `exec ... &` and Pi background execution return promptly but cannot outlive task cleanup. Unowned background launches are rejected. Cleanup seals process and worker admission, cancels workers, terminates processes and waits for reaping. Interrupt-and-continue retains ownership; SSE disconnection does not end the task. Failed cleanup retains the conversation slot and reports `cleanup_failed`; a 15-second sweep retries it.
|
||||
|
||||
Set `CS_CLEANUP_GRACE`, `CS_CLEANUP_KILL`, and `CS_CLEANUP_GUARD` to positive Go durations (for example, `10s`) to tune the graceful exit wait, post-SIGKILL wait, and isolation backend wait. Each defaults to 3 seconds when unset or invalid.
|
||||
|
||||
On Linux, only-zombie process groups count as exited once the direct child has been reaped. With the process group watchdog, if cleanup times out and every surviving member is in uninterruptible sleep (D) with SIGKILL pending, the task reports `cleanup_unconfirmed` after local workers finish. The service log records the run ID and PGID. The kernel delivers the pending signal when the process can exit. The cgroup and Windows Job Object backends still require their own exit verification.
|
||||
|
||||
### Kernel containment and crash recovery
|
||||
|
||||
- **Linux with a delegated cgroup v2 root:** each task gets a cgroup with process, memory and optional CPU limits. Go uses `clone3(CLONE_INTO_CGROUP)` to assign membership at creation. A separate guardian uses `cgroup.kill` on owner pipe EOF and checks `populated=0`. Startup exclusively locks the delegated root and recovers stale task groups. `setsid` does not escape this scope.
|
||||
|
|
|
|||
|
|
@ -580,6 +580,6 @@ On save, the system checks:
|
|||
| Graph validation | `internal/workflow/validation.go` |
|
||||
| Expressions / JSONPath / joins | `internal/workflow/expression.go`, `jsonpath.go`, `join.go` |
|
||||
| Dry-run / replay data | `internal/workflow/dry_run.go`, `internal/handler/workflow_run.go` |
|
||||
| Canvas UI | `web/static/js/workflows.js` |
|
||||
| Canvas UI | `web/frontend/src/pages/workflows/` |
|
||||
| Workflow API | `internal/handler/workflow.go` |
|
||||
| Role binding | `internal/config/config.go` (`workflow_id` field) |
|
||||
|
|
|
|||
|
|
@ -0,0 +1,34 @@
|
|||
# 前端设计系统
|
||||
|
||||
主应用前端已统一迁移到 [Semi Design](https://semi.design/zh-CN/)(React 19 + Vite),
|
||||
不再维护手写 HTML/CSS/JS 的组件体系。
|
||||
|
||||
## 结构
|
||||
|
||||
- 页面:`web/frontend/src/pages/<页面 id>/index.jsx`,路由 `#/<页面 id>`。
|
||||
- 共享组件:`web/frontend/src/components/ui.jsx`(PageHeader、SectionCard、DataTable、StatGrid、ErrorBanner、MarkdownView、JsonViewer、Drawer 等)。
|
||||
- 外壳样式:`web/frontend/src/styles/app.css`,只放布局与共享排版;颜色一律用 Semi 变量。
|
||||
- 构建产物:`web/static/app/`,由 Go 直接提供。
|
||||
|
||||
## 颜色与主题
|
||||
|
||||
品牌主色 `#3266e3`(暗色 `#81a7ff`),通过覆盖 `--semi-color-primary` 等变量接入 Semi 主题,
|
||||
暗色由 `body[theme-mode="dark"]` 驱动,偏好保存在 `localStorage['cyberstrike-theme']`(system/light/dark)。
|
||||
|
||||
## 组件约定
|
||||
|
||||
- 列表页用 `DataTable` + `useResource`,统一 loading / 空态 / 错误态(`ErrorBanner`)。
|
||||
- 指标卡用 `StatGrid`/`StatCard`;详情抽屉用 `Drawer`(封装 Semi `SideSheet`)。
|
||||
- 危险操作用 `confirmAction`;反馈用 `toastSuccess`/`toastError`。
|
||||
- Markdown 统一走 `MarkdownView`(marked + DOMPurify),不要自行插入 HTML。
|
||||
|
||||
## 校验
|
||||
|
||||
```sh
|
||||
npm ci --prefix web/frontend
|
||||
npm run --prefix web/frontend build
|
||||
go test ./internal/app -run TestSPA -count=1
|
||||
```
|
||||
|
||||
`internal/app/spa_test.go` 会检查 `web/static/app/index.html` 引用的哈希资源是否存在,
|
||||
防止构建产物缺失或未提交。页面开发契约见 `web/frontend/CONTRACT.md`。
|
||||
|
|
@ -20,6 +20,7 @@
|
|||
## 功能指南
|
||||
|
||||
- [项目任务续接](project-resume.md) · [Token 用量分析](token-usage-monitoring.md)
|
||||
- [HTTP 测试工具代理池](http-proxy-pool.md)
|
||||
- [资产管理](asset-management.md) · [知识库](knowledge-base.md) · [机器人接入](robot.md) · [视觉分析](VISION.md)
|
||||
- [WebShell](webshell.md) · [C2](c2.md) · [MCP 联邦](mcp-federation.md)
|
||||
|
||||
|
|
@ -35,3 +36,5 @@
|
|||
- [测试指南](testing.md) · [贡献规范](contributing-guide.md) · [发布流程](release-process.md)
|
||||
|
||||
- [Pi 原生运行时与迁移](pi-runtime.md)
|
||||
|
||||
- [批量任务管理](task-management.md) · [深度测评与长程恢复](deep-assessments.md)
|
||||
|
|
|
|||
|
|
@ -14,4 +14,4 @@ Pi 的 `agent_settled` 表示本次模型运行不再自动继续。业务任务
|
|||
|
||||
过程事件、思考、工具输出与最终交付分开记录。退出工具的 final_result 仍经过宿主验收,不能绕过这些规则。
|
||||
|
||||
实现:`internal/agentfinalizer/decision.go`、`internal/multiagent/pi_runner.go`。SDK 生命周期见 [Pi SDK](https://github.com/earendil-works/pi/blob/v1.5.2/packages/coding-agent/docs/sdk.md)。
|
||||
实现:`internal/agentfinalizer/decision.go`、`internal/multiagent/pi_runner.go`。
|
||||
|
|
|
|||
|
|
@ -24,10 +24,10 @@ flowchart LR
|
|||
|
||||
入口在 `cmd/server/`,应用组装在 `internal/app/`。Web 使用 Gin:
|
||||
|
||||
- `web/templates/index.html`:主页面。
|
||||
- `web/templates/api-docs.html`:API 文档页面。
|
||||
- `web/static/js/`:各业务模块前端逻辑。
|
||||
- `web/static/css/`:样式。
|
||||
- `web/frontend/`:前端源码(React 19 + Semi Design,Vite 构建),页面位于 `src/pages/<页面 id>/`。
|
||||
- `web/static/app/`:前端构建产物,`GET /` 直接返回其中的 `index.html`,`/api-docs` 跳转到 `/#/api-docs`。
|
||||
- `web/static/i18n/`:多语言词条,前端与后端共用。
|
||||
- `web/static/`:Logo、favicon 与多语言等公共静态资源。
|
||||
|
||||
路由注册集中在 `internal/app/app.go`。
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,216 @@
|
|||
# 深度测评:持续探索与图记忆
|
||||
|
||||
独立于「任务管理」的目标工作台,使用 Pi 执行规划、步骤和验收。侧边栏入口位于「对话」下一行;主页面只展示任务列表及行尾操作;点击任务名称或「详情」进入占满主内容区的任务工作区。新建表单使用右侧抽屉。返回列表、切换页面不会停止后台任务。
|
||||
|
||||
## 列表操作与归档
|
||||
|
||||
任务行末尾提供「开始 / 继续」「暂停」「详情」「归档」;操作是否可用取决于任务状态及账号权限。开始、暂停在列表内更新状态,不自动打开详情;只有点击详情才进入任务工作区。控制请求使用服务端当前版本,重复点击不会并发提交同一任务的操作。
|
||||
|
||||
工作区提供返回列表入口,保留列表筛选、分页和已有深链。攻击面图和探索图使用更大的画布,节点详情可收起;自动刷新、切换视图和画布尺寸变化会保留缩放与位置。「适应画布」查看全图,「整理布局」重新排列节点。长中文标签自动换行,完整内容在节点详情中查看。
|
||||
|
||||
点击详情默认进入运行概览。概览展示规划/独立验收阶段、当前意图、工具运行及已有输出、Pi 原生模型/工具/压缩状态、队列计数、最近进展和下次唤醒。数据来自现有执行回执、Pi 事件及任务账本;刷新不会额外调用模型或启动任务。无变化时不重建正文,定向补充的草稿、焦点和阅读位置保留。
|
||||
|
||||
概览统计可直接查看明细:累计 Token 进入上下文与用量,状态、规划轮次进入运行记录;意图总数和状态计数进入对应队列。「待核对」同时包含结果不明和资源停止待确认的意图。事实、关联漏洞统计进入全部记录的第一页,清除之前的筛选和来源定位;当前意图提供来源回执、执行会话及可访问资产的入口。这些跳转只读取记录,不触发测评执行。
|
||||
|
||||
整条测评受阻与单条意图受阻分别展示。规划器、独立验收或运行环境失败时,测评可能受阻但受阻意图数为 0;页面直接展示最近的任务级受阻事件及时间,并提供运行记录入口。该原因不会被后续执行收尾记录挤掉,旧数据没有受阻事件时沿用已保存摘要。
|
||||
|
||||
节点详情默认使用较宽的阅读栏,可拖动图与详情之间的分隔线调整宽度;键盘聚焦分隔线后,左右方向键调整,Home 或双击恢复默认宽度。「展开阅读」将当前节点铺满工作区,点击「返回图」恢复分栏。摘要、执行说明、原始回执和来源分别展示;正文独立滚动,自动刷新保留阅读位置和已展开的来源,切换节点从顶部开始。窄屏改为上下布局,也可展开阅读。
|
||||
|
||||
较大图显示缩略导航,可点击定位,也可聚焦后用方向键平移。节点类型和状态、关系颜色帮助区分链路;选中节点显示其相连关系的文字,位于画布外或缩得过小时自动定位到可读尺度。循环引用的回边保留,只在计算层级时避开,避免整组挤成单列。多个目标资产链接在正文中折叠展示,不占据固定底部操作区。全图仍按节点分页,大图概览不能保证每个节点的文字同时清晰,可选中节点或展开关联分支阅读。
|
||||
|
||||
资产范围切换、搜索和图操作集中在工具栏,说明与图例可按需展开。未关联资产或搜索无结果时显示明确提示;共享资产记录可展开查看。节点详情按字段显示资产信息,并保留原始记录和来源跳转。
|
||||
|
||||
「归档」保留目标、意图、图、回执、事实和漏洞关联,默认列表隐藏,可切换「已归档」查看和恢复。执行中、清理中或结果不明的任务必须先暂停并完成核对,不能直接归档。恢复归档只回到列表,待执行任务需要手动开始;归档记录不会被重启恢复或新事实唤醒。
|
||||
|
||||
## 持续执行
|
||||
|
||||
新建填写名称和目标即可。「补充限制与排除项」「验收条件」均为选填,留空或仅有空白字符时沿用目标;填写的补充内容会独立保留。表单提供简短说明与填写示例。模型、角色、项目、并行步骤和重启恢复也可选配。保存为草稿,点击「开始 / 继续」才执行。
|
||||
|
||||
关联项目后,资产范围就是资产库里该项目的可读资产。对话、批量任务和深度测评使用同一批记录,新建时不再要求选择资产集合。目标或项目授权范围里写明的地址也会写入资产库。补充限制和项目排除名单中的地址不会自动加入。任务中发现的同范围服务和端点写回资产库,并出现在攻击面图、项目黑板和后续规划中。信息收集可以另存一份命名检索结果,只在需要缩小范围时使用。
|
||||
|
||||
**任务没有时间窗口、累计 Token、规划轮数、总步骤数或累计执行分段次数上限。** Token 和轮次保留为观测统计,不触发任务结束。任务围绕验收条件推进,直到完成、用户暂停/停止,或需要用户补充信息、核对结果不明的操作。
|
||||
|
||||
一个方向停滞时交还规划器换路;暂时没有新方向或验收仍有缺口时保留状态,进入「等待新进展」并定时重评。临时模型故障退避后继续,没有累计重试次数终止条件;认证、权限等需修复的问题会明确显示。等待期间不保持一个空转的模型请求。
|
||||
|
||||
单次工具超时、模型上下文容量、每次规划增量和并行工作数仍按执行环境处理。Pi 在轮边界保存一个执行分段,再恢复同一会话,这些边界不构成整个目标任务的累计上限。
|
||||
|
||||
旧版本的预算字段会在升级时移除,原「预算耗尽」记录转换为暂停,等待用户继续;升级不会擅自启动旧草稿、暂停或停止的任务。旧客户端创建请求里的预算参数不再生效,`control/budget` 返回 410,请刷新页面。
|
||||
|
||||
## 探索图与记忆
|
||||
|
||||
「探索图」记录以下节点及其关系:
|
||||
|
||||
| 节点 | 来源与用途 |
|
||||
| --- | --- |
|
||||
| 目标 | 用户提供的目标、范围、验收条件 |
|
||||
| 探索步骤 | 规划器的具体方向与依赖 |
|
||||
| 观察 | 阶段检查点、步骤结果和验收缺口,保留原文 |
|
||||
| 执行回执 | 实际工具调用结果;失败与结果不明状态分别保留 |
|
||||
| Pi 摘要 | 原生 `compaction_end` 产生的会话摘要,关联原生会话条目 |
|
||||
| 历史归档 | 冷历史的引用索引,可展开原步骤和相关证据 |
|
||||
| 人工线索 | 已保存的用户补充,作为用户输入单独标识 |
|
||||
|
||||
步骤通过 `depends_on` 建立执行依赖,通过 `source_ids` 引用启发本次探索的观察、回执或摘要。源节点必须属于同一测评。状态变化和观察节点在同一 SQLite 事务提交;原始调用回执和对应节点也在同一事务提交。
|
||||
|
||||
借鉴 ARTEX 的冷热分层:活跃方向及其依赖、证据祖先保持可见。已经完成或撤下、连续多轮不参与活跃链路的历史步骤,按引用折叠为归档节点。新方向再次依赖旧步骤或旧证据时,相关链路会重新显示。折叠不删除原步骤、原始观察或工具结果,不改变完成条件。
|
||||
|
||||
归档按真实依赖/证据分支分组,并持久化连续冷却的起始轮次;重新被引用后重新计时。已登记漏洞、目标和人工线索不会因来源步骤归档而隐藏,归档的对外关系标明「经归档」。旧版按 ID 批次建立的归档改标「已替代」,原 ID 和成员仍可展开,不删除历史记录。
|
||||
|
||||
默认「主链路」收起观察和工具回执,关系标明「经执行记录」;切换「执行记录」或展开分支可查看原文。分页保留跨页引用节点,当前页最多展示 80 个引用;更多关联会明确计数,节点详情提供独立分页的完整上下游列表。跨页引用与归档投影都是视图,原始节点和边保持不变;显示与导航均遵守漏洞读取权限。
|
||||
|
||||
会话摘要由 **Pi 原生压缩**生成并沉淀为图中的记忆节点。业务图的冷分支归档保存成员索引及已有结果摘录,不另起一套模型压缩循环。摘要是模型派生的续接材料,证据仍应回查执行回执。
|
||||
|
||||
界面支持平移、缩放、适应画布、节点选择、原文分页及归档展开。大图分页面显示,分页大小仅影响本次展示,不限制总节点数;步骤清单也可分页查看。
|
||||
|
||||
Agent 可调用:
|
||||
|
||||
- `assessment_graph`:查看当前图,传 `scope` 为归档或步骤节点 ID 时展开关联内容。
|
||||
- `assessment_node`:按 ID 和字符偏移读取完整节点原文与来源。
|
||||
- `assessment_memory`:检索步骤、图记忆和原始执行过程,包含被折叠的历史。
|
||||
- `assessment_trace`:分页读取完整执行过程。
|
||||
- `assessment_checkpoint`:保存当前观察,同时保留 Pi 原生自定义条目。
|
||||
- `assessment_result`:提交 completed、blocked 或 continue;完成需引用本任务真实成功调用的回执。
|
||||
|
||||
## 验收证据矩阵
|
||||
|
||||
创建测评时建议每行填写一条验收条件。原有验收条件按非空行显示;留空并沿用任务目标时,整个目标成为一个验收项。
|
||||
|
||||
在任务工作台的「验收证据」中,审阅人可搜索并关联本次测评的事实或原始回执。关联事实会展示该事实引用的同一意图回执。可点击节点打开原文,也可给验收项加复核标记和说明。协作者并发编辑同一项时,较旧的版本无法覆盖已保存的关联。
|
||||
|
||||
- **已有证据**表示当前选中的证据包含成功原始回执,且没有待核对的关联。
|
||||
- **缺证据**表示尚未关联事实或回执,也未标记待复核。
|
||||
- **待人工复核**涵盖人工标记、推断事实、未成功的回执和已不可用的来源。
|
||||
|
||||
阶段报告按相同规则列出每个验收项、事实及其支持回执,并可跳回对应节点。证据状态用于人工审阅,保存矩阵不触发工具调用或任务调度,也不改变系统的任务完成判定。
|
||||
|
||||
### 双图联动、端点证据与历史对照
|
||||
|
||||
- 从攻击面图选中服务,打开「查看证据路径」可查看本资产关联的意图、事实、原始回执和验收项。探索图的事实节点也能打开同一视图反查资产和验收项。浏览器返回可恢复攻击面图的选择、筛选和画布位置。
|
||||
- 在「验收证据」中打开「查看局部证据图」,可按条件查看关联事实、可读资产及回执。图按事实分页,相关的归档证据可直接定位。人工验收关联、推断及原始回执使用不同的线条。直接回执缺少可见资产锚点时会单独提示。
|
||||
- 服务下的「端点证据」可筛选已有观察证据、待人工复核或缺证据。审阅人可为指定端点关联或解除同测评、同服务的事实。端点只有明确关联且仍有成功原始回执的观察事实,才计入已有观察证据。
|
||||
- 「历次测评」按同一共享资产 ID 显示可读的较早测评、观察时间、证据和待复核验收项。项目和保存的范围文字一致时,页面比较新增观察文本、新增证据端点及本次暂无记录的旧端点。文本改动可能计入新增观察。范围或项目不同的记录保留供人工对照。阶段报告对照最近一条可读的较早测评,并提供端点缺口及历史入口。
|
||||
|
||||
## 漏洞管理关联
|
||||
|
||||
执行过程中通过 `record_vulnerability` 成功登记的漏洞,按实际执行会话自动关联测评 ID、测评名称、步骤 ID 和步骤标题。只写在检查点或摘要中的观察不会自动生成漏洞。工具和权限沿用当前角色配置。
|
||||
|
||||
- **测评 → 漏洞**:在任务工作区的「关联漏洞」中查看本次测评已登记的漏洞,打开漏洞管理详情,或在测评中查看其复现步骤、证据和来源步骤回执。
|
||||
- **漏洞 → 测评**:漏洞详情显示来源测评和步骤,提供「返回测评步骤」「查看步骤与复现证据」入口。链接会定位具体步骤,不受步骤清单当前分页影响。
|
||||
- **按任务分组**:漏洞管理的任务视图以测评名称展示,内部以测评 ID 分组;同名测评及相同 ID 的批量任务不会混组。任务名称搜索同时支持测评名称,原 `task_id` 参数仍保留批量任务语义;测评可用 `assessment_id` 筛选。
|
||||
|
||||
升级会按已有的可信执行会话补建历史关联,不按标题或标签猜测。关联快照随漏洞保存;删除测评或执行会话后,漏洞及其复现内容仍保留,已删除的测评不提供返回入口。
|
||||
|
||||
读取测评和读取漏洞分别检查权限。仅分享测评不会自动分享所有漏洞;仅分享漏洞也不会授予来源测评的访问或执行权限。
|
||||
|
||||
## 共享攻击面图、意图队列与事实
|
||||
|
||||
任务工作区包含「攻击面图」「探索图」「意图队列」「事实」「关联漏洞」「证据回执」等视图。原步骤 ID 和漏洞返回链接保持兼容。
|
||||
|
||||
在「攻击面图」的「攻击面线索」中,可手动登记和编辑 AK/SK、账号凭据、API Key / Token 或其他发现。填写脱敏摘要和发现位置,可选填本次测评的事实 ID 来打开证据路径。密钥、密码和令牌原文保留在原证据位置。
|
||||
|
||||
- **攻击面图**从现有资产库投影域名、子域、IP、服务、业务应用和端点。多个测评引用同一资产 ID,不复制一套资产库。共享仍遵守资产权限和测评关联项目;IP 连线表示记录中的关联,不代替 DNS 验证。应用节点来自资产的业务系统字段。关联项目且未指定集合时,项目中的可读资产会自动进入这张图。
|
||||
- 资产库、信息收集、批量任务和深度测评使用同一批资产记录。任务中属于当前范围的新服务和端点会写回资产库,并自动成为后续意图可引用的目标。仍可从资产库手动补充。端点保存在服务资产下,按资产、HTTP 方法、路径去重;查询值和 Token 不写入端点身份。图按资产分页,选中服务后可分页读取全部端点;意图可跳转目标资产,资产节点可反查针对该资产的意图。
|
||||
- **意图**沿用步骤记录,新增 `asset_ids` 和 `priority`(1 优先、默认 100)。`source_ids` 保留派生依据,`depends_on` 控制执行前置条件。队列持久化,按优先级、原有顺序调度;不因并发已满而丢弃待办,也不会抢占正在执行的意图。
|
||||
- worker 第一次执行时保存所锚定资产的原始快照,续跑继续使用该快照,同时重新检查当前资产访问权限。资产删除后保留任务和证据历史,不能静默改打另一个目标。
|
||||
- **事实**不可原地改写。`observed` 表示有本意图原始执行回执支持的观察;`inferred` 表示依据现象或既有节点作出的推断。回执必须真实存在、成功完成且属于相应测评和意图,不能用 Pi 摘要或漏洞登记回执替代。事实通过「产出/支持/推导」边进入探索图。
|
||||
- 在攻击面图按「全部关联资产」「已有观察证据」「暂无观察证据」筛选,搜索和分页作用于当前筛选。计数基于同一测评中被 observed 事实引用的可读关联资产,同一个资产只计一次。选中服务节点可查看该资产的事实,并从事实定位具体回执。阶段报告包含相同口径的统计和缺证据清单入口。人工验收仍以具体证据和任务验收条件为准。
|
||||
|
||||
每次规划与独立验收均创建新的 **Pi 原生会话**。预取内容包括目标、队列数量、优先待办、在跑意图、近期事实、资产观察计数和有界图视图。完整队列、原文及冷历史通过工具分页读取,不把全部历史重新拼进提示词。
|
||||
|
||||
事实、漏洞及关联资产更新会在事务中递增持久版本。调度器合并轮询间隔内的变化,允许 worker 未结束时重新规划;模型调用期间又出现新变化,过时的规划/完成结论不能提交。等待新进展的任务收到变化后可提前唤醒;手动暂停、取消的任务不会因此自动启动。
|
||||
|
||||
新增工具:
|
||||
|
||||
| 工具 | 用途 |
|
||||
| --- | --- |
|
||||
| `assessment_intents` | 按状态分页读取持久队列和优先级 |
|
||||
| `assessment_assets` | 查询项目/权限范围内的共享攻击面图、原始资产和分页端点 |
|
||||
| `assessment_anchor_assets` | 补充关联资产库中已有的资产。项目资产和任务中新写入资产库的记录会自动关联,通常不必再手工调用 |
|
||||
| `assessment_fact` / `assessment_facts` | 写入不可变事实 / 分页读取事实 |
|
||||
| `assessment_endpoint` | 用本意图的原始回执登记服务端点,需要资产写权限 |
|
||||
| `assessment_findings` | 读取本测评可访问的漏洞及复现、复核记录 |
|
||||
| `assessment_review_finding` | 记录另一意图实际复现后的 confirmed/refuted/inconclusive 结论(判 refuted 需给齐五维反证与正常对照组验证) |
|
||||
| `record_coverage` / `assessment_coverage_ledger` | Worker 记录测试面与风险类别的覆盖结果(含阴性证据与排除理由)/ 读取结构化覆盖账本与待补缺口 |
|
||||
| `assessment_plan_notes` | 规划器跨轮读写多步串行验证路线草稿(带 revision 乐观锁,Worker 只读) |
|
||||
| `set_goals` / `set_constraints` | 首次启动前拆解可独立核验的交付子目标与去指代化的任务操作边界(失败自动降级沿用原目标) |
|
||||
|
||||
新资产登记继续复用 `create_asset`,写入的是资产库中的项目资产,并自动关联到本次测评。漏洞登记继续复用 `record_vulnerability`。深度测评登记漏洞须传 `evidence_receipt_ids`;普通对话与批量任务保持原来的字段要求。新的测评漏洞先显示已登记、待独立复核;独立复核不能由原报告意图自证,也不能引用原意图回执冒充自己的复现。确认或否定结果同步现有漏洞状态,并保留追加的复核历史。尚有待复核或复核未定的新增漏洞时,测评不能自动验收完成。
|
||||
|
||||
这些校验保证来源和执行记录可追溯,不能自动判断每段回显一定支持模型结论,更不承诺零误报。复核者仍须检查完整原文、对照实验及复现条件。历史漏洞会补建「待核对」图节点,不补造回执,也不会自动升级为已验证。
|
||||
|
||||
## Pi 与宿主的分工
|
||||
|
||||
Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills、重试和生命周期。固定目标与步骤职责随每段执行保留,最新图态势作为有界自定义消息提供,更多历史通过图工具按需读取。结构化工具桥保留参数/输出 schema、结构化结果、annotations、namespace 和暴露策略,权限与实际执行仍由 Go 宿主处理。
|
||||
|
||||
规划、执行、独立验收使用 Pi 会话。规划器每轮从持久态势重建输入,未提交的决定不会作为新计划执行;worker 的执行分段仍恢复同一个 Pi 会话。独立验收结合实际回执判断目标是否完成;模型验收不能替代人工复测。
|
||||
|
||||
运行中补充方向先入库,再通过 Pi 原生 `steer()` 投递给活跃执行步骤,恢复后也可回查。协作者需以自己的执行身份继续任务。
|
||||
|
||||
意图队列支持单条暂停/继续、优先级调整和定向补充。暂停一条意图只取消其执行上下文,其他意图和规划器继续工作;用户暂停标记持久保存,整任务继续和重启不会自动解除,规划器也不能退休该意图来绕过暂停。继续只恢复这一条的排队状态;整任务若已暂停,仍需手动开始整任务。优先级调整不抢占正在执行的步骤。
|
||||
|
||||
「给此意图补充方向」先保存到该意图及探索图,再通过对应 Pi 会话的原生 `steer()` 投递;暂停、排队或尚未绑定会话时保存供续跑使用。定向补充不广播给其他 worker。活跃及自动恢复中的测评只允许当前执行账号定向继续或发送执行指令,协作者可先暂停并以自己的账号继续。
|
||||
|
||||
下载的 Markdown 报告包含目标、步骤、事实、人工补充,以及当前账号有权读取的关联漏洞、复现内容和完整复核历史。每条复核绑定其原始回执摘录和可返回测评的链接;摘录不替代完整执行会话。运行中导出属于阶段报告,已登记与已独立确认分别标识。
|
||||
|
||||
## 恢复语义
|
||||
|
||||
点击「开始 / 继续」后自动规划并执行本测评的待办步骤;点击「暂停」后停止新派发,取消规划器与全部在执行的步骤,等待所管执行资源收尾后显示「已暂停」。自动重试、等待新进展和待恢复状态也可暂停;手动暂停后不会被后台恢复队列或服务重启重新启动。打开页面、查看详情和刷新均不会启动任务。
|
||||
|
||||
已停止的测评提供独立的「继续测评」入口,保留已完成步骤、原 Pi 会话及证据;只有用户明确点击才会恢复。仍有结果不明或执行资源尚未确认停止的步骤时,先处理待核对项;仍有待答复问题时进入「待答复」,不派发工作。已完成的测评不能重新执行。
|
||||
|
||||
「确认已核对」是独立的核对操作,已停止、已完成的测评也可保存。核对后该步骤从「待核对」筛选中移出,历史记录和原始回执保留,任务保持停止或完成状态。确认窗口打开期间若任务有其他更新,页面会重新读取版本;若该步骤已进入另一轮执行,则要求重新查看回执,避免核对到新的执行。
|
||||
|
||||
更新或进程退出若打断停止收尾,重启时会整理残留的执行中意图:可信终态回执沿用,未知结果进入待核对,整条测评保持已停止。资源停止尚未确认或存在待答复问题时不会加入自动执行队列。停止收尾期间,旧页面的暂停请求不能覆盖停止决定,仍在收尾的意图也不能直接归档。
|
||||
|
||||
核对列表因处理记录而减少时,分页自动回到仍有记录的一页。控制请求固定绑定点击时的测评;浏览器切换测评后,未提交的请求取消,已经提交的请求结果不会覆盖新页面。
|
||||
|
||||
1. 工具派发前提交调用意图,结果落库后才交还 Pi。
|
||||
2. 已确认回执关联原生助手条目与 tool-call ID。若回执已提交而 Pi 记录未写入就退出,恢复时补回已确认结果。
|
||||
3. 暂停与停止等待本地执行资源收尾,再从同任务、步骤、会话及工具的终态执行记录核对回执。取消信号本身不等于结果不明;确认已取消的调用保存为取消及错误回执,续跑时交回原 Pi 会话,不伪装为成功。旧版误标的记录在点击开始时同样自动核对。
|
||||
4. 远端取消未获确认、原始执行回执缺失等情况仍进入待核对,不自动重放。点击待核对状态或详情中的「处理待核对」,可跨分页查看相关步骤、回执及执行会话;人工确认只解除该步骤的核对状态,全部处理完仍需手动开始。
|
||||
5. 已完成步骤保留,结果明确的中断步骤恢复原 Pi 会话。原会话文件缺失时明确受阻,避免静默从空会话重做。
|
||||
6. 选择自动恢复时,服务重启可恢复此前正在推进且结果明确的任务;草稿、手动暂停及待核对任务不因此开始。图节点、原生摘要和归档成员均持久保存。
|
||||
|
||||
当前调度面向单服务进程。允许范围文字会传给规划与执行,实际工具权限继承角色、平台权限、HITL 和调用拦截;范围文字本身不是网络隔离沙箱。
|
||||
|
||||
新数据包括 `deep_assessments`、`deep_assessment_events`、`deep_assessment_calls`、`deep_assessment_nodes`、`deep_assessment_edges`、`deep_assessment_sessions` 和 `vulnerability_assessment_sources`。已有深度测评记录会补建图与会话索引,不恢复已撤回旧模块的 `assessments`/`long_tasks` 历史任务。删除测评会清理其任务、图和调度记录;漏洞来源快照随漏洞保留,执行会话仍按原有会话保留策略处理。
|
||||
|
||||
## API 与权限
|
||||
|
||||
所有接口需登录,使用 `assessments:read/write/delete` 和 `deep_assessment` 资源范围;执行另校验 `agent:execute` 及会话权限。
|
||||
|
||||
| 接口 | 用途 |
|
||||
| --- | --- |
|
||||
| `GET /api/deep-assessments/options` | 可用项目、角色与模型渠道 |
|
||||
| `GET / POST /api/deep-assessments` | 查询列表(`archived=true` 查看归档)/ 创建草稿 |
|
||||
| `GET / DELETE /api/deep-assessments/:id` | 详情 / 删除非活动测评 |
|
||||
| `GET /api/deep-assessments/:id?step_limit=50&step_offset=0&runtime=true` | 分页详情与运行概览;`step_order=queue&step_status=needs_review` 定位待核对步骤 |
|
||||
| `POST /api/deep-assessments/:id/control/:action` | start、continue-stopped、pause、cancel、guidance、answer、retry、reconcile、archive、restore,以及 intent-pause、intent-resume、intent-priority、intent-guidance |
|
||||
| `GET / POST /api/deep-assessments/:id/assets` | 查看共享/关联攻击面图,或关联资产;`asset_id` 查询服务端点;关联视图支持 `observation=observed` 或 `observation=missing` |
|
||||
| `GET /api/deep-assessments/:id/intents?status=&offset=0` | 优先级队列和状态计数 |
|
||||
| `GET /api/deep-assessments/:id/facts?confidence=&offset=0` | 分页读取观察/推断事实,可用 `asset_id` 按可读的关联资产筛选 |
|
||||
| `GET /api/deep-assessments/:id/acceptance` | 查看验收项、证据关联与当前复核状态 |
|
||||
| `GET /api/deep-assessments/:id/acceptance/sources?kind=fact&q=&offset=0` | 分页搜索当前测评的可关联事实或回执(`kind=receipt`) |
|
||||
| `PUT /api/deep-assessments/:id/acceptance/:criterion` | 保存指定验收项的 `fact_ids`、`receipt_ids`、`needs_review`、`review_note` 及当前 `revision` |
|
||||
| `GET /api/deep-assessments/:id/evidence-path` | 按 `asset_id`、`fact_id` 或 `criterion` 查看分页证据图;结合 `asset_id` 与 `endpoint_id` 查看端点 |
|
||||
| `GET /api/deep-assessments/:id/evidence-history?asset_id=…` | 分页读取该资产在可读测评中的历史及可比变化 |
|
||||
| `GET /api/deep-assessments/:id/endpoint-evidence?asset_id=…` | 端点证据状态与筛选;加 `endpoint_id` 浏览可关联事实 |
|
||||
| `PUT /api/deep-assessments/:id/endpoint-evidence` | 保存 `asset_id`、`endpoint_id`、`fact_id` 与布尔值 `linked` |
|
||||
| `GET /api/deep-assessments/:id/graph?scope=&view=summary&limit=80&offset=0` | 主链路或 `view=full` 执行记录;包含分页边界计数及引用 |
|
||||
| `GET /api/deep-assessments/:id/graph/node?node_id=…&offset=0&links_offset=0` | 原文及独立分页的上下游关系 |
|
||||
| `GET /api/deep-assessments/:id/vulnerabilities?limit=20&offset=0` | 当前账号可读的关联漏洞 |
|
||||
| `GET /api/deep-assessments/:id/vulnerabilities/:vulnerabilityId` | 属于该测评的漏洞详情和来源步骤 |
|
||||
| `GET /api/deep-assessments/:id/steps/:stepId` | 单个步骤,用于跨分页定位 |
|
||||
| `GET /api/deep-assessments/:id/events?after=0` | 增量事件 |
|
||||
| `GET /api/deep-assessments/:id/receipts?offset=0` | 工具回执,或用 `receipt_id` 查看单条 |
|
||||
| `GET /api/deep-assessments/:id/report` | 包含当前状态及缺口的阶段报告 |
|
||||
|
||||
控制请求携带 `revision`。核对使用 `reconcile`,传 `step_id` 和 `reconciled:true`;资源清理未确认另需 `cleanup_confirmed:true`。兼容旧客户端通过 `retry` 提交核对,但不会自动开始执行。`continue-stopped` 仅用于用户明确继续已停止测评,另检查执行权限。
|
||||
|
||||
单条意图操作另传 `step_id`;调整优先级传 `priority`(1–1000),定向补充传 `message`。响应的 `guidance_delivered` 表示是否已投递到当前 Pi 会话;未投递时已保存,后续继续生效。
|
||||
|
||||
## 验证边界
|
||||
|
||||
隔离回归验证旧预算不生效、超过原步骤/分段上限仍能继续、冷分支折叠与活跃链路恢复、原始 Pi 摘要回查、图来源隔离、重启恢复和真实 Pi SDK 模拟模型闭环。浏览器回归检查无预算表单、图渲染、节点读取、抽屉交互、桌面与手机布局,原批量任务回归仍保留。
|
||||
|
||||
这些测试验证执行机制,不等于已完成真实目标的多天效果、发现质量或成本对照试验。
|
||||
|
|
@ -193,6 +193,7 @@ SQLite 热备份时最好先停止服务,或至少复制 `*.db`、`*.db-wal`
|
|||
|
||||
在 macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,点击「一键更新」后,控制台在构建成功时自动切换到新二进制。
|
||||
构建期间旧服务继续提供服务;切换时连接会短暂中断,页面在新服务应答后自动刷新并沿用仍然有效的登录会话。
|
||||
刷新后可以在「一键更新」的「运行中的构建」字段核对当前服务的提交号。
|
||||
这一步不依赖 systemd 或 launchd;长期部署仍建议用守护进程做开机自启和异常恢复。通过 API 或命令行换过
|
||||
二进制后,可以在支持自动切换的安装上用控制台的「立即重启服务」启用磁盘上的版本。
|
||||
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ go run ./cmd/server --config config.yaml
|
|||
2. 在 `internal/database/` 增加必要的数据访问。
|
||||
3. 在 `internal/app/app.go` 构造并注册路由。
|
||||
4. 如需对外文档,更新 `internal/handler/openapi.go`。
|
||||
5. 如需前端调用,更新 `web/static/js/`。
|
||||
5. 如需前端调用,更新 `web/frontend/src/pages/`。
|
||||
|
||||
## 一键更新:让安装目录更新它自己的源码
|
||||
|
||||
|
|
@ -203,7 +203,7 @@ Skill 放在 `skills/<name>/SKILL.md`。用于提供专题能力、流程说明
|
|||
|
||||
## 前端开发
|
||||
|
||||
前端代码按功能拆分在 `web/static/js/`。新增页面或模块时:
|
||||
前端代码按功能拆分在 `web/frontend/src/pages/`。新增页面或模块时:
|
||||
|
||||
- 复用现有 `apiFetch`、modal、通知、i18n 工具。
|
||||
- 同步更新 `web/static/i18n/zh-CN.json` 和 `en-US.json`。
|
||||
|
|
|
|||
|
|
@ -1,335 +1,33 @@
|
|||
## CyberStrikeAI 前端国际化方案
|
||||
# 前端国际化
|
||||
|
||||
本文档说明 CyberStrikeAI Web 前端(`web/templates/index.html` + `web/static/js/*.js`)的国际化设计与开发规范,确保在不引入打包工具和不改动后端路由的前提下,实现可扩展、低返工的多语言支持。
|
||||
前端已迁移为 React + Semi Design 单页应用,国际化由 `web/frontend/src/lib/i18n.jsx` 提供,
|
||||
词条继续复用后端同目录 `web/static/i18n/*.json`(zh-CN / en-US / ru-RU / ar-SA)。
|
||||
|
||||
当前目标:
|
||||
## 运行时行为
|
||||
|
||||
- **支持中英文切换(zh-CN / en-US)**
|
||||
- 后续可方便扩展更多语言(如 ja-JP、ko-KR 等)
|
||||
- 语言偏好保存在 `localStorage['csai_lang']`,未设置时按 `navigator.language` 推断,默认 `zh-CN`。
|
||||
- 启动时并行加载当前语言、`zh-CN` 兜底与 `en-US`(第三兜底)三份词条;缺失的键按「当前语言 → zh-CN → en-US → 调用方兜底中文」回退。
|
||||
- 切换语言会更新 `<html lang>`,阿拉伯语自动把 `<html dir>` 设为 `rtl`,并通过 Semi `ConfigProvider` 切换组件语言包。
|
||||
- 语言切换不会刷新页面;`useT()` 返回的 `t` 会随 Provider 重新渲染。
|
||||
|
||||
---
|
||||
## 在页面里使用
|
||||
|
||||
## 一、总体设计原则
|
||||
|
||||
- **前端主导的客户端国际化**:所有 UI 文案在浏览器端根据当前语言动态渲染,后端 Go 仅负责结构和数据,不参与语言分发。
|
||||
- **单一 HTML 模板**:继续使用一份 `index.html` 模板,不为不同语言复制模板文件。
|
||||
- **文案与逻辑分离**:所有可见文本通过「键值表」管理(多语言 JSON),HTML / JS 只写 key,不直接写中文/英文常量。
|
||||
- **渐进式改造**:先覆盖 header / 登录 / 侧边栏 / 系统设置等关键区域,其他页面按模块逐步迁移,避免一次性大改动。
|
||||
- **可回退默认语言**:即使目标语言未完全翻译,也能回退到默认中文,不出现原始 key。
|
||||
|
||||
---
|
||||
|
||||
## 二、技术选型与目录结构
|
||||
|
||||
### 2.1 技术选型
|
||||
|
||||
- **i18n 引擎**:使用 [i18next](https://www.i18next.com/) 的浏览器 UMD 版本(通过 CDN 引入),无需打包器。
|
||||
- **资源格式**:每种语言一份 JSON 文件,采用「域 + 语义」的层级 key 方案,例如:
|
||||
- `common.ok`
|
||||
- `nav.dashboard`
|
||||
- `header.apiDocs`
|
||||
- `settings.robot.wecom.token`
|
||||
|
||||
### 2.2 目录结构
|
||||
|
||||
- `web/templates/index.html`
|
||||
- 页面骨架 + 所有静态文案位置,将逐步改为 `data-i18n` 标记。
|
||||
- `web/static/js/i18n.js`
|
||||
- 前端 i18n 初始化与 DOM 应用逻辑(本方案新增)。
|
||||
- `web/static/i18n/`(新增目录)
|
||||
- `zh-CN.json`:中文文案(默认语言)
|
||||
- `en-US.json`:英文文案
|
||||
- 未来可新增:`ja-JP.json`、`ko-KR.json` 等。
|
||||
|
||||
---
|
||||
|
||||
## 三、文案组织规范
|
||||
|
||||
### 3.1 Key 命名约定
|
||||
|
||||
- 采用「**模块.语义**」形式,最多 2–3 级,确保可读性:
|
||||
- 导航:`nav.dashboard`、`nav.chat`、`nav.settings`
|
||||
- 头部:`header.title`、`header.apiDocs`、`header.logout`
|
||||
- 登录:`login.title`、`login.subtitle`、`login.passwordLabel`、`login.submit`
|
||||
- 仪表盘:`dashboard.title`、`dashboard.refresh`、`dashboard.runningTasks`
|
||||
- 系统设置:`settings.title`、`settings.nav.basic`、`settings.nav.robot`、`settings.apply`
|
||||
- 机器人配置:`settings.robot.wecom.enabled`、`settings.robot.wecom.token` 等。
|
||||
- 尽量按「界面区域」而不是「文件名」划分域,便于非开发人员理解。
|
||||
|
||||
### 3.2 JSON 示例
|
||||
|
||||
`web/static/i18n/zh-CN.json` 示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"common": {
|
||||
"ok": "确定",
|
||||
"cancel": "取消"
|
||||
},
|
||||
"nav": {
|
||||
"dashboard": "仪表盘",
|
||||
"chat": "对话",
|
||||
"infoCollect": "信息收集",
|
||||
"tasks": "任务管理",
|
||||
"vulnerabilities": "漏洞管理",
|
||||
"settings": "系统设置"
|
||||
},
|
||||
"header": {
|
||||
"title": "CyberStrikeAI",
|
||||
"apiDocs": "API 文档",
|
||||
"logout": "退出登录",
|
||||
"language": "界面语言"
|
||||
},
|
||||
"login": {
|
||||
"title": "登录 CyberStrikeAI",
|
||||
"subtitle": "请输入配置中的访问密码",
|
||||
"passwordLabel": "密码",
|
||||
"passwordPlaceholder": "输入登录密码",
|
||||
"submit": "登录"
|
||||
}
|
||||
}
|
||||
```jsx
|
||||
const t = useT();
|
||||
t('vulnerability.title'); // 词条里存在键
|
||||
t('common.minutesAgo', { n: 5 }); // 支持 {{n}} 插值
|
||||
t('chat.unknownKey', null, '中文兜底'); // 键缺失时用第三参数
|
||||
```
|
||||
|
||||
英文文件 `en-US.json` 保持相同 key,不同 value:
|
||||
要求:
|
||||
|
||||
```json
|
||||
{
|
||||
"common": {
|
||||
"ok": "OK",
|
||||
"cancel": "Cancel"
|
||||
},
|
||||
"nav": {
|
||||
"dashboard": "Dashboard",
|
||||
"chat": "Chat",
|
||||
"infoCollect": "Recon",
|
||||
"tasks": "Tasks",
|
||||
"vulnerabilities": "Vulnerabilities",
|
||||
"settings": "Settings"
|
||||
},
|
||||
"header": {
|
||||
"title": "CyberStrikeAI",
|
||||
"apiDocs": "API Docs",
|
||||
"logout": "Sign out",
|
||||
"language": "Interface language"
|
||||
},
|
||||
"login": {
|
||||
"title": "Sign in to CyberStrikeAI",
|
||||
"subtitle": "Enter the access password from config",
|
||||
"passwordLabel": "Password",
|
||||
"passwordPlaceholder": "Enter password",
|
||||
"submit": "Sign in"
|
||||
}
|
||||
}
|
||||
```
|
||||
1. 可见文案统一走 `t(...)`,第三个参数写中文兜底,避免出现原始 key。
|
||||
2. 新增词条时同时更新 `web/static/i18n/zh-CN.json` 与 `en-US.json`;`ru-RU`/`ar-SA` 可暂时缺失,靠回退链。
|
||||
3. 表单校验、Toast、空态文案同样走 `t(...)`。
|
||||
4. 时间格式化使用 `src/lib/format.js` 的 `formatDateTime/relativeTime`,不要手拼日期。
|
||||
|
||||
> 约定:**新增界面时,必须先定义 i18n key,再在 HTML/JS 中使用 key**,禁止直接写死中文/英文。
|
||||
|
||||
---
|
||||
|
||||
## 四、HTML 标记规范(data-i18n)
|
||||
|
||||
### 4.1 基本规则
|
||||
|
||||
- 使用 `data-i18n` 将元素文本与某个 key 绑定:
|
||||
|
||||
```html
|
||||
<span data-i18n="nav.dashboard">仪表盘</span>
|
||||
```
|
||||
|
||||
- 默认行为:脚本会替换元素的 `textContent`。
|
||||
- 同时翻译属性时,额外使用 `data-i18n-attr`,逗号分隔多个属性名:
|
||||
|
||||
```html
|
||||
<button
|
||||
class="openapi-doc-btn"
|
||||
onclick="window.open('/api-docs', '_blank')"
|
||||
data-i18n="header.apiDocs"
|
||||
data-i18n-attr="title"
|
||||
title="API 文档">
|
||||
<span data-i18n="header.apiDocs">API 文档</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
### 4.2 默认文本的作用
|
||||
|
||||
- HTML 内的中文默认值作为「**无 JS / 初始化前**」的占位内容:
|
||||
- 页面在 JS 尚未加载完成时不会出现空白或 key。
|
||||
- JS 初始化后会用当前语言覆盖这些文本。
|
||||
|
||||
---
|
||||
|
||||
## 五、JavaScript 中的文案规范
|
||||
|
||||
### 5.1 全局翻译函数 `t()`
|
||||
|
||||
由 `i18n.js` 暴露以下全局函数:
|
||||
|
||||
- `window.t(key: string): string`
|
||||
- 返回当前语言下的翻译文本,若缺失则回退到默认语言,再不行则返回 key 本身。
|
||||
- `window.changeLanguage(lang: string): Promise<void>`
|
||||
- 切换语言并刷新页面文案(不会刷新整页)。
|
||||
|
||||
示例(以 `web/static/js/settings.js` 为例):
|
||||
|
||||
```js
|
||||
// 之前
|
||||
alert('加载配置失败: ' + error.message);
|
||||
|
||||
// 之后
|
||||
alert(t('settings.loadConfigFailed') + ': ' + error.message);
|
||||
```
|
||||
|
||||
> 规范:**JS 内所有面向用户的提示、按钮文字、对话框标题都应通过 `t()` 获取**,不直接写死中文/英文。
|
||||
|
||||
### 5.2 渐进迁移建议
|
||||
|
||||
- 优先改造:
|
||||
- 频繁弹出的错误提示 / 成功提示;
|
||||
- 登录相关、系统设置相关文案。
|
||||
- 低优先级:
|
||||
- 仅面向运维人员的调试提示,可以暂时保留英文/中文常量。
|
||||
|
||||
---
|
||||
|
||||
## 六、i18n 初始化与语言切换实现
|
||||
|
||||
### 6.1 语言选择策略
|
||||
|
||||
- 默认语言:`zh-CN`。
|
||||
- 优先级(从高到低):
|
||||
1. `localStorage` 中的用户选择(key:`csai_lang`)。
|
||||
2. 浏览器 `navigator.language`(`zh` 开头 → `zh-CN`,否则 `en-US`)。
|
||||
3. 默认 `zh-CN`。
|
||||
|
||||
### 6.2 初始化流程(`i18n.js`)
|
||||
|
||||
1. 读取初始语言。
|
||||
2. 初始化 i18next:
|
||||
- `lng` 为当前语言;
|
||||
- `fallbackLng` 为 `zh-CN`;
|
||||
- 资源先留空,采用按需加载。
|
||||
3. 通过 `fetch` 拉取 `/static/i18n/{lng}.json` 并 `i18next.addResources`。
|
||||
4. 更新:
|
||||
- `<html lang="...">` 属性;
|
||||
- 所有带 `data-i18n` / `data-i18n-attr` 的元素。
|
||||
5. 暴露 `window.t` 与 `window.changeLanguage`。
|
||||
|
||||
### 6.3 DOM 应用逻辑
|
||||
|
||||
伪代码:
|
||||
|
||||
```js
|
||||
function applyTranslations(root = document) {
|
||||
const elements = root.querySelectorAll('[data-i18n]');
|
||||
elements.forEach(el => {
|
||||
const key = el.getAttribute('data-i18n');
|
||||
if (!key) return;
|
||||
const text = i18next.t(key);
|
||||
if (text) {
|
||||
el.textContent = text;
|
||||
}
|
||||
|
||||
const attrList = el.getAttribute('data-i18n-attr');
|
||||
if (attrList) {
|
||||
attrList.split(',').map(s => s.trim()).forEach(attr => {
|
||||
if (!attr) return;
|
||||
const val = i18next.t(key);
|
||||
if (val) el.setAttribute(attr, val);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
> 对于由 JS 动态插入的元素,需要在插入后再次调用 `applyTranslations(新容器)`。
|
||||
|
||||
---
|
||||
|
||||
## 七、语言切换 UI 规范
|
||||
|
||||
### 7.1 位置与形态
|
||||
|
||||
- 位置:`index.html` header 右侧 `API 文档` 按钮附近(靠近用户头像)。
|
||||
- 交互形式:
|
||||
- 一个紧凑的语言切换组件,例如:
|
||||
- `🌐` 图标 + 当前语言文本(`中文` / `English`)的下拉按钮;
|
||||
- 下拉内容列出所有可用语言。
|
||||
|
||||
### 7.2 示例结构
|
||||
|
||||
```html
|
||||
<div class="lang-switcher">
|
||||
<button class="btn-secondary lang-switcher-btn" onclick="toggleLangDropdown()" data-i18n="header.language">
|
||||
<span class="lang-switcher-icon">🌐</span>
|
||||
<span id="current-lang-label">中文</span>
|
||||
</button>
|
||||
<div id="lang-dropdown" class="lang-dropdown" style="display: none;">
|
||||
<div class="lang-option" data-lang="zh-CN" onclick="onLanguageSelect('zh-CN')">中文</div>
|
||||
<div class="lang-option" data-lang="en-US" onclick="onLanguageSelect('en-US')">English</div>
|
||||
</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
对应 JS(在 `i18n.js` 中):
|
||||
|
||||
```js
|
||||
function onLanguageSelect(lang) {
|
||||
changeLanguage(lang).then(updateLangLabel).catch(console.error);
|
||||
closeLangDropdown();
|
||||
}
|
||||
|
||||
function updateLangLabel() {
|
||||
const labelEl = document.getElementById('current-lang-label');
|
||||
if (!labelEl) return;
|
||||
const lang = i18next.language || 'zh-CN';
|
||||
labelEl.textContent = lang.startsWith('zh') ? '中文' : 'English';
|
||||
}
|
||||
```
|
||||
|
||||
> 规范:**语言切换只更新文案,不刷新整页,也不修改 URL hash**。
|
||||
|
||||
---
|
||||
|
||||
## 八、开发流程建议
|
||||
|
||||
### 8.1 新增 / 修改界面的流程
|
||||
|
||||
1. 设计界面时,先列出所有文案。
|
||||
2. 在对应语言 JSON 中补充/修改 key 与翻译。
|
||||
3. 在 HTML 中使用 `data-i18n`,在 JS 中使用 `t('...')`。
|
||||
4. 在浏览器中切换中英文,确认两种语言显示都正确。
|
||||
|
||||
### 8.2 渐进式改造顺序(推荐)
|
||||
|
||||
1. **阶段 1(已规划)**
|
||||
- 引入 i18next 与 `i18n.js`。
|
||||
- 新建 `zh-CN.json` / `en-US.json`(先覆盖 header / 登录 / 左侧导航)。
|
||||
- 实现 header 区域语言切换组件。
|
||||
2. **阶段 2**(已完成)
|
||||
- 系统设置页面(包括机器人配置页面)全部文案 i18n 化。
|
||||
- `settings.js` 中的提示与错误信息改用 `t()`。
|
||||
3. **阶段 3**(进行中)
|
||||
- 仪表盘、任务管理、漏洞管理、MCP、Skills、Roles 等页面按模块逐步迁移。
|
||||
4. **阶段 4**
|
||||
- 清理 JS / HTML 中残留的硬编码中文,统一通过 i18n。
|
||||
|
||||
---
|
||||
|
||||
## 九、后续扩展新语言
|
||||
|
||||
当需要新增语言时:
|
||||
|
||||
1. 在 `web/static/i18n/` 中新增 `{lang}.json`,复制现有英文/中文文件结构,补充对应翻译。
|
||||
2. 在语言切换下拉中添加对应选项,例如:
|
||||
- `data-lang="ja-JP"` / 文本 `日本語`
|
||||
3. 无需修改 `i18n.js` 或现有 HTML/JS 逻辑,即可支持新语言。
|
||||
|
||||
---
|
||||
|
||||
## 十、注意事项与坑点
|
||||
|
||||
- **不要复制多份 HTML 模板** 来做多语言,那样维护成本极高,本方案统一由前端 i18n 控制。
|
||||
- **避免 key 直接用中文/英文句子**,统一采用「模块.语义」短 key,便于 diff 与搜索。
|
||||
- 避免在 CSS 中写死文本(如 `content: "xxx"`),如确有需要,应通过 JS 设置并走 i18n。
|
||||
- 对于后端返回的可本地化错误文本(未来可能支持),优先由后端根据 `Accept-Language` 返回对应语言,前端只负责展示。
|
||||
## 词条组织
|
||||
|
||||
`web/static/i18n/zh-CN.json` 按业务域分组:`common`、`nav`、`dashboard`、`vulnerability`、`chat`、
|
||||
`settings`、`knowledge`、`skills`、`roles`、`auth`、`apiDocs` 等。新增分组时保持两级键名
|
||||
(`<domain>.<key>`),避免深层嵌套影响可读性。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,116 @@
|
|||
# HTTP 测试工具代理池
|
||||
|
||||
[English](../en-US/http-proxy-pool.md) | [文档首页](README.md)
|
||||
|
||||
`http-framework-test` 支持用户提供的代理列表及代理供应商接口。连接失败或响应命中指定状态码时,在次数上限内切换代理;成功代理继续复用连接。默认沿用工具参数。也可在「系统设置 → 代理设置」统一管理此 HTTP 工具的出口。
|
||||
|
||||
## 使用
|
||||
|
||||
更新工具文件后,在系统设置中应用配置或重启服务以重新加载工具参数。也可以在代理二级菜单保存配置,后续调用立即生效;运行中进程保留启动时快照。
|
||||
|
||||
调用 `http-framework-test` 时传入以下参数(MCP 工具参数示例):
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"method": "GET",
|
||||
"proxy_pool": "[\"http://127.0.0.1:8081\",\"http://127.0.0.1:8082\"]",
|
||||
"proxy_max_attempts": 3,
|
||||
"proxy_cooldown": "60",
|
||||
"proxy_fail_status": "403,429",
|
||||
"response_max_bytes": 8192
|
||||
}
|
||||
```
|
||||
|
||||
`proxy_pool` 也接受每行一个代理的字符串。支持 `http://host:port`、`https://host:port`、`socks5://host:port` 和省略协议的 `host:port`(按 HTTP 解析);端口必须显式指定。支持 IPv6 方括号及 `user:password@host:port` 认证,凭证中的特殊字符须做 URL 编码。SOCKS 依赖包含在 `requirements.txt` 的 `httpx[http2,socks]` 中。
|
||||
|
||||
使用供应商接口自动获取代理时,增加或单独使用:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-authorized-target.example/health",
|
||||
"proxy_source": "https://your-proxy-provider.example/api/proxies"
|
||||
}
|
||||
```
|
||||
|
||||
接口返回 UTF-8 文本,每行一个代理,或以下 JSON 格式之一:
|
||||
|
||||
```json
|
||||
["http://127.0.0.1:8081", "127.0.0.1:8082"]
|
||||
```
|
||||
|
||||
```json
|
||||
{"proxies": ["http://127.0.0.1:8081"]}
|
||||
```
|
||||
|
||||
也支持 `{"data": ["http://127.0.0.1:8081"]}`。列表元素还可为 `{"host":"127.0.0.1","port":8081,"scheme":"http","username":"user","password":"pass"}`(`ip` 可代替 `host`),或 `{"url":"http://127.0.0.1:8081"}`。`scheme` 默认 HTTP,认证字段可省略;结构化凭证自动做 URL 编码。需要其他供应商字段格式时,应由供应商或自建适配接口转换为上述格式。项目不内置公共免费代理来源。
|
||||
|
||||
供应商接口在调用开始时拉取一次;每个请求或重定向跳的可用代理耗尽时,最多再拉取一次。新地址与现有地址去重合并,已有冷却记录保留。连接/读取超时为 10 秒,不跟随重定向,响应上限 1 MiB,代理总数上限 256。首次拉取失败时,有静态列表则发出提示并继续使用静态代理;仅配置供应商时结束调用;切换过程中拉取失败则保留最后的 HTTP 失败响应,若还未收到响应则报错。
|
||||
|
||||
## 切换与结果
|
||||
|
||||
| 参数 | 默认值 | 行为 |
|
||||
| --- | --- | --- |
|
||||
| `proxy_pool` | 空 | JSON 字符串数组或换行列表 |
|
||||
| `proxy_strategy` | `"sticky"` | `sticky` 成功后复用,`round_robin` 轮询并跳过冷却代理 |
|
||||
| `proxy_source` | 空 | 用户配置的 HTTP(S) 供应商接口,可与列表合用 |
|
||||
| `proxy_max_attempts` | `3` | 每个请求/重定向跳最多尝试 1–10 个不同代理 |
|
||||
| `proxy_cooldown` | `"60"` | 失败代理冷却 0–86400 秒 |
|
||||
| `proxy_fail_status` | `"403,429"` | 逗号分隔的 400–599 状态码,传 `"none"` 禁用状态码切换 |
|
||||
|
||||
具体规则:
|
||||
|
||||
- 默认保持成功代理;设置 `proxy_strategy="round_robin"` 后,每个请求/重定向跳轮询可用代理;失败后冷却,在剩余可用代理中切换。每个请求或重定向跳内,同一代理最多尝试一次。
|
||||
- 仅 GET、HEAD、OPTIONS 自动重放。POST、PUT、DELETE 等方法发生错误或命中状态码时保留首次结果;用户显式设置的 `repeat` 仍表示额外执行次数。
|
||||
- 连接、代理、超时等传输错误可触发上述切换;响应体开始读取后的中断直接报错,不重放部分响应。
|
||||
- 429 若包含有效且尚未到期的 `Retry-After`,停止自动重放并提示稍后重试。同一工具调用中,对该目标源的后续请求也会被阻止至等待期结束,等待值最多记为 24 小时。
|
||||
- 最后一次尝试若收到 HTTP 失败响应,保留该响应并返回非零退出码;网络故障或所有代理处于冷却时报告错误。不会回退到直连,也不会运行额外的目标 DNS/TCP/TLS 直连探针。
|
||||
- stderr 记录尝试编号、代理编号及失败类型;stdout 保留最终响应及最终代理编号。代理池自身诊断不输出代理凭证或供应商 URL。工具调用参数仍沿用平台既有的轨迹、审计与日志规则,带凭证的参数应按敏感配置管理。
|
||||
|
||||
## 调研结论与覆盖范围
|
||||
|
||||
[#357](https://github.com/AIPentest/CyberStrikeAI/issues/357) 仅提出自动获取代理与被封后切换,未定义供应商、识别方式或工具范围。当前实现从能读取 HTTP 响应的 `http-framework-test` 接入,使 HTTP 和 HTTPS 的切换行为都可验证。
|
||||
|
||||
HTTP CONNECT 隧道中的 HTTPS 响应需要由发起请求的客户端解密才能读取,因此单独增加全局转发代理不足以识别全部工具的 HTTPS 封禁响应。HTTPX 的代理与自定义传输接口适合在本工具内完成切换,见 [HTTPX 代理文档](https://www.python-httpx.org/advanced/proxies/)与[传输文档](https://www.python-httpx.org/advanced/transports/)。
|
||||
|
||||
403 也可能是业务权限错误,429 也可能按账号或其他维度限流;默认状态码只是可配置的失败策略,不宣称已确认 IP 被封。不匹配状态码的验证码页、HTTP 200 拦截页目前保持原样。重放和等待规则参考 [RFC 9110 §9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2) 和 [RFC 6585 §4](https://www.rfc-editor.org/rfc/rfc6585.html#section-4)。
|
||||
|
||||
池状态只在单次工具调用内保留,不跨会话共享。其他扫描工具、`exec`、Pi `execute`、外部 MCP、LLM API 连接暂不接入本池;系统设置中的代理页面只管理上述 HTTP 工具。供应商拉取使用独立客户端,开启 TLS 校验,不继承目标请求的 Cookie、Authorization、环境代理或 `allow_insecure`;生产供应商接口建议使用 HTTPS。
|
||||
|
||||
## 排错与源码
|
||||
|
||||
| 提示 | 处理 |
|
||||
| --- | --- |
|
||||
| `Proxy pool exhausted` | 检查代理可达性,等待冷却或更换列表/供应商返回值 |
|
||||
| `failure policy still matched` | 查看保留的响应;确认是 IP 限制还是正常的权限/限流结果,按需调整 `proxy_fail_status` |
|
||||
| `Retry-After is still active` | 等待目标指定的时间后再发起调用 |
|
||||
| `Could not fetch proxy source` | 检查供应商接口网络、认证和 TLS;目标的 `allow_insecure` 不影响供应商连接 |
|
||||
| `SOCKS support requires ...` | 在工具使用的 Python 环境安装 `httpx[socks]` 或更新 `requirements.txt` 依赖 |
|
||||
|
||||
执行代码与 MCP 参数定义位于 [tools/http-framework-test.yaml](../../tools/http-framework-test.yaml),回归场景位于 [scripts/test_http_proxy_pool.py](../../scripts/test_http_proxy_pool.py)。
|
||||
|
||||
## 本地验证
|
||||
|
||||
```sh
|
||||
python3 -m pip install 'httpx[http2,socks]>=0.27.0' PyYAML
|
||||
python3 -m unittest discover -s scripts -p 'test_http_proxy_pool.py' -v
|
||||
```
|
||||
|
||||
测试从 YAML 读取实际执行代码,使用本地 HTTP 代理、CONNECT 隧道及 TLS 服务验证切换、路径保真、重放限制、等待期、供应商刷新与凭证隔离;不访问外部目标或真实供应商。HTTPS 测试需要 `openssl`。
|
||||
|
||||
## 系统设置与稳定出口
|
||||
|
||||
系统设置 → 代理设置提供三种模式:沿用工具参数、固定代理、代理池。固定模式在不同调用之间持续使用配置的同一代理地址,不做失败切换;需要稳定 IP 的登录态优先选它。池模式可选择复用或轮询,界面默认最短切换间隔 60 秒。间隔同时限制故障切换,尚未到期时保留响应或报错,不提前更换出口。计时只在单次调用内有效;跨调用仍需稳定出口时使用固定模式及供应商的固定 IP 服务。
|
||||
|
||||
保存通过既有 `PUT /api/config` 的 `proxy` 段持久化并热应用,只影响以后启动的 `http-framework-test`。`proxy_url`、`proxy_pool`、`proxy_source` 在 GET 响应中整体脱敏;`********` 原样提交会保留已有值,空字符串表示清除。设置页列表每行一个 URL;结构化供应商格式仍可由供应商接口提供。配置示例见 `config.example.yaml` 的 `proxy` 段。受管设置通过该工具专用的进程环境快照传递,不加入命令参数或自动注入模型上下文;它不限制任意 Shell 命令的网络行为。
|
||||
|
||||
### 参考项目与采用的做法
|
||||
|
||||
| 参考 | 做法与本项目选择 |
|
||||
| --- | --- |
|
||||
| [Zyte Sessions](https://docs.zyte.com/zyte-api/usage/features.html#sessions) | IP、Cookie 和连接环境共同影响会话。提供固定出口模式,登录态不默认轮询。 |
|
||||
| [HTTPX Clients](https://www.python-httpx.org/advanced/clients/) | 复用连接和 Cookie。运行中的调用保持快照,设置变更不拆除已有连接。 |
|
||||
| [Nuclei](https://docs.projectdiscovery.io/opensource/nuclei/running) | 原生代理选项和请求速率分别配置。其他 Kali 工具使用自身代理与限速能力,不从文本输出猜测封禁并重新启动进程。 |
|
||||
| [Nmap 代理限制](https://nmap.org/book/man-bypass-firewalls-ids.html) | 代理支持有协议和扫描阶段限制,不能承诺统一 HTTP 环境变量覆盖所有原始报文扫描。未适配工具保持原路由。 |
|
||||
|
||||
大模型 API 的流式响应、连接池和提供商重试继续使用既有客户端,不接入扫描代理池;模型侧的账号/Token 限流应走现有退避策略。不同供应商是否要求固定公网 IP 需按其接口约定判断,本功能不会自动改动模型出口或轮询 API 连接。
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Pi 原生运行时
|
||||
|
||||
CyberStrikeAI 仅使用 Pi 1.5.2(`@earendil-works/pi-coding-agent`、`pi-ai`),Go 保留业务、权限、工具执行和证据管理。
|
||||
CyberStrikeAI 仅使用 Pi 1.7.0(`@earendil-works/pi-coding-agent`、`pi-ai`),Go 保留业务、权限、工具执行和证据管理。个人主仓库为 [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI)。
|
||||
|
||||
维护时优先使用当前锁定版本的 Pi SDK 公共接口。只有需要项目权限、业务记录或兼容行为时,才在宿主或 Worker 增加逻辑。
|
||||
|
||||
|
|
@ -29,23 +29,25 @@ agent_runtime:
|
|||
|
||||
模型请求使用 HTTP/1.1,遵循服务进程环境里的 `HTTP_PROXY`、`HTTPS_PROXY` 和 `NO_PROXY`。重定向只允许在原站点内跳转,避免模型凭据外传。
|
||||
|
||||
非 OpenAI 官方渠道的 Chat Completions 请求使用 `system` 发送系统指令,避免启用思考后被 Pi 自动改成部分兼容接口不支持的 `developer` 角色。思考参数保持原有配置;主模型、备用模型及后台生成使用同一兼容设置。OpenAI 官方渠道和 Responses/Anthropic 原生协议保留 SDK 的角色处理。
|
||||
|
||||
新服务会在接受请求前补建缺失的匹配 Worker 并检查启动握手,因此首次从 Eino 升级时,即使旧更新器只编译 Go,也能准备运行组件。补建需要 Node.js >=22.19、npm 和锁定的 npm 依赖下载渠道;失败会阻止启动并提示修复方法。已有匹配构建包时不再安装依赖。
|
||||
|
||||
## 执行边界
|
||||
|
||||
- 聊天、机器人、批量任务、工作流 Agent 节点通过统一调度入口进入 Pi。正式单代理路由为 `/api/agent`、模式值为 `single`;旧路由与模式只做输入兼容,执行始终使用 Pi。
|
||||
- Go 管理每次调用的 Worker,转发流式事件和工具回调。补充指令进入 Pi 原生队列,取消时 Pi 停止模型请求,Go 停止宿主工具。同一进程中的相同会话存储串行访问,不同会话独立运行。
|
||||
- Go 管理每次调用的 Worker,转发流式事件和工具回调;补充指令进入 Pi 原生队列,取消由 Pi 和 Go 分别停止模型请求和宿主工具。同一进程中的相同会话存储串行访问,不同会话独立运行。
|
||||
- Worker 使用显式模型、内存凭据和资源加载器,不自动发现个人 Pi 配置、全局插件或默认文件/Shell 工具。
|
||||
- 工具较多时使用 Pi 原生 tool_search 按需加载,减少模型一次接收的工具定义。TaskCreate/Update/Get/List 和 write_todos 继续写入现有对话任务板。
|
||||
- MCP、文件和 Shell 工具回到 Go,经角色过滤、HITL 和现有执行监控处理。子代理工具集合受主代理集合约束。
|
||||
- Deep 使用任务委派;Supervisor 提供专家委派和 exit;Plan-Execute 使用计划记录与执行子代理。最终文本仍需通过既有证据验收。
|
||||
- Pi 原生重试及虚拟模型路由承接聊天备用渠道。认证/配置错误不能用无界“继续”消除。
|
||||
- 上下文窗口和输出上限沿用渠道设置,包括 local profile;输入预算用于 Pi 压缩阈值。压缩后的模型上下文和完整会话记录分别保留。
|
||||
|
||||
## 数据与兼容
|
||||
|
||||
- Pi 的 `SessionManager` 直接读写模型会话及压缩记录。新会话使用固定的 `session.jsonl`,已有会话沿用 `current-session` 指向的原文件,已有证据路径仍可使用。回滚到旧 Worker 时,新格式会话的上下文会从宿主传入的历史重建,原有 Pi 压缩记录不会加载。
|
||||
- SQLite 保存业务状态、工具记录和交付证据。删除轮次时清除该对话所有模式及子代理的 Pi 会话,并递增数据库会话版本。后续请求从剩余消息重建上下文,旧 Worker 迟到写回的文件不会被恢复。运行中的任务须先停止再删轮次。
|
||||
- 旧配置中的 `agent_runtime.purge` 在加载时忽略,在保存系统设置时移除。
|
||||
- Pi 的 `SessionManager` 直接读写模型会话及压缩记录。新会话使用固定的 `session.jsonl`;已有会话沿用 `current-session` 指向的原文件,已有证据路径仍可使用。回滚到旧 Worker 时,新格式会话的上下文会从宿主传入的历史重建,原有 Pi 压缩记录不会加载。
|
||||
- SQLite 保存业务状态、工具记录和交付证据。删除轮次时清除该对话所有模式及子代理的 Pi 会话,并递增数据库会话版本;后续请求从剩余消息重建上下文,旧 Worker 迟到写回的文件不会被恢复。运行中的任务须先停止再删轮次。
|
||||
- 会话目录变更会在数据库保留历次目录,重启后删除对话或轮次仍会清理新旧目录;清理失败不会报告删除成功。
|
||||
- 每次实际调用都有独立的运行期传输 ID;模型复用自身的 tool-call ID 不会吞掉新调用。同一个传输 ID 重发时复用已完成结果;不同参数复用同一个传输 ID 会被拒绝。
|
||||
- 进程中断后,未提交结果的调用标记为结果不确定。系统不把它自动当成成功,也不直接重放它;继续前须核对执行记录。这不是跨所有外部系统的“恰好一次”保证。
|
||||
|
|
@ -64,9 +66,11 @@ npm test
|
|||
cd ../..
|
||||
go test -race ./internal/agentruntime ./internal/multiagent ./internal/workflow ./internal/knowledge
|
||||
go test ./...
|
||||
node --test web/static/js/*.test.cjs
|
||||
npm run --prefix web/frontend build
|
||||
```
|
||||
|
||||
SDK 集成测试使用本地模拟模型和无副作用的工具夹具,覆盖 OpenAI/Claude 动作建议、审批编辑、子代理工具边界、流式输出、取消、进程中断及备用模型切换。
|
||||
|
||||
2026-11-11 已用现有默认模型完成一次隔离回声工具闭环:模型调用 echo,Go 执行后返回 PONG,Pi 正常结束。该验证只使用合成消息和回声工具,未执行安全测试或更改生产服务;不代表长任务、全部模型渠道或效果指标已验收。
|
||||
|
||||
新安装示例的 update.repo 指向 Sycun/CyberStrikeAI;现有安装需单独核对更新来源。本次源码迁移不修改运行中的生产配置。
|
||||
|
|
|
|||
|
|
@ -213,4 +213,4 @@ schema 越具体,HITL 越容易判断风险,Agent 也越不容易发散。
|
|||
- 捕获:`devtools.js`、`background/service-worker.js`
|
||||
- OpenAPI:`internal/handler/openapi.go`
|
||||
- 外部 MCP:`internal/handler/external_mcp.go`
|
||||
- Web 端认证参考:`web/static/js/auth.js`
|
||||
- Web 端认证参考:`web/frontend/src/lib/auth.jsx`
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
# 批量任务管理
|
||||
|
||||
2026-11-14,任务管理恢复 v1.8.0 的批量队列逻辑及界面,撤回后续目标任务和统一列表改造。旧深度测评实现保持移除,上游 PR #383 保持关闭;新建的独立[深度测评](deep-assessments.md)栏目使用自己的接口与持久调度,批量队列行为保持不变。
|
||||
|
||||
## 使用方式
|
||||
|
||||
1. 打开「任务管理 → 新建任务」,每行填写一项任务,可设置标题、项目、角色、代理模式、工具审批和并发数。
|
||||
2. 选择手动执行或 Cron 定时执行;是否立即执行由创建窗口中的选项决定。
|
||||
3. 队列列表支持状态筛选、关键字搜索和分页。默认每页 10 个队列,可切换为 20、50 或 100。
|
||||
4. 点击队列打开详情窗口,查看子任务状态、结果和对话;按队列状态提供开始、暂停、继续、重新运行、添加及编辑子任务等操作。
|
||||
|
||||
这里执行的是用户提供的任务清单,不再提供独立的目标规划、验收、预算或补充方向控制器。
|
||||
|
||||
## 数据与兼容
|
||||
|
||||
- 保留原有批量任务、定时配置、子任务结果和执行会话;继续使用 `/api/batch-tasks` 接口。
|
||||
- 撤回 `/api/tasks` 统一列表及 `/api/long-tasks` 接口、相关权限资源和运行引擎。
|
||||
- 回退不删除已存在的目标任务或深度测评历史表,也不把它们转成批量队列,不继续执行其中的任务。需要读取这部分历史时,可使用对应历史版本和数据库备份。
|
||||
- 本次只修改开发版源码并同步个人仓库;运行环境需单独更新,源码回退不等于已经部署。
|
||||
|
||||
## 验证边界
|
||||
|
||||
使用隔离数据检查原版页面的创建、筛选、分页和详情操作,并运行现有 Go 与前端回归。不会调用真实模型或启动真实目标测试。
|
||||
|
|
@ -108,6 +108,15 @@ go build -o cyberstrike-ai ./cmd/server
|
|||
|
||||
## 前端冒烟
|
||||
|
||||
前端是 React 19 + Semi Design 单页应用(`web/frontend`)。构建与产物校验:
|
||||
|
||||
```sh
|
||||
npm ci --prefix web/frontend
|
||||
npm run --prefix web/frontend build
|
||||
git status --porcelain web/static/app # 应为空,产物需随源码提交
|
||||
go test ./internal/app -run TestSPA -count=1
|
||||
```
|
||||
|
||||
修改前端后至少验证:
|
||||
|
||||
- 登录和退出。
|
||||
|
|
@ -115,8 +124,9 @@ go build -o cyberstrike-ai ./cmd/server
|
|||
- 新建对话和流式回复。
|
||||
- 设置页面保存。
|
||||
- 相关业务页面增删改查。
|
||||
- 中英文切换。
|
||||
- 浏览器控制台无明显错误。
|
||||
- 中英文切换与暗色主题。
|
||||
- 逐个访问 `#/<页面 id>`(清单见 `web/frontend/src/lib/nav.js`),浏览器控制台无 error、无页面异常。
|
||||
- 深链接可直接打开:`#/chat?conversation=…`、`#/vulnerabilities?id=…`、`#/projects?id=…`、`#/settings?section=…`。
|
||||
|
||||
## 高风险模块测试
|
||||
|
||||
|
|
@ -149,7 +159,7 @@ C2、WebShell、终端、批量任务只能在授权测试环境验证。测试
|
|||
- `internal/multiagent/`:测流式、工具调用、摘要、重试、HITL。
|
||||
- `internal/security/`:测认证、Shell、超时、无输出。
|
||||
- `internal/database/`:测旧数据兼容。
|
||||
- `web/static/js/chat.js`:测对话、过程详情、攻击链、分组。
|
||||
- `web/frontend/src/pages/chat/`:测对话、过程详情、攻击链、分组。
|
||||
|
||||
## 测试数据管理
|
||||
|
||||
|
|
|
|||
|
|
@ -9,15 +9,14 @@
|
|||
- 供应商单独报告的推理 Token 已包含在输出中,面板单列展示。
|
||||
- 模型调用次数按已观察到的轮次统计,重试会产生新的轮次。
|
||||
- 未报告的细分不能推断为没有发生。推理 Token 等没有独立字段时,不根据文本长度伪造账单计数。
|
||||
- 深度评估使用其持久预算账本;供应商未报告用量时采用原有保守计费策略。
|
||||
|
||||
## 查看
|
||||
|
||||
首页 Token 卡片和设置页 Token 用量面板继续支持周期、模型、项目和明细查询。接口为 `GET /api/usage/tokens` 与 `GET /api/conversations/:id/token-usage`。
|
||||
从首页 Token 卡片进入「系统设置 → Token 用量」,可按周期、项目查看汇总、模型统计和最近记录。在该页搜索并选择会话即可查看单会话用量。接口为 `GET /api/usage/tokens` 与 `GET /api/conversations/:id/token-usage`。
|
||||
|
||||
已有模型用量表保持兼容。旧时间线用量事件可作为历史记录补齐;新记录仅由原生 Pi 事件生成。原生流式消息只传输增量,完整消息在结束时提交,避免重复累计与逐块重复发送整份内容。
|
||||
|
||||
实现:`internal/multiagent/pi_runner.go`、`internal/database/model_token_usage.go`、前端用量页面。基础模型 usage 语义见 [Pi AI](https://github.com/earendil-works/pi/tree/v1.5.2/packages/ai)。
|
||||
实现:`internal/multiagent/pi_runner.go`、`internal/database/model_token_usage.go`、前端用量页面。基础模型 usage 语义见 [Pi AI](https://github.com/earendil-works/pi/tree/v1.7.0/packages/ai)。
|
||||
|
||||
## DeepSeek
|
||||
|
||||
|
|
|
|||
|
|
@ -228,9 +228,11 @@ PY
|
|||
|
||||
- `exec ... &` 与 Pi 后台执行立即返回,但仍属于本轮任务;无任务归属的后台启动被拒绝。前台工具退出时清理遗留子进程,跨工具调用运行的任务应使用显式后台入口。
|
||||
- 完成、失败、超时收尾、用户停止、服务正常关闭都会封闭启动入口、取消 worker、终止进程并等待回收。“中断并继续”保留本轮归属。
|
||||
- Unix 首先给进程组 3 秒退出宽限期,再强制终止并验证;内核隔离、守护进程退出与 worker 收尾各有有界等待。清理期间仍占用本轮任务;失败保留 `cleanup_failed`、进程组/worker ID,每 15 秒巡检重试。
|
||||
- Unix 先等待进程组主动退出,再强制终止并验证。环境变量 `CS_CLEANUP_GRACE`、`CS_CLEANUP_KILL`、`CS_CLEANUP_GUARD` 分别控制主动退出、SIGKILL 后回收和隔离后端的等待时间,接受正的 Go duration(例如 `10s`),未配置或无效时各用 3 秒。普通清理失败保留 `cleanup_failed` 和进程组/worker ID,每 15 秒巡检重试。
|
||||
- 工具 worker 的登记与任务关闭互斥;即使 MCP 使用 `WithoutCancel`,任务也会等待其退出。旧轮次的延迟回调无法接管新轮次的进程或提交新 worker。
|
||||
|
||||
Linux 上,直接子进程回收后,只剩僵尸进程的组视为已退出。使用进程组 watchdog 时,若清理超时且组内仍存活的成员均处于 D 态并已有待投递的 SIGKILL,等本地 worker 退出后,任务记为 `cleanup_unconfirmed`。服务日志记录 run ID 和 PGID,进程解除阻塞后由内核处理挂起的信号。cgroup 和 Windows Job Object 仍按后端自身的机制验证清理。
|
||||
|
||||
### 操作系统隔离和崩溃回收
|
||||
|
||||
| 平台 | 实现 | 崩溃回收与限制 |
|
||||
|
|
|
|||
|
|
@ -580,6 +580,6 @@ token 与成本是否存在取决于底层模型/Agent 事件是否上报 usage
|
|||
| 图校验 | `internal/workflow/validation.go` |
|
||||
| 表达式 / JSONPath / 汇聚 | `internal/workflow/expression.go`、`jsonpath.go`、`join.go` |
|
||||
| dry-run / replay 数据 | `internal/workflow/dry_run.go`、`internal/handler/workflow_run.go` |
|
||||
| 画布前端 | `web/static/js/workflows.js` |
|
||||
| 画布前端 | `web/frontend/src/pages/workflows/` |
|
||||
| 流程 API | `internal/handler/workflow.go` |
|
||||
| 角色绑定 | `internal/config/config.go`(`workflow_id` 字段) |
|
||||
|
|
|
|||
2
go.mod
|
|
@ -10,6 +10,7 @@ require (
|
|||
github.com/creack/pty v1.1.24
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/google/jsonschema-go v0.4.2
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/larksuite/oapi-sdk-go/v3 v3.4.22
|
||||
|
|
@ -44,7 +45,6 @@ require (
|
|||
github.com/go-resty/resty/v2 v2.6.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/gogo/protobuf v1.3.2 // indirect
|
||||
github.com/google/jsonschema-go v0.4.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
|
|
|
|||
BIN
images/dark.png
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 419 KiB |
|
Before Width: | Height: | Size: 941 KiB After Width: | Height: | Size: 586 KiB |
|
After Width: | Height: | Size: 322 KiB |
|
Before Width: | Height: | Size: 741 KiB After Width: | Height: | Size: 315 KiB |
|
Before Width: | Height: | Size: 498 KiB After Width: | Height: | Size: 480 KiB |
|
Before Width: | Height: | Size: 775 KiB After Width: | Height: | Size: 408 KiB |
|
|
@ -5,8 +5,6 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
|
@ -17,14 +15,12 @@ import (
|
|||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
"cyberstrike-ai/internal/mcp/builtin"
|
||||
"cyberstrike-ai/internal/openai"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Agent AI代理
|
||||
type Agent struct {
|
||||
openAIClient *openai.Client
|
||||
config *config.OpenAIConfig
|
||||
agentConfig *config.AgentConfig
|
||||
mcpServer *mcp.Server
|
||||
|
|
@ -67,30 +63,7 @@ func NewAgent(cfg *config.OpenAIConfig, agentCfg *config.AgentConfig, mcpServer
|
|||
maxIterations = 30
|
||||
}
|
||||
|
||||
// 配置HTTP Transport,优化连接管理和超时设置
|
||||
transport := &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 300 * time.Second,
|
||||
KeepAlive: 300 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 10,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 30 * time.Second,
|
||||
ResponseHeaderTimeout: 60 * time.Minute, // 响应头超时:增加到15分钟,应对大响应
|
||||
DisableKeepAlives: false, // 启用连接复用
|
||||
}
|
||||
|
||||
// 增加超时时间到30分钟,以支持长时间运行的AI推理
|
||||
// 特别是当使用流式响应或处理复杂任务时
|
||||
httpClient := &http.Client{
|
||||
Timeout: 30 * time.Minute, // 从5分钟增加到30分钟
|
||||
Transport: transport,
|
||||
}
|
||||
llmClient := openai.NewClient(cfg, httpClient, logger)
|
||||
|
||||
return &Agent{
|
||||
openAIClient: llmClient,
|
||||
config: cfg,
|
||||
agentConfig: agentCfg,
|
||||
mcpServer: mcpServer,
|
||||
|
|
@ -217,9 +190,11 @@ type Tool struct {
|
|||
|
||||
// FunctionDefinition 函数定义
|
||||
type FunctionDefinition struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]interface{} `json:"parameters"`
|
||||
OutputSchema map[string]interface{} `json:"-"`
|
||||
Annotations map[string]bool `json:"-"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]interface{} `json:"parameters"`
|
||||
}
|
||||
|
||||
// Error OpenAI错误
|
||||
|
|
@ -340,7 +315,8 @@ func (a *Agent) getAvailableTools(roleTools []string) []Tool {
|
|||
tools = append(tools, Tool{
|
||||
Type: "function",
|
||||
Function: FunctionDefinition{
|
||||
Name: mcpTool.Name,
|
||||
Name: mcpTool.Name,
|
||||
OutputSchema: mcpTool.OutputSchema, Annotations: mcpTool.Annotations,
|
||||
Description: description, // 使用简短描述减少token消耗
|
||||
Parameters: convertedSchema,
|
||||
},
|
||||
|
|
@ -366,13 +342,6 @@ func (a *Agent) getAvailableTools(roleTools []string) []Tool {
|
|||
// 外部工具使用 "mcpName::toolName" 作为toolKey
|
||||
externalToolKey := externalTool.Name
|
||||
|
||||
// 如果指定了角色工具列表,只添加在列表中的工具
|
||||
if len(roleToolSet) > 0 {
|
||||
if !roleToolSet[externalToolKey] {
|
||||
continue // 不在角色工具列表中,跳过
|
||||
}
|
||||
}
|
||||
|
||||
// 解析工具名称:mcpName::toolName
|
||||
var mcpName, actualToolName string
|
||||
if idx := strings.Index(externalTool.Name, "::"); idx > 0 {
|
||||
|
|
@ -418,9 +387,17 @@ func (a *Agent) getAvailableTools(roleTools []string) []Tool {
|
|||
// 保存名称映射关系(OpenAI格式 -> 原始格式)
|
||||
extMap[openAIName] = externalTool.Name
|
||||
|
||||
// 如果指定了角色工具列表,只添加在列表中的工具
|
||||
if len(roleToolSet) > 0 {
|
||||
if !roleToolSet[externalToolKey] {
|
||||
continue // 不在角色工具列表中,跳过
|
||||
}
|
||||
}
|
||||
|
||||
tools = append(tools, Tool{
|
||||
Type: "function",
|
||||
Function: FunctionDefinition{
|
||||
OutputSchema: externalTool.OutputSchema, Annotations: externalTool.Annotations,
|
||||
Name: openAIName, // 使用符合OpenAI规范的名称
|
||||
Description: description,
|
||||
Parameters: convertedSchema,
|
||||
|
|
@ -514,10 +491,11 @@ func (a *Agent) convertToOpenAIType(configType string) string {
|
|||
|
||||
// ToolExecutionResult MCP 工具执行结果(供 Agent 桥与监控落库使用)。
|
||||
type ToolExecutionResult struct {
|
||||
Result string
|
||||
ExecutionID string
|
||||
IsError bool
|
||||
Blocked bool
|
||||
StructuredContent map[string]interface{}
|
||||
Result string
|
||||
ExecutionID string
|
||||
IsError bool
|
||||
Blocked bool
|
||||
}
|
||||
|
||||
func buildToolFailureMessage(toolName, detail string, err error) string {
|
||||
|
|
@ -615,10 +593,11 @@ func (a *Agent) executeToolViaMCP(ctx context.Context, toolName string, args map
|
|||
resultStr := resultText.String()
|
||||
|
||||
return &ToolExecutionResult{
|
||||
Result: resultStr,
|
||||
ExecutionID: executionID,
|
||||
IsError: result != nil && result.IsError,
|
||||
Blocked: result != nil && result.Blocked,
|
||||
Result: resultStr,
|
||||
StructuredContent: result.StructuredContent,
|
||||
ExecutionID: executionID,
|
||||
IsError: result != nil && result.IsError,
|
||||
Blocked: result != nil && result.Blocked,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ package agent
|
|||
const GeneratedContextTypeKey = "_csai_generated_context_type"
|
||||
const PlanExecuteExecutorContext = "plan_execute_executor"
|
||||
const PlanExecuteReplannerContext = "plan_execute_replanner"
|
||||
const OutputTruncationContinueContext = "output_truncation_continue"
|
||||
|
||||
func IsGeneratedExecutionContext(kind string) bool {
|
||||
return kind == PlanExecuteExecutorContext || kind == PlanExecuteReplannerContext
|
||||
return kind == PlanExecuteExecutorContext || kind == PlanExecuteReplannerContext || kind == OutputTruncationContinueContext
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,23 @@
|
|||
package agent
|
||||
package agent_test
|
||||
|
||||
import (
|
||||
"cyberstrike-ai/internal/knowledge"
|
||||
"cyberstrike-ai/internal/mcp/builtin"
|
||||
"go.uber.org/zap"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/agent"
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/knowledge"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
"cyberstrike-ai/internal/mcp/builtin"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestRegisteredKnowledgeToolsAreAvailableToDefaultAndSelectedRoles(t *testing.T) {
|
||||
a := setupTestAgent(t)
|
||||
knowledge.RegisterKnowledgeTool(a.mcpServer, nil, nil, zap.NewNop())
|
||||
logger := zap.NewNop()
|
||||
mcpServer := mcp.NewServer(logger)
|
||||
a := agent.NewAgent(&config.OpenAIConfig{APIKey: "test-key", BaseURL: "https://api.test.com/v1", Model: "test-model"},
|
||||
&config.AgentConfig{MaxIterations: 10}, mcpServer, nil, logger, 10)
|
||||
knowledge.RegisterKnowledgeTool(mcpServer, nil, nil, logger)
|
||||
for _, role := range [][]string{nil, {builtin.ToolSearchKnowledgeBase, builtin.ToolListKnowledgeRiskTypes}} {
|
||||
available := map[string]bool{}
|
||||
for _, tool := range a.ToolsForRole(role) {
|
||||
|
|
@ -27,4 +35,4 @@ func TestRegisteredKnowledgeToolsAreAvailableToDefaultAndSelectedRoles(t *testin
|
|||
t.Fatal("role restriction bypassed")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -16,13 +16,14 @@ const (
|
|||
StatusCancelled = "cancelled"
|
||||
StatusAwaitingHITL = "awaiting_hitl"
|
||||
|
||||
ReasonVerified = "verified"
|
||||
ReasonPendingTools = "pending_tool_executions"
|
||||
ReasonEmptyResponse = "empty_response"
|
||||
ReasonAwaitingHITL = "awaiting_hitl"
|
||||
ReasonFailed = "failed"
|
||||
ReasonCancelled = "cancelled"
|
||||
ReasonMissingEvidence = "missing_execution_evidence"
|
||||
ReasonVerified = "verified"
|
||||
ReasonPendingTools = "pending_tool_executions"
|
||||
ReasonPendingToolsCancelled = "pending_tool_executions_cancelled"
|
||||
ReasonEmptyResponse = "empty_response"
|
||||
ReasonAwaitingHITL = "awaiting_hitl"
|
||||
ReasonFailed = "failed"
|
||||
ReasonCancelled = "cancelled"
|
||||
ReasonMissingEvidence = "missing_execution_evidence"
|
||||
)
|
||||
|
||||
// Decision is the single contract that may promote an agent run to a final
|
||||
|
|
@ -43,6 +44,8 @@ type Decision struct {
|
|||
ConversationID string `json:"conversationId,omitempty"`
|
||||
AssistantMessageID string `json:"messageId,omitempty"`
|
||||
CandidateResponseLen int `json:"candidateResponseLen,omitempty"`
|
||||
|
||||
UnfinishedPlanSteps []multiagent.PlanStep `json:"unfinishedPlanSteps,omitempty"`
|
||||
}
|
||||
|
||||
type Input struct {
|
||||
|
|
@ -74,6 +77,9 @@ func FromRunResult(db *database.DB, result *multiagent.RunResult, in Input) Deci
|
|||
}
|
||||
d := Decide(db, in)
|
||||
if result != nil {
|
||||
if !d.Finalizable && len(result.UnfinishedPlanSteps) > 0 {
|
||||
d.UnfinishedPlanSteps = result.UnfinishedPlanSteps
|
||||
}
|
||||
result.Finalized = d.Finalized
|
||||
result.Status = d.Status
|
||||
result.CompletionReason = d.CompletionReason
|
||||
|
|
@ -114,13 +120,6 @@ func Decide(db *database.DB, in Input) Decision {
|
|||
d.MissingChecks = append(d.MissingChecks, "workflow is awaiting HITL approval")
|
||||
return d
|
||||
}
|
||||
if isEmptyCandidate(text) {
|
||||
d.Status = StatusBlocked
|
||||
d.CompletionReason = ReasonEmptyResponse
|
||||
d.EvidenceVerified = false
|
||||
d.MissingChecks = append(d.MissingChecks, "assistant final text is empty or only an empty-response placeholder")
|
||||
return d
|
||||
}
|
||||
switch status {
|
||||
case StatusInProgress, StatusBlocked, StatusFailed, StatusCancelled, StatusAwaitingHITL:
|
||||
d.Status = status
|
||||
|
|
@ -128,10 +127,24 @@ func Decide(db *database.DB, in Input) Decision {
|
|||
if d.CompletionReason == ReasonVerified {
|
||||
d.CompletionReason = status
|
||||
}
|
||||
if (d.CompletionReason == multiagent.ReasonUnfinishedPlan ||
|
||||
d.CompletionReason == multiagent.ReasonIterationLimit ||
|
||||
d.CompletionReason == multiagent.ReasonPlanningIterationLimit) && isEmptyCandidate(text) {
|
||||
d.FinalText = ""
|
||||
d.CandidateResponseLen = 0
|
||||
}
|
||||
d.MissingChecks = append(d.MissingChecks, "agent run status is "+status)
|
||||
return d
|
||||
}
|
||||
|
||||
if isEmptyCandidate(text) {
|
||||
d.Status = StatusBlocked
|
||||
d.CompletionReason = ReasonEmptyResponse
|
||||
d.EvidenceVerified = false
|
||||
d.MissingChecks = append(d.MissingChecks, "assistant final text is empty or only an empty-response placeholder")
|
||||
return d
|
||||
}
|
||||
|
||||
pending := pendingExecutions(db, in.MCPExecutionIDs)
|
||||
if len(pending) > 0 {
|
||||
d.Status = StatusInProgress
|
||||
|
|
@ -181,6 +194,9 @@ func ResponsePayload(d Decision, extra map[string]interface{}) map[string]interf
|
|||
if d.AgentMode != "" {
|
||||
out["agentMode"] = d.AgentMode
|
||||
}
|
||||
if len(d.UnfinishedPlanSteps) > 0 {
|
||||
out["unfinishedPlanSteps"] = d.UnfinishedPlanSteps
|
||||
}
|
||||
for k, v := range extra {
|
||||
out[k] = v
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
package agentfinalizer
|
||||
|
||||
import (
|
||||
"cyberstrike-ai/internal/multiagent"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/multiagent"
|
||||
)
|
||||
|
||||
func TestRuntimeIterationLimitCannotBecomeCompleted(t *testing.T) {
|
||||
|
|
@ -14,3 +15,19 @@ func TestRuntimeIterationLimitCannotBecomeCompleted(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncatedOutputRetainsReasonWithoutFinalText(t *testing.T) {
|
||||
result := &multiagent.RunResult{RuntimeStatus: StatusBlocked, RuntimeCompletionReason: multiagent.ReasonModelOutputTruncated}
|
||||
decision := FromRunResult(nil, result, Input{})
|
||||
if decision.Finalized || decision.Finalizable || decision.Status != StatusBlocked || decision.CompletionReason != multiagent.ReasonModelOutputTruncated {
|
||||
t.Fatalf("unexpected delivery: %+v", decision)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncatedOutputKeepsCandidateText(t *testing.T) {
|
||||
result := &multiagent.RunResult{Response: "已生成的前半段", RuntimeStatus: StatusBlocked, RuntimeCompletionReason: multiagent.ReasonModelOutputTruncated}
|
||||
decision := FromRunResult(nil, result, Input{})
|
||||
if decision.Finalizable || decision.Finalized || decision.FinalText != "已生成的前半段" || decision.CompletionReason != multiagent.ReasonModelOutputTruncated {
|
||||
t.Fatalf("unexpected delivery: %+v", decision)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,12 @@
|
|||
package agentruntime
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxRecordBytes = 32 * 1024 * 1024
|
||||
|
|
@ -29,6 +24,7 @@ type runRequest struct {
|
|||
type record struct {
|
||||
Type string `json:"type"`
|
||||
Version int `json:"version,omitempty"`
|
||||
KeepAlive bool `json:"keepAlive,omitempty"`
|
||||
Request *runRequest `json:"request,omitempty"`
|
||||
Event *Event `json:"event,omitempty"`
|
||||
Call *ToolCall `json:"call,omitempty"`
|
||||
|
|
@ -85,7 +81,9 @@ func workerCandidates() []string {
|
|||
return candidates
|
||||
}
|
||||
|
||||
// Run owns one isolated worker and reaps it on every exit. Tool execution stays in the host.
|
||||
// Run reuses a warm pooled worker when one is healthy, otherwise starts a fresh
|
||||
// process. Tool execution stays in the host. A worker only returns to the pool
|
||||
// after a clean result with no cancel, timeout or protocol error.
|
||||
func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit func(Event), bind func(Control) func()) (*Result, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
|
|
@ -102,7 +100,7 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
|
|||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
worker, err := ResolveWorker(p.WorkerPath)
|
||||
workerPath, err := ResolveWorker(p.WorkerPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -110,204 +108,16 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
|
|||
if node == "" {
|
||||
node = "node"
|
||||
}
|
||||
scratchParent, err := os.MkdirTemp("", "cyberstrike-pi-host-")
|
||||
w, err := pool.acquire(ctx, node, workerPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(scratchParent)
|
||||
cmd := exec.Command(node, worker)
|
||||
cmd.Env = append(os.Environ(), "CYBERSTRIKE_PI_TMP_PARENT="+scratchParent)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
stdin.Close()
|
||||
return nil, err
|
||||
}
|
||||
// Worker protocol carries failures. Never forward arbitrary stderr (which may include provider secrets).
|
||||
cmd.Stderr = io.Discard
|
||||
if err = cmd.Start(); err != nil {
|
||||
stdin.Close()
|
||||
stdout.Close()
|
||||
return nil, fmt.Errorf("start Pi worker: %w", err)
|
||||
}
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
ioCtx, stopIO := context.WithCancel(context.Background())
|
||||
defer stopIO()
|
||||
var writeMu sync.Mutex
|
||||
write := func(v any) error {
|
||||
body, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(body) > maxRecordBytes {
|
||||
return errors.New("Pi request exceeds protocol record limit")
|
||||
}
|
||||
writeMu.Lock()
|
||||
defer writeMu.Unlock()
|
||||
_, err = stdin.Write(append(body, '\n'))
|
||||
return err
|
||||
}
|
||||
incoming := make(chan record, 32)
|
||||
readDone := make(chan error, 1)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(stdout)
|
||||
scanner.Buffer(make([]byte, 64*1024), maxRecordBytes+1)
|
||||
for scanner.Scan() {
|
||||
var r record
|
||||
if err := json.Unmarshal(scanner.Bytes(), &r); err != nil {
|
||||
readDone <- fmt.Errorf("invalid Pi protocol JSON: %w", err)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case incoming <- r:
|
||||
case <-ioCtx.Done():
|
||||
readDone <- ioCtx.Err()
|
||||
return
|
||||
}
|
||||
}
|
||||
readDone <- scanner.Err()
|
||||
}()
|
||||
defer func() {
|
||||
cancel()
|
||||
stopIO()
|
||||
stdin.Close()
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
stdout.Close()
|
||||
}()
|
||||
readyTimeout := time.NewTimer(20 * time.Second)
|
||||
defer readyTimeout.Stop()
|
||||
select {
|
||||
case r := <-incoming:
|
||||
if r.Type != "ready" || r.Version != ProtocolVersion || r.SDKVersion != "1.5.2" {
|
||||
return nil, errors.New("Pi runtime protocol mismatch")
|
||||
}
|
||||
case err := <-readDone:
|
||||
return nil, fmt.Errorf("Pi worker exited before handshake: %v", err)
|
||||
case <-readyTimeout.C:
|
||||
return nil, errors.New("Pi worker startup timeout")
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
// Older protocol v1 workers require a profile object. Keep it disabled.
|
||||
run := runRequest{Request: req, LegacyProfile: json.RawMessage(`{"enabled":false}`)}
|
||||
if err = write(record{Type: "run", Version: ProtocolVersion, Request: &run}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bind != nil {
|
||||
unbind := bind(Control{
|
||||
Steer: func(s string) error { return write(map[string]any{"type": "steer", "message": s}) },
|
||||
Cancel: func() error { cancel(); return write(map[string]any{"type": "cancel"}) },
|
||||
})
|
||||
if unbind != nil {
|
||||
defer unbind()
|
||||
}
|
||||
}
|
||||
type executed struct {
|
||||
call string
|
||||
result ToolResult
|
||||
done chan struct{}
|
||||
}
|
||||
var toolMu sync.Mutex
|
||||
toolCache := map[string]*executed{}
|
||||
toolSlots := make(chan struct{}, 32)
|
||||
ctxDone := ctx.Done()
|
||||
var cancelDeadline <-chan time.Time
|
||||
var cancelTimer *time.Timer
|
||||
defer func() {
|
||||
if cancelTimer != nil {
|
||||
cancelTimer.Stop()
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case r := <-incoming:
|
||||
switch r.Type {
|
||||
case "event":
|
||||
if emit != nil && r.Event != nil {
|
||||
emit(*r.Event)
|
||||
}
|
||||
case "tool_call":
|
||||
if r.Call == nil || r.Call.ID == "" {
|
||||
return nil, errors.New("Pi tool call has no identity")
|
||||
}
|
||||
call := *r.Call
|
||||
select {
|
||||
case toolSlots <- struct{}{}:
|
||||
default:
|
||||
return nil, errors.New("Pi tool concurrency limit exceeded")
|
||||
}
|
||||
go func() {
|
||||
defer func() { <-toolSlots }()
|
||||
body, _ := json.Marshal(call)
|
||||
toolMu.Lock()
|
||||
cached := toolCache[call.ID]
|
||||
if cached == nil {
|
||||
cached = &executed{call: string(body), done: make(chan struct{})}
|
||||
toolCache[call.ID] = cached
|
||||
toolMu.Unlock()
|
||||
res := ToolResult{IsError: true, Content: "No host tool executor"}
|
||||
if execute != nil {
|
||||
var invokeErr error
|
||||
res, invokeErr = execute(runCtx, call)
|
||||
if invokeErr != nil {
|
||||
res.IsError = true
|
||||
res.Content = invokeErr.Error()
|
||||
}
|
||||
}
|
||||
cached.result = res
|
||||
close(cached.done)
|
||||
} else {
|
||||
toolMu.Unlock()
|
||||
}
|
||||
select {
|
||||
case <-cached.done:
|
||||
case <-runCtx.Done():
|
||||
return
|
||||
}
|
||||
res := cached.result
|
||||
if cached.call != string(body) {
|
||||
res = ToolResult{IsError: true, Content: "Tool call ID reused with different arguments"}
|
||||
}
|
||||
_ = write(map[string]any{"type": "tool_result", "id": call.ID, "result": res})
|
||||
}()
|
||||
case "result":
|
||||
if r.Result == nil {
|
||||
return nil, errors.New("Pi returned an empty result")
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return r.Result, ctx.Err()
|
||||
}
|
||||
if r.Result.Error != "" {
|
||||
return r.Result, fmt.Errorf("Pi runtime error: %s", r.Result.Error)
|
||||
}
|
||||
if r.Result.Status == "canceled" {
|
||||
return r.Result, context.Canceled
|
||||
}
|
||||
return r.Result, nil
|
||||
case "fatal":
|
||||
return nil, fmt.Errorf("Pi protocol failure: %s", r.Error)
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected Pi record: %s", r.Type)
|
||||
}
|
||||
case err := <-readDone:
|
||||
// All queued protocol records precede EOF; process them before interpreting exit.
|
||||
if len(incoming) > 0 {
|
||||
readDone <- err
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("Pi worker exited without a result: %v", err)
|
||||
case <-ctxDone:
|
||||
ctxDone = nil
|
||||
_ = write(map[string]any{"type": "cancel"})
|
||||
cancelTimer = time.NewTimer(2 * time.Second)
|
||||
cancelDeadline = cancelTimer.C
|
||||
case <-cancelDeadline:
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
res, runErr := w.run(ctx, req, execute, emit, bind)
|
||||
w.runs++
|
||||
if runErr == nil && ctx.Err() == nil && !w.writeFailed.Load() && len(w.incoming) == 0 && w.runs < poolMaxRunsPerWorker {
|
||||
pool.release(node, workerPath, w)
|
||||
} else {
|
||||
w.destroy()
|
||||
}
|
||||
return res, runErr
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package agentruntime
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
|
@ -17,10 +18,11 @@ func fixtureWorker(t *testing.T, body string) Pi {
|
|||
if err != nil {
|
||||
t.Skip("Node is unavailable")
|
||||
}
|
||||
t.Cleanup(CloseIdleWorkers)
|
||||
path := filepath.Join(t.TempDir(), "worker.cjs")
|
||||
script := `const readline=require('node:readline');
|
||||
const send=x=>process.stdout.write(JSON.stringify(x)+'\n');
|
||||
send({type:'ready',version:1,sdkVersion:'1.5.2'});
|
||||
send({type:'ready',version:1,sdkVersion:'1.7.0'});
|
||||
const input=readline.createInterface({input:process.stdin});
|
||||
` + body
|
||||
if err = os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||
|
|
@ -98,12 +100,49 @@ if(r.type==='cancel')send({type:'result',result:{status:'canceled',response:'par
|
|||
}
|
||||
}
|
||||
|
||||
func TestPiReportsProtocolFailures(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
write string
|
||||
want string
|
||||
wantSyntax bool
|
||||
}{
|
||||
{
|
||||
name: "blank line",
|
||||
write: "process.stdout.write(' \\t\\n');",
|
||||
want: "read Pi worker output: blank Pi protocol line 2",
|
||||
},
|
||||
{
|
||||
name: "partial JSON at EOF",
|
||||
write: "process.stdout.write('{\"type\":', () => process.exit(0));",
|
||||
want: "read Pi worker output: invalid Pi protocol JSON on line 2: unexpected end of JSON input",
|
||||
wantSyntax: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
p := fixtureWorker(t, "input.once('line', () => {"+tt.write+"});")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
result, err := p.Run(ctx, Request{}, nil, nil, nil)
|
||||
if result != nil || err == nil || err.Error() != tt.want {
|
||||
t.Fatalf("got result=%+v, err=%v, want %q", result, err, tt.want)
|
||||
}
|
||||
var syntaxErr *json.SyntaxError
|
||||
if errors.As(err, &syntaxErr) != tt.wantSyntax {
|
||||
t.Fatalf("got syntax error %v, want syntax error: %t", syntaxErr, tt.wantSyntax)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPiUnexpectedExitIsNotSuccess(t *testing.T) {
|
||||
p := fixtureWorker(t, `input.on('line',()=>process.exit(0));`)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := p.Run(ctx, Request{}, nil, nil, nil); err == nil {
|
||||
t.Fatal("worker exit without final result was accepted")
|
||||
result, err := p.Run(ctx, Request{}, nil, nil, nil)
|
||||
if result != nil || err == nil || err.Error() != "Pi worker closed stdout without a result" {
|
||||
t.Fatalf("got result=%+v, err=%v, want EOF without a result", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,364 @@
|
|||
package agentruntime
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
poolMaxIdle = 4
|
||||
poolIdleTTL = 2 * time.Minute
|
||||
poolMaxRunsPerWorker = 64
|
||||
)
|
||||
|
||||
type poolKey struct {
|
||||
node string
|
||||
worker string
|
||||
}
|
||||
|
||||
// piWorker owns one warm Node process and its protocol pipes across serial runs.
|
||||
type piWorker struct {
|
||||
cmd *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
stdout io.ReadCloser
|
||||
incoming chan record
|
||||
readDone chan error
|
||||
writeMu sync.Mutex
|
||||
writeFailed atomic.Bool
|
||||
ioCancel context.CancelFunc
|
||||
scratchParent string
|
||||
runs int
|
||||
lastUsed time.Time
|
||||
destroyOnce sync.Once
|
||||
}
|
||||
|
||||
type workerPool struct {
|
||||
mu sync.Mutex
|
||||
idle map[poolKey][]*piWorker
|
||||
}
|
||||
|
||||
var pool = &workerPool{idle: map[poolKey][]*piWorker{}}
|
||||
|
||||
func startPiWorker(ctx context.Context, node, workerPath string) (*piWorker, error) {
|
||||
scratchParent, err := os.MkdirTemp("", "cyberstrike-pi-host-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cmd := exec.Command(node, workerPath)
|
||||
cmd.Env = append(os.Environ(), "CYBERSTRIKE_PI_TMP_PARENT="+scratchParent)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
os.RemoveAll(scratchParent)
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
stdin.Close()
|
||||
os.RemoveAll(scratchParent)
|
||||
return nil, err
|
||||
}
|
||||
// Worker protocol carries failures. Never forward arbitrary stderr (which may include provider secrets).
|
||||
cmd.Stderr = io.Discard
|
||||
if err = cmd.Start(); err != nil {
|
||||
stdin.Close()
|
||||
stdout.Close()
|
||||
os.RemoveAll(scratchParent)
|
||||
return nil, fmt.Errorf("start Pi worker: %w", err)
|
||||
}
|
||||
ioCtx, ioCancel := context.WithCancel(context.Background())
|
||||
w := &piWorker{cmd: cmd, stdin: stdin, stdout: stdout, incoming: make(chan record, 32),
|
||||
readDone: make(chan error, 1), ioCancel: ioCancel, scratchParent: scratchParent}
|
||||
go w.readLoop(ioCtx)
|
||||
readyTimeout := time.NewTimer(20 * time.Second)
|
||||
defer readyTimeout.Stop()
|
||||
select {
|
||||
case r := <-w.incoming:
|
||||
if r.Type != "ready" || r.Version != ProtocolVersion || r.SDKVersion != "1.7.0" {
|
||||
w.destroy()
|
||||
return nil, errors.New("Pi runtime protocol mismatch")
|
||||
}
|
||||
case err := <-w.readDone:
|
||||
w.destroy()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Pi worker handshake: %w", err)
|
||||
}
|
||||
return nil, errors.New("Pi worker closed stdout before handshake")
|
||||
case <-readyTimeout.C:
|
||||
w.destroy()
|
||||
return nil, errors.New("Pi worker startup timeout")
|
||||
case <-ctx.Done():
|
||||
w.destroy()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *piWorker) readLoop(ioCtx context.Context) {
|
||||
scanner := bufio.NewScanner(w.stdout)
|
||||
scanner.Buffer(make([]byte, 64*1024), maxRecordBytes+1)
|
||||
for line := 1; scanner.Scan(); line++ {
|
||||
data := scanner.Bytes()
|
||||
var r record
|
||||
if err := json.Unmarshal(data, &r); err != nil {
|
||||
if len(bytes.TrimSpace(data)) == 0 {
|
||||
w.readDone <- fmt.Errorf("blank Pi protocol line %d", line)
|
||||
} else {
|
||||
w.readDone <- fmt.Errorf("invalid Pi protocol JSON on line %d: %w", line, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
select {
|
||||
case w.incoming <- r:
|
||||
case <-ioCtx.Done():
|
||||
w.readDone <- ioCtx.Err()
|
||||
return
|
||||
}
|
||||
}
|
||||
w.readDone <- scanner.Err()
|
||||
}
|
||||
|
||||
func (w *piWorker) write(v any) error {
|
||||
body, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(body) > maxRecordBytes {
|
||||
return errors.New("Pi request exceeds protocol record limit")
|
||||
}
|
||||
w.writeMu.Lock()
|
||||
defer w.writeMu.Unlock()
|
||||
_, err = w.stdin.Write(append(body, '\n'))
|
||||
if err != nil {
|
||||
w.writeFailed.Store(true)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *piWorker) alive() bool {
|
||||
select {
|
||||
case <-w.readDone:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (w *piWorker) destroy() {
|
||||
w.destroyOnce.Do(func() {
|
||||
w.ioCancel()
|
||||
w.stdin.Close()
|
||||
if w.cmd.Process != nil {
|
||||
_ = w.cmd.Process.Kill()
|
||||
}
|
||||
_ = w.cmd.Wait()
|
||||
w.stdout.Close()
|
||||
os.RemoveAll(w.scratchParent)
|
||||
})
|
||||
}
|
||||
|
||||
func (p *workerPool) acquire(ctx context.Context, node, workerPath string) (*piWorker, error) {
|
||||
key := poolKey{node, workerPath}
|
||||
p.mu.Lock()
|
||||
list := p.idle[key]
|
||||
var chosen *piWorker
|
||||
var dead []*piWorker
|
||||
for len(list) > 0 {
|
||||
w := list[len(list)-1]
|
||||
list = list[:len(list)-1]
|
||||
if time.Since(w.lastUsed) > poolIdleTTL || !w.alive() {
|
||||
dead = append(dead, w)
|
||||
continue
|
||||
}
|
||||
chosen = w
|
||||
break
|
||||
}
|
||||
p.idle[key] = list
|
||||
p.mu.Unlock()
|
||||
for _, w := range dead {
|
||||
w.destroy()
|
||||
}
|
||||
if chosen != nil {
|
||||
return chosen, nil
|
||||
}
|
||||
return startPiWorker(ctx, node, workerPath)
|
||||
}
|
||||
|
||||
func (p *workerPool) release(node, workerPath string, w *piWorker) {
|
||||
key := poolKey{node, workerPath}
|
||||
w.lastUsed = time.Now()
|
||||
p.mu.Lock()
|
||||
list := p.idle[key]
|
||||
if len(list) >= poolMaxIdle {
|
||||
p.mu.Unlock()
|
||||
w.destroy()
|
||||
return
|
||||
}
|
||||
p.idle[key] = append(list, w)
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// CloseIdleWorkers reaps every pooled idle process for tests and graceful shutdown.
|
||||
func CloseIdleWorkers() {
|
||||
pool.mu.Lock()
|
||||
all := pool.idle
|
||||
pool.idle = map[poolKey][]*piWorker{}
|
||||
pool.mu.Unlock()
|
||||
for _, list := range all {
|
||||
for _, w := range list {
|
||||
w.destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// run drives one keepAlive run over the worker. The caller decides whether the
|
||||
// worker returns to the pool; any cancel, timeout or protocol error destroys it.
|
||||
func (w *piWorker) run(ctx context.Context, req Request, execute ToolExecutor, emit func(Event), bind func(Control) func()) (*Result, error) {
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
var toolWG sync.WaitGroup
|
||||
var inFlightTools atomic.Int32
|
||||
defer func() {
|
||||
cancel()
|
||||
toolWG.Wait()
|
||||
}()
|
||||
run := runRequest{Request: req, LegacyProfile: json.RawMessage(`{"enabled":false}`)}
|
||||
if err := w.write(record{Type: "run", Version: ProtocolVersion, KeepAlive: true, Request: &run}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bind != nil {
|
||||
unbind := bind(Control{
|
||||
Steer: func(s string) error { return w.write(map[string]any{"type": "steer", "message": s}) },
|
||||
Cancel: func() error { cancel(); return w.write(map[string]any{"type": "cancel"}) },
|
||||
})
|
||||
if unbind != nil {
|
||||
defer unbind()
|
||||
}
|
||||
}
|
||||
type executed struct {
|
||||
call string
|
||||
result ToolResult
|
||||
done chan struct{}
|
||||
}
|
||||
var toolMu sync.Mutex
|
||||
toolCache := map[string]*executed{}
|
||||
toolSlots := make(chan struct{}, 32)
|
||||
ctxDone := ctx.Done()
|
||||
var cancelDeadline <-chan time.Time
|
||||
var cancelTimer *time.Timer
|
||||
defer func() {
|
||||
if cancelTimer != nil {
|
||||
cancelTimer.Stop()
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case r := <-w.incoming:
|
||||
switch r.Type {
|
||||
case "event":
|
||||
if emit != nil && r.Event != nil {
|
||||
emit(*r.Event)
|
||||
}
|
||||
case "tool_call":
|
||||
if r.Call == nil || r.Call.ID == "" {
|
||||
return nil, errors.New("Pi tool call has no identity")
|
||||
}
|
||||
call := *r.Call
|
||||
select {
|
||||
case toolSlots <- struct{}{}:
|
||||
default:
|
||||
return nil, errors.New("Pi tool concurrency limit exceeded")
|
||||
}
|
||||
toolWG.Add(1)
|
||||
inFlightTools.Add(1)
|
||||
go func() {
|
||||
defer toolWG.Done()
|
||||
defer inFlightTools.Add(-1)
|
||||
defer func() { <-toolSlots }()
|
||||
body, _ := json.Marshal(call)
|
||||
toolMu.Lock()
|
||||
cached := toolCache[call.ID]
|
||||
if cached == nil {
|
||||
cached = &executed{call: string(body), done: make(chan struct{})}
|
||||
toolCache[call.ID] = cached
|
||||
toolMu.Unlock()
|
||||
res := ToolResult{IsError: true, Content: "No host tool executor"}
|
||||
if execute != nil {
|
||||
var invokeErr error
|
||||
res, invokeErr = execute(runCtx, call)
|
||||
if invokeErr != nil {
|
||||
res.IsError = true
|
||||
res.Content = invokeErr.Error()
|
||||
}
|
||||
}
|
||||
cached.result = res
|
||||
close(cached.done)
|
||||
} else {
|
||||
toolMu.Unlock()
|
||||
}
|
||||
select {
|
||||
case <-cached.done:
|
||||
case <-runCtx.Done():
|
||||
return
|
||||
}
|
||||
if runCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
res := cached.result
|
||||
if cached.call != string(body) {
|
||||
res = ToolResult{IsError: true, Content: "Tool call ID reused with different arguments"}
|
||||
}
|
||||
_ = w.write(map[string]any{"type": "tool_result", "id": call.ID, "result": res})
|
||||
}()
|
||||
case "result":
|
||||
if r.Result == nil {
|
||||
return nil, errors.New("Pi returned an empty result")
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return r.Result, ctx.Err()
|
||||
}
|
||||
if r.Result.Error != "" {
|
||||
return r.Result, fmt.Errorf("Pi runtime error: %s", r.Result.Error)
|
||||
}
|
||||
if r.Result.Status == "canceled" {
|
||||
return r.Result, context.Canceled
|
||||
}
|
||||
if inFlightTools.Load() > 0 {
|
||||
// A run that settled while sibling tool calls were still in flight cannot
|
||||
// safely share its stdio stream with a subsequent run; mark it non-reusable.
|
||||
w.writeFailed.Store(true)
|
||||
}
|
||||
return r.Result, nil
|
||||
case "fatal":
|
||||
return nil, fmt.Errorf("Pi protocol failure: %s", r.Error)
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected Pi record: %s", r.Type)
|
||||
}
|
||||
case err := <-w.readDone:
|
||||
// Drain records queued before the reader reported EOF or an error.
|
||||
if len(w.incoming) > 0 {
|
||||
w.readDone <- err
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read Pi worker output: %w", err)
|
||||
}
|
||||
return nil, errors.New("Pi worker closed stdout without a result")
|
||||
case <-ctxDone:
|
||||
ctxDone = nil
|
||||
_ = w.write(map[string]any{"type": "cancel"})
|
||||
cancelTimer = time.NewTimer(2 * time.Second)
|
||||
cancelDeadline = cancelTimer.C
|
||||
case <-cancelDeadline:
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
package agentruntime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const pidWorkerBody = `input.on('line',line=>{const r=JSON.parse(line);
|
||||
if(r.type==='run')send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
|
||||
if(r.type==='cancel')send({type:'result',result:{status:'canceled',response:String(process.pid),history:[]}});});`
|
||||
|
||||
func idleCount() int {
|
||||
pool.mu.Lock()
|
||||
defer pool.mu.Unlock()
|
||||
n := 0
|
||||
for _, list := range pool.idle {
|
||||
n += len(list)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestPoolReusesWarmWorkerAcrossRuns(t *testing.T) {
|
||||
p := fixtureWorker(t, pidWorkerBody)
|
||||
ctx := context.Background()
|
||||
var pids []string
|
||||
for i := 0; i < 3; i++ {
|
||||
res, err := p.Run(ctx, Request{RunID: fmt.Sprintf("reuse-%d", i)}, nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pids = append(pids, res.Response)
|
||||
}
|
||||
if pids[0] == "" || pids[0] != pids[1] || pids[1] != pids[2] {
|
||||
t.Fatalf("expected one reused worker PID, got %v", pids)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolCancelDestroysWorkerAndNextRunGetsFreshPID(t *testing.T) {
|
||||
p := fixtureWorker(t, `input.on('line',line=>{const r=JSON.parse(line);
|
||||
if(r.type==='run')send({type:'tool_call',call:{id:'wait',name:'wait',arguments:{}}});
|
||||
if(r.type==='tool_result')send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
|
||||
if(r.type==='cancel')send({type:'result',result:{status:'canceled',response:String(process.pid),history:[]}});});`)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
started := make(chan struct{})
|
||||
go func() { <-started; cancel() }()
|
||||
canceled, err := p.Run(ctx, Request{RunID: "cancel-me"}, func(c context.Context, _ ToolCall) (ToolResult, error) {
|
||||
close(started)
|
||||
<-c.Done()
|
||||
return ToolResult{}, c.Err()
|
||||
}, nil, nil)
|
||||
if err == nil || canceled == nil || canceled.Response == "" {
|
||||
t.Fatalf("expected canceled result with old PID, got result=%+v err=%v", canceled, err)
|
||||
}
|
||||
fresh, err := p.Run(context.Background(), Request{RunID: "fresh"}, func(context.Context, ToolCall) (ToolResult, error) {
|
||||
return ToolResult{Content: "ok"}, nil
|
||||
}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fresh.Response == "" || fresh.Response == canceled.Response {
|
||||
t.Fatalf("expected a fresh worker PID after cancel, old=%q new=%q", canceled.Response, fresh.Response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolConcurrentRunsRaceFreeAndCloseReapsIdle(t *testing.T) {
|
||||
p := fixtureWorker(t, pidWorkerBody)
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 64)
|
||||
for i := 0; i < 16; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 3; j++ {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
res, err := p.Run(ctx, Request{RunID: fmt.Sprintf("conc-%d-%d", i, j)}, nil, nil, nil)
|
||||
cancel()
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
if res.Response == "" {
|
||||
errs <- fmt.Errorf("empty worker PID")
|
||||
return
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if idleCount() == 0 {
|
||||
t.Fatal("expected pooled idle workers after concurrent runs")
|
||||
}
|
||||
CloseIdleWorkers()
|
||||
if n := idleCount(); n != 0 {
|
||||
t.Fatalf("CloseIdleWorkers left %d idle workers", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolDiscardsWorkerWhenResultArrivesWithInFlightSiblingTool(t *testing.T) {
|
||||
p := fixtureWorker(t, `let runCount=0;input.on('line',line=>{const r=JSON.parse(line);
|
||||
if(r.type==='run'){
|
||||
if(++runCount===1){
|
||||
send({type:'tool_call',call:{id:'fast',name:'fast',arguments:{}}});
|
||||
send({type:'tool_call',call:{id:'slow',name:'slow',arguments:{}}});
|
||||
} else {
|
||||
send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
|
||||
}
|
||||
}
|
||||
if(r.type==='tool_result'&&r.id==='fast'){
|
||||
send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
|
||||
}});`)
|
||||
|
||||
slowStarted := make(chan struct{})
|
||||
first, err := p.Run(context.Background(), Request{RunID: "early-settle"}, func(c context.Context, call ToolCall) (ToolResult, error) {
|
||||
if call.Name == "fast" {
|
||||
<-slowStarted
|
||||
return ToolResult{Content: "done"}, nil
|
||||
}
|
||||
close(slowStarted)
|
||||
<-c.Done()
|
||||
return ToolResult{}, c.Err()
|
||||
}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := p.Run(context.Background(), Request{RunID: "clean-followup"}, nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Response == "" || second.Response == "" || first.Response == second.Response {
|
||||
t.Fatalf("expected tainted worker to be replaced, first=%q second=%q", first.Response, second.Response)
|
||||
}
|
||||
}
|
||||
|
|
@ -55,7 +55,7 @@ func EnsurePiRuntime(ctx context.Context, node, configuredWorker string) error {
|
|||
scanner.Buffer(make([]byte, 4096), maxRecordBytes)
|
||||
var ready record
|
||||
if !scanner.Scan() || json.Unmarshal(scanner.Bytes(), &ready) != nil ||
|
||||
ready.Type != "ready" || ready.Version != ProtocolVersion || ready.SDKVersion != "1.5.2" {
|
||||
ready.Type != "ready" || ready.Version != ProtocolVersion || ready.SDKVersion != "1.7.0" {
|
||||
return fmt.Errorf("Pi runtime readiness check failed; verify Node.js >=22.19 and rebuild with bash scripts/build-pi-runtime.sh")
|
||||
}
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ func TestStartupPreparesWorkerAfterGoOnlyUpgrade(t *testing.T) {
|
|||
"package.json": `{"name":"startup-fixture","version":"1.0.0","scripts":{"build":"node -e \"require('fs').mkdirSync('dist');require('fs').copyFileSync('src/worker.js','dist/worker.js')\""}}`,
|
||||
"package-lock.json": `{"name":"startup-fixture","version":"1.0.0","lockfileVersion":3,"packages":{"":{"name":"startup-fixture","version":"1.0.0"}}}`,
|
||||
"tsconfig.json": `{}`,
|
||||
"src/worker.js": `console.log(JSON.stringify({type:'ready',version:1,sdkVersion:'1.5.2'}));process.stdin.resume();`,
|
||||
"src/worker.js": `console.log(JSON.stringify({type:'ready',version:1,sdkVersion:'1.7.0'}));process.stdin.resume();`,
|
||||
}
|
||||
for path, body := range files {
|
||||
if err := os.WriteFile(filepath.Join(root, path), []byte(body), 0o600); err != nil {
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ type Model struct {
|
|||
Headers map[string]string `json:"headers,omitempty"`
|
||||
ContextWindow int `json:"contextWindow"`
|
||||
MaxTokens int `json:"maxTokens"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
ImageInput *bool `json:"imageInput,omitempty"`
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
ExtraFields map[string]any `json:"extraFields,omitempty"`
|
||||
Compat map[string]any `json:"compat,omitempty"`
|
||||
|
|
@ -25,29 +27,64 @@ type Model struct {
|
|||
}
|
||||
|
||||
type Tool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
OutputSchema map[string]any `json:"outputSchema,omitempty"`
|
||||
Annotations map[string]bool `json:"annotations,omitempty"`
|
||||
Exposure string `json:"exposure,omitempty"`
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
PromptSnippet string `json:"promptSnippet,omitempty"`
|
||||
PromptGuidelines []string `json:"promptGuidelines,omitempty"`
|
||||
ExecutionMode string `json:"executionMode,omitempty"`
|
||||
}
|
||||
|
||||
// NativeWorkflow opts a background assessment into Pi's native lifecycle hooks.
|
||||
// Other callers keep their existing execution policy.
|
||||
type NativeWorkflow struct {
|
||||
Receipts []NativeReceipt `json:"receipts,omitempty"`
|
||||
ResumeRequired bool `json:"resumeRequired,omitempty"`
|
||||
Context string `json:"context,omitempty"`
|
||||
CompletionTool string `json:"completionTool"`
|
||||
CheckpointTool string `json:"checkpointTool,omitempty"`
|
||||
SegmentSeconds int `json:"segmentSeconds,omitempty"`
|
||||
WrapupPrompt string `json:"wrapupPrompt,omitempty"`
|
||||
WrapupTurns int `json:"wrapupTurns,omitempty"`
|
||||
SkillPaths []string `json:"skillPaths,omitempty"`
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
MIMEType string `json:"mimeType"`
|
||||
Data []byte `json:"data"`
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
GenerateOnly bool `json:"generateOnly,omitempty"`
|
||||
RunID string `json:"runId"`
|
||||
ConversationID string `json:"conversationId"`
|
||||
WorkingDir string `json:"workingDir,omitempty"`
|
||||
SystemPrompt string `json:"systemPrompt"`
|
||||
Message string `json:"message"`
|
||||
History json.RawMessage `json:"history,omitempty"`
|
||||
Model Model `json:"model"`
|
||||
FallbackModels []Model `json:"fallbackModels,omitempty"`
|
||||
RetryMax int `json:"retryMax,omitempty"`
|
||||
RetryMaxDelayMS int `json:"retryMaxDelayMs,omitempty"`
|
||||
Tools []Tool `json:"tools"`
|
||||
ToolSearch bool `json:"toolSearch"`
|
||||
ToolSearchMinTools int `json:"toolSearchMinTools,omitempty"`
|
||||
AlwaysVisibleTools []string `json:"alwaysVisibleTools,omitempty"`
|
||||
SessionDir string `json:"sessionDir,omitempty"`
|
||||
MaxTurns int `json:"maxTurns"`
|
||||
NativeWorkflow *NativeWorkflow `json:"nativeWorkflow,omitempty"`
|
||||
GenerateOnly bool `json:"generateOnly,omitempty"`
|
||||
RunID string `json:"runId"`
|
||||
ConversationID string `json:"conversationId"`
|
||||
WorkingDir string `json:"workingDir,omitempty"`
|
||||
SystemPrompt string `json:"systemPrompt"`
|
||||
// SystemPromptDynamic is appended verbatim, including its leading separator.
|
||||
SystemPromptDynamic string `json:"systemPromptDynamic,omitempty"`
|
||||
Message string `json:"message"`
|
||||
Images []Image `json:"images,omitempty"`
|
||||
History json.RawMessage `json:"history,omitempty"`
|
||||
Model Model `json:"model"`
|
||||
FallbackModels []Model `json:"fallbackModels,omitempty"`
|
||||
RetryMax int `json:"retryMax,omitempty"`
|
||||
RetryMaxDelayMS int `json:"retryMaxDelayMs,omitempty"`
|
||||
Tools []Tool `json:"tools"`
|
||||
SkillPaths []string `json:"skillPaths,omitempty"`
|
||||
SkillToolName string `json:"skillToolName,omitempty"`
|
||||
ToolSearch bool `json:"toolSearch"`
|
||||
ToolSearchMinTools int `json:"toolSearchMinTools,omitempty"`
|
||||
AlwaysVisibleTools []string `json:"alwaysVisibleTools,omitempty"`
|
||||
Codemode bool `json:"codemode,omitempty"`
|
||||
CodemodeMode string `json:"codemodeMode,omitempty"`
|
||||
CodemodeInlineBudget int `json:"codemodeInlineBudget,omitempty"`
|
||||
SessionDir string `json:"sessionDir,omitempty"`
|
||||
MaxTurns int `json:"maxTurns"`
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
|
|
@ -56,17 +93,20 @@ type Event struct {
|
|||
}
|
||||
|
||||
type ToolCall struct {
|
||||
ID string `json:"id"`
|
||||
ProviderID string `json:"providerId,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Arguments map[string]any `json:"arguments"`
|
||||
SessionEntryID string `json:"sessionEntryId,omitempty"`
|
||||
ID string `json:"id"`
|
||||
ProviderID string `json:"providerId,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Arguments map[string]any `json:"arguments"`
|
||||
}
|
||||
|
||||
type ToolResult struct {
|
||||
Content string `json:"content"`
|
||||
IsError bool `json:"isError,omitempty"`
|
||||
ExecutionID string `json:"executionId,omitempty"`
|
||||
Terminate bool `json:"terminate,omitempty"`
|
||||
Content string `json:"content"`
|
||||
Images []Image `json:"images,omitempty"`
|
||||
IsError bool `json:"isError,omitempty"`
|
||||
ExecutionID string `json:"executionId,omitempty"`
|
||||
Terminate bool `json:"terminate,omitempty"`
|
||||
StructuredContent map[string]any `json:"structuredContent,omitempty"`
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
|
|
@ -84,3 +124,14 @@ type Control struct {
|
|||
Steer func(string) error
|
||||
Cancel func() error
|
||||
}
|
||||
|
||||
// NativeReceipt associates a durable result with its exact Pi assistant entry.
|
||||
// Provider tool-call IDs alone are not unique across a multi-day session.
|
||||
type NativeReceipt struct {
|
||||
SessionEntryID string `json:"sessionEntryId"`
|
||||
ProviderID string `json:"providerId"`
|
||||
Name string `json:"name"`
|
||||
Content string `json:"content"`
|
||||
ExecutionID string `json:"executionId,omitempty"`
|
||||
IsError bool `json:"isError"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,11 +36,12 @@ type FrontMatter struct {
|
|||
|
||||
// OrchestratorMarkdown 从 agents 目录解析出的主代理(Deep 协调者)定义。
|
||||
type OrchestratorMarkdown struct {
|
||||
Filename string
|
||||
AgentName string // 写入 deep.Config.Name / 流式事件过滤
|
||||
DisplayName string
|
||||
Description string
|
||||
Instruction string
|
||||
Filename string
|
||||
AgentName string // 写入 deep.Config.Name / 流式事件过滤
|
||||
DisplayName string
|
||||
Description string
|
||||
Instruction string
|
||||
MaxIterations int
|
||||
}
|
||||
|
||||
// MarkdownDirLoad 一次扫描 agents 目录的结果(子代理不含主代理文件)。
|
||||
|
|
@ -243,11 +244,12 @@ func orchestratorFromParsed(filename string, fm FrontMatter, body string) (*Orch
|
|||
}
|
||||
agentID := sanitizeAgentAgentID(rawID)
|
||||
return &OrchestratorMarkdown{
|
||||
Filename: filepath.Base(strings.TrimSpace(filename)),
|
||||
AgentName: agentID,
|
||||
DisplayName: display,
|
||||
Description: strings.TrimSpace(fm.Description),
|
||||
Instruction: strings.TrimSpace(body),
|
||||
Filename: filepath.Base(strings.TrimSpace(filename)),
|
||||
AgentName: agentID,
|
||||
DisplayName: display,
|
||||
Description: strings.TrimSpace(fm.Description),
|
||||
Instruction: strings.TrimSpace(body),
|
||||
MaxIterations: fm.MaxIterations,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
|
@ -256,11 +258,12 @@ func orchestratorConfigFromOrchestrator(o *OrchestratorMarkdown) config.MultiAge
|
|||
return config.MultiAgentSubConfig{}
|
||||
}
|
||||
return config.MultiAgentSubConfig{
|
||||
ID: o.AgentName,
|
||||
Name: o.DisplayName,
|
||||
Description: o.Description,
|
||||
Instruction: o.Instruction,
|
||||
Kind: "orchestrator",
|
||||
ID: o.AgentName,
|
||||
Name: o.DisplayName,
|
||||
Description: o.Description,
|
||||
Instruction: o.Instruction,
|
||||
MaxIterations: o.MaxIterations,
|
||||
Kind: "orchestrator",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -73,8 +73,8 @@ func TestLoadMarkdownAgentsDir_ModeOrchestratorsCoexist(t *testing.T) {
|
|||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write(OrchestratorMarkdownFilename, "---\nname: Deep\n---\n\ndeep\n")
|
||||
write(OrchestratorPlanExecuteMarkdownFilename, "---\nname: PE\n---\n\npe\n")
|
||||
write(OrchestratorMarkdownFilename, "---\nname: Deep\nmax_iterations: 400\n---\n\ndeep\n")
|
||||
write(OrchestratorPlanExecuteMarkdownFilename, "---\nname: PE\nmax_iterations: 600\n---\n\npe\n")
|
||||
write(OrchestratorSupervisorMarkdownFilename, "---\nname: SV\n---\n\nsv\n")
|
||||
write("worker.md", "---\nid: worker\nname: Worker\n---\n\nw\n")
|
||||
|
||||
|
|
@ -82,10 +82,10 @@ func TestLoadMarkdownAgentsDir_ModeOrchestratorsCoexist(t *testing.T) {
|
|||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if load.Orchestrator == nil || load.Orchestrator.Instruction != "deep" {
|
||||
if load.Orchestrator == nil || load.Orchestrator.Instruction != "deep" || load.Orchestrator.MaxIterations != 400 {
|
||||
t.Fatalf("deep: %+v", load.Orchestrator)
|
||||
}
|
||||
if load.OrchestratorPlanExecute == nil || load.OrchestratorPlanExecute.Instruction != "pe" {
|
||||
if load.OrchestratorPlanExecute == nil || load.OrchestratorPlanExecute.Instruction != "pe" || load.OrchestratorPlanExecute.MaxIterations != 600 {
|
||||
t.Fatalf("pe: %+v", load.OrchestratorPlanExecute)
|
||||
}
|
||||
if load.OrchestratorSupervisor == nil || load.OrchestratorSupervisor.Instruction != "sv" {
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ import (
|
|||
"cyberstrike-ai/internal/mcp"
|
||||
"cyberstrike-ai/internal/mcp/builtin"
|
||||
"cyberstrike-ai/internal/monitor"
|
||||
"cyberstrike-ai/internal/pluginhub"
|
||||
|
||||
"cyberstrike-ai/internal/robot"
|
||||
"cyberstrike-ai/internal/security"
|
||||
|
|
@ -77,6 +78,8 @@ type App struct {
|
|||
c2Handler *handler.C2Handler // C2 REST(与 Manager 生命周期同步)
|
||||
storageHandler *handler.StorageHandler // 运行空间占用统计与垃圾清理
|
||||
auditSvc *audit.Service
|
||||
pluginHub *pluginhub.Manager
|
||||
instanceUnlock func()
|
||||
}
|
||||
|
||||
// New 创建新应用
|
||||
|
|
@ -98,19 +101,26 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
gin.SetMode(gin.ReleaseMode)
|
||||
router := gin.Default()
|
||||
|
||||
// CORS中间件
|
||||
// CORS 与 Gzip 压缩中间件
|
||||
router.Use(corsMiddleware(cfg.Server.CORSAllowedOrigins))
|
||||
router.Use(gzipMiddleware())
|
||||
|
||||
// 初始化数据库
|
||||
// 初始化数据库前先申请排他实例锁,防止重复启动的新进程在端口绑定失败前提前执行
|
||||
// HITL / MCP / 深度测评的重启恢复逻辑,篡改正在运行实例的活跃任务状态。
|
||||
dbPath := cfg.Database.Path
|
||||
if dbPath == "" {
|
||||
dbPath = "data/conversations.db"
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
if err := os.MkdirAll(filepath.Dir(dbPath), 0755); err != nil {
|
||||
return nil, fmt.Errorf("创建数据库目录失败: %w", err)
|
||||
instanceUnlock, err := lockDatabaseInstance(dbPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keepInstanceLock := false
|
||||
defer func() {
|
||||
if !keepInstanceLock {
|
||||
instanceUnlock()
|
||||
}
|
||||
}()
|
||||
|
||||
db, err := database.NewDB(dbPath, log.Logger)
|
||||
if err != nil {
|
||||
|
|
@ -152,9 +162,6 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
monitorRetention.PurgeExpired()
|
||||
monitor.StartRetentionLoop(monitorRetention, log.Logger)
|
||||
|
||||
if err := handler.NewHITLManager(db, log.Logger).EnsureSchema(); err != nil {
|
||||
log.Logger.Warn("初始化 HITL 表失败", zap.Error(err))
|
||||
}
|
||||
hitlRetention := hitl.NewService(db, cfg, log.Logger)
|
||||
hitlRetention.PurgeExpired()
|
||||
hitl.StartRetentionLoop(hitlRetention, log.Logger)
|
||||
|
|
@ -170,6 +177,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
|
||||
// 创建安全工具执行器
|
||||
executor := security.NewExecutor(&cfg.Security, mcpServer, log.Logger)
|
||||
executor.SetProxyConfig(cfg.Proxy)
|
||||
executor.SetShellNoOutputTimeoutSeconds(cfg.Agent.ShellNoOutputTimeoutSeconds)
|
||||
executor.SetToolOutputMaxBytes(cfg.MultiAgent.Runtime.ReductionMaxLengthForTruncEffective())
|
||||
executor.SetToolOutputSpillRoot(cfg.MultiAgent.Runtime.ReductionRootDir)
|
||||
|
|
@ -222,6 +230,9 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
var knowledgeHandler *handler.KnowledgeHandler
|
||||
|
||||
var knowledgeDBConn *database.DB
|
||||
if !cfg.Knowledge.Enabled {
|
||||
knowledge.RegisterTaxonomyTool(mcpServer, log.Logger)
|
||||
}
|
||||
log.Logger.Debug("检查知识库配置", zap.Bool("enabled", cfg.Knowledge.Enabled))
|
||||
if cfg.Knowledge.Enabled {
|
||||
// 确定知识库数据库路径
|
||||
|
|
@ -268,6 +279,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
// 创建检索器(Agent MultiQuery + 重排流水线)
|
||||
retrievalConfig := knowledge.RetrievalConfigFromYAML(cfg.Knowledge.Retrieval)
|
||||
knowledgeRetriever = knowledge.NewRetriever(knowledgeDB, embedder, retrievalConfig, log.Logger)
|
||||
knowledgeRetriever.SetAgentRuntime(cfg.AgentRuntime)
|
||||
if err := knowledge.WireRetrieverPipeline(context.Background(), knowledgeRetriever, &cfg.OpenAI); err != nil {
|
||||
return nil, fmt.Errorf("初始化知识库检索流水线失败: %w", err)
|
||||
}
|
||||
|
|
@ -456,6 +468,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
authHandler := handler.NewAuthHandler(authManager, cfg, configPath, log.Logger)
|
||||
authHandler.SetAudit(auditSvc)
|
||||
attackChainHandler := handler.NewAttackChainHandler(db, &cfg.OpenAI, log.Logger)
|
||||
attackChainHandler.SetAgentRuntime(cfg.AgentRuntime)
|
||||
vulnerabilityHandler := handler.NewVulnerabilityHandler(db, log.Logger)
|
||||
vulnerabilityHandler.SetTaskStateProvider(agentHandler)
|
||||
assetHandler := handler.NewAssetHandler(db, log.Logger)
|
||||
|
|
@ -474,6 +487,11 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
registerWebshellTools(mcpServer, db, webshellHandler, log.Logger)
|
||||
registerWebshellManagementTools(mcpServer, db, webshellHandler, log.Logger)
|
||||
configHandler := handler.NewConfigHandler(configPath, cfg, mcpServer, executor, agent, attackChainHandler, externalMCPMgr, log.Logger)
|
||||
if err := agentHandler.InitDeepAssessments(configHandler.RuntimeConfigSnapshot); err != nil {
|
||||
return nil, fmt.Errorf("initialize deep assessments: %w", err)
|
||||
}
|
||||
mcpServer.SetSurfaceIngest(agentHandler.IngestMCPSurface)
|
||||
externalMCPMgr.SetSurfaceIngest(agentHandler.IngestMCPSurface)
|
||||
configHandler.SetDB(db)
|
||||
configHandler.SetToolGuard(toolGuard)
|
||||
configHandler.SetAudit(auditSvc)
|
||||
|
|
@ -515,7 +533,13 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
openAPIHandler := handler.NewOpenAPIHandler(db, log.Logger, conversationHandler, agentHandler)
|
||||
|
||||
// 创建 App 实例(部分字段稍后填充)
|
||||
pluginHub, err := pluginhub.New(db, cfg.Plugins, configDir, log.Logger)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize plugin runtime: %w", err)
|
||||
}
|
||||
pluginHub.ConfigureServices(authManager, configHandler.RuntimeConfigSnapshot)
|
||||
app := &App{
|
||||
pluginHub: pluginHub,
|
||||
config: cfg,
|
||||
configDir: configDir,
|
||||
logger: log,
|
||||
|
|
@ -539,6 +563,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
c2Handler: c2Handler,
|
||||
storageHandler: storageHandler,
|
||||
auditSvc: auditSvc,
|
||||
instanceUnlock: instanceUnlock,
|
||||
}
|
||||
// 飞书/钉钉长连接(无需公网),启用时在后台启动;后续前端应用配置时会通过 RestartRobotConnections 重启
|
||||
app.startRobotConnections()
|
||||
|
|
@ -624,7 +649,8 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
})
|
||||
|
||||
updateHandler := handler.NewUpdateHandler(configDir, log.Logger, auditSvc,
|
||||
app.updateRestart(configDir), updateActivation, configHandler.UpdateSource, configHandler.SetUpdateSource)
|
||||
app.updateRestart(configDir), updateActivation, configHandler.UpdateSource, configHandler.SetUpdateSource).
|
||||
WithUpdateConfig(configHandler.GetUpdateConfig, configHandler.SetUpdateConfig)
|
||||
|
||||
// 设置路由(使用 App 实例以便动态获取 handler)
|
||||
setupRoutes(
|
||||
|
|
@ -661,6 +687,8 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
|
|||
updateHandler,
|
||||
)
|
||||
|
||||
agentHandler.StartDeepAssessmentRecovery()
|
||||
keepInstanceLock = true
|
||||
return app, nil
|
||||
|
||||
}
|
||||
|
|
@ -737,7 +765,25 @@ func (a *App) RunWithContext(ctx context.Context) error {
|
|||
return tlsErr
|
||||
}
|
||||
|
||||
srv := &http.Server{Addr: addr, Handler: a.router}
|
||||
var mainHandler http.Handler = a.router
|
||||
if a.pluginHub != nil {
|
||||
var pluginTLS *tls.Config
|
||||
if tlsMode != mainTLSOff {
|
||||
pluginTLS, tlsErr = ensureMainTLSConfigCerts(tlsMode, tlsConf, certFile, keyFile)
|
||||
if tlsErr != nil {
|
||||
return fmt.Errorf("初始化插件监听证书: %w", tlsErr)
|
||||
}
|
||||
}
|
||||
if err := a.pluginHub.StartServices(a.config.Server.Host, a.config.Server.Port, pluginTLS); err != nil {
|
||||
a.logger.Warn("Plugin model gateway unavailable", zap.Error(err))
|
||||
}
|
||||
defer a.pluginHub.CloseServices()
|
||||
mainHandler = a.pluginHub.WebHandler(mainHandler)
|
||||
if err := a.pluginHub.Start(ctx); err != nil {
|
||||
a.logger.Warn("Plugin runtime unavailable", zap.Error(err))
|
||||
}
|
||||
}
|
||||
srv := &http.Server{Addr: addr, Handler: mainHandler}
|
||||
var mainMux *mainServerMux
|
||||
httpRedirect := config.ServerHTTPRedirectEnabled(&a.config.Server)
|
||||
if tlsMode != mainTLSOff {
|
||||
|
|
@ -823,6 +869,13 @@ func (a *App) Shutdown() {
|
|||
}
|
||||
|
||||
func (a *App) shutdown() {
|
||||
if a.pluginHub != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 32*time.Second)
|
||||
if err := a.pluginHub.Close(ctx); err != nil {
|
||||
a.logger.Warn("Could not finish plugin runtime cleanup", zap.Error(err))
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
if a.agentHandler != nil {
|
||||
a.agentHandler.ShutdownTasks()
|
||||
}
|
||||
|
|
@ -849,6 +902,7 @@ func (a *App) shutdown() {
|
|||
if a.externalMCPMgr != nil {
|
||||
a.externalMCPMgr.StopAll()
|
||||
}
|
||||
agentruntime.CloseIdleWorkers()
|
||||
|
||||
// 关闭知识库数据库连接(如果使用独立数据库)
|
||||
if a.knowledgeDB != nil {
|
||||
|
|
@ -863,6 +917,10 @@ func (a *App) shutdown() {
|
|||
a.logger.Logger.Warn("关闭主数据库连接失败", zap.Error(err))
|
||||
}
|
||||
}
|
||||
if a.instanceUnlock != nil {
|
||||
a.instanceUnlock()
|
||||
a.instanceUnlock = nil
|
||||
}
|
||||
}
|
||||
|
||||
// startRobotConnections 根据当前配置启动钉钉/飞书长连接(不先关闭已有连接,仅用于首次启动)
|
||||
|
|
@ -945,6 +1003,13 @@ func (a *App) RestartRobotConnections() {
|
|||
}
|
||||
|
||||
// setupRoutes 设置路由
|
||||
func pluginAwarePlatformAuth(manager *security.AuthManager, proxy config.PluginProxyConfig) gin.HandlerFunc {
|
||||
if proxy.Effective().Mode == "port" {
|
||||
return security.AuthMiddlewareWithoutCookie(manager)
|
||||
}
|
||||
return security.AuthMiddleware(manager)
|
||||
}
|
||||
|
||||
func setupRoutes(
|
||||
router *gin.Engine,
|
||||
authHandler *handler.AuthHandler,
|
||||
|
|
@ -978,6 +1043,7 @@ func setupRoutes(
|
|||
openAPIHandler *handler.OpenAPIHandler,
|
||||
updateHandler *handler.UpdateHandler,
|
||||
) {
|
||||
platformAuth := pluginAwarePlatformAuth(authManager, app.config.Plugins.Proxy)
|
||||
// API路由
|
||||
api := router.Group("/api")
|
||||
|
||||
|
|
@ -986,12 +1052,12 @@ func setupRoutes(
|
|||
loginRL := security.NewRateLimiter(10, 1*time.Minute)
|
||||
{
|
||||
authRoutes.POST("/login", security.RateLimitMiddleware(loginRL), authHandler.Login)
|
||||
authRoutes.POST("/logout", security.AuthMiddleware(authManager), authHandler.Logout)
|
||||
authRoutes.POST("/change-password", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), authHandler.ChangePassword)
|
||||
authRoutes.GET("/validate", updateHandler.SetBootHeader, security.AuthMiddleware(authManager), authHandler.Validate)
|
||||
authRoutes.POST("/robot-binding-code", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), robotHandler.CreateRobotBindingCode)
|
||||
authRoutes.GET("/robot-bindings", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), robotHandler.ListMyRobotBindings)
|
||||
authRoutes.DELETE("/robot-bindings/:id", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), robotHandler.DeleteMyRobotBinding)
|
||||
authRoutes.POST("/logout", platformAuth, authHandler.Logout)
|
||||
authRoutes.POST("/change-password", platformAuth, security.RequirePermission("auth:self"), authHandler.ChangePassword)
|
||||
authRoutes.GET("/validate", updateHandler.SetBootHeader, platformAuth, authHandler.Validate)
|
||||
authRoutes.POST("/robot-binding-code", platformAuth, security.RequirePermission("auth:self"), robotHandler.CreateRobotBindingCode)
|
||||
authRoutes.GET("/robot-bindings", platformAuth, security.RequirePermission("auth:self"), robotHandler.ListMyRobotBindings)
|
||||
authRoutes.DELETE("/robot-bindings/:id", platformAuth, security.RequirePermission("auth:self"), robotHandler.DeleteMyRobotBinding)
|
||||
}
|
||||
|
||||
// 机器人回调(无需登录,供企业微信/钉钉/飞书服务器调用)
|
||||
|
|
@ -1007,7 +1073,7 @@ func setupRoutes(
|
|||
}
|
||||
|
||||
protected := api.Group("")
|
||||
protected.Use(security.AuthMiddleware(authManager))
|
||||
protected.Use(platformAuth)
|
||||
protected.Use(security.RBACMiddlewareWithDenyHook(app.db, func(c *gin.Context, reason, permission string) {
|
||||
if auditSvc != nil {
|
||||
auditSvc.Record(c, audit.Entry{
|
||||
|
|
@ -1017,6 +1083,7 @@ func setupRoutes(
|
|||
})
|
||||
}
|
||||
}))
|
||||
handler.NewPluginHandler(app.db, auditSvc, app.pluginHub).Register(protected)
|
||||
{
|
||||
protected.GET("/rbac/me", rbacHandler.Me)
|
||||
protected.GET("/rbac/metadata", rbacHandler.Metadata)
|
||||
|
|
@ -1062,6 +1129,7 @@ func setupRoutes(
|
|||
protected.POST("/hitl/dismiss", agentHandler.DismissHITLInterrupt)
|
||||
protected.GET("/hitl/config/:conversationId", agentHandler.GetHITLConversationConfig)
|
||||
protected.PUT("/hitl/config", agentHandler.UpsertHITLConversationConfig)
|
||||
protected.PUT("/hitl/config/:conversationId/human-approval", agentHandler.RequireHITLConversationHumanApproval)
|
||||
protected.GET("/hitl/tool-whitelist", agentHandler.GetHITLGlobalToolWhitelist)
|
||||
protected.PUT("/hitl/tool-whitelist", agentHandler.SetHITLGlobalToolWhitelist)
|
||||
protected.POST("/hitl/tool-whitelist", agentHandler.MergeHITLGlobalToolWhitelist)
|
||||
|
|
@ -1096,6 +1164,9 @@ func setupRoutes(
|
|||
protected.GET("/assets", assetHandler.List)
|
||||
protected.GET("/assets/selection", assetHandler.Selection)
|
||||
protected.GET("/assets/stats", assetHandler.Stats)
|
||||
protected.GET("/assets/collections", assetHandler.ListCollections)
|
||||
protected.GET("/assets/collections/:id", assetHandler.GetCollection)
|
||||
protected.GET("/assets/:id/facts", assetHandler.Facts)
|
||||
protected.POST("/assets/import", assetHandler.Import)
|
||||
protected.POST("/assets/scan-links", assetHandler.RecordScans)
|
||||
protected.PUT("/assets/bulk", assetHandler.BulkUpdate)
|
||||
|
|
@ -1105,6 +1176,37 @@ func setupRoutes(
|
|||
protected.PUT("/assets/:id", assetHandler.Update)
|
||||
protected.DELETE("/assets/:id", assetHandler.Delete)
|
||||
|
||||
// Deep assessments have independent APIs, state, permissions and UI.
|
||||
protected.GET("/deep-assessments/options", agentHandler.DeepAssessmentOptions)
|
||||
protected.GET("/deep-assessments", agentHandler.ListDeepAssessments)
|
||||
protected.POST("/deep-assessments", agentHandler.CreateDeepAssessment)
|
||||
protected.GET("/deep-assessments/:id", agentHandler.GetDeepAssessment)
|
||||
protected.POST("/deep-assessments/:id/question", security.RequirePermission("agent:execute"), agentHandler.AskDeepAssessment)
|
||||
protected.GET("/deep-assessments/:id/graph", agentHandler.DeepAssessmentGraph)
|
||||
protected.GET("/deep-assessments/:id/assets", agentHandler.DeepAssessmentAssets)
|
||||
protected.POST("/deep-assessments/:id/assets", agentHandler.DeepAssessmentAssets)
|
||||
protected.GET("/deep-assessments/:id/surface-items", agentHandler.DeepAssessmentSurfaceItems)
|
||||
protected.POST("/deep-assessments/:id/surface-items", agentHandler.DeepAssessmentSurfaceItems)
|
||||
protected.PUT("/deep-assessments/:id/surface-items/:itemId", agentHandler.DeepAssessmentSurfaceItems)
|
||||
protected.GET("/deep-assessments/:id/facts", agentHandler.DeepAssessmentFacts)
|
||||
protected.GET("/deep-assessments/:id/acceptance", agentHandler.DeepAssessmentAcceptance)
|
||||
protected.GET("/deep-assessments/:id/coverage", agentHandler.DeepAssessmentCoverage)
|
||||
protected.GET("/deep-assessments/:id/acceptance/sources", agentHandler.DeepAssessmentAcceptanceSources)
|
||||
protected.PUT("/deep-assessments/:id/acceptance/:criterion", agentHandler.SaveDeepAssessmentAcceptance)
|
||||
protected.GET("/deep-assessments/:id/evidence-path", agentHandler.DeepAssessmentEvidencePath)
|
||||
protected.GET("/deep-assessments/:id/evidence-history", agentHandler.DeepAssessmentEvidenceHistory)
|
||||
protected.GET("/deep-assessments/:id/endpoint-evidence", agentHandler.DeepAssessmentEndpointEvidence)
|
||||
protected.PUT("/deep-assessments/:id/endpoint-evidence", agentHandler.DeepAssessmentEndpointEvidence)
|
||||
protected.GET("/deep-assessments/:id/intents", agentHandler.DeepAssessmentIntents)
|
||||
protected.GET("/deep-assessments/:id/graph/node", agentHandler.DeepAssessmentNode)
|
||||
protected.GET("/deep-assessments/:id/vulnerabilities", agentHandler.DeepAssessmentFindings)
|
||||
protected.GET("/deep-assessments/:id/vulnerabilities/:vulnerabilityId", agentHandler.DeepAssessmentFinding)
|
||||
protected.GET("/deep-assessments/:id/steps/:stepId", agentHandler.DeepAssessmentStep)
|
||||
protected.GET("/deep-assessments/:id/events", agentHandler.DeepAssessmentEvents)
|
||||
protected.GET("/deep-assessments/:id/receipts", agentHandler.DeepAssessmentReceipts)
|
||||
protected.GET("/deep-assessments/:id/report", agentHandler.DeepAssessmentReport)
|
||||
protected.POST("/deep-assessments/:id/control/:action", agentHandler.ControlDeepAssessment)
|
||||
protected.DELETE("/deep-assessments/:id", agentHandler.DeleteDeepAssessment)
|
||||
// 批量任务管理
|
||||
protected.POST("/batch-tasks", agentHandler.CreateBatchQueue)
|
||||
protected.GET("/batch-tasks", agentHandler.ListBatchQueues)
|
||||
|
|
@ -1160,11 +1262,14 @@ func setupRoutes(
|
|||
protected.POST("/config/test-openai", configHandler.TestOpenAI)
|
||||
protected.POST("/config/detect-context", configHandler.DetectContext)
|
||||
protected.POST("/config/test-typesafe", configHandler.TestTypeSafe)
|
||||
protected.POST("/config/test-audit-model", configHandler.TestAuditModel)
|
||||
protected.POST("/config/test-vision", configHandler.TestVision)
|
||||
protected.POST("/config/test-embedding", configHandler.TestEmbedding)
|
||||
protected.POST("/config/list-models", configHandler.ListModels)
|
||||
|
||||
// 系统更新(保持本安装自身源码最新:查看、检查、应用、进度、回滚、接入、更新源)
|
||||
protected.GET("/system/update", updateHandler.GetStatus)
|
||||
protected.GET("/system/update/branches", updateHandler.Branches)
|
||||
protected.GET("/system/update/job", updateHandler.Job)
|
||||
protected.POST("/system/update/check", updateHandler.Check)
|
||||
protected.POST("/system/update/apply", updateHandler.Apply)
|
||||
|
|
@ -1364,6 +1469,7 @@ func setupRoutes(
|
|||
protected.POST("/vulnerabilities", vulnerabilityHandler.CreateVulnerability)
|
||||
protected.POST("/vulnerabilities/:id/retest", vulnerabilityHandler.CreateRetest)
|
||||
protected.PUT("/vulnerabilities/:id", vulnerabilityHandler.UpdateVulnerability)
|
||||
protected.PUT("/vulnerabilities/:id/archive", vulnerabilityHandler.SetVulnerabilityArchived)
|
||||
protected.DELETE("/vulnerabilities/:id", vulnerabilityHandler.DeleteVulnerability)
|
||||
|
||||
// 项目管理与事实黑板
|
||||
|
|
@ -1374,6 +1480,8 @@ func setupRoutes(
|
|||
protected.GET("/projects/:id/conversations", projectHandler.ListProjectConversations)
|
||||
protected.GET("/projects/:id", projectHandler.GetProject)
|
||||
protected.PUT("/projects/:id", projectHandler.UpdateProject)
|
||||
protected.GET("/projects/:id/lessons", projectHandler.ListLessons)
|
||||
protected.POST("/projects/:id/lessons/extract", projectHandler.ExtractLessons)
|
||||
protected.DELETE("/projects/:id", projectHandler.DeleteProject)
|
||||
protected.GET("/projects/:id/fact-graph", projectHandler.GetFactGraph)
|
||||
protected.GET("/projects/:id/fact-edges", projectHandler.ListFactEdges)
|
||||
|
|
@ -1511,22 +1619,20 @@ func setupRoutes(
|
|||
// OpenAPI规范(需要认证,避免暴露API结构信息)
|
||||
protected.GET("/openapi/spec", openAPIHandler.GetOpenAPISpec)
|
||||
|
||||
// API文档页面(公开访问,但需要登录后才能使用API)
|
||||
router.GET("/api-docs", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "api-docs.html", nil)
|
||||
})
|
||||
// 静态文件(前端为 React + Semi Design 单页应用,构建产物在 web/static/app)
|
||||
// 带内容哈希的 Vite 产物使用长期不可变缓存,减少跨境与高延迟链路重复下载。
|
||||
staticGroup := router.Group("/static", staticCacheControlMiddleware())
|
||||
staticGroup.Static("/", "./web/static")
|
||||
|
||||
// 静态文件
|
||||
router.Static("/static", "./web/static")
|
||||
router.LoadHTMLGlob("web/templates/*")
|
||||
// API 文档已并入单页应用路由(#/api-docs),保留旧地址跳转
|
||||
router.GET("/api-docs", func(c *gin.Context) {
|
||||
c.Redirect(http.StatusFound, "/#/api-docs")
|
||||
})
|
||||
|
||||
// 前端页面
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
version := app.config.Version
|
||||
if version == "" {
|
||||
version = "v1.0.0"
|
||||
}
|
||||
c.HTML(http.StatusOK, "index.html", gin.H{"Version": version})
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
c.File("./web/static/app/index.html")
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -2180,6 +2286,7 @@ func initializeKnowledge(
|
|||
// 创建检索器(Agent MultiQuery + 重排流水线)
|
||||
retrievalConfig := knowledge.RetrievalConfigFromYAML(cfg.Knowledge.Retrieval)
|
||||
knowledgeRetriever := knowledge.NewRetriever(knowledgeDB, embedder, retrievalConfig, logger)
|
||||
knowledgeRetriever.SetAgentRuntime(cfg.AgentRuntime)
|
||||
if err := knowledge.WireRetrieverPipeline(context.Background(), knowledgeRetriever, &cfg.OpenAI); err != nil {
|
||||
return nil, fmt.Errorf("初始化知识库检索流水线失败: %w", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,58 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
"cyberstrike-ai/internal/mcp/builtin"
|
||||
"encoding/json"
|
||||
"go.uber.org/zap"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRecordVulnerabilityAssessmentEvidenceCannotBeRedirected(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "fixture.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
deep, _ := db.CreateConversation("deep", database.ConversationCreateMeta{})
|
||||
ordinary, _ := db.CreateConversation("ordinary", database.ConversationCreateMeta{})
|
||||
payload, _ := json.Marshal(map[string]any{"id": "assessment", "steps": []map[string]any{{"id": "intent", "status": "running", "conversation_id": deep.ID}}})
|
||||
if _, err = db.Exec("INSERT INTO deep_assessments VALUES('assessment','','','fixture','running',?,?)", string(payload), time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.Exec("INSERT INTO deep_assessment_sessions VALUES('assessment','intent',?)", deep.ID)
|
||||
db.Exec("INSERT INTO deep_assessment_calls(id,task_id,step_id,tool,arguments,status,result,updated_at) VALUES('proof','assessment','intent','fixture_check','{}','completed','original bytes',?)", time.Now())
|
||||
server := mcp.NewServer(zap.NewNop())
|
||||
server.SetToolAuthorizer(func(context.Context, string, map[string]interface{}) error { return nil })
|
||||
registerVulnerabilityTools(server, db, zap.NewNop())
|
||||
args := map[string]interface{}{"title": "fixture", "description": "fixture impact", "severity": "low", "vulnerability_type": "test", "target": "https://example.test", "reproduction_steps": "read fixture", "evidence": "original bytes", "impact": "fixture only", "recommendation": "correct fixture", "conversation_id": ordinary.ID}
|
||||
ctx := mcp.WithMCPConversationID(context.Background(), deep.ID)
|
||||
res, _, err := server.CallTool(ctx, builtin.ToolRecordVulnerability, args)
|
||||
if err == nil && res != nil && !res.IsError {
|
||||
t.Fatal("redirect bypassed assessment evidence")
|
||||
}
|
||||
args["evidence_receipt_ids"] = []any{"invented"}
|
||||
res, _, err = server.CallTool(ctx, builtin.ToolRecordVulnerability, args)
|
||||
if err == nil && res != nil && !res.IsError {
|
||||
t.Fatal("invented receipt accepted")
|
||||
}
|
||||
args["evidence_receipt_ids"] = []any{"proof"}
|
||||
res, _, err = server.CallTool(ctx, builtin.ToolRecordVulnerability, args)
|
||||
if err != nil || res == nil || res.IsError {
|
||||
t.Fatal(err, res)
|
||||
}
|
||||
var count int
|
||||
db.QueryRow("SELECT COUNT(*) FROM vulnerability_assessment_sources WHERE assessment_id='assessment'").Scan(&count)
|
||||
if count != 1 {
|
||||
t.Fatal(count)
|
||||
}
|
||||
delete(args, "evidence_receipt_ids")
|
||||
res, _, err = server.CallTool(mcp.WithMCPConversationID(context.Background(), ordinary.ID), builtin.ToolRecordVulnerability, args)
|
||||
if err != nil || res == nil || res.IsError {
|
||||
t.Fatal("ordinary/batch behavior changed", err, res)
|
||||
}
|
||||
}
|
||||
|
|
@ -36,7 +36,20 @@ func registerAssetTools(server *mcp.Server, db *database.DB, logger *zap.Logger)
|
|||
return textResult("错误: "+err.Error(), true), nil
|
||||
}
|
||||
access, owner, global := assetAccessFromToolContext(ctx, "asset:write")
|
||||
result, err := db.UpsertAssets([]*database.Asset{asset}, owner, global)
|
||||
projectID, scoped, err := agentAssetProjectScope(db, ctx)
|
||||
if err != nil {
|
||||
return textResult("错误: "+err.Error(), true), nil
|
||||
}
|
||||
var result database.AssetImportResult
|
||||
if scoped {
|
||||
if asset.ProjectID != "" && asset.ProjectID != projectID {
|
||||
return textResult("错误: 资产不属于当前项目", true), nil
|
||||
}
|
||||
asset.ProjectID = projectID
|
||||
result, err = db.UpsertAssetsInProject([]*database.Asset{asset}, owner, global, projectID)
|
||||
} else {
|
||||
result, err = db.UpsertAssets([]*database.Asset{asset}, owner, global)
|
||||
}
|
||||
if err != nil {
|
||||
logger.Error("Agent 保存资产失败", zap.Error(err))
|
||||
return textResult("错误: "+err.Error(), true), nil
|
||||
|
|
@ -436,6 +449,9 @@ func assetAccessFromToolContext(ctx context.Context, permission string) (databas
|
|||
// conversation) keeps the existing all-accessible-assets behavior. A bound
|
||||
// conversation can only read assets assigned to that exact project.
|
||||
func agentAssetProjectScope(db *database.DB, ctx context.Context) (projectID string, scoped bool, err error) {
|
||||
if projectID = strings.TrimSpace(mcp.MCPProjectIDFromContext(ctx)); projectID != "" {
|
||||
return projectID, true, nil
|
||||
}
|
||||
conversationID := conversationIDFromToolCtx(ctx)
|
||||
if conversationID == "" {
|
||||
return "", false, nil
|
||||
|
|
|
|||
|
|
@ -188,7 +188,7 @@ func TestAssetReadToolsRespectConversationProjectScope(t *testing.T) {
|
|||
}
|
||||
|
||||
result, _, err = server.CallTool(boundCtx, builtin.ToolGetAsset, map[string]interface{}{"id": assets[1].ID})
|
||||
if err != nil || result == nil || !result.IsError {
|
||||
if err == nil || !strings.Contains(err.Error(), "tool authorization denied") {
|
||||
t.Fatalf("bound get read a foreign-project asset: result=%#v err=%v", result, err)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,204 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var gzipWriterPool = sync.Pool{
|
||||
New: func() any {
|
||||
w, _ := gzip.NewWriterLevel(io.Discard, gzip.BestSpeed)
|
||||
return w
|
||||
},
|
||||
}
|
||||
|
||||
// gzipMiddleware 对可压缩的 JSON/文本/静态资源响应启用 Gzip 压缩,
|
||||
// 自动跳过 SSE、WebSocket、二进制压缩格式及客户端未声明 gzip 的请求。
|
||||
func gzipMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !shouldTryGzipRequest(c.Request) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
origWriter := c.Writer
|
||||
gw := &gzipResponseWriter{
|
||||
ResponseWriter: origWriter,
|
||||
}
|
||||
c.Writer = gw
|
||||
defer func() {
|
||||
gw.close()
|
||||
c.Writer = origWriter
|
||||
}()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func shouldTryGzipRequest(r *http.Request) bool {
|
||||
if r == nil || r.Method == http.MethodHead {
|
||||
return false
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(r.Header.Get("Accept-Encoding")), "gzip") {
|
||||
return false
|
||||
}
|
||||
if r.Header.Get("Upgrade") != "" {
|
||||
return false
|
||||
}
|
||||
if strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/event-stream") {
|
||||
return false
|
||||
}
|
||||
path := strings.ToLower(r.URL.Path)
|
||||
if strings.HasSuffix(path, "/stream") ||
|
||||
strings.HasSuffix(path, "/task-events") ||
|
||||
strings.HasSuffix(path, "/events") ||
|
||||
strings.Contains(path, "/ws") ||
|
||||
strings.Contains(path, "/terminal") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func shouldCompressResponse(status int, header http.Header) bool {
|
||||
if status == http.StatusNoContent || status == http.StatusNotModified || (status >= 100 && status < 200) {
|
||||
return false
|
||||
}
|
||||
if header.Get("Content-Encoding") != "" {
|
||||
return false
|
||||
}
|
||||
ct := strings.ToLower(header.Get("Content-Type"))
|
||||
if strings.Contains(ct, "text/event-stream") {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(ct, "image/") && !strings.Contains(ct, "svg") {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(ct, "video/") ||
|
||||
strings.HasPrefix(ct, "audio/") ||
|
||||
strings.HasPrefix(ct, "font/") ||
|
||||
strings.Contains(ct, "application/gzip") ||
|
||||
strings.Contains(ct, "application/zip") ||
|
||||
strings.Contains(ct, "application/octet-stream") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type gzipResponseWriter struct {
|
||||
gin.ResponseWriter
|
||||
gz *gzip.Writer
|
||||
decided bool
|
||||
compressing bool
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) decide(status int) {
|
||||
if w.decided {
|
||||
return
|
||||
}
|
||||
w.decided = true
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
w.statusCode = status
|
||||
if !shouldCompressResponse(status, w.Header()) {
|
||||
return
|
||||
}
|
||||
w.compressing = true
|
||||
h := w.Header()
|
||||
h.Set("Content-Encoding", "gzip")
|
||||
h.Del("Content-Length")
|
||||
vary := h.Get("Vary")
|
||||
if vary == "" {
|
||||
h.Set("Vary", "Accept-Encoding")
|
||||
} else if !strings.Contains(strings.ToLower(vary), "accept-encoding") {
|
||||
h.Set("Vary", vary+", Accept-Encoding")
|
||||
}
|
||||
gz := gzipWriterPool.Get().(*gzip.Writer)
|
||||
gz.Reset(w.ResponseWriter)
|
||||
w.gz = gz
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) WriteHeader(code int) {
|
||||
if w.Written() {
|
||||
return
|
||||
}
|
||||
w.decide(code)
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) WriteHeaderNow() {
|
||||
if !w.decided {
|
||||
w.decide(w.Status())
|
||||
}
|
||||
w.ResponseWriter.WriteHeaderNow()
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) Write(data []byte) (int, error) {
|
||||
if !w.decided {
|
||||
if w.Header().Get("Content-Type") == "" && len(data) > 0 {
|
||||
w.Header().Set("Content-Type", http.DetectContentType(data))
|
||||
}
|
||||
status := w.statusCode
|
||||
if status == 0 {
|
||||
status = w.ResponseWriter.Status()
|
||||
}
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
w.decide(status)
|
||||
}
|
||||
if w.compressing && w.gz != nil {
|
||||
return w.gz.Write(data)
|
||||
}
|
||||
return w.ResponseWriter.Write(data)
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) WriteString(s string) (int, error) {
|
||||
return w.Write([]byte(s))
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) Flush() {
|
||||
if w.compressing && w.gz != nil {
|
||||
_ = w.gz.Flush()
|
||||
}
|
||||
w.ResponseWriter.Flush()
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
w.close()
|
||||
return w.ResponseWriter.Hijack()
|
||||
}
|
||||
|
||||
func (w *gzipResponseWriter) close() {
|
||||
if w.gz != nil {
|
||||
_ = w.gz.Close()
|
||||
w.gz.Reset(io.Discard)
|
||||
gzipWriterPool.Put(w.gz)
|
||||
w.gz = nil
|
||||
}
|
||||
}
|
||||
|
||||
// staticCacheControlMiddleware 为带内容哈希的 Vite 前端构建产物设置长期不可变缓存,
|
||||
// 对语言包设置适度缓存,对 index.html 等入口文件保持 no-cache。
|
||||
func staticCacheControlMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
path := c.Request.URL.Path
|
||||
switch {
|
||||
case strings.HasPrefix(path, "/static/app/assets/"):
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
case strings.HasPrefix(path, "/static/i18n/"):
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
case path == "/static/app/" || path == "/static/app/index.html":
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestGzipMiddlewareCompressesJSONAndSkipsSSE(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(gzipMiddleware())
|
||||
|
||||
payload := strings.Repeat(`{"toolName":"nmap","result":"open port 80/tcp http"}`, 200)
|
||||
r.GET("/api/conversations/1", func(c *gin.Context) {
|
||||
c.Data(http.StatusOK, "application/json; charset=utf-8", []byte(payload))
|
||||
})
|
||||
r.POST("/api/agent/stream", func(c *gin.Context) {
|
||||
c.Header("Content-Type", "text/event-stream; charset=utf-8")
|
||||
c.Writer.WriteHeader(http.StatusOK)
|
||||
_, _ = c.Writer.Write([]byte("data: {\"type\":\"done\"}\n\n"))
|
||||
c.Writer.Flush()
|
||||
})
|
||||
r.GET("/api/empty", func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
|
||||
// 1. JSON with Accept-Encoding: gzip should be compressed and round-trip cleanly.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/conversations/1", nil)
|
||||
req.Header.Set("Accept-Encoding", "gzip, deflate")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if got := w.Header().Get("Content-Encoding"); got != "gzip" {
|
||||
t.Fatalf("Content-Encoding = %q, want gzip", got)
|
||||
}
|
||||
if !strings.Contains(w.Header().Get("Vary"), "Accept-Encoding") {
|
||||
t.Fatalf("Vary = %q, want Accept-Encoding", w.Header().Get("Vary"))
|
||||
}
|
||||
if w.Body.Len() >= len(payload)/4 {
|
||||
t.Fatalf("compressed len = %d, expected much smaller than %d", w.Body.Len(), len(payload))
|
||||
}
|
||||
gr, err := gzip.NewReader(w.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("gzip.NewReader: %v", err)
|
||||
}
|
||||
decoded, err := io.ReadAll(gr)
|
||||
_ = gr.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read gzip body: %v", err)
|
||||
}
|
||||
if string(decoded) != payload {
|
||||
t.Fatalf("decoded payload mismatch: len=%d want=%d", len(decoded), len(payload))
|
||||
}
|
||||
|
||||
// 2. SSE stream endpoint must NOT be gzipped.
|
||||
sseReq := httptest.NewRequest(http.MethodPost, "/api/agent/stream", nil)
|
||||
sseReq.Header.Set("Accept-Encoding", "gzip")
|
||||
sseW := httptest.NewRecorder()
|
||||
r.ServeHTTP(sseW, sseReq)
|
||||
if got := sseW.Header().Get("Content-Encoding"); got != "" {
|
||||
t.Fatalf("SSE Content-Encoding = %q, want empty", got)
|
||||
}
|
||||
if !strings.Contains(sseW.Body.String(), `"done"`) {
|
||||
t.Fatalf("unexpected SSE body: %q", sseW.Body.String())
|
||||
}
|
||||
|
||||
// 3. 204 No Content must NOT set Content-Encoding.
|
||||
emptyReq := httptest.NewRequest(http.MethodGet, "/api/empty", nil)
|
||||
emptyReq.Header.Set("Accept-Encoding", "gzip")
|
||||
emptyW := httptest.NewRecorder()
|
||||
r.ServeHTTP(emptyW, emptyReq)
|
||||
if emptyW.Code != http.StatusNoContent {
|
||||
t.Fatalf("204 status = %d", emptyW.Code)
|
||||
}
|
||||
if got := emptyW.Header().Get("Content-Encoding"); got != "" {
|
||||
t.Fatalf("204 Content-Encoding = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticCacheControlMiddleware(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
g := r.Group("/static", staticCacheControlMiddleware())
|
||||
g.GET("/*filepath", func(c *gin.Context) {
|
||||
c.String(http.StatusOK, "ok")
|
||||
})
|
||||
|
||||
cases := []struct {
|
||||
path string
|
||||
want string
|
||||
}{
|
||||
{"/static/app/assets/chat-abc123.js", "public, max-age=31536000, immutable"},
|
||||
{"/static/i18n/zh-CN.json", "public, max-age=3600"},
|
||||
{"/static/app/index.html", "no-cache"},
|
||||
{"/static/logo.png", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, tc.path, nil))
|
||||
if got := w.Header().Get("Cache-Control"); got != tc.want {
|
||||
t.Fatalf("%s Cache-Control = %q, want %q", tc.path, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// lockDatabaseInstance acquires a non-blocking OS kernel lock for dbPath before
|
||||
// startup recovery mutates SQLite tables (such as hitl_interrupts, messages,
|
||||
// mcp_executions, or deep_assessments). If a second server process is started
|
||||
// accidentally while the primary server is still bound and running tasks, the
|
||||
// second process fails fast without corrupting the live server's task state.
|
||||
func lockDatabaseInstance(dbPath string) (func(), error) {
|
||||
absPath, err := filepath.Abs(dbPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {
|
||||
return nil, fmt.Errorf("创建数据库目录失败: %w", err)
|
||||
}
|
||||
lockPath := absPath + ".instance.lock"
|
||||
f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("打开实例锁文件失败 (%s): %w", lockPath, err)
|
||||
}
|
||||
if err := tryLockInstanceFile(f); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, fmt.Errorf("另一个 CyberStrikeAI 服务实例正在运行并占用数据库 %s(请先停止旧进程,或在系统设置中使用一键更新)", dbPath)
|
||||
}
|
||||
var once sync.Once
|
||||
return func() {
|
||||
once.Do(func() {
|
||||
_ = f.Close()
|
||||
})
|
||||
}, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
//go:build !darwin && !linux && !freebsd && !openbsd && !netbsd && !dragonfly && !windows
|
||||
|
||||
package app
|
||||
|
||||
import "os"
|
||||
|
||||
func tryLockInstanceFile(_ *os.File) error {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLockDatabaseInstanceRejectsConcurrentOwnerAndReacquiresAfterUnlock(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "data", "conversations.db")
|
||||
|
||||
unlock, err := lockDatabaseInstance(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("first lockDatabaseInstance failed: %v", err)
|
||||
}
|
||||
|
||||
if _, err := lockDatabaseInstance(dbPath); err == nil || !strings.Contains(err.Error(), "另一个 CyberStrikeAI 服务实例正在运行") {
|
||||
t.Fatalf("expected concurrent lock to be rejected with clear message, got: %v", err)
|
||||
}
|
||||
|
||||
unlock()
|
||||
|
||||
unlock2, err := lockDatabaseInstance(dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("reacquiring lock after unlock failed: %v", err)
|
||||
}
|
||||
unlock2()
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
//go:build darwin || linux || freebsd || openbsd || netbsd || dragonfly
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func tryLockInstanceFile(f *os.File) error {
|
||||
return unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
//go:build windows
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func tryLockInstanceFile(f *os.File) error {
|
||||
return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{})
|
||||
}
|
||||
|
|
@ -2,6 +2,8 @@ package app
|
|||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
|
|
@ -92,6 +94,9 @@ func mcpToolAuthorizer(db *database.DB) func(context.Context, string, map[string
|
|||
}
|
||||
id := mcpAuthorizationString(args, "id")
|
||||
if db == nil || id == "" || !db.UserCanAccessResource(principal.UserID, principal.ScopeFor(permission), "vulnerability", id) {
|
||||
if toolName == builtin.ToolUpdateVulnerabilityStatus {
|
||||
return fmt.Errorf("找不到可更新的漏洞。%s", vulnerabilityIDRecovery)
|
||||
}
|
||||
return fmt.Errorf("no access to vulnerability %s", id)
|
||||
}
|
||||
convID := mcpAuthorizationConversationID(ctx)
|
||||
|
|
@ -115,7 +120,11 @@ func mcpToolAuthorizer(db *database.DB) func(context.Context, string, map[string
|
|||
}
|
||||
return nil
|
||||
}
|
||||
return authorizeMCPProjectResourceBoundary(ctx, db, "vulnerability", id)
|
||||
err := authorizeMCPProjectResourceBoundary(ctx, db, "vulnerability", id)
|
||||
if toolName == builtin.ToolUpdateVulnerabilityStatus && errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("找不到可更新的漏洞。%s", vulnerabilityIDRecovery)
|
||||
}
|
||||
return err
|
||||
case builtin.ToolQueryAssets:
|
||||
return require("asset:read")
|
||||
case builtin.ToolGetAsset:
|
||||
|
|
@ -124,6 +133,11 @@ func mcpToolAuthorizer(db *database.DB) func(context.Context, string, map[string
|
|||
if err := require("asset:write"); err != nil {
|
||||
return err
|
||||
}
|
||||
if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" {
|
||||
if bound := mcpEffectiveProjectFilter(ctx, db); bound != "" && bound != projectID {
|
||||
return fmt.Errorf("asset destination is outside the current project")
|
||||
}
|
||||
}
|
||||
if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" && (db == nil || !db.UserCanAccessResource(principal.UserID, principal.ScopeFor("asset:write"), "project", projectID)) {
|
||||
return fmt.Errorf("no access to project %s", projectID)
|
||||
}
|
||||
|
|
@ -139,6 +153,11 @@ func mcpToolAuthorizer(db *database.DB) func(context.Context, string, map[string
|
|||
}
|
||||
return nil
|
||||
}
|
||||
if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" {
|
||||
if bound := mcpEffectiveProjectFilter(ctx, db); bound != "" && bound != projectID {
|
||||
return fmt.Errorf("asset destination is outside the current project")
|
||||
}
|
||||
}
|
||||
if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" && (db == nil || !db.UserCanAccessResource(principal.UserID, principal.ScopeFor("asset:write"), "project", projectID)) {
|
||||
return fmt.Errorf("no access to project %s", projectID)
|
||||
}
|
||||
|
|
@ -149,7 +168,7 @@ func mcpToolAuthorizer(db *database.DB) func(context.Context, string, map[string
|
|||
return authorizeProjectTool(ctx, principal, db, "project:write")
|
||||
case builtin.ToolGetProjectFact, builtin.ToolListProjectFacts, builtin.ToolSearchProjectFacts:
|
||||
return authorizeProjectTool(ctx, principal, db, "project:read")
|
||||
case builtin.ToolListKnowledgeRiskTypes, builtin.ToolSearchKnowledgeBase:
|
||||
case builtin.ToolListKnowledgeRiskTypes, builtin.ToolSearchKnowledgeBase, builtin.ToolLookupSecurityTaxonomy:
|
||||
return require("knowledge:read")
|
||||
case builtin.ToolAnalyzeImage:
|
||||
return require("agent:execute")
|
||||
|
|
@ -316,6 +335,11 @@ func authorizeMCPProjectResourceBoundary(ctx context.Context, db *database.DB, r
|
|||
return nil
|
||||
}
|
||||
if filter == database.ProjectFilterUnbound {
|
||||
// Asset/vulnerability managers historically allow an unbound session to
|
||||
// operate across its RBAC-visible records; bound sessions remain constrained.
|
||||
if resourceType == "asset" || resourceType == "vulnerability" {
|
||||
return nil
|
||||
}
|
||||
if projectID != "" {
|
||||
return fmt.Errorf("resource %s %s belongs to project %s, current conversation is unbound", resourceType, resourceID, projectID)
|
||||
}
|
||||
|
|
@ -332,6 +356,14 @@ func authorizeMCPProjectResourceBoundary(ctx context.Context, db *database.DB, r
|
|||
|
||||
func mcpResourceProjectID(db *database.DB, resourceType, resourceID string) (string, bool, error) {
|
||||
switch resourceType {
|
||||
case "asset", "vulnerability":
|
||||
table := "assets"
|
||||
if resourceType == "vulnerability" {
|
||||
table = "vulnerabilities"
|
||||
}
|
||||
var projectID string
|
||||
err := db.QueryRow(`SELECT COALESCE(project_id,'') FROM `+table+` WHERE id=?`, resourceID).Scan(&projectID)
|
||||
return projectID, true, err
|
||||
case "webshell":
|
||||
conn, err := db.GetWebshellConnection(resourceID)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,78 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/security"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Stub the post-authorization endpoint handler. This verifies the actual
|
||||
// platform middleware and route permissions without starting terminal or C2 tasks.
|
||||
func TestPluginPortModePreservesChatWebShellAndC2StreamingAuthentication(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "auth.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
auth := security.NewAuthManager(1)
|
||||
password, err := auth.AttachRBACStore(db)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _, err := auth.Authenticate("admin", password)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := gin.New()
|
||||
api := r.Group("/api", pluginAwarePlatformAuth(auth, config.PluginProxyConfig{}), security.RBACMiddleware(db))
|
||||
ok := func(c *gin.Context) { c.Status(http.StatusNoContent) }
|
||||
api.POST("/agent/stream", ok)
|
||||
api.POST("/multi-agent/stream", ok)
|
||||
api.POST("/webshell/exec", ok)
|
||||
api.POST("/terminal/run/stream", ok)
|
||||
api.GET("/terminal/ws", ok)
|
||||
api.GET("/c2/events/stream", ok)
|
||||
for _, tt := range []struct {
|
||||
name, method, path, transport string
|
||||
}{
|
||||
{"Chat SSE", "POST", "/api/agent/stream", "bearer"},
|
||||
{"Multi-agent SSE", "POST", "/api/multi-agent/stream", "bearer"},
|
||||
{"WebShell", "POST", "/api/webshell/exec", "bearer"},
|
||||
{"Terminal SSE", "POST", "/api/terminal/run/stream", "bearer"},
|
||||
{"Terminal WebSocket", "GET", "/api/terminal/ws", "ws"},
|
||||
{"C2 event SSE", "GET", "/api/c2/events/stream", "sse"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(tt.method, tt.path, nil)
|
||||
req.AddCookie(&http.Cookie{Name: "auth_token", Value: token})
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("primary cookie authenticates on port mode: %d", w.Code)
|
||||
}
|
||||
switch tt.transport {
|
||||
case "bearer":
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
case "ws":
|
||||
req.URL.RawQuery = "token=" + token
|
||||
req.Header.Set("Upgrade", "websocket")
|
||||
case "sse":
|
||||
req.URL.RawQuery = "token=" + token
|
||||
req.Header.Set("Accept", "text/event-stream")
|
||||
}
|
||||
w = httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("authorized client rejected: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"fmt"
|
||||
"strings"
|
||||
|
||||
"cyberstrike-ai/internal/authctx"
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
|
|
@ -26,6 +27,13 @@ func projectIDFromConversation(db *database.DB, ctx context.Context) (string, er
|
|||
if strings.TrimSpace(pid) == "" {
|
||||
return "", fmt.Errorf("当前对话未绑定项目,请先在对话中选择项目或创建带项目的对话")
|
||||
}
|
||||
p, err := db.GetProject(pid)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if p.Status == database.ProjectStatusArchived {
|
||||
return "", fmt.Errorf("项目已归档,恢复项目后可在对话中使用项目事实")
|
||||
}
|
||||
return pid, nil
|
||||
}
|
||||
|
||||
|
|
@ -78,9 +86,13 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
|
|||
},
|
||||
"confidence": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "confirmed | tentative | deprecated",
|
||||
"description": "confirmed | tentative | deprecated。升级为 confirmed 必须同时提供 confirmation_note。",
|
||||
"enum": []string{"confirmed", "tentative", "deprecated"},
|
||||
},
|
||||
"confirmation_note": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "把事实标为 confirmed 时的审核说明。省略则不能从其他可信度升级为已确认。",
|
||||
},
|
||||
"pinned": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "是否优先出现在黑板索引",
|
||||
|
|
@ -89,6 +101,16 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
|
|||
"type": "string",
|
||||
"description": "可选:关联的漏洞记录 ID",
|
||||
},
|
||||
"asset_ids": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "可选:这条事实对应的资产 ID。传入后替换原关联;不传则保留。已确认且同时有成功工具回执时,计入资产观察覆盖。",
|
||||
"items": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
"execution_ids": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "可选:支持这条事实的成功工具执行 ID(tool_executions.id)。传入后替换原关联;不传则保留。",
|
||||
"items": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
"links": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "可选:关系边(from → 当前 fact)。finding 至少 1 条 {from:target/*, type:discovered_on};finding 上记录 exploit 用 {from:exploit/*, type:exploits}。省略保留已有边;传 [] 清空全部关系边。",
|
||||
|
|
@ -141,11 +163,14 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
|
|||
Confidence: strArg(args, "confidence"),
|
||||
Pinned: boolArg(args, "pinned"),
|
||||
RelatedVulnerabilityID: strArg(args, "related_vulnerability_id"),
|
||||
ConfirmationNote: strArg(args, "confirmation_note"),
|
||||
}
|
||||
if convID := mcpAuthorizationConversationID(ctx); convID != "" {
|
||||
f.SourceConversationID = convID
|
||||
}
|
||||
created, err := db.UpsertProjectFact(f)
|
||||
_, hasAssets := args["asset_ids"]
|
||||
_, hasExecutions := args["execution_ids"]
|
||||
created, err := db.SaveProjectFact(f, stringListArg(args["asset_ids"]), stringListArg(args["execution_ids"]), hasAssets, hasExecutions)
|
||||
if err != nil {
|
||||
return textResult("错误: "+err.Error(), true), nil
|
||||
}
|
||||
|
|
@ -175,6 +200,15 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
|
|||
if warn := project.SparseBodyWarningIfNeeded(f.Category, f.FactKey, f.Body); warn != "" {
|
||||
msg += warn
|
||||
}
|
||||
if principal, hasPrincipal := authctx.PrincipalFromContext(ctx); !hasPrincipal || principal.HasPermission("asset:write") {
|
||||
ownerID := ""
|
||||
allowGlobal := true
|
||||
if hasPrincipal {
|
||||
ownerID = principal.UserID
|
||||
allowGlobal = principal.ScopeFor("asset:write") == database.RBACScopeAll
|
||||
}
|
||||
_, _ = db.SyncFactTargetsToAssets(projectID, created, ownerID, allowGlobal)
|
||||
}
|
||||
return textResult(msg, false), nil
|
||||
})
|
||||
|
||||
|
|
@ -397,6 +431,20 @@ func registerProjectFactTools(mcpServer *mcp.Server, db *database.DB, cfg *confi
|
|||
}
|
||||
}
|
||||
|
||||
func stringListArg(raw interface{}) []string {
|
||||
items, ok := raw.([]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
if text, ok := item.(string); ok {
|
||||
out = append(out, text)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func strArg(args map[string]interface{}, key string) string {
|
||||
if v, ok := args[key].(string); ok {
|
||||
return v
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSPABuildArtifacts 校验前端构建产物已随仓库提交:
|
||||
// 首页必须引用 /static/app/assets/ 下的哈希资源,且这些文件真实存在。
|
||||
// 前端源码在 web/frontend,构建命令:npm run --prefix web/frontend build。
|
||||
func TestSPABuildArtifacts(t *testing.T) {
|
||||
root := filepath.Join("..", "..", "web", "static", "app")
|
||||
indexPath := filepath.Join(root, "index.html")
|
||||
index, err := os.ReadFile(indexPath)
|
||||
if err != nil {
|
||||
t.Fatalf("前端构建产物缺失 %s: %v", indexPath, err)
|
||||
}
|
||||
html := string(index)
|
||||
if !strings.Contains(html, `<div id="root">`) {
|
||||
t.Fatalf("index.html 缺少 React 挂载点: %s", indexPath)
|
||||
}
|
||||
|
||||
assetPattern := regexp.MustCompile(`(?:src|href)="(/static/app/[^"]+)"`)
|
||||
matches := assetPattern.FindAllStringSubmatch(html, -1)
|
||||
if len(matches) == 0 {
|
||||
t.Fatalf("index.html 未引用任何构建资源: %s", indexPath)
|
||||
}
|
||||
staticRoot := filepath.Join("..", "..", "web", "static")
|
||||
for _, match := range matches {
|
||||
relative := strings.TrimPrefix(match[1], "/static/")
|
||||
if strings.HasPrefix(relative, "favicon") || strings.HasPrefix(relative, "site.webmanifest") {
|
||||
continue
|
||||
}
|
||||
assetPath := filepath.Join(staticRoot, filepath.FromSlash(relative))
|
||||
if _, err := os.Stat(assetPath); err != nil {
|
||||
t.Fatalf("index.html 引用的资源不存在: %s", assetPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSPAEntryDoesNotDependOnLegacyTemplates 防止页面回退到 Go 模板渲染。
|
||||
func TestSPAEntryDoesNotDependOnLegacyTemplates(t *testing.T) {
|
||||
source, err := os.ReadFile("app.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code := string(source)
|
||||
if strings.Contains(code, "LoadHTMLGlob") {
|
||||
t.Fatal("app.go 仍在加载 Go 模板,前端应统一由 web/static/app 提供")
|
||||
}
|
||||
if !strings.Contains(code, `c.File("./web/static/app/index.html")`) {
|
||||
t.Fatal("app.go 未通过 c.File 提供前端入口")
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/authctx"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/knowledge"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
"cyberstrike-ai/internal/mcp/builtin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestTaxonomyToolUsesKnowledgeReadPermission(t *testing.T) {
|
||||
server := mcp.NewServer(zap.NewNop())
|
||||
server.SetToolAuthorizer(mcpToolAuthorizer(nil))
|
||||
knowledge.RegisterTaxonomyTool(server, zap.NewNop())
|
||||
args := map[string]any{"source": "wstg", "query": "WSTG-SESS-02"}
|
||||
denied := authctx.WithPrincipal(context.Background(), authctx.NewPrincipal("viewer", "viewer", database.RBACScopeOwn, nil))
|
||||
if result, _, err := server.CallTool(denied, builtin.ToolLookupSecurityTaxonomy, args); err == nil && (result == nil || !result.IsError) {
|
||||
t.Fatal("taxonomy was accessible without knowledge:read")
|
||||
}
|
||||
reader := authctx.WithPrincipal(context.Background(), authctx.NewPrincipal("reader", "reader", database.RBACScopeOwn, map[string]bool{"knowledge:read": true}))
|
||||
result, _, err := server.CallTool(reader, builtin.ToolLookupSecurityTaxonomy, args)
|
||||
if err != nil || result == nil || result.IsError || !strings.Contains(mcp.ToolResultPlainText(result), "WSTG-SESS-02") {
|
||||
t.Fatalf("knowledge reader request: %+v, %v", result, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"html/template"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFrontendTemplatesRender(t *testing.T) {
|
||||
templates, err := template.ParseGlob(filepath.Join("..", "..", "web", "templates", "*"))
|
||||
if err != nil {
|
||||
t.Fatalf("server template initialization fails: %v", err)
|
||||
}
|
||||
var output bytes.Buffer
|
||||
if err = templates.ExecuteTemplate(&output, "index.html", map[string]interface{}{"Version": "test"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
|
@ -54,6 +54,19 @@ func TestVulnerabilityRetestMCPUpdatesOnlyAssignedFinding(t *testing.T) {
|
|||
registerVulnerabilityTools(server, db, zap.NewNop())
|
||||
principal := authctx.NewPrincipal(user.ID, user.Username, database.RBACScopeAssigned, map[string]bool{"vulnerability:read": true, "vulnerability:write": true})
|
||||
ctx := authctx.WithPrincipal(mcp.WithMCPConversationID(context.Background(), branch.ID), principal)
|
||||
sourceCtx := authctx.WithPrincipal(mcp.WithMCPConversationID(context.Background(), source.ID),
|
||||
authctx.NewPrincipal(user.ID, user.Username, database.RBACScopeAll, map[string]bool{"vulnerability:read": true, "vulnerability:write": true}))
|
||||
idPrefix := strings.SplitN(findings[0].ID, "-", 2)[0]
|
||||
_, _, err = server.CallTool(sourceCtx, builtin.ToolUpdateVulnerabilityStatus, map[string]interface{}{
|
||||
"id": idPrefix, "status": "fixed", "retest_notes": "fixture",
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), vulnerabilityIDRecovery) {
|
||||
t.Fatalf("short ID did not return recovery guidance: %v", err)
|
||||
}
|
||||
result, _, err := server.CallTool(sourceCtx, builtin.ToolListVulnerabilities, map[string]interface{}{"q": idPrefix})
|
||||
if err != nil || result == nil || result.IsError || !strings.Contains(mcp.ToolResultPlainText(result), "id="+findings[0].ID) {
|
||||
t.Fatalf("search by short ID did not return the full ID: %v %+v", err, result)
|
||||
}
|
||||
call := func(id, status, notes string) bool {
|
||||
t.Helper()
|
||||
result, _, err := server.CallTool(ctx, builtin.ToolUpdateVulnerabilityStatus, map[string]interface{}{"id": id, "status": status, "retest_notes": notes})
|
||||
|
|
@ -62,9 +75,18 @@ func TestVulnerabilityRetestMCPUpdatesOnlyAssignedFinding(t *testing.T) {
|
|||
if call(findings[0].ID, "fixed", "") || call(findings[0].ID, "invalid", "evidence") || call(findings[1].ID, "fixed", "evidence") || call(findings[2].ID, "fixed", "evidence") {
|
||||
t.Fatal("invalid or unrelated update succeeded")
|
||||
}
|
||||
if !call(findings[0].ID, "confirmed", "still reproducible") || !call(findings[0].ID, "fixed", "now access denied with control request succeeding") {
|
||||
if !call(findings[0].ID, "confirmed", "still reproducible") {
|
||||
t.Fatal("assigned finding update denied")
|
||||
}
|
||||
fixed, _, err := server.CallTool(ctx, builtin.ToolUpdateVulnerabilityStatus, map[string]interface{}{
|
||||
"id": findings[0].ID, "status": "fixed", "retest_notes": "now access denied with control request succeeding",
|
||||
"reachability": "control request returns the normal page", "preconditions": "same authenticated session",
|
||||
"reproducibility": "the original request no longer changes state", "scope": "the same endpoint",
|
||||
"impact": "the previous effect is gone", "control_reachable": true, "mechanism_invalid": true,
|
||||
})
|
||||
if err != nil || fixed == nil || fixed.IsError {
|
||||
t.Fatalf("assigned finding update denied: %v %+v", err, fixed)
|
||||
}
|
||||
got, err := db.GetVulnerability(findings[0].ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
|
@ -81,7 +103,7 @@ func TestVulnerabilityRetestMCPUpdatesOnlyAssignedFinding(t *testing.T) {
|
|||
t.Fatalf("unrelated finding changed: %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
result, _, err := server.CallTool(ctx, builtin.ToolGetVulnerability, map[string]interface{}{"id": findings[0].ID})
|
||||
result, _, err = server.CallTool(ctx, builtin.ToolGetVulnerability, map[string]interface{}{"id": findings[0].ID})
|
||||
if err != nil || result.IsError {
|
||||
t.Fatalf("branch cannot read source finding: %v %+v", err, result)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package app
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
|
|
@ -14,6 +15,8 @@ import (
|
|||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const vulnerabilityIDRecovery = "请用 list_vulnerabilities 的 q 参数搜索标题或 ID 片段,再使用返回的完整 id。"
|
||||
|
||||
func conversationIDFromToolCtx(ctx context.Context) string {
|
||||
if id := agent.ConversationIDFromContext(ctx); id != "" {
|
||||
return id
|
||||
|
|
@ -49,6 +52,11 @@ func buildVulnerabilityListFilter(db *database.DB, ctx context.Context, args map
|
|||
if pid, err := db.GetConversationProjectID(convID); err == nil {
|
||||
projectID = strings.TrimSpace(pid)
|
||||
}
|
||||
if projectID != "" {
|
||||
if p, err := db.GetProject(projectID); err == nil && p.Status == database.ProjectStatusArchived {
|
||||
return database.VulnerabilityListFilter{}, "", fmt.Errorf("项目已归档,关联漏洞已随项目归档;恢复项目后可在对话中查询,或从控制台已归档项目中查阅")
|
||||
}
|
||||
}
|
||||
|
||||
scope := strings.TrimSpace(strArg(args, "scope"))
|
||||
if scope == "" {
|
||||
|
|
@ -59,7 +67,9 @@ func buildVulnerabilityListFilter(db *database.DB, ctx context.Context, args map
|
|||
}
|
||||
}
|
||||
|
||||
archived := false
|
||||
filter := database.VulnerabilityListFilter{
|
||||
Archived: &archived,
|
||||
Severity: strings.TrimSpace(strArg(args, "severity")),
|
||||
Status: strings.TrimSpace(strArg(args, "status")),
|
||||
}
|
||||
|
|
@ -103,6 +113,13 @@ func formatVulnerabilityDetail(v *database.Vulnerability) string {
|
|||
b.WriteString(fmt.Sprintf("标题: %s\n", v.Title))
|
||||
b.WriteString(fmt.Sprintf("严重程度: %s\n", v.Severity))
|
||||
b.WriteString(fmt.Sprintf("状态: %s\n", v.Status))
|
||||
if v.Archived {
|
||||
if v.ProjectArchived {
|
||||
b.WriteString("归档状态: 随项目归档\n")
|
||||
} else {
|
||||
b.WriteString("归档状态: 已归档\n")
|
||||
}
|
||||
}
|
||||
if v.Type != "" {
|
||||
b.WriteString(fmt.Sprintf("类型: %s\n", v.Type))
|
||||
}
|
||||
|
|
@ -208,6 +225,9 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
|
|||
InputSchema: map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"evidence_receipt_ids": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "深度测评专用:本意图已成功执行的原始回执 ID(1–32 个)。存疑线索应写为事实,不能用摘要或其他意图回执替代。"},
|
||||
"asset_ids": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "可选。受影响资产 ID。提供后指纹优先使用这些 ID,而不是从目标文本猜测主机。"},
|
||||
"force_distinct_reason": map[string]interface{}{"type": "string", "description": "可选。同路径但根因不同时填写,例如水平越权与垂直越权。非空则不并入已有指纹相同的漏洞。最多 500 个字符。"},
|
||||
"title": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "漏洞标题(必需)。建议格式:<资产/接口> 存在 <漏洞类型>,例如“/api/login 存在 SQL 注入”。",
|
||||
|
|
@ -266,6 +286,31 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
|
|||
if conversationID == "" {
|
||||
return textResult("错误: conversation_id 未设置。这是系统错误,请重试。", true), nil
|
||||
}
|
||||
// The execution context owns provenance; a model cannot redirect an
|
||||
// assessment report into another conversation to bypass evidence checks.
|
||||
if actual := conversationIDFromToolCtx(ctx); actual != "" {
|
||||
assessment, err := db.IsAssessmentConversation(actual)
|
||||
if err != nil {
|
||||
return textResult(err.Error(), true), nil
|
||||
}
|
||||
if assessment {
|
||||
conversationID = actual
|
||||
}
|
||||
}
|
||||
refs := []string{}
|
||||
switch values := args["evidence_receipt_ids"].(type) {
|
||||
case []any:
|
||||
for _, value := range values {
|
||||
if ref, ok := value.(string); ok {
|
||||
refs = append(refs, ref)
|
||||
}
|
||||
}
|
||||
case []string:
|
||||
refs = values
|
||||
}
|
||||
if err := db.ValidateAssessmentFinding(conversationID, refs); err != nil {
|
||||
return textResult(err.Error(), true), nil
|
||||
}
|
||||
|
||||
title := strings.TrimSpace(strArg(args, "title"))
|
||||
if title == "" {
|
||||
|
|
@ -291,22 +336,65 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
|
|||
if pid, perr := db.GetConversationProjectID(conversationID); perr == nil {
|
||||
projectID = strings.TrimSpace(pid)
|
||||
}
|
||||
if projectID != "" {
|
||||
if p, perr := db.GetProject(projectID); perr == nil && p.Status == database.ProjectStatusArchived {
|
||||
return textResult("错误: 当前对话绑定的项目已归档,恢复项目或切换工作区后可记录新漏洞", true), nil
|
||||
}
|
||||
}
|
||||
assetIDs := stringArgs(args["asset_ids"])
|
||||
distinct := strings.TrimSpace(strArg(args, "force_distinct_reason"))
|
||||
if len([]rune(distinct)) > 500 {
|
||||
return textResult("错误: force_distinct_reason 最多 500 个字符", true), nil
|
||||
}
|
||||
fingerprint := database.VulnerabilityFingerprint(strArg(args, "vulnerability_type"), strArg(args, "target"), strings.Join([]string{title, strArg(args, "description"), strArg(args, "evidence")}, "\n"), assetIDs)
|
||||
if distinct == "" && fingerprint != "" {
|
||||
scope := database.DedupScope{ProjectID: projectID}
|
||||
if projectID == "" {
|
||||
assessmentID, ok, err := db.AssessmentIDForConversation(conversationID)
|
||||
if err != nil {
|
||||
return textResult("错误: "+err.Error(), true), nil
|
||||
}
|
||||
if ok {
|
||||
scope.AssessmentID = assessmentID
|
||||
} else {
|
||||
scope.ConversationID = conversationID
|
||||
}
|
||||
}
|
||||
userID, access := "", ""
|
||||
if principal, ok := authctx.PrincipalFromContext(ctx); ok {
|
||||
userID = principal.UserID
|
||||
access = principal.ScopeFor("vulnerability:read")
|
||||
}
|
||||
duplicate, err := db.FindVulnerabilityDuplicate(scope, fingerprint, userID, access)
|
||||
if err != nil {
|
||||
return textResult("错误: 指纹查重失败", true), nil
|
||||
}
|
||||
if duplicate != nil {
|
||||
if !duplicate.Readable {
|
||||
return textResult("未重复建单。当前范围内已有相同指纹的漏洞,但当前身份不能查看它。若这是不同根因,请带 force_distinct_reason 重新记录。", true), nil
|
||||
}
|
||||
return textResult(fmt.Sprintf("未重复建单。已有相同指纹的漏洞。\n\n漏洞ID: %s\n若同路径但是不同根因(例如水平越权与垂直越权),请带 force_distinct_reason 说明差异后重新记录。", duplicate.ID), false), nil
|
||||
}
|
||||
}
|
||||
|
||||
vuln := &database.Vulnerability{
|
||||
ConversationID: conversationID,
|
||||
ProjectID: projectID,
|
||||
Title: title,
|
||||
Description: strArg(args, "description"),
|
||||
Severity: severity,
|
||||
Status: "open",
|
||||
Type: strArg(args, "vulnerability_type"),
|
||||
Target: strArg(args, "target"),
|
||||
Preconditions: strArg(args, "preconditions"),
|
||||
ReproSteps: strArg(args, "reproduction_steps"),
|
||||
Evidence: strArg(args, "evidence"),
|
||||
Impact: strArg(args, "impact"),
|
||||
Recommendation: strArg(args, "recommendation"),
|
||||
RetestNotes: strArg(args, "retest_notes"),
|
||||
EvidenceReceiptIDs: refs,
|
||||
ConversationID: conversationID,
|
||||
ProjectID: projectID,
|
||||
Title: title,
|
||||
Description: strArg(args, "description"),
|
||||
Severity: severity,
|
||||
Status: "open",
|
||||
Type: strArg(args, "vulnerability_type"),
|
||||
Target: strArg(args, "target"),
|
||||
Preconditions: strArg(args, "preconditions"),
|
||||
ReproSteps: strArg(args, "reproduction_steps"),
|
||||
Evidence: strArg(args, "evidence"),
|
||||
Impact: strArg(args, "impact"),
|
||||
Recommendation: strArg(args, "recommendation"),
|
||||
RetestNotes: strArg(args, "retest_notes"),
|
||||
Fingerprint: fingerprint,
|
||||
AssetIDs: assetIDs,
|
||||
}
|
||||
|
||||
created, err := db.CreateVulnerability(vuln)
|
||||
|
|
@ -319,6 +407,11 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
|
|||
if principal, ok := authctx.PrincipalFromContext(ctx); ok {
|
||||
_ = db.SetResourceOwner("vulnerability", created.ID, principal.UserID)
|
||||
_ = db.AssignResourceToUser(principal.UserID, "vulnerability", created.ID)
|
||||
if projectID != "" && principal.HasPermission("asset:write") {
|
||||
_, _ = db.SyncVulnerabilityTargetToAssets(projectID, created.Target, principal.UserID, principal.ScopeFor("asset:write") == database.RBACScopeAll)
|
||||
}
|
||||
} else if projectID != "" {
|
||||
_, _ = db.SyncVulnerabilityTargetToAssets(projectID, created.Target, "", true)
|
||||
}
|
||||
db.NotifyVulnerabilityCreated(created)
|
||||
|
||||
|
|
@ -361,7 +454,7 @@ func registerListVulnerabilitiesTool(mcpServer *mcp.Server, db *database.DB, log
|
|||
},
|
||||
"q": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "关键词搜索(标题、描述、类型、目标等)",
|
||||
"description": "搜索标题、描述、类型、目标或漏洞 ID(支持搜索 ID 片段,结果包含完整 ID)",
|
||||
},
|
||||
"limit": map[string]interface{}{
|
||||
"type": "integer",
|
||||
|
|
@ -486,9 +579,17 @@ func registerUpdateVulnerabilityStatusTool(server *mcp.Server, db *database.DB,
|
|||
ShortDescription: "更新漏洞状态与复测结果",
|
||||
InputSchema: map[string]interface{}{
|
||||
"type": "object", "properties": map[string]interface{}{
|
||||
"id": map[string]interface{}{"type": "string", "description": "已有漏洞 ID"},
|
||||
"status": map[string]interface{}{"type": "string", "enum": []string{"open", "confirmed", "fixed", "false_positive", "ignored"}},
|
||||
"retest_notes": map[string]interface{}{"type": "string", "description": "本次复测方法、请求/响应或工具输出证据及结论,必填"},
|
||||
"id": map[string]interface{}{"type": "string", "description": "list_vulnerabilities 返回的完整漏洞 id"},
|
||||
"status": map[string]interface{}{"type": "string", "enum": []string{"open", "confirmed", "fixed", "false_positive", "ignored"}},
|
||||
"retest_notes": map[string]interface{}{"type": "string", "description": "本次复测方法、请求/响应或工具输出证据及结论,必填"},
|
||||
"reachability": map[string]interface{}{"type": "string", "description": "可达性。判 fixed 或 false_positive 时必填。"},
|
||||
"preconditions": map[string]interface{}{"type": "string", "description": "前置条件。判 fixed 或 false_positive 时必填。"},
|
||||
"reproducibility": map[string]interface{}{"type": "string", "description": "可复现性。判 fixed 或 false_positive 时必填。"},
|
||||
"scope": map[string]interface{}{"type": "string", "description": "影响范围是否仍是原目标。判 fixed 或 false_positive 时必填。"},
|
||||
"impact": map[string]interface{}{"type": "string", "description": "实际影响是否仍然成立。判 fixed 或 false_positive 时必填。"},
|
||||
"control_reachable": map[string]interface{}{"type": "boolean", "description": "正常对照组是否可达。判 fixed 或 false_positive 时必须为 true。"},
|
||||
"mechanism_invalid": map[string]interface{}{"type": "boolean", "description": "原漏洞机理是否已失效。判 fixed 或 false_positive 时必须为 true。"},
|
||||
"blocked_by": map[string]interface{}{"type": "string", "enum": []string{"waf", "missing_login", "single_failure"}, "description": "单次失败、缺登录或 WAF。设置后 status 只能是 open。"},
|
||||
}, "required": []string{"id", "status", "retest_notes"},
|
||||
},
|
||||
}, func(ctx context.Context, args map[string]interface{}) (*mcp.ToolResult, error) {
|
||||
|
|
@ -504,18 +605,73 @@ func registerUpdateVulnerabilityStatusTool(server *mcp.Server, db *database.DB,
|
|||
}
|
||||
v, err := db.GetVulnerability(id)
|
||||
if err != nil {
|
||||
return textResult("错误: 漏洞不存在", true), nil
|
||||
if errors.Is(err, database.ErrVulnerabilityNotFound) {
|
||||
return textResult("错误: 未找到该漏洞。"+vulnerabilityIDRecovery, true), nil
|
||||
}
|
||||
if logger != nil {
|
||||
logger.Error("读取待更新漏洞失败", zap.Error(err))
|
||||
}
|
||||
return textResult("错误: 读取待更新漏洞失败", true), nil
|
||||
}
|
||||
pid, err := db.GetConversationProjectID(convID)
|
||||
if err != nil || !canAccessVulnerabilityForRetest(db, v, convID, strings.TrimSpace(pid)) {
|
||||
return textResult("错误: 无权更新该漏洞", true), nil
|
||||
}
|
||||
review, present := adversarialReviewFromToolArgs(args)
|
||||
if status == "fixed" || status == "false_positive" || present {
|
||||
if review == nil {
|
||||
review = &database.AdversarialReview{}
|
||||
}
|
||||
if err = review.Validate(status); err != nil {
|
||||
return textResult("错误: "+err.Error(), true), nil
|
||||
}
|
||||
}
|
||||
if err = db.UpdateVulnerabilityRetestResult(id, status, notes, convID); err != nil {
|
||||
return textResult("错误: 更新漏洞失败", true), nil
|
||||
}
|
||||
if present {
|
||||
if err = db.SaveVulnerabilityQuality(id, *review); err != nil {
|
||||
return textResult("错误: 保存五维复核失败", true), nil
|
||||
}
|
||||
}
|
||||
if logger != nil {
|
||||
logger.Info("更新漏洞复测状态", zap.String("id", id), zap.String("status", status), zap.String("conversation_id", convID))
|
||||
}
|
||||
return textResult(fmt.Sprintf("漏洞 %s 状态已更新为 %s,复测证据已保存。", id, status), false), nil
|
||||
})
|
||||
}
|
||||
|
||||
func stringArgs(value interface{}) []string {
|
||||
switch values := value.(type) {
|
||||
case []string:
|
||||
return values
|
||||
case []any:
|
||||
out := make([]string, 0, len(values))
|
||||
for _, item := range values {
|
||||
if text, ok := item.(string); ok {
|
||||
out = append(out, text)
|
||||
}
|
||||
}
|
||||
return out
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func adversarialReviewFromToolArgs(args map[string]interface{}) (*database.AdversarialReview, bool) {
|
||||
review := database.AdversarialReview{
|
||||
Reachability: strings.TrimSpace(strArg(args, "reachability")),
|
||||
Preconditions: strings.TrimSpace(strArg(args, "preconditions")),
|
||||
Reproducibility: strings.TrimSpace(strArg(args, "reproducibility")),
|
||||
Scope: strings.TrimSpace(strArg(args, "scope")),
|
||||
Impact: strings.TrimSpace(strArg(args, "impact")),
|
||||
BlockedBy: strings.TrimSpace(strArg(args, "blocked_by")),
|
||||
ControlReachable: boolArg(args, "control_reachable"),
|
||||
MechanismInvalid: boolArg(args, "mechanism_invalid"),
|
||||
}
|
||||
present := review.Reachability != "" || review.Preconditions != "" || review.Reproducibility != "" || review.Scope != "" || review.Impact != "" || review.BlockedBy != "" || review.ControlReachable || review.MechanismInvalid
|
||||
if !present {
|
||||
return nil, false
|
||||
}
|
||||
return &review, true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,105 @@
|
|||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/authctx"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
"cyberstrike-ai/internal/mcp/builtin"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestVulnerabilityToolsRespectArchivedProject(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "vuln-archive-tools.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
user, err := db.CreateRBACUser("tester", "Tester", "hash", true, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proj, err := db.CreateProject(&database.Project{Name: "Project Alpha"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conv, err := db.CreateConversation("Alpha chat", database.ConversationCreateMeta{ProjectID: proj.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
server := mcp.NewServer(zap.NewNop())
|
||||
server.SetToolAuthorizer(mcpToolAuthorizer(db))
|
||||
registerVulnerabilityTools(server, db, zap.NewNop())
|
||||
|
||||
ctx := authctx.WithPrincipal(
|
||||
mcp.WithMCPConversationID(context.Background(), conv.ID),
|
||||
authctx.NewPrincipal(user.ID, user.Username, database.RBACScopeAll, map[string]bool{
|
||||
"vulnerability:read": true,
|
||||
"vulnerability:write": true,
|
||||
}),
|
||||
)
|
||||
|
||||
recordArgs := map[string]interface{}{
|
||||
"title": "/api/login 存在 SQL 注入",
|
||||
"description": "username 参数直接拼接 SQL",
|
||||
"severity": "high",
|
||||
"vulnerability_type": "SQL注入",
|
||||
"target": "https://example.com/api/login",
|
||||
"reproduction_steps": "1. POST /api/login username=' OR 1=1--",
|
||||
"evidence": "HTTP/1.1 200 OK admin session",
|
||||
"impact": "绕过登录认证",
|
||||
"recommendation": "使用参数化查询",
|
||||
}
|
||||
|
||||
res, _, err := server.CallTool(ctx, builtin.ToolRecordVulnerability, recordArgs)
|
||||
if err != nil || res == nil || res.IsError {
|
||||
t.Fatalf("expected active project record_vulnerability to succeed: %v %+v", err, res)
|
||||
}
|
||||
listRes, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{})
|
||||
if err != nil || listRes == nil || listRes.IsError || !strings.Contains(mcp.ToolResultPlainText(listRes), "/api/login 存在 SQL 注入") {
|
||||
t.Fatalf("expected active project list_vulnerabilities to include finding: %v %+v", err, listRes)
|
||||
}
|
||||
|
||||
items, err := db.ListVulnerabilities(10, 0, database.VulnerabilityListFilter{ProjectID: proj.ID})
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("expected 1 finding in DB, got %d (%v)", len(items), err)
|
||||
}
|
||||
findingID := items[0].ID
|
||||
|
||||
archivedStatus := database.ProjectStatusArchived
|
||||
if _, err := db.UpdateProject(proj.ID, database.ProjectUpdate{Status: &archivedStatus}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
recBlocked, _, err := server.CallTool(ctx, builtin.ToolRecordVulnerability, recordArgs)
|
||||
if err != nil || recBlocked == nil || !recBlocked.IsError || !strings.Contains(mcp.ToolResultPlainText(recBlocked), "项目已归档") {
|
||||
t.Fatalf("expected record_vulnerability to reject archived project: %v %+v", err, recBlocked)
|
||||
}
|
||||
for _, scope := range []string{"project", "conversation"} {
|
||||
listBlocked, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{"scope": scope})
|
||||
if err != nil || listBlocked == nil || !listBlocked.IsError || !strings.Contains(mcp.ToolResultPlainText(listBlocked), "项目已归档") {
|
||||
t.Fatalf("expected list_vulnerabilities(%s) to report archived project: %v %+v", scope, err, listBlocked)
|
||||
}
|
||||
}
|
||||
|
||||
detailRes, _, err := server.CallTool(ctx, builtin.ToolGetVulnerability, map[string]interface{}{"id": findingID})
|
||||
if err != nil || detailRes == nil || detailRes.IsError || !strings.Contains(mcp.ToolResultPlainText(detailRes), "归档状态: 随项目归档") {
|
||||
t.Fatalf("expected get_vulnerability to show project-archived status: %v %+v", err, detailRes)
|
||||
}
|
||||
|
||||
activeStatus := "active"
|
||||
if _, err := db.UpdateProject(proj.ID, database.ProjectUpdate{Status: &activeStatus}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restoredList, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{})
|
||||
if err != nil || restoredList == nil || restoredList.IsError || !strings.Contains(mcp.ToolResultPlainText(restoredList), findingID) {
|
||||
t.Fatalf("expected restored project list_vulnerabilities to show finding again: %v %+v", err, restoredList)
|
||||
}
|
||||
}
|
||||
|
|
@ -5,16 +5,13 @@ import (
|
|||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/agent"
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/database"
|
||||
"cyberstrike-ai/internal/openai"
|
||||
"cyberstrike-ai/internal/multiagent"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
|
@ -24,8 +21,8 @@ import (
|
|||
type Builder struct {
|
||||
db *database.DB
|
||||
logger *zap.Logger
|
||||
openAIClient *openai.Client
|
||||
openAIConfig *config.OpenAIConfig
|
||||
agentRuntime config.AgentRuntimeConfig
|
||||
tokenCounter agent.TokenCounter
|
||||
maxTokens int // 最大tokens限制,默认100000
|
||||
}
|
||||
|
|
@ -45,13 +42,6 @@ type Chain struct {
|
|||
|
||||
// NewBuilder 创建新的攻击链构建器
|
||||
func NewBuilder(db *database.DB, openAIConfig *config.OpenAIConfig, logger *zap.Logger) *Builder {
|
||||
transport := &http.Transport{
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 10,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
httpClient := &http.Client{Timeout: 5 * time.Minute, Transport: transport}
|
||||
|
||||
// 优先使用配置文件中的统一 Token 上限(config.yaml -> openai.max_total_tokens)
|
||||
maxTokens := 0
|
||||
if openAIConfig != nil && openAIConfig.MaxTotalTokens > 0 {
|
||||
|
|
@ -76,13 +66,19 @@ func NewBuilder(db *database.DB, openAIConfig *config.OpenAIConfig, logger *zap.
|
|||
return &Builder{
|
||||
db: db,
|
||||
logger: logger,
|
||||
openAIClient: openai.NewClient(openAIConfig, httpClient, logger),
|
||||
openAIConfig: openAIConfig,
|
||||
tokenCounter: agent.NewTikTokenCounter(),
|
||||
maxTokens: maxTokens,
|
||||
}
|
||||
}
|
||||
|
||||
// SetAgentRuntime 配置 Pi 运行时路径覆盖。
|
||||
func (b *Builder) SetAgentRuntime(rt config.AgentRuntimeConfig) {
|
||||
if b != nil {
|
||||
b.agentRuntime = rt
|
||||
}
|
||||
}
|
||||
|
||||
// BuildChainFromConversation 从对话构建攻击链(单次 LLM 调用;输入为当前任务轮次的 last_react 轨迹,与继续对话续跑范围一致)。
|
||||
func (b *Builder) BuildChainFromConversation(ctx context.Context, conversationID string) (*Chain, error) {
|
||||
b.logger.Info("开始构建攻击链(简化版本)", zap.String("conversationId", conversationID))
|
||||
|
|
@ -885,51 +881,23 @@ func (b *Builder) LoadChainFromDatabase(conversationID string) (*Chain, error) {
|
|||
|
||||
// callAIForChainGeneration 调用AI生成攻击链
|
||||
func (b *Builder) callAIForChainGeneration(ctx context.Context, prompt string) (string, error) {
|
||||
requestBody := map[string]interface{}{
|
||||
"model": b.openAIConfig.Model,
|
||||
"messages": []map[string]interface{}{
|
||||
{
|
||||
"role": "system",
|
||||
"content": "你是一个专业的安全测试分析师,擅长构建攻击链图。请严格按照JSON格式返回攻击链数据。",
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt,
|
||||
},
|
||||
},
|
||||
"temperature": 0.3,
|
||||
"max_completion_tokens": attackChainMaxCompletionTokens(b.maxTokens),
|
||||
if b.openAIConfig == nil {
|
||||
return "", fmt.Errorf("OpenAI配置未初始化")
|
||||
}
|
||||
|
||||
var apiResponse struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
|
||||
if b.openAIClient == nil {
|
||||
return "", fmt.Errorf("OpenAI客户端未初始化")
|
||||
}
|
||||
if err := b.openAIClient.ChatCompletion(ctx, requestBody, &apiResponse); err != nil {
|
||||
var apiErr *openai.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
bodyStr := strings.ToLower(apiErr.Body)
|
||||
if strings.Contains(bodyStr, "context") || strings.Contains(bodyStr, "length") || strings.Contains(bodyStr, "too long") {
|
||||
return "", fmt.Errorf("context length exceeded")
|
||||
}
|
||||
} else if strings.Contains(strings.ToLower(err.Error()), "context") || strings.Contains(strings.ToLower(err.Error()), "length") {
|
||||
content, err := multiagent.CompleteTextWithRuntime(ctx, b.agentRuntime, *b.openAIConfig, multiagent.SingleShot{
|
||||
SystemPrompt: "你是一个专业的安全测试分析师,擅长构建攻击链图。请严格按照JSON格式返回攻击链数据。",
|
||||
Message: prompt,
|
||||
MaxTokens: attackChainMaxCompletionTokens(b.maxTokens),
|
||||
ExtraFields: map[string]any{"temperature": 0.3},
|
||||
})
|
||||
if err != nil {
|
||||
lower := strings.ToLower(err.Error())
|
||||
if strings.Contains(lower, "context") || strings.Contains(lower, "length") || strings.Contains(lower, "too long") {
|
||||
return "", fmt.Errorf("context length exceeded")
|
||||
}
|
||||
return "", fmt.Errorf("请求失败: %w", err)
|
||||
}
|
||||
|
||||
if len(apiResponse.Choices) == 0 {
|
||||
return "", fmt.Errorf("API未返回有效响应")
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(apiResponse.Choices[0].Message.Content)
|
||||
// 尝试提取JSON(可能包含markdown代码块)
|
||||
content = strings.TrimPrefix(content, "```json")
|
||||
content = strings.TrimPrefix(content, "```")
|
||||
|
|
|
|||
|
|
@ -197,6 +197,7 @@ func TestCachedSingleNodeAndEmptyGraphSerializeArrays(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestBuildAndCachedContextKeepConversationScopeAndGraphEvidence(t *testing.T) {
|
||||
requirePiRuntime(t)
|
||||
db := newContextSummaryTestDB(t)
|
||||
project, err := db.CreateProject(&database.Project{Name: "Shared project"})
|
||||
if err != nil {
|
||||
|
|
@ -246,7 +247,7 @@ func TestBuildAndCachedContextKeepConversationScopeAndGraphEvidence(t *testing.T
|
|||
return
|
||||
}
|
||||
requests <- payload.Messages[1].Content
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"choices": []interface{}{map[string]interface{}{"message": map[string]string{"content": `{"nodes":[{"id":"target","type":"target","label":"scope.example"},{"id":"scan","type":"action","label":"Actual scan","tool_call_id":"call-1","metadata":{"tool_name":"scan"}}],"edges":[{"source":"target","target":"scan","type":"leads_to"}],"context_summaries":[{"content":"MODEL_INVENTED_SUMMARY"}]}`}}}})
|
||||
piTextReply(w, `{"nodes":[{"id":"target","type":"target","label":"scope.example"},{"id":"scan","type":"action","label":"Actual scan","tool_call_id":"call-1","metadata":{"tool_name":"scan"}}],"edges":[{"source":"target","target":"scan","type":"leads_to"}],"context_summaries":[{"content":"MODEL_INVENTED_SUMMARY"}]}`)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
b := NewBuilder(db, &config.OpenAIConfig{BaseURL: server.URL, APIKey: "test-only", Model: "gpt-4", MaxTotalTokens: 32000}, zap.NewNop())
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
package attackchain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/agentruntime"
|
||||
)
|
||||
|
||||
func requirePiRuntime(t *testing.T) {
|
||||
t.Helper()
|
||||
if _, err := exec.LookPath("node"); err != nil {
|
||||
t.Skip("Node not installed")
|
||||
}
|
||||
if _, err := agentruntime.ResolveWorker(""); err != nil {
|
||||
t.Skip("build runtime/pi before Pi integration tests")
|
||||
}
|
||||
}
|
||||
|
||||
func piTextReply(w http.ResponseWriter, text string) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
for _, choice := range []map[string]any{
|
||||
{"index": 0, "delta": map[string]any{"role": "assistant", "content": text}, "finish_reason": nil},
|
||||
{"index": 0, "delta": map[string]any{}, "finish_reason": "stop"},
|
||||
} {
|
||||
body, _ := json.Marshal(map[string]any{"id": "fixture", "object": "chat.completion.chunk", "model": "fixture", "choices": []any{choice}})
|
||||
fmt.Fprintf(w, "data: %s\n\n", body)
|
||||
}
|
||||
fmt.Fprint(w, "data: [DONE]\n\n")
|
||||
}
|
||||
|
|
@ -21,6 +21,8 @@ import (
|
|||
)
|
||||
|
||||
type Config struct {
|
||||
Plugins PluginsConfig `yaml:"plugins,omitempty" json:"-"`
|
||||
Proxy ProxyConfig `yaml:"proxy,omitempty" json:"proxy"`
|
||||
Version string `yaml:"version,omitempty" json:"version,omitempty"` // 前端显示的版本号,如 v1.3.3
|
||||
Server ServerConfig `yaml:"server"`
|
||||
Log LogConfig `yaml:"log"`
|
||||
|
|
@ -55,11 +57,13 @@ type Config struct {
|
|||
Update UpdateConfig `yaml:"update,omitempty" json:"update,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateConfig 一键更新的更新源(可选):一个仓库地址,更新跟随该仓库的默认分支。
|
||||
// 留空即官方仓库(internal/update.DefaultRepoURL),跟随镜像或自己的二开只需改这一处。
|
||||
// UpdateConfig 一键更新的更新源(可选):仓库地址与目标分支。
|
||||
// 仓库留空即官方仓库(internal/update.DefaultRepoURL);分支留空即跟随该仓库的默认分支。
|
||||
type UpdateConfig struct {
|
||||
// Repo 更新源仓库地址(https/http/ssh/git/file:// 或本机绝对路径);留空 = 官方仓库。
|
||||
Repo string `yaml:"repo,omitempty" json:"repo,omitempty"`
|
||||
// Branch 目标分支名(如 main、feat/plugin-capability-platform);留空 = 跟随仓库默认分支。
|
||||
Branch string `yaml:"branch,omitempty" json:"branch,omitempty"`
|
||||
}
|
||||
|
||||
type EnsureLocalConfigResult struct {
|
||||
|
|
@ -126,7 +130,7 @@ type MultiAgentConfig struct {
|
|||
Orchestration string `yaml:"orchestration,omitempty" json:"orchestration,omitempty"`
|
||||
// MaxIteration 已废弃:统一使用 agent.max_iterations(YAML 中保留字段仅为兼容旧配置,运行时不读取)。
|
||||
MaxIteration int `yaml:"max_iteration,omitempty" json:"max_iteration,omitempty"`
|
||||
// PlanExecuteLoopMaxIterations plan_execute 模式下 execute↔replan 外层循环上限;0 表示用 Agent 默认 10。
|
||||
// PlanExecuteLoopMaxIterations plan_execute 模式下向 executor 委派的外层步数上限;0 表示不单独限制(统一受 agent.max_iterations 约束)。
|
||||
PlanExecuteLoopMaxIterations int `yaml:"plan_execute_loop_max_iterations,omitempty" json:"plan_execute_loop_max_iterations,omitempty"`
|
||||
// SubAgentMaxIterations 已废弃:子代理与主代理均使用 agent.max_iterations(Markdown max_iterations>0 可覆盖)。
|
||||
SubAgentMaxIterations int `yaml:"sub_agent_max_iterations,omitempty" json:"sub_agent_max_iterations,omitempty"`
|
||||
|
|
@ -154,6 +158,8 @@ func (c MultiAgentConfig) SubAgentUserContextMaxRunesEffective() int {
|
|||
|
||||
// AgentTuningConfig optional Pi middleware and Deep / supervisor tuning.
|
||||
type AgentTuningConfig struct {
|
||||
// PromptCachePrefixSplit sends the stable role prompt and per-run context in separate Pi request fields.
|
||||
PromptCachePrefixSplit bool `yaml:"prompt_cache_prefix_split,omitempty" json:"prompt_cache_prefix_split,omitempty"`
|
||||
// PatchToolCalls inserts placeholder tool results for dangling assistant tool_calls (nil = enabled).
|
||||
PatchToolCalls *bool `yaml:"patch_tool_calls,omitempty" json:"patch_tool_calls,omitempty"`
|
||||
// ToolSearch enables dynamictool/toolsearch: hide tail tools until model calls tool_search (reduces prompt tools).
|
||||
|
|
@ -164,10 +170,19 @@ type AgentTuningConfig struct {
|
|||
ToolSearchAlwaysVisibleTools []string `yaml:"tool_search_always_visible_tools,omitempty" json:"tool_search_always_visible_tools,omitempty"`
|
||||
// ToolSearchIncludeBuiltins keeps backend builtin tools always visible (nil = true).
|
||||
ToolSearchIncludeBuiltins *bool `yaml:"tool_search_include_builtins,omitempty" json:"tool_search_include_builtins,omitempty"`
|
||||
// CodemodeEnable turns on Pi's native QuickJS-WASI codemode extension for sandboxed batched tool orchestration.
|
||||
CodemodeEnable bool `yaml:"codemode_enable" json:"codemode_enable"`
|
||||
// CodemodeMode selects the codemode loadout presentation: "" / "on" (default) / "only".
|
||||
CodemodeMode string `yaml:"codemode_mode,omitempty" json:"codemode_mode,omitempty"`
|
||||
// CodemodeInlineBudget caps estimated tokens of tool declarations in the codemode description; positive values pass through.
|
||||
CodemodeInlineBudget int `yaml:"codemode_inline_budget,omitempty" json:"codemode_inline_budget,omitempty"`
|
||||
// Plantask adds TaskCreate/Get/Update/List (file-backed under skills dir); requires skills and its configured directory.
|
||||
PlantaskEnable bool `yaml:"plantask_enable,omitempty" json:"plantask_enable,omitempty"`
|
||||
// PlantaskRelDir relative to skills_dir for per-conversation task boards (default .pi/plantask).
|
||||
PlantaskRelDir string `yaml:"plantask_rel_dir,omitempty" json:"plantask_rel_dir,omitempty"`
|
||||
// PromptGuardToolResults frames untrusted tool output with a per-message nonce.
|
||||
// Nil or false keeps the existing result text, including spill notices.
|
||||
PromptGuardToolResults *bool `yaml:"prompt_guard_tool_results,omitempty" json:"prompt_guard_tool_results,omitempty"`
|
||||
// Reduction truncates/offloads large tool outputs (uses the host output store).
|
||||
ReductionEnable bool `yaml:"reduction_enable,omitempty" json:"reduction_enable,omitempty"`
|
||||
ReductionRootDir string `yaml:"reduction_root_dir,omitempty" json:"reduction_root_dir,omitempty"` // 非空:落盘根目录(默认 tmp/reduction);其下按 projects/{id} 或 conversations/{id} 隔离
|
||||
|
|
@ -222,10 +237,22 @@ type AgentTuningConfig struct {
|
|||
RunRetryMaxBackoffSec int `yaml:"run_retry_max_backoff_sec,omitempty" json:"run_retry_max_backoff_sec,omitempty"`
|
||||
// EmptyResponseContinueMaxAttempts Run 成功但未捕获助手正文时 Handler 层退避续跑次数;0=默认 5。
|
||||
EmptyResponseContinueMaxAttempts int `yaml:"empty_response_continue_max_attempts,omitempty" json:"empty_response_continue_max_attempts,omitempty"`
|
||||
// OutputTruncationContinueMaxAttempts 模型输出触达长度上限后的自动续写次数;0=默认 2,小于 0 关闭,大于 5 按 5。
|
||||
OutputTruncationContinueMaxAttempts int `yaml:"output_truncation_continue_max_attempts,omitempty" json:"output_truncation_continue_max_attempts,omitempty"`
|
||||
// TaskToolDescriptionPrefix when non-empty sets deep.Config TaskToolDescriptionGenerator (sub-agent names appended).
|
||||
TaskToolDescriptionPrefix string `yaml:"task_tool_description_prefix,omitempty" json:"task_tool_description_prefix,omitempty"`
|
||||
}
|
||||
|
||||
// ValidateCodemode rejects codemode_mode values Pi cannot interpret.
|
||||
func (c AgentTuningConfig) ValidateCodemode() error {
|
||||
switch c.CodemodeMode {
|
||||
case "", "on", "only":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("multi_agent.runtime.codemode_mode 仅支持留空、on 或 only,当前为 %q", c.CodemodeMode)
|
||||
}
|
||||
}
|
||||
|
||||
func (c AgentTuningConfig) SummarizationTriggerRatioEffective() float64 {
|
||||
v := c.SummarizationTriggerRatio
|
||||
if v <= 0 {
|
||||
|
|
@ -331,6 +358,10 @@ func (c AgentTuningConfig) PlanExecuteKeepLastStepsEffective() int {
|
|||
return 8
|
||||
}
|
||||
|
||||
func (c AgentTuningConfig) PromptGuardToolResultsEnabled() bool {
|
||||
return c.PromptGuardToolResults != nil && *c.PromptGuardToolResults
|
||||
}
|
||||
|
||||
func (c AgentTuningConfig) ReductionMaxLengthForTruncEffective() int {
|
||||
if c.ReductionMaxLengthForTrunc > 0 {
|
||||
return c.ReductionMaxLengthForTrunc
|
||||
|
|
@ -376,7 +407,7 @@ func (c AgentTuningConfig) ToolSearchIncludeBuiltinsEffective() bool {
|
|||
return c.ToolSearchIncludeBuiltins == nil || *c.ToolSearchIncludeBuiltins
|
||||
}
|
||||
|
||||
// MultiAgentSubConfig 子代理(Pi):deep 下由 task 调度;supervisor 下由 transfer 委派;plan_execute 不使用子代理列表。
|
||||
// MultiAgentSubConfig 子代理(Agent ChatModelAgent):deep 下由 task 调度;supervisor 下由 transfer 委派;plan_execute 不使用子代理列表。
|
||||
type MultiAgentSubConfig struct {
|
||||
ID string `yaml:"id" json:"id"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
|
|
@ -723,6 +754,7 @@ type OpenAIConfig struct {
|
|||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
BaseURL string `yaml:"base_url" json:"base_url"`
|
||||
Model string `yaml:"model" json:"model"`
|
||||
ImageInput string `yaml:"image_input,omitempty" json:"image_input,omitempty"`
|
||||
MaxTotalTokens int `yaml:"max_total_tokens,omitempty" json:"max_total_tokens,omitempty"`
|
||||
MaxCompletionTokens int `yaml:"max_completion_tokens,omitempty" json:"max_completion_tokens,omitempty"`
|
||||
// Headers 追加或覆盖发给模型网关的 HTTP 请求头,值支持 ${ENV_VAR} 展开。
|
||||
|
|
@ -750,6 +782,7 @@ type AIChannelConfig struct {
|
|||
APIKey string `yaml:"api_key" json:"api_key"`
|
||||
BaseURL string `yaml:"base_url" json:"base_url"`
|
||||
Model string `yaml:"model" json:"model"`
|
||||
ImageInput string `yaml:"image_input,omitempty" json:"image_input,omitempty"`
|
||||
MaxTotalTokens int `yaml:"max_total_tokens,omitempty" json:"max_total_tokens,omitempty"`
|
||||
MaxCompletionTokens int `yaml:"max_completion_tokens,omitempty" json:"max_completion_tokens,omitempty"`
|
||||
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"`
|
||||
|
|
@ -768,6 +801,7 @@ func (c AIChannelConfig) ToOpenAIConfig() OpenAIConfig {
|
|||
APIKey: c.APIKey,
|
||||
BaseURL: c.BaseURL,
|
||||
Model: c.Model,
|
||||
ImageInput: c.ImageInput,
|
||||
MaxTotalTokens: c.MaxTotalTokens,
|
||||
MaxCompletionTokens: c.MaxCompletionTokens,
|
||||
Headers: ExpandHeaderMap(c.Headers),
|
||||
|
|
@ -787,6 +821,7 @@ func AIChannelFromOpenAI(id, name string, oa OpenAIConfig) AIChannelConfig {
|
|||
APIKey: oa.APIKey,
|
||||
BaseURL: oa.BaseURL,
|
||||
Model: oa.Model,
|
||||
ImageInput: oa.ImageInput,
|
||||
MaxTotalTokens: oa.MaxTotalTokens,
|
||||
MaxCompletionTokens: oa.MaxCompletionTokens,
|
||||
Headers: ExpandHeaderMap(oa.Headers),
|
||||
|
|
@ -1553,9 +1588,18 @@ func Load(path string) (*Config, error) {
|
|||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("解析配置文件失败: %w", err)
|
||||
}
|
||||
if err := cfg.Proxy.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.Plugins.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.Agent.validateTaskTimeout(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.MultiAgent.Runtime.ValidateCodemode(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.ToolGuard != nil {
|
||||
if err := validateToolGuardYAML(data); err != nil {
|
||||
return nil, fmt.Errorf("调用拦截配置无效: %w", err)
|
||||
|
|
@ -2314,7 +2358,7 @@ func Default() *Config {
|
|||
},
|
||||
OpenAI: OpenAIConfig{},
|
||||
Agent: AgentConfig{
|
||||
MaxIterations: 30, // 默认最大迭代次数
|
||||
MaxIterations: 3000, // 默认最大迭代次数(与 multiagent.defaultAgentMaxIterations 一致)
|
||||
ToolTimeoutMinutes: 10, // 单次工具执行默认最多 10 分钟,避免异常长时间占用
|
||||
ToolWaitTimeoutSeconds: 60, // 外部 MCP 工具单轮最多等待 60 秒,超时后返回 execution_id 可继续等待
|
||||
ExternalMCPMaxConcurrentPerServer: 2, // 单个外部 MCP server 默认最多 2 个工具同时执行
|
||||
|
|
|
|||
|
|
@ -167,6 +167,8 @@ func TestLoadUsesAIDefaultChannelAsRuntimeOpenAI(t *testing.T) {
|
|||
" api_key: deepseek-key",
|
||||
" model: deepseek-chat",
|
||||
" max_total_tokens: 64000",
|
||||
" context_window: 131072",
|
||||
" context_profile: local",
|
||||
"server:",
|
||||
" host: 127.0.0.1",
|
||||
" port: 8080",
|
||||
|
|
@ -183,12 +185,88 @@ func TestLoadUsesAIDefaultChannelAsRuntimeOpenAI(t *testing.T) {
|
|||
if cfg.OpenAI.Model != "deepseek-chat" || cfg.OpenAI.APIKey != "deepseek-key" || cfg.OpenAI.MaxTotalTokens != 64000 {
|
||||
t.Fatalf("runtime OpenAI config did not follow ai.default_channel: %+v", cfg.OpenAI)
|
||||
}
|
||||
if cfg.OpenAI.ContextWindow != 131072 || cfg.OpenAI.ContextProfile != "local" {
|
||||
t.Fatalf("context profile fields not loaded: %+v", cfg.OpenAI)
|
||||
}
|
||||
oa, id, ok := cfg.ResolveAIChannel("qwen")
|
||||
if !ok || id != "qwen" || oa.Model != "qwen-max" || oa.APIKey != "qwen-key" {
|
||||
t.Fatalf("ResolveAIChannel(qwen) = (%+v, %q, %v)", oa, id, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidChannelContextSettings(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
profile string
|
||||
window string
|
||||
wantErr string
|
||||
}{
|
||||
{name: "unknown profile", profile: "turbo", wantErr: "context_profile"},
|
||||
{name: "negative window", profile: "local", window: "-1", wantErr: "context_window"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
lines := []string{
|
||||
"ai:",
|
||||
" default_channel: qwen",
|
||||
" channels:",
|
||||
" qwen:",
|
||||
" base_url: https://example.invalid/v1",
|
||||
" api_key: key",
|
||||
" model: qwen-max",
|
||||
}
|
||||
if tc.profile != "" {
|
||||
lines = append(lines, " context_profile: "+tc.profile)
|
||||
}
|
||||
if tc.window != "" {
|
||||
lines = append(lines, " context_window: "+tc.window)
|
||||
}
|
||||
lines = append(lines, "")
|
||||
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0644); err != nil {
|
||||
t.Fatalf("write config: %v", err)
|
||||
}
|
||||
_, err := Load(path)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("Load error = %v, want containing %q", err, tc.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidCodemodeMode(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, mode := range []string{"", "on", "only", "off", "batch"} {
|
||||
mode := mode
|
||||
t.Run("mode="+mode, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
body := "multi_agent:\n runtime:\n codemode_enable: true\n codemode_mode: " + mode + "\n"
|
||||
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
|
||||
t.Fatalf("write config: %v", err)
|
||||
}
|
||||
cfg, err := Load(path)
|
||||
if mode == "off" || mode == "batch" {
|
||||
if err == nil || !strings.Contains(err.Error(), "codemode_mode") {
|
||||
t.Fatalf("Load error = %v, want codemode_mode rejection", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if !cfg.MultiAgent.Runtime.CodemodeEnable || cfg.MultiAgent.Runtime.CodemodeMode != mode {
|
||||
t.Fatalf("codemode fields not preserved: %+v", cfg.MultiAgent.Runtime)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAIProviderProfilesForOfficialDeepSeekEndpoint(t *testing.T) {
|
||||
cfg := &Config{
|
||||
OpenAI: OpenAIConfig{
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ const (
|
|||
DefaultMaxTotalTokens = 120000
|
||||
// DefaultLocalContextWindow 是 local 档位下未提供 context_window 时的保守窗口。
|
||||
DefaultLocalContextWindow = 32768
|
||||
// DeepSeek's official /models response reports this total input and output window.
|
||||
deepSeekContextWindow = 1048576
|
||||
// LocalContextBudgetPercent 是 local 档位把原生窗口折算成提示词预算的比例。
|
||||
LocalContextBudgetPercent = 60
|
||||
// LocalContextBudgetCap 防止 256K/1M 窗口把预算放大到超出本地模型有效上下文。
|
||||
|
|
@ -58,14 +60,25 @@ func (c OpenAIConfig) OutputLimitField() string {
|
|||
return "max_completion_tokens"
|
||||
}
|
||||
|
||||
// EffectiveContextWindow 返回用于预算计算的原生窗口;local 档位缺省时按保守值处理。
|
||||
// EffectiveContextWindow returns the window used to calculate the token budget.
|
||||
func (c OpenAIConfig) EffectiveContextWindow() int {
|
||||
if c.ContextWindow > 0 {
|
||||
return c.ContextWindow
|
||||
}
|
||||
return c.DefaultContextWindow()
|
||||
}
|
||||
|
||||
// DefaultContextWindow is the fallback when the channel has no explicit window.
|
||||
func (c OpenAIConfig) DefaultContextWindow() int {
|
||||
if c.IsLocalContextProfile() {
|
||||
return DefaultLocalContextWindow
|
||||
}
|
||||
if c.IsDeepSeekOfficialEndpoint() {
|
||||
switch strings.ToLower(strings.TrimSpace(c.Model)) {
|
||||
case "deepseek-flash", "deepseek-v4-pro":
|
||||
return deepSeekContextWindow
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -42,6 +42,24 @@ func TestEffectiveMaxTotalTokens(t *testing.T) {
|
|||
oa: OpenAIConfig{},
|
||||
want: 120000,
|
||||
},
|
||||
{
|
||||
name: "official DeepSeek Flash uses its default window",
|
||||
oa: OpenAIConfig{BaseURL: "https://api.deepseek.com/v1", Model: "deepseek-flash",
|
||||
MaxTotalTokens: 2000000, MaxCompletionTokens: 32768},
|
||||
want: 1048576 - 32768,
|
||||
},
|
||||
{
|
||||
name: "official DeepSeek Flash preserves a manual window",
|
||||
oa: OpenAIConfig{BaseURL: "https://api.deepseek.com", Model: "deepseek-flash", ContextWindow: 65536,
|
||||
MaxTotalTokens: 2000000, MaxCompletionTokens: 32768},
|
||||
want: 65536 - 32768,
|
||||
},
|
||||
{
|
||||
name: "same model name on a different host has no known window",
|
||||
oa: OpenAIConfig{BaseURL: "https://api.deepseek.com.example.test", Model: "deepseek-flash",
|
||||
MaxTotalTokens: 2000000, MaxCompletionTokens: 32768},
|
||||
want: 2000000,
|
||||
},
|
||||
{
|
||||
name: "remote window reserves output",
|
||||
oa: OpenAIConfig{ContextWindow: 131072, MaxTotalTokens: 120000},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,39 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ImageInputCapability resolves explicit channel settings and known official
|
||||
// models whose capabilities are newer than the bundled Pi model catalog.
|
||||
// A nil result lets Pi look up the model and endpoint in its catalog.
|
||||
func (c OpenAIConfig) ImageInputCapability() *bool {
|
||||
switch c.ImageInput {
|
||||
case "enabled":
|
||||
enabled := true
|
||||
return &enabled
|
||||
case "disabled":
|
||||
enabled := false
|
||||
return &enabled
|
||||
}
|
||||
endpoint, err := url.Parse(strings.TrimSpace(c.BaseURL))
|
||||
if err != nil || endpoint.Scheme != "https" || endpoint.Host != "api.deepseek.com" || endpoint.User != nil {
|
||||
return nil
|
||||
}
|
||||
switch strings.TrimRight(endpoint.Path, "/") {
|
||||
case "", "/v1":
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
switch strings.TrimSpace(c.Model) {
|
||||
case "deepseek-flash", "deepseek-v4-flash-vision-exp":
|
||||
enabled := true
|
||||
return &enabled
|
||||
case "deepseek-v4-pro":
|
||||
enabled := false
|
||||
return &enabled
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestImageInputCapability(t *testing.T) {
|
||||
tests := []struct {
|
||||
url, model, mode string
|
||||
want string
|
||||
}{
|
||||
{"https://api.deepseek.com", "deepseek-flash", "", "enabled"},
|
||||
{"https://api.deepseek.com/v1", "deepseek-v4-pro", "", "disabled"},
|
||||
{"https://api.deepseek.com", "deepseek-flash", "disabled", "disabled"},
|
||||
{"https://custom.example/v1", "deepseek-flash", "", "unknown"},
|
||||
{"https://custom.example/v1", "local-model", "enabled", "enabled"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
capability := (OpenAIConfig{BaseURL: tt.url, Model: tt.model, ImageInput: tt.mode}).ImageInputCapability()
|
||||
got := "unknown"
|
||||
if capability != nil {
|
||||
got = "disabled"
|
||||
if *capability {
|
||||
got = "enabled"
|
||||
}
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("%s %s %s: got %s, want %s", tt.url, tt.model, tt.mode, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,205 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
PluginApprovalAdminConfirm = "admin_confirm"
|
||||
PluginApprovalHostConfigOnly = "host_config_only"
|
||||
)
|
||||
|
||||
// PluginsConfig is read at startup. The approval policy controls how locked
|
||||
// plans become eligible for execution.
|
||||
type PluginsConfig struct {
|
||||
ApprovalPolicy string `yaml:"approval_policy,omitempty" json:"-"`
|
||||
Directory string `yaml:"directory,omitempty" json:"-"`
|
||||
Egress PluginEgress `yaml:"egress,omitempty" json:"-"`
|
||||
ApprovedArtifacts map[string][]string `yaml:"approved_artifacts,omitempty" json:"-"`
|
||||
Proxy PluginProxyConfig `yaml:"proxy,omitempty" json:"-"`
|
||||
LLMGateway PluginLLMGatewayConfig `yaml:"llm_gateway,omitempty" json:"-"`
|
||||
}
|
||||
|
||||
type PluginEgress struct {
|
||||
ProxyMode string `yaml:"proxy_mode,omitempty"`
|
||||
ProxyURL string `yaml:"proxy_url,omitempty"`
|
||||
GitHubTokenEnv string `yaml:"github_token_env,omitempty"`
|
||||
AdditionalHosts []string `yaml:"additional_hosts,omitempty"`
|
||||
}
|
||||
|
||||
var pluginSHA256 = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
var pluginEnvName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,63}$`)
|
||||
var pluginRemoteHost = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]+$`)
|
||||
|
||||
func (p PluginsConfig) EffectiveApprovalPolicy() string {
|
||||
if p.ApprovalPolicy == "" {
|
||||
return PluginApprovalAdminConfirm
|
||||
}
|
||||
return p.ApprovalPolicy
|
||||
}
|
||||
|
||||
func (p PluginsConfig) Validate() error {
|
||||
if err := p.Proxy.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := p.LLMGateway.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
switch p.EffectiveApprovalPolicy() {
|
||||
case PluginApprovalAdminConfirm, PluginApprovalHostConfigOnly:
|
||||
default:
|
||||
return fmt.Errorf("plugins.approval_policy must be admin_confirm or host_config_only")
|
||||
}
|
||||
switch p.Egress.ProxyMode {
|
||||
case "", "system", "direct":
|
||||
if p.Egress.ProxyURL != "" {
|
||||
return fmt.Errorf("plugins.egress.proxy_url requires fixed mode")
|
||||
}
|
||||
case "fixed":
|
||||
u, err := url.Parse(p.Egress.ProxyURL)
|
||||
if err != nil || u.Host == "" || !strings.Contains("|http|https|socks5|", "|"+u.Scheme+"|") ||
|
||||
u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
||||
return fmt.Errorf("invalid plugins.egress.proxy_url")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("plugins.egress.proxy_mode must be system, direct or fixed")
|
||||
}
|
||||
if p.Egress.GitHubTokenEnv != "" && !pluginEnvName.MatchString(p.Egress.GitHubTokenEnv) {
|
||||
return fmt.Errorf("invalid plugins.egress.github_token_env")
|
||||
}
|
||||
for _, host := range p.Egress.AdditionalHosts {
|
||||
if !pluginRemoteHost.MatchString(host) || !strings.Contains(host, ".") || strings.Contains(host, "..") {
|
||||
return fmt.Errorf("invalid plugins.egress.additional_hosts entry")
|
||||
}
|
||||
}
|
||||
for declaration, artifacts := range p.ApprovedArtifacts {
|
||||
if !pluginSHA256.MatchString(declaration) || len(artifacts) == 0 {
|
||||
return fmt.Errorf("plugins.approved_artifacts requires declaration and artifact SHA-256 digests")
|
||||
}
|
||||
for _, artifact := range artifacts {
|
||||
if !pluginSHA256.MatchString(artifact) {
|
||||
return fmt.Errorf("invalid plugins.approved_artifacts artifact digest")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type PluginProxyConfig struct {
|
||||
Mode string `yaml:"mode,omitempty"`
|
||||
BindHost string `yaml:"bind_host,omitempty"`
|
||||
PortPool PluginPortPool `yaml:"port_pool,omitempty"`
|
||||
HostSuffix string `yaml:"host_suffix,omitempty"`
|
||||
PublicOrigin string `yaml:"public_origin,omitempty"`
|
||||
ExternalPorts map[int]int `yaml:"external_ports,omitempty"`
|
||||
}
|
||||
|
||||
type PluginPortPool struct {
|
||||
Start int `yaml:"start,omitempty"`
|
||||
End int `yaml:"end,omitempty"`
|
||||
}
|
||||
|
||||
func (p PluginProxyConfig) Effective() PluginProxyConfig {
|
||||
if p.Mode == "" {
|
||||
p.Mode = "port"
|
||||
}
|
||||
if p.PortPool == (PluginPortPool{}) {
|
||||
p.PortPool = PluginPortPool{43100, 43131}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p PluginProxyConfig) Validate() error {
|
||||
p = p.Effective()
|
||||
if p.Mode != "port" && p.Mode != "host" {
|
||||
return fmt.Errorf("plugins.proxy.mode must be port or host")
|
||||
}
|
||||
if p.Mode == "host" && (len(p.HostSuffix) > 180 || !pluginDNSHost.MatchString(p.HostSuffix) || netipAddr(p.HostSuffix)) {
|
||||
return fmt.Errorf("plugins.proxy.host_suffix must be a DNS suffix in host mode")
|
||||
}
|
||||
if p.PortPool.Start < 1024 || p.PortPool.End > 65535 || p.PortPool.End < p.PortPool.Start || p.PortPool.End-p.PortPool.Start > 2047 {
|
||||
return fmt.Errorf("invalid plugins.proxy.port_pool")
|
||||
}
|
||||
if p.BindHost != "" && strings.ContainsAny(p.BindHost, " /\\@#?[]") {
|
||||
return fmt.Errorf("invalid plugins.proxy.bind_host")
|
||||
}
|
||||
ports := map[int]bool{}
|
||||
for port := p.PortPool.Start; port <= p.PortPool.End; port++ {
|
||||
mapped := port
|
||||
if external, exists := p.ExternalPorts[port]; exists {
|
||||
mapped = external
|
||||
}
|
||||
if mapped < 1 || mapped > 65535 || ports[mapped] {
|
||||
return fmt.Errorf("invalid or duplicate plugins.proxy.external_ports value")
|
||||
}
|
||||
ports[mapped] = true
|
||||
}
|
||||
for port := range p.ExternalPorts {
|
||||
if p.Mode != "port" || port < p.PortPool.Start || port > p.PortPool.End {
|
||||
return fmt.Errorf("invalid plugins.proxy.external_ports key")
|
||||
}
|
||||
}
|
||||
if p.PublicOrigin != "" {
|
||||
u, err := url.Parse(p.PublicOrigin)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil ||
|
||||
u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
||||
return fmt.Errorf("plugins.proxy.public_origin must be an HTTP(S) origin")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var pluginDNSHost = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$`)
|
||||
|
||||
func netipAddr(host string) bool {
|
||||
_, err := netip.ParseAddr(host)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
type PluginLLMGatewayConfig struct {
|
||||
ListenHost string `yaml:"listen_host,omitempty"`
|
||||
ListenPort int `yaml:"listen_port,omitempty"`
|
||||
ContainerHost string `yaml:"container_host,omitempty"`
|
||||
Concurrency int `yaml:"concurrency,omitempty"`
|
||||
RPM int `yaml:"rpm,omitempty"`
|
||||
TokenBudget int64 `yaml:"token_budget,omitempty"`
|
||||
}
|
||||
|
||||
func (g PluginLLMGatewayConfig) Effective() PluginLLMGatewayConfig {
|
||||
if g.ListenHost == "" {
|
||||
g.ListenHost = "127.0.0.1"
|
||||
}
|
||||
if g.Concurrency == 0 {
|
||||
g.Concurrency = 4
|
||||
}
|
||||
if g.RPM == 0 {
|
||||
g.RPM = 30
|
||||
}
|
||||
if g.TokenBudget == 0 {
|
||||
g.TokenBudget = 200000
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
func (g PluginLLMGatewayConfig) Validate() error {
|
||||
g = g.Effective()
|
||||
ip, err := netip.ParseAddr(g.ListenHost)
|
||||
if err != nil || (!ip.IsLoopback() && !ip.IsPrivate()) || ip.Zone() != "" {
|
||||
return fmt.Errorf("plugins.llm_gateway.listen_host must be a loopback or specific private IP")
|
||||
}
|
||||
if g.ContainerHost != "" {
|
||||
address, addrErr := netip.ParseAddr(g.ContainerHost)
|
||||
if g.ContainerHost != "host.docker.internal" && (addrErr != nil || !address.IsPrivate() || address.Zone() != "") {
|
||||
return fmt.Errorf("plugins.llm_gateway.container_host must be host.docker.internal or a private IP")
|
||||
}
|
||||
}
|
||||
if g.ListenPort < 0 || g.ListenPort > 65535 || g.Concurrency < 1 || g.Concurrency > 64 ||
|
||||
g.RPM < 1 || g.RPM > 1200 || g.TokenBudget < 1 || g.TokenBudget > 1000000000 {
|
||||
return fmt.Errorf("invalid plugins.llm_gateway port or limits")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ProxyConfig governs only the built-in HTTP test tool, never process-wide routing.
|
||||
type ProxyConfig struct {
|
||||
Mode string `yaml:"mode" json:"mode"`
|
||||
URL string `yaml:"proxy_url" json:"proxy_url"`
|
||||
Pool string `yaml:"proxy_pool" json:"proxy_pool"`
|
||||
Source string `yaml:"proxy_source" json:"proxy_source"`
|
||||
Strategy string `yaml:"strategy" json:"strategy"`
|
||||
MaxAttempts int `yaml:"max_attempts" json:"max_attempts"`
|
||||
Cooldown int `yaml:"cooldown" json:"cooldown"`
|
||||
MinSwitchInterval int `yaml:"min_switch_interval" json:"min_switch_interval"`
|
||||
}
|
||||
|
||||
func (p ProxyConfig) Validate() error {
|
||||
if p.Mode != "" && p.Mode != "manual" && p.Mode != "fixed" && p.Mode != "pool" {
|
||||
return fmt.Errorf("proxy.mode must be manual, fixed or pool")
|
||||
}
|
||||
if p.Strategy != "" && p.Strategy != "sticky" && p.Strategy != "round_robin" {
|
||||
return fmt.Errorf("proxy.strategy must be sticky or round_robin")
|
||||
}
|
||||
if p.MaxAttempts < 0 || p.MaxAttempts > 10 || p.Cooldown < 0 || p.Cooldown > 86400 || p.MinSwitchInterval < 0 || p.MinSwitchInterval > 86400 {
|
||||
return fmt.Errorf("invalid proxy attempt or timing limits")
|
||||
}
|
||||
if p.Mode == "fixed" {
|
||||
return validateProxyEndpoint(p.URL)
|
||||
}
|
||||
if p.Mode != "pool" {
|
||||
return nil
|
||||
}
|
||||
count := 0
|
||||
for _, line := range strings.Split(p.Pool, "\n") {
|
||||
if strings.TrimSpace(line) != "" {
|
||||
count++
|
||||
if err := validateProxyEndpoint(line); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if count > 256 {
|
||||
return fmt.Errorf("proxy pool exceeds 256 endpoints")
|
||||
}
|
||||
if p.Source != "" {
|
||||
u, err := url.Parse(p.Source)
|
||||
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.Fragment != "" {
|
||||
return fmt.Errorf("proxy source must be an HTTP(S) URL")
|
||||
}
|
||||
}
|
||||
if count == 0 && p.Source == "" {
|
||||
return fmt.Errorf("proxy pool requires endpoints or a provider URL")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func validateProxyEndpoint(value string) error {
|
||||
value = strings.TrimSpace(value)
|
||||
if !strings.Contains(value, "://") {
|
||||
value = "http://" + value
|
||||
}
|
||||
u, err := url.Parse(value)
|
||||
if err == nil && u.Hostname() != "" && (u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "socks5") && (u.Path == "" || u.Path == "/") && u.RawQuery == "" && u.Fragment == "" && !strings.ContainsAny(value, "\r\n\t ") {
|
||||
if port, err := strconv.Atoi(u.Port()); err == nil && port > 0 && port <= 65535 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("proxy endpoint must be http(s)://host:port or socks5://host:port")
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestProxyValidation(t *testing.T) {
|
||||
for _, p := range []ProxyConfig{{}, {Mode: "manual"}, {Mode: "fixed", URL: "http://u:p@localhost:8080"}, {Mode: "pool", Pool: "[::1]:8080\nlocalhost:8081", MinSwitchInterval: 60}} {
|
||||
if err := p.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, p := range []ProxyConfig{{Mode: "bad"}, {Mode: "fixed"}, {Mode: "fixed", URL: "file:///secret"}, {Mode: "pool"}, {Mode: "pool", Pool: "http://host:80/path"}, {Mode: "pool", Source: "file:///secret"}, {MinSwitchInterval: -1}, {MaxAttempts: 11}} {
|
||||
if p.Validate() == nil {
|
||||
t.Fatalf("accepted invalid config: mode=%s", p.Mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package database
|
||||
|
||||
// Use the same definition for the coverage counts and for both asset filters.
|
||||
const assessmentObservedAssetIDs = `SELECT j.value FROM deep_assessment_facts f, json_each(f.assets_json) j
|
||||
WHERE f.task_id=? AND f.confidence='observed' AND j.type='text'`
|
||||
|
||||
func (db *DB) AssessmentAssetCoverage(task, project string, access RBACListAccess) (map[string]int, error) {
|
||||
where, args := assetWhere(AssetListFilter{AssessmentID: task, ProjectID: project}, access)
|
||||
var total, observed int
|
||||
query := "SELECT COUNT(*), COALESCE(SUM(assets.id IN (" + assessmentObservedAssetIDs + ")),0) FROM assets" + where
|
||||
if err := db.QueryRow(query, append([]any{task}, args...)...).Scan(&total, &observed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]int{"linked": total, "with_observed_evidence": observed}, nil
|
||||
}
|
||||
|
||||
func (db *DB) CanReadAssessmentAsset(task, project, asset string, access RBACListAccess) (bool, error) {
|
||||
where, args := assetWhere(AssetListFilter{ID: asset, AssessmentID: task, ProjectID: project}, access)
|
||||
var allowed bool
|
||||
err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM assets"+where+")", args...).Scan(&allowed)
|
||||
return allowed, err
|
||||
}
|
||||
|
||||
func (db *DB) ValidateIntentEvidence(task, step string, refs []string) error {
|
||||
_, err := assessmentReceipts(db, task, step, refs)
|
||||
return err
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package database
|
||||
|
||||
// Shared asset changes notify only assessments already referencing that asset.
|
||||
// Timestamps, risk-cache writes and scan counters do not wake the planner.
|
||||
func (db *DB) initAssessmentAssetSignals() error {
|
||||
queries := []string{
|
||||
`CREATE TRIGGER IF NOT EXISTS assessment_project_asset_added AFTER INSERT ON assets
|
||||
WHEN NEW.project_id IS NOT NULL AND NEW.project_id <> ''
|
||||
BEGIN INSERT INTO deep_assessment_changes(task_id,version)
|
||||
SELECT id,1 FROM deep_assessments WHERE project_id=NEW.project_id AND COALESCE(json_extract(payload,'$.collection_id'),'')=''
|
||||
ON CONFLICT(task_id) DO UPDATE SET version=version+1; END`,
|
||||
`CREATE TRIGGER IF NOT EXISTS assessment_asset_changed AFTER UPDATE OF host,domain,ip,port,protocol,title,server,business_system,status ON assets
|
||||
WHEN OLD.host IS NOT NEW.host OR OLD.domain IS NOT NEW.domain OR OLD.ip IS NOT NEW.ip OR OLD.port IS NOT NEW.port OR OLD.protocol IS NOT NEW.protocol OR OLD.title IS NOT NEW.title OR OLD.server IS NOT NEW.server OR OLD.business_system IS NOT NEW.business_system OR OLD.status IS NOT NEW.status
|
||||
BEGIN INSERT INTO deep_assessment_changes(task_id,version) SELECT task_id,1 FROM deep_assessment_assets WHERE asset_id=NEW.id ON CONFLICT(task_id) DO UPDATE SET version=version+1; END`,
|
||||
`CREATE TRIGGER IF NOT EXISTS assessment_endpoint_added AFTER INSERT ON asset_endpoints
|
||||
BEGIN INSERT INTO deep_assessment_changes(task_id,version) SELECT task_id,1 FROM deep_assessment_assets WHERE asset_id=NEW.asset_id ON CONFLICT(task_id) DO UPDATE SET version=version+1; END`,
|
||||
`CREATE TRIGGER IF NOT EXISTS assessment_endpoint_changed AFTER UPDATE OF title ON asset_endpoints WHEN OLD.title IS NOT NEW.title
|
||||
BEGIN INSERT INTO deep_assessment_changes(task_id,version) SELECT task_id,1 FROM deep_assessment_assets WHERE asset_id=NEW.asset_id ON CONFLICT(task_id) DO UPDATE SET version=version+1; END`,
|
||||
}
|
||||
for _, q := range queries {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -0,0 +1,239 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/google/uuid"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AssessmentFindingReview struct {
|
||||
ID string `json:"id"`
|
||||
StepID string `json:"step_id"`
|
||||
Verdict string `json:"verdict"`
|
||||
Reason string `json:"reason"`
|
||||
Evidence []string `json:"evidence"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
type assessmentQuery interface{ QueryRow(string, ...any) *sql.Row }
|
||||
|
||||
// AssessmentIDForConversation reports the single deep-assessment task bound to
|
||||
// a conversation. Batch-task conversations and ambiguous sessions return false.
|
||||
func (db *DB) AssessmentIDForConversation(conversation string) (string, bool, error) {
|
||||
task, _, err := assessmentSession(db, conversation)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return task, task != "", nil
|
||||
}
|
||||
|
||||
func assessmentSession(q assessmentQuery, conversation string) (string, string, error) {
|
||||
var task, step string
|
||||
err := q.QueryRow("SELECT task_id,step_id FROM deep_assessment_sessions s WHERE conversation_id=? AND (SELECT COUNT(*) FROM deep_assessment_sessions x WHERE x.conversation_id=s.conversation_id)=1 AND NOT EXISTS(SELECT 1 FROM batch_tasks b WHERE b.conversation_id=s.conversation_id)", conversation).Scan(&task, &step)
|
||||
return task, step, err
|
||||
}
|
||||
func assessmentReceipts(q assessmentQuery, task, step string, refs []string) ([]string, error) {
|
||||
if len(refs) == 0 || len(refs) > 32 {
|
||||
return nil, fmt.Errorf("深度测评漏洞须引用 1–32 条本意图的真实执行回执;推断或特征匹配请记录为 inferred 事实")
|
||||
}
|
||||
out := []string{}
|
||||
seen := map[string]bool{}
|
||||
for _, ref := range refs {
|
||||
var id string
|
||||
err := q.QueryRow("SELECT id FROM deep_assessment_calls WHERE task_id=? AND step_id=? AND (id=? OR execution_id=?) AND status='completed' AND tool NOT LIKE 'assessment_%' AND tool NOT IN ('record_vulnerability','list_vulnerabilities','get_vulnerability')", task, step, ref, ref).Scan(&id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("证据 %s 不属于本意图的成功原始执行回执", ref)
|
||||
}
|
||||
if !seen[id] {
|
||||
out = append(out, id)
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (db *DB) ValidateAssessmentFinding(conversation string, refs []string) error {
|
||||
task, step, err := assessmentSession(db, conversation)
|
||||
if err == sql.ErrNoRows {
|
||||
assessment, checkErr := db.IsAssessmentConversation(conversation)
|
||||
if checkErr != nil {
|
||||
return checkErr
|
||||
}
|
||||
if assessment {
|
||||
return fmt.Errorf("测评会话来源不唯一,不能登记漏洞")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = assessmentReceipts(db, task, step, refs)
|
||||
return err
|
||||
}
|
||||
func (db *DB) IsAssessmentConversation(conversation string) (bool, error) {
|
||||
var found bool
|
||||
err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM deep_assessment_sessions WHERE conversation_id=?) AND NOT EXISTS(SELECT 1 FROM batch_tasks WHERE conversation_id=?)", conversation, conversation).Scan(&found)
|
||||
return found, err
|
||||
}
|
||||
func findingGraph(tx *sql.Tx, id, task, step, title, body, state string, refs []string) error {
|
||||
now := time.Now().UTC()
|
||||
source, _ := json.Marshal(map[string]any{"vulnerability_id": id, "evidence": refs})
|
||||
_, err := tx.Exec("INSERT INTO deep_assessment_nodes(task_id,id,step_id,kind,state,title,body,source,updated_round,updated_at) VALUES(?,?,?,'finding',?,?,?,?,0,?) ON CONFLICT(task_id,id) DO UPDATE SET state=excluded.state,body=excluded.body,source=excluded.source,updated_at=excluded.updated_at", task, "finding:"+id, step, state, title, body, string(source), now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec("INSERT OR IGNORE INTO deep_assessment_edges(task_id,source_id,target_id,relation) VALUES(?,?,?,'produces')", task, "step:"+step, "finding:"+id); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if _, err = tx.Exec("INSERT OR IGNORE INTO deep_assessment_edges(task_id,source_id,target_id,relation) VALUES(?,?,?,'supports')", task, "receipt:"+ref, "finding:"+id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, err = tx.Exec("INSERT INTO deep_assessment_changes(task_id,version) VALUES(?,1) ON CONFLICT(task_id) DO UPDATE SET version=version+1", task)
|
||||
return err
|
||||
}
|
||||
func recordAssessmentReport(tx *sql.Tx, v *Vulnerability) error {
|
||||
task, step, err := assessmentSession(tx, v.ConversationID)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
refs := []string{}
|
||||
state := "unreviewed"
|
||||
if len(v.EvidenceReceiptIDs) > 0 {
|
||||
refs, err = assessmentReceipts(tx, task, step, v.EvidenceReceiptIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
raw, _ := json.Marshal(refs)
|
||||
state = "reported"
|
||||
if _, err = tx.Exec("INSERT INTO deep_assessment_finding_reviews(id,vulnerability_id,task_id,step_id,verdict,reason,evidence_json,created_at) VALUES(?,?,?,?,'reported',?,?,?)", uuid.NewString(), v.ID, task, step, "原始复现回执已绑定,待独立复核。", string(raw), time.Now().UTC()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return findingGraph(tx, v.ID, task, step, v.Title, "查看关联漏洞中的复现步骤、证据及独立复核记录。", state, refs)
|
||||
}
|
||||
func (db *DB) ReviewAssessmentFinding(task, step, id, verdict, reason string, refs []string, requestIDs ...string) error {
|
||||
return db.reviewAssessmentFinding(task, step, id, verdict, reason, refs, nil, requestIDs...)
|
||||
}
|
||||
|
||||
// ReviewAssessmentFindingWithQuality keeps the independent-intent and receipt
|
||||
// rules, and records the shared five-dimension review on the same transaction.
|
||||
func (db *DB) ReviewAssessmentFindingWithQuality(task, step, id, verdict, reason string, refs []string, review *AdversarialReview, requestIDs ...string) error {
|
||||
if review != nil {
|
||||
if err := review.Validate(verdict); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return db.reviewAssessmentFinding(task, step, id, verdict, reason, refs, review, requestIDs...)
|
||||
}
|
||||
|
||||
func (db *DB) reviewAssessmentFinding(task, step, id, verdict, reason string, refs []string, review *AdversarialReview, requestIDs ...string) error {
|
||||
if !map[string]bool{"confirmed": true, "refuted": true, "inconclusive": true}[verdict] || strings.TrimSpace(reason) == "" || len(reason) > 8000 {
|
||||
return fmt.Errorf("invalid independent review")
|
||||
}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var origin, title, conversation string
|
||||
if err = tx.QueryRow("SELECT s.step_id,v.title,s.conversation_id FROM vulnerability_assessment_sources s JOIN vulnerabilities v ON v.id=s.vulnerability_id WHERE s.assessment_id=? AND s.vulnerability_id=?", task, id).Scan(&origin, &title, &conversation); err != nil {
|
||||
return err
|
||||
}
|
||||
if origin == step {
|
||||
return fmt.Errorf("独立复核必须由另一条意图执行,不能以原报告会话自证")
|
||||
}
|
||||
var running int
|
||||
if err = tx.QueryRow("SELECT COUNT(*) FROM deep_assessments d,json_each(d.payload,'$.steps') st WHERE d.id=? AND json_extract(st.value,'$.id')=? AND json_extract(st.value,'$.status')='running'", task, step).Scan(&running); err != nil {
|
||||
return err
|
||||
}
|
||||
if running != 1 {
|
||||
return fmt.Errorf("复核意图未执行")
|
||||
}
|
||||
canonical, err := assessmentReceipts(tx, task, step, refs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
raw, _ := json.Marshal(canonical)
|
||||
reviewID := uuid.NewString()
|
||||
if len(requestIDs) > 0 && requestIDs[0] != "" {
|
||||
reviewID = fmt.Sprintf("review:%x", sha256.Sum256([]byte(task+"\n"+step+"\n"+requestIDs[0])))
|
||||
}
|
||||
result, err := tx.Exec("INSERT INTO deep_assessment_finding_reviews(id,vulnerability_id,task_id,step_id,verdict,reason,evidence_json,created_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING", reviewID, id, task, step, verdict, reason, string(raw), time.Now().UTC())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := result.RowsAffected(); n == 0 {
|
||||
return tx.Commit()
|
||||
}
|
||||
if verdict == "confirmed" || verdict == "refuted" {
|
||||
status := "confirmed"
|
||||
if verdict == "refuted" {
|
||||
status = "false_positive"
|
||||
}
|
||||
if _, err = tx.Exec("UPDATE vulnerabilities SET status=?,updated_at=? WHERE id=? AND status NOT IN ('fixed','ignored')", status, time.Now().UTC(), id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Keep the original producing intent; review edges identify the independent path.
|
||||
if err = findingGraph(tx, id, task, origin, title, reason, verdict, canonical); err != nil {
|
||||
return err
|
||||
}
|
||||
if review != nil {
|
||||
if _, err = tx.Exec(`INSERT INTO vulnerability_quality(
|
||||
vulnerability_id, reachability, preconditions, reproducibility, scope_check, impact_check,
|
||||
control_reachable, mechanism_invalid, blocked_by, updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(vulnerability_id) DO UPDATE SET
|
||||
reachability=excluded.reachability, preconditions=excluded.preconditions,
|
||||
reproducibility=excluded.reproducibility, scope_check=excluded.scope_check,
|
||||
impact_check=excluded.impact_check, control_reachable=excluded.control_reachable,
|
||||
mechanism_invalid=excluded.mechanism_invalid, blocked_by=excluded.blocked_by,
|
||||
updated_at=excluded.updated_at`,
|
||||
id, strings.TrimSpace(review.Reachability), strings.TrimSpace(review.Preconditions), strings.TrimSpace(review.Reproducibility),
|
||||
strings.TrimSpace(review.Scope), strings.TrimSpace(review.Impact), boolToInt(review.ControlReachable), boolToInt(review.MechanismInvalid),
|
||||
strings.TrimSpace(review.BlockedBy), time.Now().UTC()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec("INSERT OR IGNORE INTO deep_assessment_edges(task_id,source_id,target_id,relation) VALUES(?,?,?,'reviews')", task, "step:"+step, "finding:"+id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = syncProjectLesson(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
db.refreshAssetRiskCacheForConversationsBestEffort(conversation)
|
||||
return nil
|
||||
}
|
||||
func (db *DB) AssessmentFindingReviews(id string) ([]AssessmentFindingReview, error) {
|
||||
rows, err := db.Query("SELECT id,step_id,verdict,reason,evidence_json,created_at FROM deep_assessment_finding_reviews WHERE vulnerability_id=? ORDER BY created_at DESC,id DESC LIMIT 100", id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AssessmentFindingReview{}
|
||||
for rows.Next() {
|
||||
var r AssessmentFindingReview
|
||||
var raw string
|
||||
if err = rows.Scan(&r.ID, &r.StepID, &r.Verdict, &r.Reason, &raw, &r.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(raw), &r.Evidence); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package database
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// AssessmentEvidenceAssets resolves the readable anchors for an evidence projection.
|
||||
func (db *DB) AssessmentEvidenceAssets(task, project string, ids []string, access RBACListAccess) (map[string]string, error) {
|
||||
out := map[string]string{}
|
||||
if len(ids) == 0 || access.UserID == "" {
|
||||
return out, nil
|
||||
}
|
||||
where, args := assetWhere(AssetListFilter{AssessmentID: task, ProjectID: project}, access)
|
||||
raw, _ := json.Marshal(ids)
|
||||
rows, err := db.Query(`SELECT assets.id,COALESCE(NULLIF(assets.host,''),NULLIF(assets.domain,''),NULLIF(assets.ip,''),assets.id)
|
||||
FROM assets`+where+` AND assets.id IN (SELECT value FROM json_each(?))`, append(args, string(raw))...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var id, title string
|
||||
if err := rows.Scan(&id, &title); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[id] = title
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSharedAssetGraphKeepsIdentityAndPermissionBoundaries(t *testing.T) {
|
||||
db := newRBACTestDB(t)
|
||||
owner, _ := db.CreateRBACUser("graph-owner", "owner", "hash", true, nil)
|
||||
other, _ := db.CreateRBACUser("graph-other", "other", "hash", true, nil)
|
||||
a := &Asset{Host: "https://app.example.com", IP: "192.0.2.10", BusinessSystem: "Fixture app"}
|
||||
secret := &Asset{Host: "https://secret.example.net"}
|
||||
if _, err := db.UpsertAssets([]*Asset{a}, owner.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.UpsertAssets([]*Asset{secret}, other.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assessmentSourceFixture(t, db, "a", "A", owner.ID)
|
||||
assessmentSourceFixture(t, db, "b", "B", owner.ID)
|
||||
for _, task := range []string{"a", "b"} {
|
||||
if _, err := db.Exec("INSERT INTO deep_assessment_assets VALUES(?,?)", task, a.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
access := RBACListAccess{UserID: owner.ID, Scope: RBACScopeOwn}
|
||||
ep := &AssetEndpoint{AssetID: a.ID, Method: "GET", Path: "/api/items", Title: "items"}
|
||||
if err := db.PutAssetEndpoint(ep, access); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstID := ep.ID
|
||||
if err := db.PutAssetEndpoint(ep, access); err != nil || ep.ID != firstID {
|
||||
t.Fatal("endpoint not idempotent", err)
|
||||
}
|
||||
if err := db.PutAssetEndpoint(&AssetEndpoint{AssetID: secret.ID, Method: "GET", Path: "/admin"}, access); err == nil {
|
||||
t.Fatal("foreign endpoint write allowed")
|
||||
}
|
||||
if err := db.PutAssetEndpoint(&AssetEndpoint{AssetID: a.ID, Method: "GET", Path: "/api?token=secret"}, access); err == nil {
|
||||
t.Fatal("query values persisted")
|
||||
}
|
||||
ga, err := db.SharedAssetGraph(AssetListFilter{AssessmentID: "a"}, access, 20, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gb, err := db.SharedAssetGraph(AssetListFilter{AssessmentID: "b"}, access, 20, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ga.Total != 1 || gb.Total != 1 {
|
||||
t.Fatal(ga, gb)
|
||||
}
|
||||
kinds := map[string]bool{}
|
||||
ids := map[string]bool{}
|
||||
for _, n := range ga.Nodes {
|
||||
kinds[n.Kind] = true
|
||||
ids[n.ID] = true
|
||||
}
|
||||
for _, n := range gb.Nodes {
|
||||
if !ids[n.ID] {
|
||||
t.Fatal("shared identity drift", n)
|
||||
}
|
||||
}
|
||||
for _, kind := range []string{"domain", "subdomain", "ip", "service", "application", "endpoint"} {
|
||||
if !kinds[kind] {
|
||||
t.Fatal("missing kind", kind)
|
||||
}
|
||||
}
|
||||
all, err := db.SharedAssetGraph(AssetListFilter{}, access, 20, 0)
|
||||
if err != nil || all.Total != 1 {
|
||||
t.Fatal("foreign asset leak", all, err)
|
||||
}
|
||||
var before, after int
|
||||
db.QueryRow("SELECT version FROM deep_assessment_changes WHERE task_id='a'").Scan(&before)
|
||||
db.Exec("UPDATE assets SET title='new' WHERE id=?", a.ID)
|
||||
db.QueryRow("SELECT version FROM deep_assessment_changes WHERE task_id='a'").Scan(&after)
|
||||
if after != before+1 {
|
||||
t.Fatal("asset change did not signal", before, after)
|
||||
}
|
||||
db.Exec("UPDATE assets SET title='new' WHERE id=?", a.ID)
|
||||
db.QueryRow("SELECT version FROM deep_assessment_changes WHERE task_id='a'").Scan(&before)
|
||||
if before != after {
|
||||
t.Fatal("unchanged write caused wake")
|
||||
}
|
||||
}
|
||||
func TestAssessmentFindingRequiresOriginalReceiptsAndIndependentReview(t *testing.T) {
|
||||
db := newRBACTestDB(t)
|
||||
original, _ := db.CreateConversation("original", ConversationCreateMeta{})
|
||||
reviewer, _ := db.CreateConversation("reviewer", ConversationCreateMeta{})
|
||||
assessmentSourceFixture(t, db, "assessment", "Fixture", "", original.ID, reviewer.ID)
|
||||
for _, c := range []struct{ id, step, tool string }{{"proof", "one", "fixture_check"}, {"review-proof", "two", "fixture_recheck"}, {"summary", "two", "assessment_facts"}} {
|
||||
if _, err := db.Exec("INSERT INTO deep_assessment_calls(id,task_id,step_id,tool,arguments,status,result,updated_at) VALUES(?,'assessment',?,?,'{}','completed','fixture',?)", c.id, c.step, c.tool, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := db.ValidateAssessmentFinding(original.ID, nil); err == nil {
|
||||
t.Fatal("empty evidence accepted")
|
||||
}
|
||||
if err := db.ValidateAssessmentFinding(original.ID, []string{"review-proof"}); err == nil {
|
||||
t.Fatal("foreign intent evidence accepted")
|
||||
}
|
||||
if err := db.ValidateAssessmentFinding(reviewer.ID, []string{"summary"}); err == nil {
|
||||
t.Fatal("summary accepted as original evidence")
|
||||
}
|
||||
if err := db.ValidateAssessmentFinding(original.ID, []string{"proof"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, err := db.CreateVulnerability(&Vulnerability{ConversationID: original.ID, Title: "Fixture finding", Severity: "low", ReproSteps: "read fixture", Evidence: "bytes", EvidenceReceiptIDs: []string{"proof"}})
|
||||
if err != nil || len(v.AssessmentReviews) != 1 || v.AssessmentReviews[0].Verdict != "reported" {
|
||||
t.Fatal(v, err)
|
||||
}
|
||||
if err := db.ReviewAssessmentFinding("assessment", "one", v.ID, "confirmed", "self proof", []string{"proof"}); err == nil {
|
||||
t.Fatal("self review allowed")
|
||||
}
|
||||
var raw string
|
||||
db.QueryRow("SELECT payload FROM deep_assessments WHERE id='assessment'").Scan(&raw)
|
||||
var payload map[string]any
|
||||
json.Unmarshal([]byte(raw), &payload)
|
||||
for _, st := range payload["steps"].([]any) {
|
||||
st.(map[string]any)["status"] = "running"
|
||||
}
|
||||
b, _ := json.Marshal(payload)
|
||||
db.Exec("UPDATE deep_assessments SET payload=? WHERE id='assessment'", string(b))
|
||||
if err := db.ReviewAssessmentFinding("assessment", "two", v.ID, "confirmed", "independent fixture reproduction", []string{"proof"}); err == nil {
|
||||
t.Fatal("original proof reused")
|
||||
}
|
||||
if err := db.ReviewAssessmentFinding("assessment", "two", v.ID, "confirmed", "independent fixture reproduction", []string{"review-proof"}, "same-call"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.ReviewAssessmentFinding("assessment", "two", v.ID, "confirmed", "independent fixture reproduction", []string{"review-proof"}, "same-call"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, err = db.GetVulnerability(v.ID)
|
||||
if err != nil || len(v.AssessmentReviews) != 2 || v.Status != "confirmed" {
|
||||
t.Fatal(v, err)
|
||||
}
|
||||
db.Exec("DELETE FROM deep_assessments WHERE id='assessment'")
|
||||
v, err = db.GetVulnerability(v.ID)
|
||||
if err != nil || len(v.AssessmentReviews) != 2 || !v.AssessmentDeleted {
|
||||
t.Fatal("review provenance lost", v, err)
|
||||
}
|
||||
}
|
||||
|
|
@ -56,10 +56,14 @@ type Asset struct {
|
|||
}
|
||||
|
||||
type AssetListFilter struct {
|
||||
ID string
|
||||
AssessmentID string
|
||||
AssessmentObserved *bool
|
||||
Search string
|
||||
Status string
|
||||
Protocol string
|
||||
ProjectID string
|
||||
ProjectUnassigned bool
|
||||
Source string
|
||||
Tag string
|
||||
Host string
|
||||
|
|
@ -90,9 +94,12 @@ type AssetListFilter struct {
|
|||
}
|
||||
|
||||
type AssetImportResult struct {
|
||||
Created int `json:"created"`
|
||||
Updated int `json:"updated"`
|
||||
Skipped int `json:"skipped"`
|
||||
Created int `json:"created"`
|
||||
Updated int `json:"updated"`
|
||||
Skipped int `json:"skipped"`
|
||||
ProjectConflicts int `json:"project_conflicts,omitempty"`
|
||||
AppliedIDs []string `json:"-"`
|
||||
Collection *AssetCollection `json:"collection,omitempty"`
|
||||
}
|
||||
|
||||
func normalizeAsset(a *Asset) {
|
||||
|
|
@ -304,6 +311,15 @@ func appendAssetAccess(query string, args []interface{}, access RBACListAccess,
|
|||
}
|
||||
|
||||
func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...bool) (AssetImportResult, error) {
|
||||
return db.upsertAssets(assets, ownerUserID, len(allowGlobal) > 0 && allowGlobal[0], nil)
|
||||
}
|
||||
|
||||
// UpsertAssetsInProject enforces the caller's project boundary inside the same
|
||||
// transaction that resolves deduplication, including for globally scoped users.
|
||||
func (db *DB) UpsertAssetsInProject(assets []*Asset, ownerUserID string, global bool, projectID string) (AssetImportResult, error) {
|
||||
return db.upsertAssets(assets, ownerUserID, global, &projectID)
|
||||
}
|
||||
func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, projectBoundary *string) (AssetImportResult, error) {
|
||||
result := AssetImportResult{}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
|
|
@ -317,6 +333,9 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
|
|||
continue
|
||||
}
|
||||
normalizeAsset(asset)
|
||||
if projectBoundary != nil && asset.ProjectID != *projectBoundary {
|
||||
return result, fmt.Errorf("asset is outside the current project")
|
||||
}
|
||||
if err := validateAsset(asset); err != nil {
|
||||
return result, fmt.Errorf("第 %d 个资产无效: %w", result.Created+result.Updated+result.Skipped+1, err)
|
||||
}
|
||||
|
|
@ -326,8 +345,8 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
|
|||
continue
|
||||
}
|
||||
var existingID string
|
||||
var existingOwner sql.NullString
|
||||
err := tx.QueryRow(`SELECT id,owner_user_id FROM assets WHERE dedup_key = ?`, key).Scan(&existingID, &existingOwner)
|
||||
var existingOwner, existingProject sql.NullString
|
||||
err := tx.QueryRow(`SELECT id,owner_user_id,project_id FROM assets WHERE dedup_key = ?`, key).Scan(&existingID, &existingOwner, &existingProject)
|
||||
tagsJSON, _ := json.Marshal(asset.Tags)
|
||||
if err == sql.ErrNoRows {
|
||||
asset.ID = uuid.NewString()
|
||||
|
|
@ -350,24 +369,33 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
|
|||
}
|
||||
}
|
||||
result.Created++
|
||||
result.AppliedIDs = append(result.AppliedIDs, asset.ID)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("检查资产去重键失败: %w", err)
|
||||
}
|
||||
asset.ID = existingID
|
||||
global := len(allowGlobal) > 0 && allowGlobal[0]
|
||||
if !global && existingOwner.Valid && strings.TrimSpace(existingOwner.String) != "" && strings.TrimSpace(existingOwner.String) != strings.TrimSpace(ownerUserID) {
|
||||
if !global && strings.TrimSpace(existingOwner.String) != strings.TrimSpace(ownerUserID) {
|
||||
result.Skipped++
|
||||
continue
|
||||
}
|
||||
existingProj := strings.TrimSpace(existingProject.String)
|
||||
if existingProj != asset.ProjectID {
|
||||
if existingProj != "" || asset.ProjectID == "" {
|
||||
result.Skipped++
|
||||
result.ProjectConflicts++
|
||||
continue
|
||||
}
|
||||
}
|
||||
_, err = tx.Exec(`UPDATE assets SET
|
||||
project_id=CASE WHEN COALESCE(project_id, '')='' AND ?<>'' THEN ? ELSE project_id END,
|
||||
host=CASE WHEN ?<>'' THEN ? ELSE host END, ip=CASE WHEN ?<>'' THEN ? ELSE ip END,
|
||||
domain=CASE WHEN ?<>'' THEN ? ELSE domain END, protocol=CASE WHEN ?<>'' THEN ? ELSE protocol END,
|
||||
title=CASE WHEN ?<>'' THEN ? ELSE title END, server=CASE WHEN ?<>'' THEN ? ELSE server END,
|
||||
country=CASE WHEN ?<>'' THEN ? ELSE country END, province=CASE WHEN ?<>'' THEN ? ELSE province END,
|
||||
city=CASE WHEN ?<>'' THEN ? ELSE city END, source=CASE WHEN ?<>'' THEN ? ELSE source END,
|
||||
source_query=CASE WHEN ?<>'' THEN ? ELSE source_query END, project_id=CASE WHEN ?<>'' THEN ? ELSE project_id END,
|
||||
source_query=CASE WHEN ?<>'' THEN ? ELSE source_query END,
|
||||
responsible_person=CASE WHEN ?<>'' THEN ? ELSE responsible_person END,
|
||||
department=CASE WHEN ?<>'' THEN ? ELSE department END,
|
||||
business_system=CASE WHEN ?<>'' THEN ? ELSE business_system END,
|
||||
|
|
@ -375,9 +403,10 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
|
|||
criticality=CASE WHEN ?<>'' THEN ? ELSE criticality END,
|
||||
tags_json=CASE WHEN ?<>'[]' THEN ? ELSE tags_json END,
|
||||
last_seen_at=?, updated_at=? WHERE id=?`,
|
||||
asset.ProjectID, asset.ProjectID,
|
||||
asset.Host, asset.Host, asset.IP, asset.IP, asset.Domain, asset.Domain, asset.Protocol, asset.Protocol,
|
||||
asset.Title, asset.Title, asset.Server, asset.Server, asset.Country, asset.Country, asset.Province, asset.Province,
|
||||
asset.City, asset.City, asset.Source, asset.Source, asset.SourceQuery, asset.SourceQuery, asset.ProjectID, nullIfEmpty(asset.ProjectID),
|
||||
asset.City, asset.City, asset.Source, asset.Source, asset.SourceQuery, asset.SourceQuery,
|
||||
asset.ResponsiblePerson, asset.ResponsiblePerson, asset.Department, asset.Department, asset.BusinessSystem, asset.BusinessSystem,
|
||||
asset.Environment, asset.Environment, asset.Criticality, asset.Criticality, string(tagsJSON), string(tagsJSON),
|
||||
now, now, existingID)
|
||||
|
|
@ -390,6 +419,7 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
|
|||
}
|
||||
}
|
||||
result.Updated++
|
||||
result.AppliedIDs = append(result.AppliedIDs, existingID)
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return result, err
|
||||
|
|
@ -400,6 +430,10 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
|
|||
func assetWhere(filter AssetListFilter, access RBACListAccess) (string, []interface{}) {
|
||||
query := " WHERE 1=1"
|
||||
args := []interface{}{}
|
||||
if filter.ID != "" {
|
||||
query += " AND assets.id=?"
|
||||
args = append(args, filter.ID)
|
||||
}
|
||||
if q := strings.TrimSpace(filter.Search); q != "" {
|
||||
pattern := "%" + escapeAssetLike(strings.ToLower(q)) + "%"
|
||||
query += ` AND (LOWER(assets.host) LIKE ? ESCAPE '\' OR LOWER(assets.ip) LIKE ? ESCAPE '\' OR LOWER(assets.domain) LIKE ? ESCAPE '\'
|
||||
|
|
@ -421,6 +455,21 @@ func assetWhere(filter AssetListFilter, access RBACListAccess) (string, []interf
|
|||
query += " AND assets.project_id = ?"
|
||||
args = append(args, filter.ProjectID)
|
||||
}
|
||||
if filter.ProjectUnassigned {
|
||||
query += " AND (assets.project_id IS NULL OR assets.project_id = '')"
|
||||
}
|
||||
if filter.AssessmentID != "" {
|
||||
query += " AND EXISTS(SELECT 1 FROM deep_assessment_assets da WHERE da.asset_id=assets.id AND da.task_id=?)"
|
||||
args = append(args, filter.AssessmentID)
|
||||
if filter.AssessmentObserved != nil {
|
||||
operator := " IN "
|
||||
if !*filter.AssessmentObserved {
|
||||
operator = " NOT IN "
|
||||
}
|
||||
query += " AND assets.id" + operator + "(" + assessmentObservedAssetIDs + ")"
|
||||
args = append(args, filter.AssessmentID)
|
||||
}
|
||||
}
|
||||
if filter.Source != "" {
|
||||
query += " AND LOWER(assets.source) = LOWER(?)"
|
||||
args = append(args, strings.TrimSpace(filter.Source))
|
||||
|
|
@ -575,12 +624,20 @@ const assetVulnerabilityMatchExpr = `(
|
|||
))
|
||||
)`
|
||||
|
||||
const assetVulnerabilityCountExpr = `(SELECT COUNT(DISTINCT v.id) FROM vulnerabilities v WHERE ` + assetVulnerabilityMatchExpr + `)`
|
||||
const assetActiveVulnerabilityExpr = `(
|
||||
v.manually_archived = 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM projects archive_project
|
||||
WHERE archive_project.id = v.project_id AND archive_project.status = 'archived'
|
||||
)
|
||||
)`
|
||||
|
||||
const assetVulnerabilityCountExpr = `(SELECT COUNT(DISTINCT v.id) FROM vulnerabilities v WHERE ` + assetActiveVulnerabilityExpr + ` AND ` + assetVulnerabilityMatchExpr + `)`
|
||||
|
||||
const assetRiskScoreQueryExpr = `COALESCE((
|
||||
SELECT MAX(CASE LOWER(COALESCE(v.severity,'')) WHEN 'critical' THEN 5 WHEN 'high' THEN 4 WHEN 'medium' THEN 3 WHEN 'low' THEN 2 WHEN 'info' THEN 1 ELSE 0 END)
|
||||
FROM vulnerabilities v
|
||||
WHERE LOWER(COALESCE(v.status,'open')) NOT IN ('fixed','false_positive','ignored') AND ` + assetVulnerabilityMatchExpr + `
|
||||
WHERE LOWER(COALESCE(v.status,'open')) NOT IN ('fixed','false_positive','ignored') AND ` + assetActiveVulnerabilityExpr + ` AND ` + assetVulnerabilityMatchExpr + `
|
||||
),0)`
|
||||
|
||||
const assetRiskLevelQueryExpr = `(CASE WHEN ` + assetEffectiveLastScanExpr + ` IS NULL THEN 'unassessed' ELSE CASE ` + assetRiskScoreQueryExpr + `
|
||||
|
|
@ -844,6 +901,67 @@ func (db *DB) ListAssetsForOperation(limit int, filter AssetListFilter, access R
|
|||
return items, total, rows.Err()
|
||||
}
|
||||
|
||||
// AssetScopeSeed is the host identity used to decide whether a discovered
|
||||
// name belongs to an assessment. It is not an asset record.
|
||||
type AssetScopeSeed struct {
|
||||
Host string
|
||||
IP string
|
||||
Domain string
|
||||
}
|
||||
|
||||
// ListAssetIDs returns every matching asset ID. limit is a hard upper bound;
|
||||
// exceeding it returns the total and an error instead of a truncated set.
|
||||
func (db *DB) ListAssetIDs(limit int, filter AssetListFilter, access RBACListAccess) ([]string, int, error) {
|
||||
if limit < 1 || limit > 5000 {
|
||||
limit = 5000
|
||||
}
|
||||
where, args := assetWhere(filter, access)
|
||||
var total int
|
||||
if err := db.QueryRow("SELECT COUNT(*) FROM assets"+where, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if total > limit {
|
||||
return nil, total, fmt.Errorf("匹配资产超过 %d 条,请缩小筛选范围", limit)
|
||||
}
|
||||
rows, err := db.Query("SELECT assets.id FROM assets"+where+" ORDER BY assets.id", args...)
|
||||
if err != nil {
|
||||
return nil, total, err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := make([]string, 0, total)
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
return nil, total, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, total, rows.Err()
|
||||
}
|
||||
|
||||
// ListAssetScopeSeeds reads only the names needed to keep discovered hosts
|
||||
// inside an existing project or assessment scope.
|
||||
func (db *DB) ListAssetScopeSeeds(limit int, filter AssetListFilter, access RBACListAccess) ([]AssetScopeSeed, error) {
|
||||
if limit < 1 || limit > 5000 {
|
||||
limit = 5000
|
||||
}
|
||||
where, args := assetWhere(filter, access)
|
||||
rows, err := db.Query("SELECT COALESCE(assets.host,''), COALESCE(assets.ip,''), COALESCE(assets.domain,'') FROM assets"+where+" ORDER BY assets.id LIMIT ?", append(args, limit)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AssetScopeSeed{}
|
||||
for rows.Next() {
|
||||
var seed AssetScopeSeed
|
||||
if err = rows.Scan(&seed.Host, &seed.IP, &seed.Domain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, seed)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func assetOrderBy(sortBy, sortOrder string) string {
|
||||
direction := "DESC"
|
||||
if strings.EqualFold(strings.TrimSpace(sortOrder), "asc") {
|
||||
|
|
@ -1137,21 +1255,27 @@ func (db *DB) MergeAssets(primary *Asset, duplicateIDs []string, writeAccess, de
|
|||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
primaryQuery, primaryArgs := appendAssetAccess("SELECT COUNT(*) FROM assets WHERE id=?", []interface{}{primary.ID}, writeAccess, "assets")
|
||||
var primaryCount int
|
||||
if err := tx.QueryRow(primaryQuery, primaryArgs...).Scan(&primaryCount); err != nil || primaryCount != 1 {
|
||||
primaryQuery, primaryArgs := appendAssetAccess("SELECT COALESCE(project_id,'') FROM assets WHERE id=?", []interface{}{primary.ID}, writeAccess, "assets")
|
||||
var projectID string
|
||||
if err := tx.QueryRow(primaryQuery, primaryArgs...).Scan(&projectID); err != nil {
|
||||
return 0, fmt.Errorf("主资产不存在或无权更新")
|
||||
}
|
||||
if projectID != primary.ProjectID {
|
||||
return 0, fmt.Errorf("主资产的项目归属已变更")
|
||||
}
|
||||
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(duplicates)), ",")
|
||||
deleteArgs := make([]interface{}, len(duplicates))
|
||||
for i, id := range duplicates {
|
||||
deleteArgs[i] = id
|
||||
}
|
||||
countQuery, countArgs := appendAssetAccess("SELECT COUNT(*) FROM assets WHERE id IN ("+placeholders+")", deleteArgs, deleteAccess, "assets")
|
||||
var accessible int
|
||||
if err := tx.QueryRow(countQuery, countArgs...).Scan(&accessible); err != nil || accessible != len(duplicates) {
|
||||
countQuery, countArgs := appendAssetAccess("SELECT COUNT(*), COUNT(CASE WHEN COALESCE(project_id,'') = ? THEN 1 END) FROM assets WHERE id IN ("+placeholders+")", append([]interface{}{projectID}, deleteArgs...), deleteAccess, "assets")
|
||||
var accessible, sameProject int
|
||||
if err := tx.QueryRow(countQuery, countArgs...).Scan(&accessible, &sameProject); err != nil || accessible != len(duplicates) {
|
||||
return 0, fmt.Errorf("部分重复资产不存在或无权删除")
|
||||
}
|
||||
if sameProject != len(duplicates) {
|
||||
return 0, fmt.Errorf("只能合并同一项目或均未归属项目的资产")
|
||||
}
|
||||
deleteQuery, scopedDeleteArgs := appendAssetAccess("DELETE FROM assets WHERE id IN ("+placeholders+")", deleteArgs, deleteAccess, "assets")
|
||||
if result, err := tx.Exec(deleteQuery, scopedDeleteArgs...); err != nil {
|
||||
return 0, err
|
||||
|
|
@ -1292,6 +1416,20 @@ func (db *DB) GetAssetStats(access RBACListAccess, requestedDays ...int) (map[st
|
|||
coverage["rate"], coverage["recent_rate"] = 0, 0
|
||||
}
|
||||
stats["coverage"] = coverage
|
||||
observedTotal, observed, err := db.ObservationCoverage(access, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
observation := map[string]interface{}{
|
||||
"total": observedTotal, "observed": observed,
|
||||
"meaning": "已有观察证据的资产。成功原始回执支持的测评观察,或带成功工具回执的已确认项目事实,同一资产只计一次。这不是扫描覆盖。",
|
||||
}
|
||||
if observedTotal > 0 {
|
||||
observation["rate"] = int(float64(observed) / float64(observedTotal) * 100)
|
||||
} else {
|
||||
observation["rate"] = 0
|
||||
}
|
||||
stats["observation"] = observation
|
||||
|
||||
assetDaily := map[string]map[string]int{}
|
||||
trendWhere, trendArgs := appendAssetAccess(" WHERE datetime(first_seen_at)>=datetime('now',?)", []interface{}{fmt.Sprintf("-%d days", days-1)}, access, "assets")
|
||||
|
|
@ -1334,7 +1472,7 @@ func (db *DB) GetAssetStats(access RBACListAccess, requestedDays ...int) (map[st
|
|||
}
|
||||
|
||||
riskDaily := map[string]map[string]int{}
|
||||
riskWhere, riskArgs := appendVulnerabilityAccessFilter(" WHERE datetime(created_at)>=datetime('now',?)", []interface{}{fmt.Sprintf("-%d days", days-1)}, access)
|
||||
riskWhere, riskArgs := appendVulnerabilityAccessFilter(" WHERE datetime(created_at)>=datetime('now',?) AND NOT "+vulnerabilityArchivedSQL, []interface{}{fmt.Sprintf("-%d days", days-1)}, access)
|
||||
riskRows, err := db.Query(`SELECT date(created_at), COUNT(*),
|
||||
COALESCE(SUM(CASE WHEN LOWER(severity) IN ('critical','high') THEN 1 ELSE 0 END),0)
|
||||
FROM vulnerabilities`+riskWhere+` GROUP BY date(created_at) ORDER BY date(created_at)`, riskArgs...)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,214 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AssetCollection is a project-owned set of existing assets.
|
||||
type AssetCollection struct {
|
||||
ID string `json:"id"`
|
||||
ProjectID string `json:"project_id"`
|
||||
Name string `json:"name"`
|
||||
Source string `json:"source,omitempty"`
|
||||
SourceQuery string `json:"source_query,omitempty"`
|
||||
MemberCount int `json:"member_count"`
|
||||
Observed int `json:"observed"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
const observationEvidenceMeaning = "已有观察证据:成功原始回执支持的测评观察,或带成功工具回执的已确认项目事实。同一资产只计一次。这不是扫描覆盖,也不表示没有漏洞。"
|
||||
|
||||
// An asset counts once when either evidence path is present.
|
||||
func observationAssetPredicate(assetIDExpr, projectClause string) string {
|
||||
return `(
|
||||
EXISTS (
|
||||
SELECT 1 FROM deep_assessment_facts f
|
||||
WHERE f.confidence='observed'
|
||||
AND EXISTS (SELECT 1 FROM json_each(f.assets_json) j WHERE j.value=` + assetIDExpr + `)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM json_each(f.evidence_json) e
|
||||
JOIN deep_assessment_calls c ON c.id=e.value
|
||||
WHERE c.task_id=f.task_id AND c.step_id=f.step_id AND c.status='completed'
|
||||
AND c.tool NOT GLOB 'assessment_*'
|
||||
AND c.tool NOT IN ('record_vulnerability','list_vulnerabilities','get_vulnerability')
|
||||
)
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM project_fact_assets pa
|
||||
JOIN project_facts pf ON pf.id=pa.fact_id AND pf.confidence='confirmed'
|
||||
JOIN project_fact_receipts pr ON pr.fact_id=pf.id
|
||||
JOIN tool_executions te ON te.id=pr.execution_id AND te.status='completed'
|
||||
WHERE pa.asset_id=` + assetIDExpr + projectClause + `
|
||||
)
|
||||
)`
|
||||
}
|
||||
|
||||
// ObservationCoverage counts accessible assets, or the members of one collection.
|
||||
// total is the population; observed is how many of them have observation evidence.
|
||||
func (db *DB) ObservationCoverage(access RBACListAccess, collectionID string) (int, int, error) {
|
||||
collectionID = strings.TrimSpace(collectionID)
|
||||
var query string
|
||||
var args []interface{}
|
||||
if collectionID == "" {
|
||||
query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", "") + ` THEN 1 ELSE 0 END),0) FROM assets WHERE 1=1`
|
||||
query, args = appendAssetAccess(query, nil, access, "assets")
|
||||
} else {
|
||||
query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", "") + ` THEN 1 ELSE 0 END),0)
|
||||
FROM asset_collection_members m JOIN assets ON assets.id=m.asset_id WHERE m.collection_id=?`
|
||||
args = []interface{}{collectionID}
|
||||
query, args = appendAssetAccess(query, args, access, "assets")
|
||||
}
|
||||
var total, observed int
|
||||
err := db.QueryRow(query, args...).Scan(&total, &observed)
|
||||
return total, observed, err
|
||||
}
|
||||
|
||||
// ObservationCoverageVisible applies the caller's project read boundary to shared facts.
|
||||
func (db *DB) ObservationCoverageVisible(access RBACListAccess, vis FactVisibility, collectionID string) (int, int, error) {
|
||||
clause, clauseArgs := vis.projectSQL("pf")
|
||||
collectionID = strings.TrimSpace(collectionID)
|
||||
var query string
|
||||
args := append([]any{}, clauseArgs...)
|
||||
if collectionID == "" {
|
||||
query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", clause) + ` THEN 1 ELSE 0 END),0) FROM assets WHERE 1=1`
|
||||
query, args = appendAssetAccess(query, args, access, "assets")
|
||||
} else {
|
||||
query = `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ` + observationAssetPredicate("assets.id", clause) + ` THEN 1 ELSE 0 END),0)
|
||||
FROM asset_collection_members m JOIN assets ON assets.id=m.asset_id WHERE m.collection_id=?`
|
||||
args = append(args, collectionID)
|
||||
query, args = appendAssetAccess(query, args, access, "assets")
|
||||
}
|
||||
var total, observed int
|
||||
err := db.QueryRow(query, args...).Scan(&total, &observed)
|
||||
return total, observed, err
|
||||
}
|
||||
|
||||
func (db *DB) CreateAssetCollection(projectID, name, source, sourceQuery, owner string, assetIDs []string) (*AssetCollection, error) {
|
||||
projectID = strings.TrimSpace(projectID)
|
||||
name = strings.TrimSpace(name)
|
||||
if projectID == "" {
|
||||
return nil, fmt.Errorf("资产集合必须属于项目")
|
||||
}
|
||||
if name == "" {
|
||||
return nil, fmt.Errorf("资产集合名称不能为空")
|
||||
}
|
||||
if utf8.RuneCountInString(name) > 120 {
|
||||
name = string([]rune(name)[:120])
|
||||
}
|
||||
var projectExists int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM projects WHERE id=?`, projectID).Scan(&projectExists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if projectExists != 1 {
|
||||
return nil, fmt.Errorf("项目不存在")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
id := uuid.NewString()
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.Exec(`INSERT INTO asset_collections(id,project_id,name,source,source_query,created_by,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)`,
|
||||
id, projectID, name, strings.TrimSpace(source), strings.TrimSpace(sourceQuery), strings.TrimSpace(owner), now, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
members, err := insertCollectionMembers(tx, id, projectID, assetIDs, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &AssetCollection{ID: id, ProjectID: projectID, Name: name, Source: strings.TrimSpace(source), SourceQuery: strings.TrimSpace(sourceQuery), MemberCount: members, CreatedAt: now, UpdatedAt: now}, nil
|
||||
}
|
||||
|
||||
func insertCollectionMembers(tx *sql.Tx, collectionID, projectID string, assetIDs []string, now time.Time) (int, error) {
|
||||
seen := map[string]bool{}
|
||||
n := 0
|
||||
for _, id := range assetIDs {
|
||||
id = strings.TrimSpace(id)
|
||||
if id == "" || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
var assetProject string
|
||||
err := tx.QueryRow(`SELECT COALESCE(project_id,'') FROM assets WHERE id=?`, id).Scan(&assetProject)
|
||||
if err == sql.ErrNoRows {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if assetProject != "" && assetProject != projectID {
|
||||
continue
|
||||
}
|
||||
if _, err = tx.Exec(`INSERT OR IGNORE INTO asset_collection_members(collection_id,asset_id,created_at) VALUES(?,?,?)`, collectionID, id, now); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n++
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (db *DB) ListAssetCollections(projectID string) ([]AssetCollection, error) {
|
||||
rows, err := db.Query(`SELECT id,project_id,name,source,source_query,created_at,updated_at,
|
||||
(SELECT COUNT(*) FROM asset_collection_members m WHERE m.collection_id=asset_collections.id)
|
||||
FROM asset_collections WHERE project_id=? ORDER BY updated_at DESC, id`, strings.TrimSpace(projectID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AssetCollection{}
|
||||
for rows.Next() {
|
||||
var item AssetCollection
|
||||
if err = rows.Scan(&item.ID, &item.ProjectID, &item.Name, &item.Source, &item.SourceQuery, &item.CreatedAt, &item.UpdatedAt, &item.MemberCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (db *DB) GetAssetCollection(id string) (*AssetCollection, error) {
|
||||
var item AssetCollection
|
||||
err := db.QueryRow(`SELECT id,project_id,name,source,source_query,created_at,updated_at,
|
||||
(SELECT COUNT(*) FROM asset_collection_members m WHERE m.collection_id=asset_collections.id)
|
||||
FROM asset_collections WHERE id=?`, strings.TrimSpace(id)).Scan(&item.ID, &item.ProjectID, &item.Name, &item.Source, &item.SourceQuery, &item.CreatedAt, &item.UpdatedAt, &item.MemberCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, observed, err := db.ObservationCoverage(RBACListAccess{Scope: RBACScopeAll}, item.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.Observed = observed
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (db *DB) CollectionMemberIDs(id string, limit int) ([]string, error) {
|
||||
if limit <= 0 || limit > 5000 {
|
||||
limit = 5000
|
||||
}
|
||||
rows, err := db.Query(`SELECT asset_id FROM asset_collection_members WHERE collection_id=? ORDER BY created_at, asset_id LIMIT ?`, strings.TrimSpace(id), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []string{}
|
||||
for rows.Next() {
|
||||
var assetID string
|
||||
if err = rows.Scan(&assetID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, assetID)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"golang.org/x/net/publicsuffix"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AssetGraph is a permission-filtered projection of the shared asset library.
|
||||
// Graph identities never contain assessment IDs; a task only holds references.
|
||||
type AssetGraphNode struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
State string `json:"state"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
AssetIDs []string `json:"asset_ids"`
|
||||
}
|
||||
type AssetGraphEdge struct {
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Relation string `json:"relation"`
|
||||
}
|
||||
type AssetGraph struct {
|
||||
Coverage map[string]int `json:"coverage,omitempty"`
|
||||
Nodes []AssetGraphNode `json:"nodes"`
|
||||
Edges []AssetGraphEdge `json:"edges"`
|
||||
Assets []*Asset `json:"assets"`
|
||||
Total int `json:"total"`
|
||||
NextOffset int `json:"next_offset"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
type AssetEndpoint struct {
|
||||
ID string `json:"id"`
|
||||
AssetID string `json:"asset_id"`
|
||||
Method string `json:"method"`
|
||||
Path string `json:"path"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
func (db *DB) PutAssetEndpoint(e *AssetEndpoint, access RBACListAccess) error {
|
||||
if _, err := db.GetAsset(e.AssetID, access); err != nil {
|
||||
return err
|
||||
}
|
||||
e.Method = strings.ToUpper(strings.TrimSpace(e.Method))
|
||||
if !map[string]bool{"GET": true, "POST": true, "PUT": true, "PATCH": true, "DELETE": true, "HEAD": true, "OPTIONS": true, "CONNECT": true, "TRACE": true}[e.Method] {
|
||||
return fmt.Errorf("invalid HTTP method")
|
||||
}
|
||||
u, err := url.Parse(e.Path)
|
||||
if err != nil || !strings.HasPrefix(e.Path, "/") || strings.HasPrefix(e.Path, "//") || u.IsAbs() || u.RawQuery != "" || u.Fragment != "" || len(e.Path) > 2048 || len(e.Title) > 500 || strings.ContainsAny(e.Path, "\r\n\x00") {
|
||||
return fmt.Errorf("endpoint path must be relative to the asset, without query values or fragments")
|
||||
}
|
||||
e.ID = fmt.Sprintf("endpoint:%x", sha256.Sum256([]byte(e.AssetID+"\n"+e.Method+"\n"+e.Path)))
|
||||
now := time.Now().UTC()
|
||||
_, err = db.Exec("INSERT INTO asset_endpoints(id,asset_id,method,path,title,first_seen_at,last_seen_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(asset_id,method,path) DO UPDATE SET title=CASE WHEN excluded.title<>'' THEN excluded.title ELSE asset_endpoints.title END,last_seen_at=excluded.last_seen_at", e.ID, e.AssetID, e.Method, e.Path, e.Title, now, now)
|
||||
return err
|
||||
}
|
||||
func (db *DB) AssetEndpoints(asset string, offset int, access RBACListAccess) ([]AssetEndpoint, error) {
|
||||
if _, err := db.GetAsset(asset, access); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
rows, err := db.Query("SELECT id,asset_id,method,path,title FROM asset_endpoints WHERE asset_id=? ORDER BY id LIMIT 50 OFFSET ?", asset, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []AssetEndpoint{}
|
||||
for rows.Next() {
|
||||
var e AssetEndpoint
|
||||
if err = rows.Scan(&e.ID, &e.AssetID, &e.Method, &e.Path, &e.Title); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (db *DB) SharedAssetGraph(filter AssetListFilter, access RBACListAccess, limit, offset int) (*AssetGraph, error) {
|
||||
if limit < 1 || limit > 20 {
|
||||
limit = 20
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
assets, total, err := db.ListAssets(limit, offset, filter, access)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g := &AssetGraph{Nodes: []AssetGraphNode{}, Edges: []AssetGraphEdge{}, Assets: assets, Total: total, NextOffset: offset + len(assets), HasMore: offset+len(assets) < total}
|
||||
nodes := map[string]*AssetGraphNode{}
|
||||
edges := map[string]bool{}
|
||||
add := func(id, kind, title, body, asset string) string {
|
||||
if n := nodes[id]; n != nil {
|
||||
found := false
|
||||
for _, v := range n.AssetIDs {
|
||||
found = found || v == asset
|
||||
}
|
||||
if !found {
|
||||
n.AssetIDs = append(n.AssetIDs, asset)
|
||||
}
|
||||
} else {
|
||||
nodes[id] = &AssetGraphNode{ID: id, Kind: kind, Title: title, Body: body, State: "inventory", AssetIDs: []string{asset}}
|
||||
}
|
||||
return id
|
||||
}
|
||||
edge := func(a, b, r string) {
|
||||
if a == "" || b == "" || a == b {
|
||||
return
|
||||
}
|
||||
k := a + "\n" + b + "\n" + r
|
||||
if !edges[k] {
|
||||
g.Edges = append(g.Edges, AssetGraphEdge{a, b, r})
|
||||
edges[k] = true
|
||||
}
|
||||
}
|
||||
for _, a := range assets {
|
||||
raw, _ := json.Marshal(a)
|
||||
title := a.Host
|
||||
if title == "" {
|
||||
title = a.Domain
|
||||
}
|
||||
if title == "" {
|
||||
title = a.IP
|
||||
}
|
||||
service := add("asset:"+a.ID, "service", title, string(raw), a.ID)
|
||||
domain := ""
|
||||
if a.Domain != "" {
|
||||
kind := "domain"
|
||||
root, err := publicsuffix.EffectiveTLDPlusOne(a.Domain)
|
||||
if err == nil && root != a.Domain {
|
||||
kind = "subdomain"
|
||||
add("domain:"+root, "domain", root, "", a.ID)
|
||||
edge("domain:"+root, "domain:"+a.Domain, "contains")
|
||||
}
|
||||
domain = add("domain:"+a.Domain, kind, a.Domain, "", a.ID)
|
||||
edge(domain, service, "exposes")
|
||||
}
|
||||
if a.IP != "" {
|
||||
ip := add("ip:"+a.IP, "ip", a.IP, "", a.ID)
|
||||
edge(domain, ip, "associated_with")
|
||||
edge(ip, service, "associated_with")
|
||||
}
|
||||
if a.BusinessSystem != "" {
|
||||
id := fmt.Sprintf("application:%x", sha256.Sum256([]byte(a.ID+"\n"+a.BusinessSystem)))
|
||||
app := add(id, "application", a.BusinessSystem, "", a.ID)
|
||||
edge(service, app, "serves")
|
||||
}
|
||||
endpoints, err := db.AssetEndpoints(a.ID, 0, access)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, ep := range endpoints {
|
||||
raw, _ := json.Marshal(ep)
|
||||
id := add(ep.ID, "endpoint", ep.Method+" "+ep.Path, string(raw), a.ID)
|
||||
edge(service, id, "contains")
|
||||
}
|
||||
}
|
||||
ids := []string{}
|
||||
for id := range nodes {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
g.Nodes = append(g.Nodes, *nodes[id])
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||