bugx-cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/README.md +193 -185
  2. package/core/README.md +2 -2
  3. package/core/agent/README.md +2 -1
  4. package/core/agent/agent_artifacts.py +8 -6
  5. package/core/agent/agent_eval.py +136 -54
  6. package/core/agent/agent_execution.py +218 -52
  7. package/core/agent/agent_orchestrator.py +14 -8
  8. package/core/agent/agent_targets.py +8 -2
  9. package/core/agent/feature_baseline.py +150 -0
  10. package/core/assets/README.md +3 -2
  11. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  12. package/core/assets/axe-core/LICENSE.txt +362 -0
  13. package/core/assets/axe-core/UPSTREAM.md +10 -0
  14. package/core/assets/axe-core/axe.min.js +12 -0
  15. package/core/assets/bugx-hero-en.svg +74 -0
  16. package/core/assets/bugx-hero-zh.svg +74 -0
  17. package/core/assets/bugx-social-preview.svg +71 -0
  18. package/core/assets/bugx-wechat-group.png +0 -0
  19. package/core/assets/codex.png +0 -0
  20. package/core/assets/dsh.png +0 -0
  21. package/core/assets/webui-chatgpt.jpg +0 -0
  22. package/core/assets/webui-session.jpg +0 -0
  23. package/core/assets/webui-skills.jpg +0 -0
  24. package/core/assets/webui-studio.jpg +0 -0
  25. package/core/assets/webui-zcode.jpg +0 -0
  26. package/core/assets/zcode.png +0 -0
  27. package/core/audit_packs/README.md +2 -0
  28. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  29. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  30. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  31. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  32. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  33. package/core/audit_packs/pitfalls/python_web.json +82 -0
  34. package/core/autonomous_cve/SPEC.md +1 -1
  35. package/core/autonomous_cve/attack_graph_store.py +152 -106
  36. package/core/autonomous_cve/behavior_graph.py +8 -2
  37. package/core/autonomous_cve/verifier.py +4 -1
  38. package/core/bugx.md +1 -1
  39. package/core/bugx_paths.py +43 -8
  40. package/core/cli-help.txt +66 -0
  41. package/core/cloud_sync/SPEC.md +1 -1
  42. package/core/cloud_sync/cloud_client.py +81 -11
  43. package/core/cloud_sync/cloud_onboard.py +42 -1
  44. package/core/cloud_sync/consent.py +33 -3
  45. package/core/cloud_sync/flywheel_client.py +186 -15
  46. package/core/cloud_sync/network_transport.py +24 -3
  47. package/core/cloud_sync/sensitive_filter.py +2 -2
  48. package/core/cloud_sync/sync_push.py +12 -10
  49. package/core/contracts/AGENT_GUIDE.md +6 -9
  50. package/core/contracts/README.md +2 -2
  51. package/core/contracts/bugx-runtime-contract.md +1 -1
  52. package/core/contracts/bugx-worker.md +1 -1
  53. package/core/contracts/engine_gap_contracts.py +86 -3
  54. package/core/coverage/coverage_discovery.py +599 -29
  55. package/core/coverage/coverage_evidence.py +47 -0
  56. package/core/coverage/coverage_forensics.py +9 -0
  57. package/core/coverage/coverage_validate.py +6 -1
  58. package/core/dev_harness/SPEC.md +1 -1
  59. package/core/engine-integrity.json +670 -442
  60. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  61. package/core/fuzzing/differential_oracle.py +562 -27
  62. package/core/fuzzing/fuzz_input.py +109 -6
  63. package/core/fuzzing/stateful_fuzzer.py +72 -0
  64. package/core/governance/secret_redactor.py +22 -10
  65. package/core/host_acp/SPEC.md +1 -1
  66. package/core/host_acp/__init__.py +4 -4
  67. package/core/host_acp/claude.py +59 -1
  68. package/core/host_acp/cline.py +64 -1
  69. package/core/host_acp/codex.py +56 -1
  70. package/core/host_acp/dsh.py +59 -1
  71. package/core/host_acp/opencode.py +56 -1
  72. package/core/host_acp/pi.py +59 -1
  73. package/core/host_acp/zcode.py +59 -1
  74. package/core/host_runtime/SPEC.md +1 -1
  75. package/core/host_runtime/adapters.py +1 -1
  76. package/core/host_runtime/cline.py +13 -0
  77. package/core/host_runtime/host_evaluators.py +44 -4
  78. package/core/host_runtime/host_probe.py +1 -1
  79. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  80. package/core/host_runtime/host_registry.py +15 -8
  81. package/core/host_runtime/mcp_registry_gate.py +12 -1
  82. package/core/host_runtime/pi.py +102 -0
  83. package/core/host_runtime/provider_facts.py +66 -0
  84. package/core/hosts/SPEC.md +1 -1
  85. package/core/hosts/__init__.py +6 -2
  86. package/core/hosts/_dsh_usage.py +1 -1
  87. package/core/hosts/base.py +32 -4
  88. package/core/hosts/claude.py +55 -0
  89. package/core/hosts/cline.py +6 -2
  90. package/core/hosts/codex.py +58 -0
  91. package/core/hosts/dsh.py +9 -1
  92. package/core/hosts/opencode.py +6 -6
  93. package/core/hosts/pi.py +159 -2
  94. package/core/infra/README.md +4 -2
  95. package/core/infra/__init__.py +2 -0
  96. package/core/infra/build_info.py +22 -3
  97. package/core/infra/client_metadata.py +1 -1
  98. package/core/infra/json_utils.py +22 -0
  99. package/core/launch_phases/README.md +6 -3
  100. package/core/launch_phases/SPEC.md +1 -1
  101. package/core/launch_phases/common.py +21 -2
  102. package/core/launch_phases/finding_confirm_phase.py +170 -5
  103. package/core/launch_phases/finding_settlement.py +188 -1
  104. package/core/launch_phases/judge_phase.py +69 -12
  105. package/core/launch_phases/orchestrator_controls.py +11 -7
  106. package/core/launch_phases/post_coverage_sync.py +9 -2
  107. package/core/launch_phases/post_phase.py +144 -8
  108. package/core/launch_phases/post_receipt.py +12 -1
  109. package/core/launch_phases/pre_phase.py +3 -3
  110. package/core/launch_phases/pre_recon_scout.py +66 -36
  111. package/core/launch_phases/pre_state_builder.py +23 -176
  112. package/core/launch_phases/report_sharing.py +3 -7
  113. package/core/launch_phases/round_orchestrator.py +129 -58
  114. package/core/launch_phases/semantic_recon.py +545 -0
  115. package/core/launch_phases/session_runtime.py +56 -9
  116. package/core/launch_phases/startup_gates.py +36 -8
  117. package/core/launch_phases/startup_interaction.py +68 -12
  118. package/core/launch_phases/startup_version_gate.py +13 -3
  119. package/core/launch_phases/supervisor_bridge.py +46 -17
  120. package/core/launch_phases/supervisor_coverage.py +8 -2
  121. package/core/launch_phases/supervisor_degraded.py +1 -9
  122. package/core/launch_phases/verify_loop.py +767 -0
  123. package/core/launch_phases/worker_barriers.py +15 -5
  124. package/core/launch_phases/worker_orchestrator.py +105 -25
  125. package/core/launch_phases/worker_prior.py +115 -0
  126. package/core/ledger/README.md +2 -1
  127. package/core/ledger/SPEC.md +1 -1
  128. package/core/ledger/_facade.py +2 -1
  129. package/core/ledger/archive_ops.py +60 -2
  130. package/core/ledger/cli.py +6 -1
  131. package/core/ledger/export_ops.py +6 -1
  132. package/core/ledger/finding_confirmation.py +48 -6
  133. package/core/ledger/finding_lifecycle.py +428 -5
  134. package/core/ledger/finding_verification.py +555 -10
  135. package/core/ledger/fp_ledger.py +255 -0
  136. package/core/ledger/incidents.py +10 -4
  137. package/core/ledger/patterns.py +10 -7
  138. package/core/ledger/receipt_contract.py +17 -1
  139. package/core/ledger/sync_ops.py +21 -16
  140. package/core/ledger/tool_experience.py +2 -1
  141. package/core/ledger/verify_life.py +88 -17
  142. package/core/locales/en-US.json +2 -2
  143. package/core/locales/zh-CN.json +2 -2
  144. package/core/mcp_handlers/SPEC.md +1 -1
  145. package/core/mcp_handlers/base.py +23 -3
  146. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  147. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  148. package/core/mcp_handlers/rpc_server.py +6 -1
  149. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  150. package/core/mcp_handlers/tool_table.py +15 -0
  151. package/core/mcp_runtime_support/environment.py +0 -38
  152. package/core/mcp_runtime_support/verifier.py +0 -52
  153. package/core/metadata.txt +2 -3
  154. package/core/planning/README.md +2 -1
  155. package/core/planning/domain_router.py +4 -2
  156. package/core/planning/dynamic_flow_analyzer.py +219 -14
  157. package/core/planning/judge_pipeline.py +87 -4
  158. package/core/planning/prompt_harness.py +57 -15
  159. package/core/planning/prompt_policy_engine.py +386 -0
  160. package/core/planning/spec_harvester.py +4 -4
  161. package/core/probes/INTERFACE.md +11 -1
  162. package/core/probes/SPEC.md +11 -1
  163. package/core/probes/__init__.py +46 -40
  164. package/core/probes/android_probe.py +177 -9
  165. package/core/probes/codebase_memory_probe.py +57 -0
  166. package/core/probes/desktop_probe.py +104 -0
  167. package/core/probes/differential_probe.py +99 -21
  168. package/core/probes/efficiency_probe.py +64 -0
  169. package/core/probes/ios_binary_probe.py +105 -1
  170. package/core/probes/memory_probe.py +66 -0
  171. package/core/probes/miniprogram_probe.py +75 -13
  172. package/core/probes/mobile_probe.py +215 -30
  173. package/core/probes/native_probe.py +88 -0
  174. package/core/probes/openwiki_probe.py +70 -0
  175. package/core/probes/pattern_probe.py +106 -0
  176. package/core/probes/platform_probe.py +81 -0
  177. package/core/probes/probe_registry.py +108 -7
  178. package/core/probes/sast_fixture_corpus.py +340 -0
  179. package/core/probes/sast_probe.py +553 -52
  180. package/core/probes/sast_rules.py +668 -28
  181. package/core/probes/sca_scanner.py +48 -0
  182. package/core/probes/ui_accessibility.py +149 -0
  183. package/core/probes/ui_audit.py +513 -0
  184. package/core/probes/ui_contract.py +273 -0
  185. package/core/probes/ui_evidence.py +212 -0
  186. package/core/probes/ui_measurements.py +314 -0
  187. package/core/probes/ui_repair.py +250 -0
  188. package/core/probes/ui_review.py +133 -0
  189. package/core/probes/ui_storybook.py +107 -0
  190. package/core/probes/ui_tokens.py +185 -0
  191. package/core/probes/ui_visual_diff.py +131 -0
  192. package/core/probes/web_probe.py +373 -18
  193. package/core/project_profiler/SPEC.md +1 -1
  194. package/core/project_profiler/arbitrator.py +6 -1
  195. package/core/project_profiler/detector.py +8 -1
  196. package/core/project_profiler/strategy.py +51 -15
  197. package/core/prompts/README.md +4 -2
  198. package/core/prompts/command_routing_en.md +2 -2
  199. package/core/prompts/command_routing_zh.md +2 -2
  200. package/core/prompts/policies/prompt_policies.json +101 -0
  201. package/core/prompts/stages/stage_repair.md +1 -1
  202. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  203. package/core/prompts/stages/stage_verify.md +44 -0
  204. package/core/repair/README.md +1 -1
  205. package/core/repair/l7_repair_loop.py +1 -4
  206. package/core/repair/rsi_fixer.py +4 -4
  207. package/core/repair/rsi_loop.py +1 -3
  208. package/core/repair/rsi_repair.py +7 -7
  209. package/core/repair/rsi_scope.py +27 -8
  210. package/core/report_engine/SPEC.md +1 -1
  211. package/core/report_engine/attestation.py +8 -4
  212. package/core/report_engine/finding_report.py +2 -1
  213. package/core/report_engine/models.py +7 -9
  214. package/core/report_engine/report_share.py +0 -8
  215. package/core/report_engine/sast_bridge.py +2 -2
  216. package/core/report_engine/server.py +18 -8
  217. package/core/report_engine/web-conformance.md +123 -18
  218. package/core/report_engine/web_conformance.py +21 -52
  219. package/core/retrieval/README.md +2 -1
  220. package/core/retrieval/SPEC.md +1 -1
  221. package/core/retrieval/code_analyzer.py +50 -14
  222. package/core/retrieval/context_assembler.py +7 -1
  223. package/core/retrieval/knowledge_sync.py +108 -14
  224. package/core/retrieval/pitfall_packs.py +277 -0
  225. package/core/retrieval/symbol_index.py +25 -6
  226. package/core/retrieval/universal_code_matcher.py +234 -49
  227. package/core/runtime/README.md +1 -1
  228. package/core/runtime/bugx_logging.py +78 -7
  229. package/core/runtime/fixture_solidify.py +5 -10
  230. package/core/runtime/global_telemetry.py +20 -0
  231. package/core/runtime/incident_eval.py +1 -1
  232. package/core/runtime/model_runner.py +4 -41
  233. package/core/runtime/platform_adapter.py +2 -2
  234. package/core/runtime/prep_validate.py +4 -2
  235. package/core/runtime/project_settings.py +2 -1
  236. package/core/runtime/scenario_eval.py +50 -8
  237. package/core/skills/bugx_docs_mcp_server.py +3 -1
  238. package/core/skills/bugx_mcp_server.py +29 -2
  239. package/core/skills/tools_kb.py +1 -1
  240. package/core/supervisor/README.md +1 -1
  241. package/core/supervisor/SPEC.md +1 -1
  242. package/core/supervisor/budget_governor.py +503 -9
  243. package/core/supervisor/checkpoint_pipeline.py +248 -6
  244. package/core/supervisor/checkpoint_sync.py +13 -0
  245. package/core/supervisor/claim_events.py +1 -1
  246. package/core/supervisor/finding_workflow.py +22 -5
  247. package/core/supervisor/lease_manager.py +1 -1
  248. package/core/supervisor/lifecycle_blocks.py +6 -1
  249. package/core/supervisor/rejection_remedies.py +52 -5
  250. package/core/supervisor/serial_authorization.py +48 -4
  251. package/core/supervisor/task_scheduler.py +2 -2
  252. package/core/supervisor/worker_checkpoint.py +8 -1
  253. package/core/supervisor/worker_runtime.py +8 -2
  254. package/core/supervisor_types/worker_claim.py +9 -0
  255. package/core/webui/README.md +1 -1
  256. package/core/webui/SPEC.md +2 -1
  257. package/core/webui/adapters/claude.py +5 -1
  258. package/core/webui/adapters/cline.py +10 -2
  259. package/core/webui/adapters/codex.py +5 -1
  260. package/core/webui/adapters/dsh.py +5 -1
  261. package/core/webui/docs_session_service.py +2 -2
  262. package/core/webui/mcp_inspector.py +11 -7
  263. package/core/webui/static/00-base.css +1060 -0
  264. package/core/webui/static/01-monitoring.css +802 -0
  265. package/core/webui/static/02-header-actions.css +321 -0
  266. package/core/webui/static/03-trigger-popover.css +697 -0
  267. package/core/webui/static/04-composer.css +628 -0
  268. package/core/webui/static/05-skills-center.css +878 -0
  269. package/core/webui/static/06-mcp-center.css +623 -0
  270. package/core/webui/static/07-skill-detail.css +265 -0
  271. package/core/webui/static/08-files-management.css +167 -0
  272. package/core/webui/static/09-files-center.css +386 -0
  273. package/core/webui/static/10-icons.css +105 -0
  274. package/core/webui/static/11-project-options.css +185 -0
  275. package/core/webui/static/12-profile-tab.css +383 -0
  276. package/core/webui/static/design-tokens.css +113 -0
  277. package/core/webui/static/index.html +14 -1
  278. package/core/webui/workspace_service.py +1 -1
  279. package/docs/07_distribution/01_README_NPM.md +193 -185
  280. package/ecosystem/integrations/README.md +1 -1
  281. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  282. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  283. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  284. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  285. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  286. package/ecosystem/integrations/opencode/opencode.json +23 -12
  287. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  288. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  289. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  290. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  291. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  292. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  293. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  294. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  295. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  296. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  297. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  298. package/interfaces/bin/bugx.js +37 -0
  299. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  300. package/interfaces/cli/bugx_cli/cli.py +172 -69
  301. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  302. package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
  303. package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
  304. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  305. package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
  306. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  307. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  308. package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
  309. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  310. package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
  311. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  312. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  313. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  314. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  315. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  316. package/interfaces/cli/bugx_cli/commands/system.py +524 -169
  317. package/interfaces/cli/bugx_cli/common.py +21 -15
  318. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  319. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  320. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  321. package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
  322. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  323. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  324. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  325. package/package.json +30 -15
  326. package/pyproject.toml +60 -9
  327. package/scripts/ensure-python.mjs +7 -7
  328. package/scripts/sync-version.mjs +10 -21
  329. package/scripts/test-npm-wrapper.mjs +1 -1
  330. package/core/assets/bugx-hero-cn.png +0 -0
  331. package/core/assets/bugx-hero-en.png +0 -0
  332. package/core/webui/static/project-settings.css +0 -6458
  333. package/docs/07_distribution/README.md +0 -16
  334. package/docs/README.md +0 -121
  335. package/interfaces/README.md +0 -143
  336. package/interfaces/bin/README.md +0 -35
  337. package/interfaces/cli/README.md +0 -90
  338. package/scripts/README.md +0 -118
@@ -14,7 +14,12 @@ from dataclasses import dataclass, field
14
14
  from pathlib import Path
15
15
  from typing import Any
16
16
 
17
- from core.retrieval.universal_code_matcher import CallNode, ParsedSource, UniversalCodeMatcher
17
+ from core.retrieval.universal_code_matcher import (
18
+ CallNode,
19
+ ParsedSource,
20
+ UniversalCodeMatcher,
21
+ detect_string_concat,
22
+ )
18
23
 
19
24
  from core.planning.dynamic_flow_analyzer import DynamicFlowAnalyzer, STRONG_SANITIZERS
20
25
 
@@ -27,6 +32,15 @@ class LanguageRuleSpec:
27
32
  arg_patterns: list[str] = field(default_factory=list) # 实参中必须命中的特征正则
28
33
  sanitizer_patterns: list[str] = field(default_factory=list) # 净化器过滤正则(命中则抵消告警)
29
34
  line_patterns: list[str] = field(default_factory=list) # 行级特征正则(如弱类型比较运算符)
35
+ require_param_operand: bool = False # 是否必须命中所在函数的形参(外部可控的最小判据)
36
+ require_dynamic_origin: bool = False # 是否要求实参的**目标 origin** 动态可控(SSRF 专用)
37
+ require_callee_base: tuple[str, ...] | None = None # callee 基对象白名单;None=不约束,"" 表示裸调用
38
+ arg_patterns_allow_taint: bool = False # arg_patterns 未命中时是否允许污点兜底(仅限「特征只是来源命名启发式」的规则)
39
+ # 调用点邻近窗口特征(组间 AND、组内 OR,匹配净代码行 [line-before, end+after])。
40
+ # 用于「shell 特征不在调用实参而在属性赋值」的形态(如 swift Process.run()
41
+ # 的 executableURL/arguments 赋值)——arg_patterns 对无实参调用结构性不可满足,
42
+ # 只能由调用点上下文承担(靶场 I-CMD 实证零命中,F-RSI-20261118-003)。
43
+ context_patterns: list[list[str]] = field(default_factory=list)
30
44
 
31
45
 
32
46
  @dataclass
@@ -73,10 +87,17 @@ BUILTIN_RULES: list[SASTRule] = [
73
87
  ),
74
88
  "javascript": LanguageRuleSpec(
75
89
  callee_patterns=[r"^(child_process\.)?(exec|execSync)$"],
90
+ # `RegExp.prototype.exec` 与 `child_process.exec` 同名同参形状:
91
+ # 压缩产物里的 `this.rules.inline.link.exec(e)`、`/x/g.exec(s)`
92
+ # 曾被整批报成 critical 命令注入。区别只在 receiver——命令执行
93
+ # 是裸调用或 child_process 命名空间调用,正则匹配则是「任意表达式
94
+ # 上的方法」。白名单里的空串专指裸调用(见 ``_callee_base_allowed``)。
95
+ require_callee_base=("", "child_process"),
76
96
  sanitizer_patterns=[r"execFile"],
77
97
  ),
78
98
  "typescript": LanguageRuleSpec(
79
99
  callee_patterns=[r"^(child_process\.)?(exec|execSync)$"],
100
+ require_callee_base=("", "child_process"),
80
101
  sanitizer_patterns=[r"execFile"],
81
102
  ),
82
103
  "php": LanguageRuleSpec(
@@ -101,7 +122,16 @@ BUILTIN_RULES: list[SASTRule] = [
101
122
  ),
102
123
  "swift": LanguageRuleSpec(
103
124
  callee_patterns=[r"^(Process|Foundation\.Process)\.run$"],
104
- arg_patterns=[r"/bin/(sh|bash)\b", r"\b(input|request|query|command)\b"],
125
+ # swift 的 Process.run() 惯用调用**无实参**——shell 特征在
126
+ # executableURL/arguments 属性赋值行。原 arg_patterns 要求实参
127
+ # 命中 /bin/sh 与输入命名,对无实参调用结构性不可满足,靶场
128
+ # I-CMD 实证零命中(F-RSI-20261118-003)。改由调用点邻近窗口
129
+ # 判定:可执行文件指向 sh/bash(组1)且 arguments 赋值含动态
130
+ # 拼接或插值(组2,组间 AND)——纯字面量 arguments 不报。
131
+ context_patterns=[
132
+ [r"/bin/(sh|bash)\b"],
133
+ [r"arguments\s*=[^\n]*(\+|\\\()"],
134
+ ],
105
135
  sanitizer_patterns=[r"\barguments\s*:\s*\[\s*\"[^\"]+\"\s*\]"],
106
136
  ),
107
137
  "ruby": LanguageRuleSpec(
@@ -125,8 +155,18 @@ BUILTIN_RULES: list[SASTRule] = [
125
155
  remediation="严格改用预编译参数化占位符(Parameterized Prepared Statements),禁止字符串拼接查询语句。",
126
156
  languages={
127
157
  "python": LanguageRuleSpec(
128
- callee_patterns=[r"^(cursor|db|conn|session)\.(execute|raw|select|query)$"],
158
+ # 基对象不能限定成 cursor/db/conn/session 这几个字面名:
159
+ # 真实代码里 sink 大量写作 ``_conn().execute(...)``、``cur.execute``、
160
+ # ``self.db.execute``,甚至链式 ``_conn().execute(q).fetchall()``——
161
+ # 后者的 callee 只剩裸 ``execute``。原模式对上述形态全部不匹配,
162
+ # 规则等于只覆盖了四个变量名的运气。判定精度改由
163
+ # ``require_string_concat`` 承担:只有实参确实是动态构造出来的
164
+ # 查询串才报,参数化查询(``execute(sql, params)``)不触发。
165
+ callee_patterns=[
166
+ r"(?:^|\.)(?:execute|executemany|executescript|raw|select|query)$",
167
+ ],
129
168
  require_string_concat=True,
169
+ require_param_operand=True,
130
170
  sanitizer_patterns=[r"parametrize", r"placeholder"],
131
171
  ),
132
172
  "go": LanguageRuleSpec(
@@ -143,11 +183,17 @@ BUILTIN_RULES: list[SASTRule] = [
143
183
  callee_patterns=[r"^(db|pool|client|connection)\.(query|execute)$"],
144
184
  require_string_concat=True,
145
185
  arg_patterns=[r'(`[^`]*\${|\+\s*[A-Za-z_])'],
186
+ # 这里的 arg_patterns 描述的是「SQL 文本在调用点上被动态拼出来」。
187
+ # 整条语句来自一个受污染变量(``db.query(sql)``,sql 赋值于
188
+ # ``req.body.q``)时,调用点上根本看不到 `+`/`${`,拼接发生在
189
+ # 上一行——污点已足以证明 SQL 文本动态可控,故允许它兜底。
190
+ arg_patterns_allow_taint=True,
146
191
  ),
147
192
  "typescript": LanguageRuleSpec(
148
193
  callee_patterns=[r"^(db|pool|client|connection)\.(query|execute)$"],
149
194
  require_string_concat=True,
150
195
  arg_patterns=[r'(`[^`]*\${|\+\s*[A-Za-z_])'],
196
+ arg_patterns_allow_taint=True,
151
197
  ),
152
198
  "php": LanguageRuleSpec(
153
199
  callee_patterns=[r"^(mysqli_query|mysql_query|\$db->query|\$pdo->query)$"],
@@ -160,7 +206,16 @@ BUILTIN_RULES: list[SASTRule] = [
160
206
  sanitizer_patterns=[r"\bParameters\.Add\("],
161
207
  ),
162
208
  "kotlin": LanguageRuleSpec(
163
- callee_patterns=[r"^(Statement\.(executeQuery|executeUpdate|execute)|JdbcTemplate\.(query|update)|SQLiteDatabase\.(rawQuery|execSQL))$"],
209
+ # 原锚定 ``^SQLiteDatabase\.(rawQuery|execSQL)$`` 把接收者限定成
210
+ # 字面类名,惯用 ``db.rawQuery(...)`` 全部漏检(靶场 A-SQLI 双
211
+ # 形态实证:锚定变体命中、惯用变体漏检,F-RSI-20261118-003)。
212
+ # rawQuery/execSQL 是 Android SQLite 专有 API 名,放开接收者
213
+ # (任意 ``.rawQuery``/``.execSQL``)后精度仍由
214
+ # require_string_concat + SQL 关键字 arg_patterns 承担。
215
+ callee_patterns=[
216
+ r"(?:^|\.)(rawQuery|execSQL)$",
217
+ r"^(Statement\.(executeQuery|executeUpdate|execute)|JdbcTemplate\.(query|update))$",
218
+ ],
164
219
  require_string_concat=True,
165
220
  arg_patterns=[r"\+\s*[A-Za-z_]", r"\b(SELECT|INSERT|UPDATE|DELETE)\b"],
166
221
  sanitizer_patterns=[r"\b(selectionArgs|arrayOf)\b", r"\?"],
@@ -175,6 +230,7 @@ BUILTIN_RULES: list[SASTRule] = [
175
230
  callee_patterns=[r"^(db\.execute|find_by_sql)$"],
176
231
  require_string_concat=True,
177
232
  arg_patterns=[r"\+\s*[A-Za-z_]", r"\b(SELECT|INSERT|UPDATE|DELETE)\b"],
233
+ arg_patterns_allow_taint=True,
178
234
  sanitizer_patterns=[r"\bsanitize_sql(?:_array|_for_conditions)?\b"],
179
235
  ),
180
236
  }
@@ -335,6 +391,42 @@ BUILTIN_RULES: list[SASTRule] = [
335
391
  }
336
392
  ),
337
393
 
394
+ # 5b. pathlib 拼接式路径穿越 (CWE-22)
395
+ #
396
+ # 现代 Python 惯用 `Path(base) / user_input` 组合路径后调用 read_text/write_text,
397
+ # 既没有字符串拼接(不触发 require_string_concat),也不落在 open/os.open 上,
398
+ # 因而逃过 SEC-PATH-001。解析器已把变量折叠进 resolved_callee
399
+ # (形如 `base_dir / username.read_text`),故此处直接匹配「`/` 拼接 + pathlib sink」形态。
400
+ #
401
+ # 精度约束:`/` 右操作数必须**不是**字符串字面量——`Path(__file__).parent / "x.txt"`
402
+ # 这类常量拼接不告警,避免对健康代码误报。
403
+ SASTRule(
404
+ id="SEC-PATH-002",
405
+ name="pathlib Path Traversal",
406
+ category="path-traversal",
407
+ severity="high",
408
+ confidence="medium",
409
+ cwe="CWE-22",
410
+ owasp="A01:2021-Broken-Access-Control",
411
+ message="使用 `/` 运算符将外部可控变量拼入 Path 后直接做文件读写,未约束在基目录内,存在路径穿越风险",
412
+ remediation="拼接后调用 `.resolve()` 归一化,并用 `is_relative_to(基目录)` 校验,或对输入做白名单校验。",
413
+ languages={
414
+ "python": LanguageRuleSpec(
415
+ callee_patterns=[
416
+ r"/\s+(?![\"'])[A-Za-z_][\w.\[\]'\"]*\s*\.\s*"
417
+ r"(?:read_text|read_bytes|write_text|write_bytes|open)$",
418
+ ],
419
+ require_param_operand=True,
420
+ sanitizer_patterns=[
421
+ r"\.resolve\(\)",
422
+ r"\bis_relative_to\b",
423
+ r"\.relative_to\(",
424
+ r"os\.path\.abspath",
425
+ ],
426
+ ),
427
+ }
428
+ ),
429
+
338
430
  # 6. 服务端请求伪造 SSRF (CWE-918)
339
431
  SASTRule(
340
432
  id="SEC-SSRF-001",
@@ -348,24 +440,36 @@ BUILTIN_RULES: list[SASTRule] = [
348
440
  remediation="对目标 URL 实施严格白名单域名与协议校验,阻断向 127.0.0.1/169.254.169.254 等私有内网段的请求。",
349
441
  languages={
350
442
  "python": LanguageRuleSpec(
351
- callee_patterns=[r"^(requests\.(get|post|put|delete)|urllib\.request\.urlopen|httpx\.(get|post))$"],
352
- require_string_concat=True,
443
+ # 只认全限定名会漏掉最常见的两种导入写法,实测都是真阳性:
444
+ # ``from urllib.request import urlopen`` 之后的裸 ``urlopen(...)``,
445
+ # 以及 ``import urllib.request as u`` 之后的 ``u.urlopen(...)``。
446
+ # ``urlopen`` 不是 ``exec`` 那种泛用名(不存在同名的高频标准库
447
+ # 方法),所以放开单层别名 receiver 的误报面很小;即便命中,
448
+ # 还要再过 require_dynamic_origin 这道 host 可控性判据。
449
+ callee_patterns=[
450
+ r"^(requests\.(get|post|put|delete)"
451
+ r"|urllib\.request\.urlopen"
452
+ r"|[A-Za-z_]\w*\.urlopen"
453
+ r"|urlopen"
454
+ r"|httpx\.(get|post))$"
455
+ ],
456
+ require_dynamic_origin=True,
353
457
  ),
354
458
  "go": LanguageRuleSpec(
355
459
  callee_patterns=[r"^(http\.(Get|Post|Head)|http\.NewRequest)$"],
356
- require_string_concat=True,
460
+ require_dynamic_origin=True,
357
461
  ),
358
462
  "java": LanguageRuleSpec(
359
463
  callee_patterns=[r"^(new URL|HttpClient\.send|HttpClients\.createDefault)$"],
360
- require_string_concat=True,
464
+ require_dynamic_origin=True,
361
465
  ),
362
466
  "javascript": LanguageRuleSpec(
363
467
  callee_patterns=[r"^(axios\.(get|post)|fetch|http\.(get|request)|https\.(get|request))$"],
364
- require_string_concat=True,
468
+ require_dynamic_origin=True,
365
469
  ),
366
470
  "typescript": LanguageRuleSpec(
367
471
  callee_patterns=[r"^(axios\.(get|post)|fetch|http\.(get|request)|https\.(get|request))$"],
368
- require_string_concat=True,
472
+ require_dynamic_origin=True,
369
473
  ),
370
474
  }
371
475
  ),
@@ -539,14 +643,360 @@ BUILTIN_RULES: list[SASTRule] = [
539
643
  ),
540
644
  }
541
645
  ),
646
+ # 14. 移动端 PII 日志泄露 (CWE-532):Log/System.out/print 将用户敏感字段
647
+ # 拼入日志。靶场 A-LOG 实证零命中(F-RSI-20261118-003);判据 = 日志调用
648
+ # + 实参含 PII 形态(email 字面量或敏感命名)+ 动态拼接——纯静态文案
649
+ # 日志(``Log.d("T", "started")``)不触发。
650
+ SASTRule(
651
+ id="SEC-PII-LOG",
652
+ name="PII Leakage via Application Logging",
653
+ category="privacy",
654
+ severity="medium",
655
+ confidence="medium",
656
+ cwe="CWE-532",
657
+ owasp="A09:2021-Security-Logging-and-Monitoring-Failures",
658
+ message="日志调用拼接了疑似个人敏感信息(邮箱/手机号/token/密码等),存在凭据或 PII 落盘泄露风险",
659
+ remediation="日志中禁止输出凭据与 PII;确需排障时对字段做脱敏(掩码/哈希前缀)并降低日志级别。",
660
+ languages={
661
+ "java": LanguageRuleSpec(
662
+ callee_patterns=[r"^(Log|R\.Log)\.(d|i|w|e|v)$", r"^System\.(out|err)\.print(ln)?$"],
663
+ arg_patterns=[r"@[\w.+-]+\.\w+", r"\b(email|phone|mobile|token|password|secret|ssn|api[_-]?key)\w*\b"],
664
+ require_string_concat=True,
665
+ ),
666
+ "kotlin": LanguageRuleSpec(
667
+ callee_patterns=[r"^(Log|R\.Log)\.(d|i|w|e|v)$", r"^println$", r"^System\.(out|err)\.print(ln)?$"],
668
+ arg_patterns=[r"@[\w.+-]+\.\w+", r"\b(email|phone|mobile|token|password|secret|ssn|api[_-]?key)\w*\b"],
669
+ require_string_concat=True,
670
+ ),
671
+ "swift": LanguageRuleSpec(
672
+ callee_patterns=[r"^(print|NSLog|debugPrint)$"],
673
+ arg_patterns=[r"@[\w.+-]+\.\w+", r"\b(email|phone|mobile|token|password|secret)\w*\b"],
674
+ require_string_concat=True,
675
+ ),
676
+ }
677
+ ),
542
678
  ]
543
679
 
544
680
 
681
+ def _touches_param(
682
+ call: Any, resolved_callee: str, resolved_args: str, category: str
683
+ ) -> bool:
684
+ """命中的动态片段里是否引用了**函数形参**(「外部可控」的最小判据)。
685
+
686
+ 正则规则引擎没有真正的污点分析,「外部可控」只能用一个可判定的代理指标:
687
+ 被拼进去的那一段是否来自函数入参。局部计算结果与模块级常量不满足,因此不会把
688
+ `Path(root) / hashed_name`、`f"SELECT {','.join(COLUMNS)} ..."` 这类内部构造
689
+ 当成注入。
690
+
691
+ 判据按漏洞类别取「可控片段」:
692
+ - 路径穿越:``/`` 的**右操作数**。左操作数通常就是形参(``artifact_root / name``),
693
+ 把「形参出现在任意位置」当可控,会把内部拼接全部报出来。
694
+ - 其它注入类:f-string 的 ``{...}`` 插值片段与 ``+`` 的右操作数。
695
+ """
696
+ params = getattr(call, "param_names", ()) or ()
697
+ if not params:
698
+ return False
699
+ allowed = set(params)
700
+
701
+ if category == "path-traversal":
702
+ operands = re.findall(r"/\s+([A-Za-z_][\w.]*)", resolved_callee)
703
+ if not operands:
704
+ return False
705
+ return any(
706
+ operand.split(".")[0].split("[")[0] in allowed for operand in operands
707
+ )
708
+
709
+ fragments = re.findall(r"\{([^{}]*)\}", resolved_args)
710
+ fragments += re.findall(r"\+\s*([A-Za-z_][\w.]*)", resolved_args)
711
+ for fragment in fragments:
712
+ for name in re.findall(r"[A-Za-z_][A-Za-z0-9_]*", fragment):
713
+ if name in allowed:
714
+ return True
715
+ return False
716
+
717
+
718
+ _ORIGIN_FIXED_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*://[A-Za-z0-9.\-]+")
719
+ _RELATIVE_URL_PREFIXES = ("/", "./", "../", "?", "#")
720
+
721
+
722
+ def _strip_quotes(text: str) -> str:
723
+ """去掉包裹实参的引号/反引号与首尾空白,便于判定相对 URL。"""
724
+ return text.strip().strip("\"'`").strip()
725
+
726
+
727
+ def _split_top_level(text: str, separators: str) -> list[str]:
728
+ """按顶层分隔符切分表达式,忽略字符串字面量与括号内部的分隔符。"""
729
+ parts: list[str] = []
730
+ depth = 0
731
+ quote: str | None = None
732
+ start = 0
733
+ index = 0
734
+ length = len(text)
735
+ while index < length:
736
+ char = text[index]
737
+ if quote is not None:
738
+ if char == "\\":
739
+ index += 2
740
+ continue
741
+ if char == quote:
742
+ quote = None
743
+ elif char in "\"'`":
744
+ quote = char
745
+ elif char in "([{":
746
+ depth += 1
747
+ elif char in ")]}":
748
+ if depth == 0:
749
+ break
750
+ depth -= 1
751
+ elif depth == 0 and char in separators:
752
+ parts.append(text[start:index])
753
+ start = index + 1
754
+ index += 1
755
+ parts.append(text[start:])
756
+ return parts
757
+
758
+
759
+ def _first_positional_arg(text: str) -> str:
760
+ """取第一个位置实参(到顶层逗号为止)。"""
761
+ return _split_top_level(text, ",")[0].strip()
762
+
763
+
764
+ _BARE_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
765
+
766
+
767
+ def _sql_text_dynamic(raw_sql: str, resolved_sql: str) -> bool:
768
+ """SQL 文本是否**在代码层面**被动态构造(f-string / 模板插值 / 顶层拼接)。
769
+
770
+ 只判第一个位置实参——``execute(sql, params)`` 里 bind 参数中的 f-string
771
+ 不构成注入,SQL 文本本身是参数化的。实测仓库自身因此产出 4 条 critical
772
+ 假阳性(``c.execute("... WHERE event_id=?", (f"...",))``)。
773
+
774
+ 原始实参是裸变量名时(``execute(sql)``)才采信折叠文本:真正的拼接发生在
775
+ ``sql`` 的赋值行上。反之绝不采信——折叠器会在**字符串内容**里按变量名做
776
+ 替换,把静态三引号 DDL 改写成带插值的假 f-string。
777
+ """
778
+ if detect_string_concat(raw_sql):
779
+ return True
780
+ if _BARE_IDENTIFIER_RE.match(raw_sql.strip()):
781
+ return detect_string_concat(resolved_sql)
782
+ return False
783
+
784
+
785
+ # 折叠器把 `const cp = require("child_process"); cp.exec(cmd)` 的 receiver
786
+ # 还原成 `require("child_process").exec`。规则层的 callee 正则与 receiver
787
+ # 白名单此前只看原始 `base_obj='cp'`,认不出这个等价形态,导致别名调用漏报
788
+ # (而解构 `const {exec} = ...` 与全限定 `child_process.exec` 都命中)。
789
+ # 这里把「折叠后的模块调用」规范化回白名单声明的模块名,只认**双引号或单引号
790
+ # 包裹的精确模块名**,不做子串/模糊匹配,以免放行 `foobar.exec`。
791
+ _REQUIRE_MODULE_CALL_RE = re.compile(
792
+ r'^require\(\s*["\'](?P<module>[A-Za-z0-9_@./\-]+)["\']\s*\)\.(?P<method>[A-Za-z_]\w*)$'
793
+ )
794
+
795
+
796
+ def _normalized_callee_base(call: CallNode) -> tuple[str, bool]:
797
+ """返回 (用于白名单判定的基对象, 是否任意对象的成员调用)。
798
+
799
+ 对折叠器还原出的 ``require("mod").method`` 形态,提取 ``mod`` 作为
800
+ 基对象,并把 ``preceded_by_dot`` 归零——它是**模块命名空间调用**,
801
+ 与 ``re.exec`` / ``obj.exec`` 这类"任意对象上的同名方法"性质不同。
802
+ 其余调用沿用解析器原始的 ``base_obj`` / ``preceded_by_dot``。
803
+
804
+ 绝不能把还原形态标记为成员调用:那会让空串基对象(正则字面量
805
+ ``/x/g.exec``、`re.exec`)借白名单里的 "" 混过——正是 RegExp.exec
806
+ 假阳性的根因。
807
+ """
808
+ resolved = call.resolved_callee or ""
809
+ match = _REQUIRE_MODULE_CALL_RE.match(resolved)
810
+ if match:
811
+ return match.group("module"), False
812
+ return call.base_obj, call.preceded_by_dot
813
+
814
+
815
+ def _callee_base_allowed(spec: LanguageRuleSpec, call: CallNode) -> bool:
816
+ """callee 的 receiver 是否落在规则声明的白名单内。
817
+
818
+ ``RegExp.prototype.exec`` 与 ``child_process.exec`` 在结构上只差 receiver:
819
+ 前者是 ``re.exec(s)`` / ``/x/g.exec(s)``(receiver 可以以 ``)``、``]`` 或
820
+ 正则字面量结尾,抽出来只剩裸方法名,``base_obj`` 为空),后者是裸
821
+ ``exec(cmd)`` 或 ``child_process.exec(cmd)``。白名单里的空串专指**非成员
822
+ 调用**,所以 ``preceded_by_dot`` 为真的调用一律不算裸调用。
823
+
824
+ ``require("child_process").exec`` 这类折叠后的模块调用先经
825
+ ``_normalized_callee_base`` 还原为模块名再判定,别名赋值调用因此能命中,
826
+ 而 ``re.exec`` / ``obj.exec`` 仍因基对象不在白名单被拒。
827
+ """
828
+ allowed = spec.require_callee_base
829
+ if allowed is None:
830
+ return True
831
+ base_obj, preceded_by_dot = _normalized_callee_base(call)
832
+ if preceded_by_dot:
833
+ # 任意对象上的同名方法(re.exec / obj.exec)不算裸调用。折叠还原的
834
+ # require("mod").exec 已在 _normalized_callee_base 里归零 dotted,
835
+ # 不会走到这里。
836
+ return False
837
+ return base_obj in allowed
838
+
839
+
840
+ def _unwrap_url_expression(text: str, depth: int = 0) -> str:
841
+ """剥掉包在 URL 外面的构造器(``urllib.request.Request(...)`` / ``new Request(...)``)。
842
+
843
+ 解析器把 ``urlopen(req)`` 折叠成 ``Request(url, ...)`` 之后,真正的 URL 表达式在
844
+ 内层第一个实参上;不剥这一层就只能看到 ``Request(...)`` 这个壳,判不出 origin。
845
+ """
846
+ expression = _first_positional_arg(text)
847
+ if depth >= 3 or not expression.endswith(")"):
848
+ return expression
849
+ match = re.match(r"^(?:new\s+)?[A-Za-z_][\w.]*\s*\(", expression)
850
+ if not match:
851
+ return expression
852
+ inner = expression[match.end():].rstrip()[:-1]
853
+ return _unwrap_url_expression(inner, depth + 1)
854
+
855
+
856
+ def _concat_chain(expression: str) -> list[str]:
857
+ """顶层 ``+`` 链的操作数,从左到右。
858
+
859
+ origin 由**最左操作数**决定:``base + "/api"`` 的 host 是 ``base``,
860
+ ``BASE + "?" + q`` 的 host 是常量 ``BASE``。只看右操作数会把前者漏掉、把后者误报。
861
+ """
862
+ return [part.strip() for part in _split_top_level(expression, "+")]
863
+
864
+
865
+ _LITERAL_RE = re.compile(r"^[rbfuRBFU]*[\"'][^\"']*[\"']$")
866
+
867
+
868
+ def _is_literal(expression: str) -> bool:
869
+ return bool(_LITERAL_RE.match(expression.strip()))
870
+
871
+
872
+ def _first_interpolation(expression: str, language: str) -> int | None:
873
+ """第一个插值位置:JS 模板 ``${``,Python f-string ``{``。"""
874
+ match = re.search(r"\$\{", expression)
875
+ if match:
876
+ return match.start()
877
+ if language == "python" and re.search(r"[fF][\"']", expression):
878
+ match = re.search(r"(?<![{\w])\{", expression)
879
+ if match:
880
+ return match.start()
881
+ return None
882
+
883
+
884
+ def _ssrf_origin_dynamic(
885
+ text: str, language: str, tainted: bool, param_names: tuple[str, ...] = ()
886
+ ) -> bool:
887
+ """URL 实参是否可能把**目标主机**交给外部输入。
888
+
889
+ SSRF 的必要条件是 host 可控,而不是"实参里出现过拼接"。旧实现只看
890
+ ``has_string_concat``,于是三类本该零告警的写法全被报出来:
891
+
892
+ * 相对 URL(``fetch(`/api/x`)``)——origin 就是当前页面,打不到内网;
893
+ * 常量 origin 只拼后缀(``BASE + "/x"``、``BASE + "?" + q``)——host 由常量决定;
894
+ * origin 已写全(``f"https://api.x.com/{id}"``)——只有路径段可控。
895
+
896
+ 反过来,实参是**受污染**的裸标识符时无法证明 origin 固定,仍按动态处理——
897
+ 云端技能包下载就是这种形状(``url`` 由 ``base_url``/环境变量决定)。
898
+ """
899
+ if not text:
900
+ return False
901
+ expression = _unwrap_url_expression(text)
902
+ if not expression:
903
+ return False
904
+ if _strip_quotes(expression).startswith(_RELATIVE_URL_PREFIXES):
905
+ return False
906
+
907
+ chain = _concat_chain(expression)
908
+ if len(chain) > 1:
909
+ base = chain[0]
910
+ if _is_literal(base):
911
+ # ``"https://" + host`` 只固定了协议,host 仍可控;写全 host 才算固定。
912
+ return not _ORIGIN_FIXED_RE.match(_strip_quotes(base))
913
+ # 基是标识符/调用:只有它能被外部输入决定时才可能换 host。
914
+ if param_names and not tainted:
915
+ return bool(set(re.findall(r"[A-Za-z_]\w*", base)) & set(param_names))
916
+ return True
917
+
918
+ position = _first_interpolation(expression, language)
919
+ if position is None:
920
+ # 没有可见的动态构造。两种情况下 origin 仍不可证固定:
921
+ # 1. 实参受污染(云端技能包下载:``url`` 由 ``base_url``/环境变量决定);
922
+ # 2. 表达式**本身就是所在函数的形参**——``requests.get(url)`` 的 url
923
+ # 完全由调用方决定,是最典型的 SSRF 形态,而形参不会被标记为污点,
924
+ # 只按 ``tainted`` 判会把这条真阳性漏掉。
925
+ # 字面量实参(``requests.get("https://api.x.com/x")``)与 JS 的
926
+ # ``fetch(target.url)``(无 param_names)都不会落到这里为真。
927
+ if tainted:
928
+ return True
929
+ return bool(param_names) and expression.strip() in param_names
930
+ prefix = _strip_quotes(expression[:position])
931
+ if _ORIGIN_FIXED_RE.match(prefix):
932
+ return False
933
+ if param_names and not tainted:
934
+ fragment = expression[position:].split("}", 1)[0]
935
+ return bool(set(re.findall(r"[A-Za-z_]\w*", fragment)) & set(param_names))
936
+ return True
937
+
938
+
939
+
940
+ def _secret_value_looks_real(value: str) -> bool:
941
+ """硬编码密钥字面量的高置信形态判据(SEC-SECRET-001 值过滤)。
942
+
943
+ 宁漏勿误:已知密钥前缀(AWS/GitHub/Slack/OpenAI/Google/bugx)直接
944
+ 放行;否则要求值含大写+小写+数字且不含 ``/``、空白、``_`` 之外的路径
945
+ 分隔符——URL 路径、小写配置词、模块路径因此不再误报,而随机混合串
946
+ (靶场 ``Zq7Vm4Kd9Xw2Ps5Nb8Rt3Hf6L`` 类)继续命中。
947
+ """
948
+ known_prefixes = (
949
+ "akia", "asia", "sk-", "sk_live_", "sk_test_", "ghp_", "gho_",
950
+ "xoxb-", "xoxp-", "aiza", "bxk_", "-----begin",
951
+ )
952
+ lowered = value.lower()
953
+ if lowered.startswith(known_prefixes):
954
+ return True
955
+ if any(ch in value for ch in ("/", " ")):
956
+ return False
957
+ has_upper = any(ch.isupper() for ch in value)
958
+ has_lower = any(ch.islower() for ch in value)
959
+ has_digit = any(ch.isdigit() for ch in value)
960
+ return has_upper and has_lower and has_digit
961
+
962
+
963
+ def _call_context_window(
964
+ parsed: "ParsedSource", call: Any, *, before: int = 8, after: int = 2,
965
+ ) -> str:
966
+ """取调用点邻近窗口的净代码文本(注释/字符串内容已剥离)。
967
+
968
+ 供 ``context_patterns`` 判定使用:行区间 [line-before, end_line+after],
969
+ 越界自动夹取。净代码行保证注释里的文案提及(如规则说明文字)不会
970
+ 误触发上下文特征。
971
+ """
972
+ start = max(1, int(call.span.line) - before)
973
+ end = min(len(parsed.lines), int(call.span.end_line) + after)
974
+ if end < start:
975
+ return ""
976
+ # 用原始行而非净代码行:净代码行会把字符串内容替换成空格(实测
977
+ # ``"/bin/sh"``/``"-c"`` 均被抹除,上下文特征因此不可见)。原始行
978
+ # 剔除纯注释行(//、#、*、/*、--),规则文案提及不误触发。
979
+ pieces: list[str] = []
980
+ for raw in parsed.lines[start - 1:end]:
981
+ stripped = raw.strip()
982
+ if stripped.startswith(("//", "#", "*", "/*", "--")):
983
+ continue
984
+ pieces.append(raw)
985
+ return "\n".join(pieces)
986
+
987
+
545
988
  class SASTRuleMatcher:
546
989
  """基于声明式规则库对 ParsedSource 执行多语言模式匹配"""
547
990
 
991
+
992
+
548
993
  def __init__(self, rules: list[SASTRule] | None = None) -> None:
549
994
  self.rules = rules or BUILTIN_RULES
995
+ # 逐文件解析失败的**结构化**跳过清单(F-207)。``_scan_python_specifics``
996
+ # 在 ``ast.parse`` 失败时写入一条带 file/reason/行定位的记录;调用方
997
+ # (``scan_multilang_sources`` → ``run_scan``)读取并对外暴露。
998
+ # 没有这条记录时,「解析失败」与「文件里没缺陷」在证据上完全同形。
999
+ self.parse_errors: list[dict[str, Any]] = []
550
1000
 
551
1001
  def match_file(self, parsed: ParsedSource) -> list[dict[str, Any]]:
552
1002
  findings: list[dict[str, Any]] = []
@@ -568,12 +1018,20 @@ class SASTRuleMatcher:
568
1018
  if not spec:
569
1019
  continue
570
1020
 
571
- # 检查 callee_patterns 命中 (支持原始与解析展开的 callee)
1021
+ # 检查 callee_patterns 命中 (支持原始与解析展开的 callee)。
1022
+ # 折叠器还原出的 `require("child_process").exec` 会被规范化成
1023
+ # `child_process.exec` 一并参与匹配——否则 `^(child_process\.)?exec$`
1024
+ # 这类别名调用会被锚定正则挡在门外(别名赋值调用的假阴性)。
1025
+ base_obj, _ = _normalized_callee_base(call)
1026
+ normalized_callee = (
1027
+ f"{base_obj}.{call.method_name}" if base_obj else call.method_name
1028
+ )
572
1029
  callee_matched = False
573
1030
  for pat in spec.callee_patterns:
574
1031
  if (
575
1032
  re.search(pat, call.callee)
576
1033
  or re.search(pat, resolved_callee)
1034
+ or re.search(pat, normalized_callee)
577
1035
  or re.search(pat, f"{call.callee}({call.args_raw})")
578
1036
  or re.search(pat, f"{resolved_callee}({resolved_args})")
579
1037
  ):
@@ -582,6 +1040,24 @@ class SASTRuleMatcher:
582
1040
  if not callee_matched:
583
1041
  continue
584
1042
 
1043
+ # callee 的 receiver 约束:把「裸函数调用」与「任意对象上的同名
1044
+ # 方法」区分开(JS 的 RegExp.exec vs child_process.exec)。
1045
+ if not _callee_base_allowed(spec, call):
1046
+ continue
1047
+
1048
+ # SQL 类规则的全部判据都只作用于第一个位置实参(SQL 文本)。
1049
+ # ``execute(sql, params)`` 的 bind 参数里出现 f-string / 形参
1050
+ # 都不是注入——判据作用在整段实参文本上会把参数化查询报成
1051
+ # critical SQL 注入(实测仓库自身 4 条)。
1052
+ if rule.category == "sql-injection":
1053
+ analysis_raw = _first_positional_arg(call.args_raw or "")
1054
+ analysis_resolved = _first_positional_arg(resolved_args or "")
1055
+ concat = _sql_text_dynamic(analysis_raw, analysis_resolved)
1056
+ else:
1057
+ analysis_raw = call.args_raw or ""
1058
+ analysis_resolved = resolved_args
1059
+ concat = call.has_string_concat
1060
+
585
1061
  # 检查行级特征匹配 (如弱类型比较运算符)
586
1062
  if spec.line_patterns:
587
1063
  line_matched = any(re.search(pat, call.span.snippet) for pat in spec.line_patterns)
@@ -590,33 +1066,78 @@ class SASTRuleMatcher:
590
1066
 
591
1067
  # 检查动态字符串拼接或受污染变量要求
592
1068
  has_concat_or_taint = (
593
- call.has_string_concat
1069
+ concat
594
1070
  or is_tainted
595
- or analyzer.has_framework_source(resolved_args)
596
- or analyzer.has_framework_source(call.args_raw)
1071
+ or analyzer.has_framework_source(
1072
+ analyzer.payload_portion(analysis_resolved)
1073
+ )
1074
+ or analyzer.has_framework_source(
1075
+ analyzer.payload_portion(analysis_raw)
1076
+ )
597
1077
  )
598
1078
  if spec.require_string_concat and not has_concat_or_taint:
599
1079
  continue
600
1080
 
1081
+ # SSRF 的必要条件是 **host 可控**,不是"实参里出现过拼接"。判据见
1082
+ # ``_ssrf_origin_dynamic``:相对 URL、只拼 query、origin 已写全都不算。
1083
+ #
1084
+ # 取哪份实参文本取决于解析器有没有真实作用域信息:Python 有 AST,
1085
+ # ``resolved_args`` 的变量折叠是精确的,能把 ``urlopen(req)`` 展开成
1086
+ # ``Request(url, ...)``;JS/TS 没有作用域,``resolved_args`` 会把整段
1087
+ # 变量初始化语句塞进来——压缩包一个 30KB 的 blob 里到处是 ``+``,
1088
+ # 拼接判据就彻底失效(实测仓库自身因此产出 13 条假 SSRF)。
1089
+ if spec.require_dynamic_origin:
1090
+ url_text = resolved_args if call.param_names else (call.args_raw or "")
1091
+ if not _ssrf_origin_dynamic(
1092
+ url_text, lang, is_tainted, call.param_names or ()
1093
+ ):
1094
+ continue
1095
+
601
1096
  # 检查实参特征 (支持原始实参、解析展开后的实参与被调用者特征)
1097
+ #
1098
+ # arg_patterns 默认是**硬性判据**:它编码的是结构性必要条件
1099
+ # (``shell=True``、``"sh","-c"``、``"MD5"`` 字面量……),"实参
1100
+ # 被污点污染"不能替代它——否则 ``subprocess.run([git, "--version"])``
1101
+ # 这种列表形式、没开 shell 的调用会因为 git 是形参而被报成
1102
+ # critical 命令注入。只有声明了 ``arg_patterns_allow_taint`` 的
1103
+ # 规则(其 arg_patterns 只是「来源命名启发式」)才允许污点兜底。
602
1104
  if spec.arg_patterns:
603
1105
  arg_matched = any(
604
- re.search(pat, call.args_raw)
605
- or re.search(pat, resolved_args)
1106
+ re.search(pat, analysis_raw)
1107
+ or re.search(pat, analysis_resolved)
606
1108
  or re.search(pat, call.callee)
607
1109
  or re.search(pat, resolved_callee)
608
1110
  for pat in spec.arg_patterns
609
1111
  )
610
- if not arg_matched and is_tainted:
1112
+ if not arg_matched and spec.arg_patterns_allow_taint and is_tainted:
611
1113
  arg_matched = True
612
1114
  if not arg_matched:
613
1115
  continue
614
1116
 
1117
+ # 调用点邻近窗口特征(组间 AND、组内 OR):用于 shell 特征在
1118
+ # 属性赋值而非调用实参的形态(swift Process.run())。窗口取
1119
+ # 净代码行(注释/字符串内容已剥离,文案提及不误报)。
1120
+ if spec.context_patterns:
1121
+ window = _call_context_window(parsed, call, before=8, after=2)
1122
+ if not all(
1123
+ any(re.search(pat, window) for pat in group)
1124
+ for group in spec.context_patterns
1125
+ ):
1126
+ continue
1127
+
1128
+ # 「外部可控」的最小判据:命中的动态片段必须引用所在函数的形参。
1129
+ # 没有这一层,任何 `Path(x) / y` 后接文件读写、任何 f-string SQL
1130
+ # 都会被报——实测仓库自身就因此产出 8 条假路径穿越与 27 条假 SQLi。
1131
+ if spec.require_param_operand and not _touches_param(
1132
+ call, resolved_callee, analysis_resolved, rule.category
1133
+ ):
1134
+ continue
1135
+
615
1136
  # 检查规则自带的净化器阻断
616
1137
  if spec.sanitizer_patterns:
617
1138
  is_sanitized = any(
618
- re.search(pat, call.args_raw)
619
- or re.search(pat, resolved_args)
1139
+ re.search(pat, analysis_raw)
1140
+ or re.search(pat, analysis_resolved)
620
1141
  or re.search(pat, call.span.snippet)
621
1142
  for pat in spec.sanitizer_patterns
622
1143
  )
@@ -626,8 +1147,8 @@ class SASTRuleMatcher:
626
1147
  # 检查分类强类型安全防御净化器消歧
627
1148
  if rule.category in STRONG_SANITIZERS:
628
1149
  if (
629
- analyzer.is_strong_sanitized(call.args_raw, rule.category, lang)
630
- or analyzer.is_strong_sanitized(resolved_args, rule.category, lang)
1150
+ analyzer.is_strong_sanitized(analysis_raw, rule.category, lang)
1151
+ or analyzer.is_strong_sanitized(analysis_resolved, rule.category, lang)
631
1152
  or analyzer.is_strong_sanitized(call.span.snippet, rule.category, lang)
632
1153
  ):
633
1154
  continue
@@ -665,7 +1186,10 @@ class SASTRuleMatcher:
665
1186
  elif lang == "ruby":
666
1187
  findings.extend(self._scan_ruby_specifics(parsed))
667
1188
  elif lang == "python":
668
- findings.extend(self._scan_python_specifics(parsed))
1189
+ python_findings, parse_failure = self._scan_python_specifics(parsed)
1190
+ findings.extend(python_findings)
1191
+ if parse_failure is not None:
1192
+ self.parse_errors.append(parse_failure)
669
1193
 
670
1194
  # 去重并返回
671
1195
  seen = set()
@@ -679,7 +1203,12 @@ class SASTRuleMatcher:
679
1203
 
680
1204
  def _scan_hardcoded_secrets(self, parsed: ParsedSource) -> list[dict[str, Any]]:
681
1205
  findings = []
682
- secret_kw = re.compile(r'\b(api[_-]?key|secret|password|passwd|private_key|token|access_token)\b\s*[:=]\s*["\']([^"\']{12,})["\']', re.IGNORECASE)
1206
+ # 标识符关键字放宽(F-RSI-20261118-003):原正则以 ``\b`` 锚定裸名
1207
+ # (``api_key =``/``token =``),靶场 ``apiKeyValue``/``sessionTokenValue``
1208
+ # 这类驼峰复合名因无词边界而整体漏检(A-KEY/I-TOKEN 零命中实证)。
1209
+ # 现语义 = 标识符**包含**敏感关键字(前后不要求词边界)+ 12+ 字符
1210
+ # 字符串字面量赋值;短值与占位符仍被下方过滤排除。
1211
+ secret_kw = re.compile(r'(api[_-]?key|secret|password|passwd|private[_-]?key|token)\w*\s*[:=]\s*["\']([^"\']{12,})["\']', re.IGNORECASE)
683
1212
 
684
1213
  for line_no, line in enumerate(parsed.lines, 1):
685
1214
  if UniversalCodeMatcher.is_line_suppressed(parsed, line_no, "SEC-SECRET-001"):
@@ -687,9 +1216,31 @@ class SASTRuleMatcher:
687
1216
  m = secret_kw.search(line)
688
1217
  if m:
689
1218
  val = m.group(2)
1219
+ # 匹配必须落在代码区:净代码行在同位置已被抹成空白说明
1220
+ # 赋值发生在字符串/注释内容里(文档性提及 ``token='x'``、
1221
+ # ``len("耗时/Token:")`` 切片文案),不是硬编码凭据。
1222
+ clean = (
1223
+ parsed.clean_lines[line_no - 1]
1224
+ if 0 <= line_no - 1 < len(parsed.clean_lines) else ""
1225
+ )
1226
+ if clean and m.start(1) < len(clean) and clean[m.start(1)].isspace():
1227
+ continue
690
1228
  # 排除占位符
691
1229
  if val.lower() in {"your_token_here", "placeholder", "changeme", "your_password", "env_variable"}:
692
1230
  continue
1231
+ # 排除模板占位(${VAR}/{{VAR}}/<VAR>)——不是字面量密钥。
1232
+ if val.startswith(("${", "{{")) or re.fullmatch(r"<[^>]*>", val):
1233
+ continue
1234
+ # 排除全大写常量子符串(BUGX_HEADLESS_OK 类哨兵/标志值,
1235
+ # 真实密钥几乎总是混合大小写或含符号)。
1236
+ if re.fullmatch(r"[A-Z][A-Z0-9_]+", val):
1237
+ continue
1238
+ # 值形态必须「像密钥」(宁漏勿误,仓库自身 17→7→5 收敛实证):
1239
+ # 已知密钥前缀直接放行;否则要求大小写混合+数字且无路径/空白
1240
+ # 分隔符——``DEVICE_TOKEN_PATH = "/api/..."``(URL 路径)与
1241
+ # ``token_method = "worker_reported"``(小写配置值)不再报。
1242
+ if not _secret_value_looks_real(val):
1243
+ continue
693
1244
  findings.append({
694
1245
  "rule_id": "SEC-SECRET-001",
695
1246
  "name": "Hardcoded Secret or Access Token",
@@ -708,12 +1259,21 @@ class SASTRuleMatcher:
708
1259
  })
709
1260
  return findings
710
1261
 
711
- def _scan_python_specifics(self, parsed: ParsedSource) -> list[dict[str, Any]]:
712
- findings = []
1262
+ def _scan_python_specifics(
1263
+ self, parsed: ParsedSource,
1264
+ ) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
1265
+ """Python 专有 AST 规则。
1266
+
1267
+ 返回 ``(findings, parse_failure)``:解析失败时 findings 为空,同时返回
1268
+ **结构化降级对象**(``skipped=True`` + ``reason`` + file/行定位),由
1269
+ ``match_file`` 记入 ``self.parse_errors``。原实现直接 ``return []``,
1270
+ 让「解析失败」与「文件无缺陷」在调用方看来完全一样(F-207)。
1271
+ """
1272
+ findings: list[dict[str, Any]] = []
713
1273
  try:
714
1274
  tree = ast.parse(parsed.raw_text, filename=str(parsed.filepath))
715
- except Exception:
716
- return []
1275
+ except (SyntaxError, ValueError) as exc:
1276
+ return [], self._parse_failure_record(parsed, exc)
717
1277
 
718
1278
  for node in ast.walk(tree):
719
1279
  if isinstance(node, ast.ExceptHandler):
@@ -739,7 +1299,34 @@ class SASTRuleMatcher:
739
1299
  "remediation": "指定具体的异常捕获类型,并在 except 块中输出诊断日志或妥善恢复。",
740
1300
  "language": "python",
741
1301
  })
742
- return findings
1302
+ return findings, None
1303
+
1304
+ @staticmethod
1305
+ def _parse_failure_record(parsed: ParsedSource, exc: Exception) -> dict[str, Any]:
1306
+ """把 ``ast.parse`` 的失败折成可区分、可定位的结构化跳过记录。
1307
+
1308
+ ``SyntaxError`` 自带 lineno/offset/msg,直接透出;其余(如 NUL 字节触发的
1309
+ ``ValueError``)没有行定位,仍保留 file 与 reason,不用空值伪装成「扫过」。
1310
+ """
1311
+ if isinstance(exc, SyntaxError):
1312
+ reason = "syntax_error"
1313
+ line = int(exc.lineno or 0)
1314
+ col = int(exc.offset or 0)
1315
+ detail = exc.msg or ""
1316
+ else:
1317
+ reason = "parse_error"
1318
+ line = 0
1319
+ col = 0
1320
+ detail = str(exc)
1321
+ return {
1322
+ "skipped": True,
1323
+ "reason": reason,
1324
+ "stage": "python_ast_rules",
1325
+ "file": parsed.rel_path,
1326
+ "line": line,
1327
+ "col": col,
1328
+ "detail": detail,
1329
+ }
743
1330
 
744
1331
  def _scan_js_specifics(self, parsed: ParsedSource) -> list[dict[str, Any]]:
745
1332
  findings = []
@@ -839,3 +1426,56 @@ class SASTRuleMatcher:
839
1426
  "language": "ruby",
840
1427
  })
841
1428
  return findings
1429
+
1430
+
1431
+ def is_available(matcher: "SASTRuleMatcher | None" = None) -> tuple[bool, str]:
1432
+ """降级契约:机械探活规则库完整性(纯内存检查,零 I/O、零子进程)。
1433
+
1434
+ 规则库为空或存在缺语言规格的规则时返回 False;调用方必须走
1435
+ ``run_static_degraded`` 显式标记降级匹配,禁止把空结果伪装成「未发现漏洞」。
1436
+ """
1437
+ rules = (matcher.rules if matcher is not None else BUILTIN_RULES) or []
1438
+ if not rules:
1439
+ return False, "SAST 规则库为空;模式匹配能力不可用"
1440
+ broken = [rule.id for rule in rules if not rule.languages]
1441
+ if broken:
1442
+ return False, f"规则缺少语言规格(含 generic 回退也没有): {', '.join(sorted(broken)[:8])}"
1443
+ return True, f"{len(rules)} 条内置规则就绪"
1444
+
1445
+
1446
+ def run_static_degraded(parsed, *, matcher: "SASTRuleMatcher | None" = None) -> dict:
1447
+ """降级契约:目标语言无专属规则时回退 generic 规则,输出可区分的降级结果。
1448
+
1449
+ 输出与成功路径(``match_file`` 返回的裸 findings 列表)字段级可区分:
1450
+ 本契约返回结构化 dict,``status="degraded"`` + ``degraded=True`` +
1451
+ ``degraded_reason``,并声明该语言有多少条规则是靠 generic 规格兜底匹配的。
1452
+ """
1453
+ active = matcher if matcher is not None else SASTRuleMatcher()
1454
+ language = getattr(parsed, "language", "") or ""
1455
+ native_rules = sum(1 for rule in active.rules if language in rule.languages)
1456
+ generic_only = native_rules == 0
1457
+ findings = active.match_file(parsed)
1458
+ return {
1459
+ "schema_version": 1,
1460
+ "success": True,
1461
+ "status": "degraded",
1462
+ "degraded": True,
1463
+ "degraded_reason": (
1464
+ "language_native_spec_missing" if generic_only
1465
+ else "static_rule_match_only"
1466
+ ),
1467
+ "probe_mode": "static_degraded",
1468
+ "language": language,
1469
+ "rules_with_native_spec": native_rules,
1470
+ "rules_total": len(active.rules),
1471
+ "total_findings": len(findings),
1472
+ "findings": findings,
1473
+ "evidence": {
1474
+ "generic_fallback_used": generic_only,
1475
+ "availability_detail": "规则库带 generic 回退" if generic_only else "目标语言有专属规则规格",
1476
+ },
1477
+ "metadata": {
1478
+ "degraded_mode": "declarative_rule_match_static",
1479
+ "fallback": "目标语言缺专属规则时只报 generic 覆盖的置信度较低模式;禁止把降级覆盖伪装成全量规则扫描",
1480
+ },
1481
+ }