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.
- package/README.md +193 -185
- package/core/README.md +2 -2
- package/core/agent/README.md +2 -1
- package/core/agent/agent_artifacts.py +8 -6
- package/core/agent/agent_eval.py +136 -54
- package/core/agent/agent_execution.py +218 -52
- package/core/agent/agent_orchestrator.py +14 -8
- package/core/agent/agent_targets.py +8 -2
- package/core/agent/feature_baseline.py +150 -0
- package/core/assets/README.md +3 -2
- package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
- package/core/assets/axe-core/LICENSE.txt +362 -0
- package/core/assets/axe-core/UPSTREAM.md +10 -0
- package/core/assets/axe-core/axe.min.js +12 -0
- package/core/assets/bugx-hero-en.svg +74 -0
- package/core/assets/bugx-hero-zh.svg +74 -0
- package/core/assets/bugx-social-preview.svg +71 -0
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/assets/codex.png +0 -0
- package/core/assets/dsh.png +0 -0
- package/core/assets/webui-chatgpt.jpg +0 -0
- package/core/assets/webui-session.jpg +0 -0
- package/core/assets/webui-skills.jpg +0 -0
- package/core/assets/webui-studio.jpg +0 -0
- package/core/assets/webui-zcode.jpg +0 -0
- package/core/assets/zcode.png +0 -0
- package/core/audit_packs/README.md +2 -0
- package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
- package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
- package/core/audit_packs/pitfalls/go_backend.json +66 -0
- package/core/audit_packs/pitfalls/java_spring.json +64 -0
- package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
- package/core/audit_packs/pitfalls/python_web.json +82 -0
- package/core/autonomous_cve/SPEC.md +1 -1
- package/core/autonomous_cve/attack_graph_store.py +152 -106
- package/core/autonomous_cve/behavior_graph.py +8 -2
- package/core/autonomous_cve/verifier.py +4 -1
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +43 -8
- package/core/cli-help.txt +66 -0
- package/core/cloud_sync/SPEC.md +1 -1
- package/core/cloud_sync/cloud_client.py +81 -11
- package/core/cloud_sync/cloud_onboard.py +42 -1
- package/core/cloud_sync/consent.py +33 -3
- package/core/cloud_sync/flywheel_client.py +186 -15
- package/core/cloud_sync/network_transport.py +24 -3
- package/core/cloud_sync/sensitive_filter.py +2 -2
- package/core/cloud_sync/sync_push.py +12 -10
- package/core/contracts/AGENT_GUIDE.md +6 -9
- package/core/contracts/README.md +2 -2
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/contracts/engine_gap_contracts.py +86 -3
- package/core/coverage/coverage_discovery.py +599 -29
- package/core/coverage/coverage_evidence.py +47 -0
- package/core/coverage/coverage_forensics.py +9 -0
- package/core/coverage/coverage_validate.py +6 -1
- package/core/dev_harness/SPEC.md +1 -1
- package/core/engine-integrity.json +670 -442
- package/core/fuzzing/concurrency_fuzzer.py +53 -0
- package/core/fuzzing/differential_oracle.py +562 -27
- package/core/fuzzing/fuzz_input.py +109 -6
- package/core/fuzzing/stateful_fuzzer.py +72 -0
- package/core/governance/secret_redactor.py +22 -10
- package/core/host_acp/SPEC.md +1 -1
- package/core/host_acp/__init__.py +4 -4
- package/core/host_acp/claude.py +59 -1
- package/core/host_acp/cline.py +64 -1
- package/core/host_acp/codex.py +56 -1
- package/core/host_acp/dsh.py +59 -1
- package/core/host_acp/opencode.py +56 -1
- package/core/host_acp/pi.py +59 -1
- package/core/host_acp/zcode.py +59 -1
- package/core/host_runtime/SPEC.md +1 -1
- package/core/host_runtime/adapters.py +1 -1
- package/core/host_runtime/cline.py +13 -0
- package/core/host_runtime/host_evaluators.py +44 -4
- package/core/host_runtime/host_probe.py +1 -1
- package/core/host_runtime/host_provider_arbitrator.py +116 -62
- package/core/host_runtime/host_registry.py +15 -8
- package/core/host_runtime/mcp_registry_gate.py +12 -1
- package/core/host_runtime/pi.py +102 -0
- package/core/host_runtime/provider_facts.py +66 -0
- package/core/hosts/SPEC.md +1 -1
- package/core/hosts/__init__.py +6 -2
- package/core/hosts/_dsh_usage.py +1 -1
- package/core/hosts/base.py +32 -4
- package/core/hosts/claude.py +55 -0
- package/core/hosts/cline.py +6 -2
- package/core/hosts/codex.py +58 -0
- package/core/hosts/dsh.py +9 -1
- package/core/hosts/opencode.py +6 -6
- package/core/hosts/pi.py +159 -2
- package/core/infra/README.md +4 -2
- package/core/infra/__init__.py +2 -0
- package/core/infra/build_info.py +22 -3
- package/core/infra/client_metadata.py +1 -1
- package/core/infra/json_utils.py +22 -0
- package/core/launch_phases/README.md +6 -3
- package/core/launch_phases/SPEC.md +1 -1
- package/core/launch_phases/common.py +21 -2
- package/core/launch_phases/finding_confirm_phase.py +170 -5
- package/core/launch_phases/finding_settlement.py +188 -1
- package/core/launch_phases/judge_phase.py +69 -12
- package/core/launch_phases/orchestrator_controls.py +11 -7
- package/core/launch_phases/post_coverage_sync.py +9 -2
- package/core/launch_phases/post_phase.py +144 -8
- package/core/launch_phases/post_receipt.py +12 -1
- package/core/launch_phases/pre_phase.py +3 -3
- package/core/launch_phases/pre_recon_scout.py +66 -36
- package/core/launch_phases/pre_state_builder.py +23 -176
- package/core/launch_phases/report_sharing.py +3 -7
- package/core/launch_phases/round_orchestrator.py +129 -58
- package/core/launch_phases/semantic_recon.py +545 -0
- package/core/launch_phases/session_runtime.py +56 -9
- package/core/launch_phases/startup_gates.py +36 -8
- package/core/launch_phases/startup_interaction.py +68 -12
- package/core/launch_phases/startup_version_gate.py +13 -3
- package/core/launch_phases/supervisor_bridge.py +46 -17
- package/core/launch_phases/supervisor_coverage.py +8 -2
- package/core/launch_phases/supervisor_degraded.py +1 -9
- package/core/launch_phases/verify_loop.py +767 -0
- package/core/launch_phases/worker_barriers.py +15 -5
- package/core/launch_phases/worker_orchestrator.py +105 -25
- package/core/launch_phases/worker_prior.py +115 -0
- package/core/ledger/README.md +2 -1
- package/core/ledger/SPEC.md +1 -1
- package/core/ledger/_facade.py +2 -1
- package/core/ledger/archive_ops.py +60 -2
- package/core/ledger/cli.py +6 -1
- package/core/ledger/export_ops.py +6 -1
- package/core/ledger/finding_confirmation.py +48 -6
- package/core/ledger/finding_lifecycle.py +428 -5
- package/core/ledger/finding_verification.py +555 -10
- package/core/ledger/fp_ledger.py +255 -0
- package/core/ledger/incidents.py +10 -4
- package/core/ledger/patterns.py +10 -7
- package/core/ledger/receipt_contract.py +17 -1
- package/core/ledger/sync_ops.py +21 -16
- package/core/ledger/tool_experience.py +2 -1
- package/core/ledger/verify_life.py +88 -17
- package/core/locales/en-US.json +2 -2
- package/core/locales/zh-CN.json +2 -2
- package/core/mcp_handlers/SPEC.md +1 -1
- package/core/mcp_handlers/base.py +23 -3
- package/core/mcp_handlers/channel_lifecycle.py +85 -30
- package/core/mcp_handlers/retrieval_handlers.py +11 -1
- package/core/mcp_handlers/rpc_server.py +6 -1
- package/core/mcp_handlers/supervisor_handlers.py +32 -6
- package/core/mcp_handlers/tool_table.py +15 -0
- package/core/mcp_runtime_support/environment.py +0 -38
- package/core/mcp_runtime_support/verifier.py +0 -52
- package/core/metadata.txt +2 -3
- package/core/planning/README.md +2 -1
- package/core/planning/domain_router.py +4 -2
- package/core/planning/dynamic_flow_analyzer.py +219 -14
- package/core/planning/judge_pipeline.py +87 -4
- package/core/planning/prompt_harness.py +57 -15
- package/core/planning/prompt_policy_engine.py +386 -0
- package/core/planning/spec_harvester.py +4 -4
- package/core/probes/INTERFACE.md +11 -1
- package/core/probes/SPEC.md +11 -1
- package/core/probes/__init__.py +46 -40
- package/core/probes/android_probe.py +177 -9
- package/core/probes/codebase_memory_probe.py +57 -0
- package/core/probes/desktop_probe.py +104 -0
- package/core/probes/differential_probe.py +99 -21
- package/core/probes/efficiency_probe.py +64 -0
- package/core/probes/ios_binary_probe.py +105 -1
- package/core/probes/memory_probe.py +66 -0
- package/core/probes/miniprogram_probe.py +75 -13
- package/core/probes/mobile_probe.py +215 -30
- package/core/probes/native_probe.py +88 -0
- package/core/probes/openwiki_probe.py +70 -0
- package/core/probes/pattern_probe.py +106 -0
- package/core/probes/platform_probe.py +81 -0
- package/core/probes/probe_registry.py +108 -7
- package/core/probes/sast_fixture_corpus.py +340 -0
- package/core/probes/sast_probe.py +553 -52
- package/core/probes/sast_rules.py +668 -28
- package/core/probes/sca_scanner.py +48 -0
- package/core/probes/ui_accessibility.py +149 -0
- package/core/probes/ui_audit.py +513 -0
- package/core/probes/ui_contract.py +273 -0
- package/core/probes/ui_evidence.py +212 -0
- package/core/probes/ui_measurements.py +314 -0
- package/core/probes/ui_repair.py +250 -0
- package/core/probes/ui_review.py +133 -0
- package/core/probes/ui_storybook.py +107 -0
- package/core/probes/ui_tokens.py +185 -0
- package/core/probes/ui_visual_diff.py +131 -0
- package/core/probes/web_probe.py +373 -18
- package/core/project_profiler/SPEC.md +1 -1
- package/core/project_profiler/arbitrator.py +6 -1
- package/core/project_profiler/detector.py +8 -1
- package/core/project_profiler/strategy.py +51 -15
- package/core/prompts/README.md +4 -2
- package/core/prompts/command_routing_en.md +2 -2
- package/core/prompts/command_routing_zh.md +2 -2
- package/core/prompts/policies/prompt_policies.json +101 -0
- package/core/prompts/stages/stage_repair.md +1 -1
- package/core/prompts/stages/stage_verify.defensive.md +42 -0
- package/core/prompts/stages/stage_verify.md +44 -0
- package/core/repair/README.md +1 -1
- package/core/repair/l7_repair_loop.py +1 -4
- package/core/repair/rsi_fixer.py +4 -4
- package/core/repair/rsi_loop.py +1 -3
- package/core/repair/rsi_repair.py +7 -7
- package/core/repair/rsi_scope.py +27 -8
- package/core/report_engine/SPEC.md +1 -1
- package/core/report_engine/attestation.py +8 -4
- package/core/report_engine/finding_report.py +2 -1
- package/core/report_engine/models.py +7 -9
- package/core/report_engine/report_share.py +0 -8
- package/core/report_engine/sast_bridge.py +2 -2
- package/core/report_engine/server.py +18 -8
- package/core/report_engine/web-conformance.md +123 -18
- package/core/report_engine/web_conformance.py +21 -52
- package/core/retrieval/README.md +2 -1
- package/core/retrieval/SPEC.md +1 -1
- package/core/retrieval/code_analyzer.py +50 -14
- package/core/retrieval/context_assembler.py +7 -1
- package/core/retrieval/knowledge_sync.py +108 -14
- package/core/retrieval/pitfall_packs.py +277 -0
- package/core/retrieval/symbol_index.py +25 -6
- package/core/retrieval/universal_code_matcher.py +234 -49
- package/core/runtime/README.md +1 -1
- package/core/runtime/bugx_logging.py +78 -7
- package/core/runtime/fixture_solidify.py +5 -10
- package/core/runtime/global_telemetry.py +20 -0
- package/core/runtime/incident_eval.py +1 -1
- package/core/runtime/model_runner.py +4 -41
- package/core/runtime/platform_adapter.py +2 -2
- package/core/runtime/prep_validate.py +4 -2
- package/core/runtime/project_settings.py +2 -1
- package/core/runtime/scenario_eval.py +50 -8
- package/core/skills/bugx_docs_mcp_server.py +3 -1
- package/core/skills/bugx_mcp_server.py +29 -2
- package/core/skills/tools_kb.py +1 -1
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/SPEC.md +1 -1
- package/core/supervisor/budget_governor.py +503 -9
- package/core/supervisor/checkpoint_pipeline.py +248 -6
- package/core/supervisor/checkpoint_sync.py +13 -0
- package/core/supervisor/claim_events.py +1 -1
- package/core/supervisor/finding_workflow.py +22 -5
- package/core/supervisor/lease_manager.py +1 -1
- package/core/supervisor/lifecycle_blocks.py +6 -1
- package/core/supervisor/rejection_remedies.py +52 -5
- package/core/supervisor/serial_authorization.py +48 -4
- package/core/supervisor/task_scheduler.py +2 -2
- package/core/supervisor/worker_checkpoint.py +8 -1
- package/core/supervisor/worker_runtime.py +8 -2
- package/core/supervisor_types/worker_claim.py +9 -0
- package/core/webui/README.md +1 -1
- package/core/webui/SPEC.md +2 -1
- package/core/webui/adapters/claude.py +5 -1
- package/core/webui/adapters/cline.py +10 -2
- package/core/webui/adapters/codex.py +5 -1
- package/core/webui/adapters/dsh.py +5 -1
- package/core/webui/docs_session_service.py +2 -2
- package/core/webui/mcp_inspector.py +11 -7
- package/core/webui/static/00-base.css +1060 -0
- package/core/webui/static/01-monitoring.css +802 -0
- package/core/webui/static/02-header-actions.css +321 -0
- package/core/webui/static/03-trigger-popover.css +697 -0
- package/core/webui/static/04-composer.css +628 -0
- package/core/webui/static/05-skills-center.css +878 -0
- package/core/webui/static/06-mcp-center.css +623 -0
- package/core/webui/static/07-skill-detail.css +265 -0
- package/core/webui/static/08-files-management.css +167 -0
- package/core/webui/static/09-files-center.css +386 -0
- package/core/webui/static/10-icons.css +105 -0
- package/core/webui/static/11-project-options.css +185 -0
- package/core/webui/static/12-profile-tab.css +383 -0
- package/core/webui/static/design-tokens.css +113 -0
- package/core/webui/static/index.html +14 -1
- package/core/webui/workspace_service.py +1 -1
- package/docs/07_distribution/01_README_NPM.md +193 -185
- package/ecosystem/integrations/README.md +1 -1
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
- package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
- package/ecosystem/integrations/opencode/opencode.json +23 -12
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
- package/interfaces/bin/bugx.js +37 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -2
- package/interfaces/cli/bugx_cli/cli.py +172 -69
- package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
- package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
- package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
- package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
- package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
- package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
- package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
- package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
- package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
- package/interfaces/cli/bugx_cli/commands/project.py +6 -13
- package/interfaces/cli/bugx_cli/commands/report.py +2 -6
- package/interfaces/cli/bugx_cli/commands/system.py +524 -169
- package/interfaces/cli/bugx_cli/common.py +21 -15
- package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
- package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
- package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
- package/interfaces/cli/bugx_cli/infra/security.py +13 -6
- package/package.json +30 -15
- package/pyproject.toml +60 -9
- package/scripts/ensure-python.mjs +7 -7
- package/scripts/sync-version.mjs +10 -21
- package/scripts/test-npm-wrapper.mjs +1 -1
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/webui/static/project-settings.css +0 -6458
- package/docs/07_distribution/README.md +0 -16
- package/docs/README.md +0 -121
- package/interfaces/README.md +0 -143
- package/interfaces/bin/README.md +0 -35
- package/interfaces/cli/README.md +0 -90
- package/scripts/README.md +0 -118
|
@@ -6,7 +6,9 @@ SAST 层定位:
|
|
|
6
6
|
2. 零外部依赖多语言支持:内置通用结构化分词与括号平衡树引擎,
|
|
7
7
|
原生覆盖 Go、Java、TypeScript/JavaScript、Rust、C/C++、Python、PHP 等主流语言;
|
|
8
8
|
3. 供应链安全 (SCA):内置轻量离线依赖漏洞匹配器 (pom.xml/package.json/go.mod/requirements.txt/Cargo.lock);
|
|
9
|
-
4. 企业级工程治理:支持跨语言行级抑制 (// bugx-ignore)
|
|
9
|
+
4. 企业级工程治理:支持跨语言行级抑制 (// bugx-ignore)、项目级路径忽略
|
|
10
|
+
(根目录 ``.bugxignore``,gitignore 子集)、基线快照 (--baseline) 与
|
|
11
|
+
OASIS SARIF v2.1.0 标准导出;
|
|
10
12
|
5. 非侵入容灾原则:严禁强制外部工具安装,无外部工具时 100% 自动无缝降级至内置多语言引擎。
|
|
11
13
|
"""
|
|
12
14
|
|
|
@@ -50,7 +52,13 @@ from core.probes.sca_scanner import SCAScanner
|
|
|
50
52
|
from core.planning.dynamic_flow_analyzer import DynamicFlowAnalyzer
|
|
51
53
|
|
|
52
54
|
from core.runtime.tool_install_targets import OPTIONAL_TOOL_PACKAGE_SPECS
|
|
53
|
-
from core.retrieval.universal_code_matcher import
|
|
55
|
+
from core.retrieval.universal_code_matcher import (
|
|
56
|
+
EXT_TO_LANG,
|
|
57
|
+
ParsedSource,
|
|
58
|
+
UniversalCodeMatcher,
|
|
59
|
+
extract_suppressions,
|
|
60
|
+
is_suppressed,
|
|
61
|
+
)
|
|
54
62
|
|
|
55
63
|
VALIDATED = {
|
|
56
64
|
"semgrep": "1.80.0",
|
|
@@ -74,21 +82,236 @@ SKIP_DIRS = {
|
|
|
74
82
|
"vendor", "Pods", ".gradle", ".idea",
|
|
75
83
|
}
|
|
76
84
|
|
|
85
|
+
#: 项目级忽略文件名(放在项目根,gitignore 语法)。
|
|
86
|
+
#: ``SKIP_DIRS`` 只能排除固定的**目录名**,排不掉「本仓里这段路径是靶场/夹具」
|
|
87
|
+
#: 这种 per-project 事实:``verification/sandboxes`` 下故意留洞的 CVE 修复
|
|
88
|
+
#: 样例被当产品代码扫出 20 条 finding,只能靠用户配置的路径模式排除。
|
|
89
|
+
IGNORE_FILE_NAME = ".bugxignore"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _ignore_glob_to_regex(pattern: str) -> str:
|
|
93
|
+
"""把 gitignore 风格的 glob 译成正则体(不含首尾锚点)。
|
|
94
|
+
|
|
95
|
+
支持 ``*``(不跨 ``/``)、``**``(跨层级)、``?``、``[abc]`` / ``[!abc]``
|
|
96
|
+
与 ``\\`` 转义;不支持 ``{a,b}`` 花括号展开(正则里会被当字面量)。
|
|
97
|
+
"""
|
|
98
|
+
out: list[str] = []
|
|
99
|
+
index = 0
|
|
100
|
+
length = len(pattern)
|
|
101
|
+
while index < length:
|
|
102
|
+
char = pattern[index]
|
|
103
|
+
if char == "*":
|
|
104
|
+
end = index
|
|
105
|
+
while end < length and pattern[end] == "*":
|
|
106
|
+
end += 1
|
|
107
|
+
if end - index >= 2 and end < length and pattern[end] == "/":
|
|
108
|
+
out.append("(?:.*/)?") # ``**/``:跨任意层级目录
|
|
109
|
+
index = end + 1
|
|
110
|
+
elif end - index >= 2:
|
|
111
|
+
out.append(".*")
|
|
112
|
+
index = end
|
|
113
|
+
else:
|
|
114
|
+
out.append("[^/]*")
|
|
115
|
+
index = end
|
|
116
|
+
elif char == "?":
|
|
117
|
+
out.append("[^/]")
|
|
118
|
+
index += 1
|
|
119
|
+
elif char == "[":
|
|
120
|
+
close = pattern.find("]", index + 1)
|
|
121
|
+
if close == -1:
|
|
122
|
+
out.append(re.escape(char))
|
|
123
|
+
index += 1
|
|
124
|
+
else:
|
|
125
|
+
inner = pattern[index + 1:close]
|
|
126
|
+
if inner.startswith("!"):
|
|
127
|
+
inner = "^" + inner[1:]
|
|
128
|
+
out.append(f"[{inner}]")
|
|
129
|
+
index = close + 1
|
|
130
|
+
elif char == "\\" and index + 1 < length:
|
|
131
|
+
out.append(re.escape(pattern[index + 1]))
|
|
132
|
+
index += 2
|
|
133
|
+
else:
|
|
134
|
+
out.append(re.escape(char))
|
|
135
|
+
index += 1
|
|
136
|
+
return "".join(out)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class PathIgnoreSpec:
|
|
140
|
+
"""某个项目根下 ``.bugxignore`` 解析出的忽略规格。
|
|
141
|
+
|
|
142
|
+
刻意**不做模块级缓存**:本探针可能在同一进程里被多次以不同 ``--root``
|
|
143
|
+
调用,进程级缓存会让 A 项目的模式串到 B 项目。规格由 ``load()`` 读一次,
|
|
144
|
+
调用方(``run_scan``)持有并在整轮扫描内复用;「重新加载」的时机就是
|
|
145
|
+
「下一次 ``run_scan(root)``」,与 ``SKIP_DIRS`` 这类进程级常量解耦。
|
|
146
|
+
|
|
147
|
+
语义是 gitignore 的子集:按行序取**最后一条命中**,``!`` 取反;不带
|
|
148
|
+
``/`` 的模式匹配任意层级的同名节点,带 ``/`` 的模式锚定项目根;命中
|
|
149
|
+
某个目录时其下所有文件一并忽略。与 git 的差异:``!`` 可以直接把被忽略
|
|
150
|
+
目录内的文件重新纳入(git 要求先解除父目录忽略)。
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
def __init__(
|
|
154
|
+
self,
|
|
155
|
+
root: Path,
|
|
156
|
+
rules: tuple[tuple[bool, re.Pattern[str]], ...],
|
|
157
|
+
patterns: tuple[str, ...],
|
|
158
|
+
) -> None:
|
|
159
|
+
self.root = root
|
|
160
|
+
self._rules = rules
|
|
161
|
+
self.patterns = patterns
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def load(cls, root: Path) -> "PathIgnoreSpec":
|
|
165
|
+
root = root.resolve()
|
|
166
|
+
rules: list[tuple[bool, re.Pattern[str]]] = []
|
|
167
|
+
patterns: list[str] = []
|
|
168
|
+
try:
|
|
169
|
+
text = (root / IGNORE_FILE_NAME).read_text(encoding="utf-8", errors="replace")
|
|
170
|
+
except OSError:
|
|
171
|
+
return cls(root, (), ())
|
|
172
|
+
for raw in text.splitlines():
|
|
173
|
+
line = raw.strip()
|
|
174
|
+
if not line or line.startswith("#"):
|
|
175
|
+
continue
|
|
176
|
+
negated = line.startswith("!")
|
|
177
|
+
body = line[1:].strip() if negated else line
|
|
178
|
+
if body.endswith("/"):
|
|
179
|
+
body = body.rstrip("/")
|
|
180
|
+
anchored = body.startswith("/") or "/" in body
|
|
181
|
+
body = body.lstrip("/")
|
|
182
|
+
if not body:
|
|
183
|
+
continue
|
|
184
|
+
prefix = "" if anchored else "(?:.*/)?"
|
|
185
|
+
try:
|
|
186
|
+
regex = re.compile(f"^{prefix}{_ignore_glob_to_regex(body)}$")
|
|
187
|
+
except re.error:
|
|
188
|
+
continue
|
|
189
|
+
rules.append((negated, regex))
|
|
190
|
+
patterns.append(line)
|
|
191
|
+
return cls(root, tuple(rules), tuple(patterns))
|
|
192
|
+
|
|
193
|
+
def matches(self, relative: str | Path) -> bool:
|
|
194
|
+
"""``relative`` 为相对项目根的路径;命中任一祖先目录同样算忽略。"""
|
|
195
|
+
if not self._rules:
|
|
196
|
+
return False
|
|
197
|
+
rel = str(relative).replace("\\", "/").strip("/")
|
|
198
|
+
if not rel:
|
|
199
|
+
return False
|
|
200
|
+
parts = rel.split("/")
|
|
201
|
+
candidates = [rel]
|
|
202
|
+
for depth in range(1, len(parts)):
|
|
203
|
+
candidates.append("/".join(parts[:depth]))
|
|
204
|
+
ignored = False
|
|
205
|
+
for negated, regex in self._rules:
|
|
206
|
+
if any(regex.match(candidate) for candidate in candidates):
|
|
207
|
+
ignored = not negated
|
|
208
|
+
return ignored
|
|
209
|
+
|
|
210
|
+
def literal_excludes(self) -> tuple[str, ...]:
|
|
211
|
+
"""可下发给外部工具的**字面量**前缀:含通配的规则无法安全翻译,跳过。"""
|
|
212
|
+
literals: list[str] = []
|
|
213
|
+
for pattern in self.patterns:
|
|
214
|
+
if pattern.startswith("!"):
|
|
215
|
+
continue
|
|
216
|
+
if any(char in pattern for char in "*?["):
|
|
217
|
+
continue
|
|
218
|
+
literals.append(pattern.strip("/"))
|
|
219
|
+
return tuple(literals)
|
|
220
|
+
|
|
221
|
+
def describe(self) -> dict[str, Any]:
|
|
222
|
+
return {
|
|
223
|
+
"file": str(self.root / IGNORE_FILE_NAME),
|
|
224
|
+
"patterns": list(self.patterns),
|
|
225
|
+
}
|
|
77
226
|
|
|
78
|
-
def _skipped(relative: Path) -> bool:
|
|
79
|
-
"""SAST 也要排除引擎/宿主的 ``.bugx*`` 运行态命名空间。
|
|
80
227
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
228
|
+
def _skipped(relative: Path, ignore: PathIgnoreSpec | None = None) -> bool:
|
|
229
|
+
"""枚举期跳过判定:内置目录白名单 + 引擎命名空间 + 项目级忽略。
|
|
230
|
+
|
|
231
|
+
SAST 也要排除引擎/宿主的 ``.bugx*`` 运行态命名空间:此前只按 ``SKIP_DIRS``
|
|
232
|
+
的字面名排除 ``.bugx``,``.bugx-audit-artifacts`` 这类兄弟目录会被当源码
|
|
233
|
+
扫描——实测靶场里宿主写的 ``repro.py`` 就产生了两条
|
|
234
|
+
``SEC-006-SILENT-EXCEPTION``,被报告当成被测产品的缺陷。判定与覆盖枚举
|
|
235
|
+
同源(``core.retrieval.symbol_index``),避免两份名单漂移。
|
|
236
|
+
|
|
237
|
+
``ignore`` 是**按 root 加载**的 ``PathIgnoreSpec``(``None`` = 只有内置规则)。
|
|
238
|
+
三条判定串成一条链:用户模式不再另起一条过滤通道,避免「枚举跳过」与
|
|
239
|
+
「事后过滤」两处口径漂移。
|
|
85
240
|
"""
|
|
86
|
-
from core.retrieval.symbol_index import
|
|
241
|
+
from core.retrieval.symbol_index import is_engine_namespace_segment
|
|
87
242
|
|
|
88
|
-
|
|
89
|
-
part in SKIP_DIRS or
|
|
243
|
+
if any(
|
|
244
|
+
part in SKIP_DIRS or is_engine_namespace_segment(part)
|
|
90
245
|
for part in relative.parts
|
|
91
|
-
)
|
|
246
|
+
):
|
|
247
|
+
return True
|
|
248
|
+
return ignore is not None and ignore.matches(relative)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
#: 逐文件扫描失败的分类(F-207)。``syntax_error``/``parse_error`` 属解析失败,
|
|
252
|
+
#: ``unreadable``/``scanner_error`` 属读取或扫描期失败;两者都必须带 file+reason
|
|
253
|
+
#: 出现在 ``run_scan`` 的 ``skipped_files`` 里,不能与「文件无缺陷」同形。
|
|
254
|
+
_PARSE_FAILURE_REASONS = frozenset({"syntax_error", "parse_error"})
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _skip_reason(exc: BaseException) -> str:
|
|
258
|
+
if isinstance(exc, SyntaxError):
|
|
259
|
+
return "syntax_error"
|
|
260
|
+
if isinstance(exc, ValueError):
|
|
261
|
+
return "parse_error"
|
|
262
|
+
if isinstance(exc, OSError):
|
|
263
|
+
return "unreadable"
|
|
264
|
+
return "scanner_error"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _record_skip(
|
|
268
|
+
stats: dict[str, Any] | None, *, rel: str, stage: str, exc: BaseException,
|
|
269
|
+
) -> dict[str, Any]:
|
|
270
|
+
"""把一次逐文件跳过折成结构化记录并挂到 ``stats["skipped_files"]``。
|
|
271
|
+
|
|
272
|
+
聚合层(``run_scan``)据此输出 ``parse_errors``/``skipped_files``;没有它,
|
|
273
|
+
解析失败的文件只会让 ``scanned_files`` 少一,报告层无法区分「漏扫」与
|
|
274
|
+
「按规则排除」(F-207)。
|
|
275
|
+
"""
|
|
276
|
+
reason = _skip_reason(exc)
|
|
277
|
+
if isinstance(exc, SyntaxError):
|
|
278
|
+
line = int(exc.lineno or 0)
|
|
279
|
+
col = int(exc.offset or 0)
|
|
280
|
+
detail = exc.msg or ""
|
|
281
|
+
else:
|
|
282
|
+
line = 0
|
|
283
|
+
col = 0
|
|
284
|
+
detail = str(exc)
|
|
285
|
+
record = {
|
|
286
|
+
"skipped": True,
|
|
287
|
+
"reason": reason,
|
|
288
|
+
"stage": stage,
|
|
289
|
+
"file": rel,
|
|
290
|
+
"line": line,
|
|
291
|
+
"col": col,
|
|
292
|
+
"detail": detail,
|
|
293
|
+
}
|
|
294
|
+
if stats is not None:
|
|
295
|
+
stats.setdefault("skipped_files", []).append(record)
|
|
296
|
+
return record
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _merge_skipped(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
300
|
+
"""按 (file, reason) 去重并稳定排序逐文件跳过记录。
|
|
301
|
+
|
|
302
|
+
Python 源码会经过 AST 与多语言两条枚举路径,同一份解析失败会被两边各记
|
|
303
|
+
一次;去重后 ``parse_errors`` 才是「文件数」而不是「路径数」。
|
|
304
|
+
"""
|
|
305
|
+
seen: set[tuple[str, str]] = set()
|
|
306
|
+
merged: list[dict[str, Any]] = []
|
|
307
|
+
for item in records:
|
|
308
|
+
key = (str(item.get("file")), str(item.get("reason")))
|
|
309
|
+
if key in seen:
|
|
310
|
+
continue
|
|
311
|
+
seen.add(key)
|
|
312
|
+
merged.append(item)
|
|
313
|
+
merged.sort(key=lambda item: (str(item.get("file")), str(item.get("reason"))))
|
|
314
|
+
return merged
|
|
92
315
|
|
|
93
316
|
|
|
94
317
|
def _probe_environment() -> dict[str, str]:
|
|
@@ -229,6 +452,14 @@ def check_tool(name: str) -> dict:
|
|
|
229
452
|
return _command((name,), name)
|
|
230
453
|
|
|
231
454
|
|
|
455
|
+
#: 通道状态探针声明(AM-6 差距修复):``check``/``status`` 只探测外部工具链
|
|
456
|
+
#: 在场性(findings 恒空),与 mobile/ios_binary 的 ``check``(产出 findings)
|
|
457
|
+
#: 语义不同。显式输出声明行,避免调用方把「通道就绪」误读成「扫过没问题」。
|
|
458
|
+
CHANNEL_STATUS_NOTE = (
|
|
459
|
+
"channel-status only; run 'bugx probe sast scan' for findings"
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
|
|
232
463
|
def inspect(root: Path) -> dict:
|
|
233
464
|
root = root.resolve()
|
|
234
465
|
base = [
|
|
@@ -243,6 +474,8 @@ def inspect(root: Path) -> dict:
|
|
|
243
474
|
"required": False,
|
|
244
475
|
"recommended": True,
|
|
245
476
|
"root": str(root),
|
|
477
|
+
"probe_kind": "channel_status",
|
|
478
|
+
"semantic_note": CHANNEL_STATUS_NOTE,
|
|
246
479
|
"base_tools": base,
|
|
247
480
|
"install": {
|
|
248
481
|
"semgrep": f"pipx install {OPTIONAL_TOOL_PACKAGE_SPECS['semgrep']}",
|
|
@@ -260,6 +493,9 @@ def print_report(report: dict, as_json: bool = False) -> None:
|
|
|
260
493
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
261
494
|
return
|
|
262
495
|
print(f"[{report['status']}] SAST 静态分析工具链(推荐,非硬依赖,支持多语言自动降级)")
|
|
496
|
+
# 通道状态探针声明:check/status 不产出 findings,「READY」只代表工具链
|
|
497
|
+
# 就绪,绝不代表「扫过没问题」;实际扫描必须走 scan 子命令。
|
|
498
|
+
print(f" · 通道状态探针({CHANNEL_STATUS_NOTE})——findings 恒空,非漏洞扫描结果")
|
|
263
499
|
for item in report["base_tools"]:
|
|
264
500
|
print(f" {'✓' if item['ok'] else '!'} {item['name']}: {item['detail']}")
|
|
265
501
|
if report["status"] != "READY":
|
|
@@ -273,8 +509,6 @@ _SECRET_PLACEHOLDER_HINTS = (
|
|
|
273
509
|
"your_", "xxxxx", "todo", "fixme", "fake",
|
|
274
510
|
)
|
|
275
511
|
_SECRET_CHAR_CLASSES = (r"[a-z]", r"[A-Z]", r"\d", r"[^A-Za-z0-9]")
|
|
276
|
-
#: 行级抑制注释,语义与多语言引擎的 ``// bugx-ignore`` / ``# nosec`` 保持一致。
|
|
277
|
-
_SUPPRESSION_RE = re.compile(r"(?:#|//)\s*(?:bugx-ignore(?::[^\n]*)?|nosec\b)", re.IGNORECASE)
|
|
278
512
|
|
|
279
513
|
|
|
280
514
|
def _shannon_entropy(value: str) -> float:
|
|
@@ -329,10 +563,6 @@ class BuiltinAstScanner(ast.NodeVisitor):
|
|
|
329
563
|
return self.source_lines[lineno - 1].strip()
|
|
330
564
|
return ""
|
|
331
565
|
|
|
332
|
-
def _is_suppressed(self, lineno: int) -> bool:
|
|
333
|
-
"""行级抑制:``# bugx-ignore`` / ``# nosec``(与多语言引擎语义一致)。"""
|
|
334
|
-
return bool(_SUPPRESSION_RE.search(self._get_snippet(lineno)))
|
|
335
|
-
|
|
336
566
|
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
|
|
337
567
|
self.var_env.update(self.dynamic_analyzer.fold_python_function_scope(node))
|
|
338
568
|
self.generic_visit(node)
|
|
@@ -523,7 +753,8 @@ class BuiltinAstScanner(ast.NodeVisitor):
|
|
|
523
753
|
if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
|
|
524
754
|
val = node.value.value
|
|
525
755
|
# QUA-08:变量名匹配只是必要条件;值本身还必须像机密。
|
|
526
|
-
|
|
756
|
+
# 行级抑制不在这里判——``scan_source_ast`` 汇合点统一按规则名过滤。
|
|
757
|
+
if _looks_like_hardcoded_secret(val):
|
|
527
758
|
self.findings.append({
|
|
528
759
|
"rule_id": "SEC-004-HARDCODED-SECRET",
|
|
529
760
|
"name": "Hardcoded Secret",
|
|
@@ -542,12 +773,19 @@ class BuiltinAstScanner(ast.NodeVisitor):
|
|
|
542
773
|
|
|
543
774
|
|
|
544
775
|
def scan_source_ast(
|
|
545
|
-
root: Path, max_files: int = 1000, stats: dict[str,
|
|
776
|
+
root: Path, max_files: int = 1000, stats: dict[str, Any] | None = None,
|
|
777
|
+
ignore: PathIgnoreSpec | None = None,
|
|
546
778
|
) -> list[dict[str, Any]]:
|
|
547
779
|
"""扫描 Python 源码(BuiltinAstScanner,保持向前兼容)。
|
|
548
780
|
|
|
549
|
-
``stats`` 若给出,会填入 ``files
|
|
550
|
-
|
|
781
|
+
``stats`` 若给出,会填入 ``files``(成功解析的文件数)与 ``skipped_files``
|
|
782
|
+
(逐文件跳过记录:``reason`` 区分 ``syntax_error``/``unreadable`` 等)。
|
|
783
|
+
报告层需要这两个数字才能说清覆盖范围:只有 ``files`` 时,解析失败的文件
|
|
784
|
+
与「扫描范围外」在证据上无法区分(F-207)。
|
|
785
|
+
|
|
786
|
+
行级抑制**不在这里**判:抑制统一在 ``run_scan`` 的去重之后执行(见
|
|
787
|
+
``_apply_suppressions``)。若在收集期就吃掉命中,跨规则去重会把同源的另一
|
|
788
|
+
条规则顶上来,用户抑制掉一条、报告里换个规则名继续报。
|
|
551
789
|
"""
|
|
552
790
|
findings: list[dict[str, Any]] = []
|
|
553
791
|
scanned = 0
|
|
@@ -560,35 +798,40 @@ def scan_source_ast(
|
|
|
560
798
|
rel = path.relative_to(root).as_posix()
|
|
561
799
|
except ValueError:
|
|
562
800
|
rel = str(path)
|
|
563
|
-
if _skipped(Path(rel)):
|
|
801
|
+
if _skipped(Path(rel), ignore):
|
|
564
802
|
continue
|
|
565
803
|
try:
|
|
566
804
|
content = path.read_text(encoding="utf-8", errors="replace")
|
|
567
805
|
source_lines = content.splitlines()
|
|
568
806
|
tree = ast.parse(content, filename=str(path))
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
findings.extend(scanner.findings)
|
|
572
|
-
scanned += 1
|
|
573
|
-
except (SyntaxError, OSError):
|
|
807
|
+
except (SyntaxError, OSError) as exc:
|
|
808
|
+
_record_skip(stats, rel=rel, stage="builtin_ast", exc=exc)
|
|
574
809
|
continue
|
|
810
|
+
scanner = BuiltinAstScanner(path, rel, source_lines)
|
|
811
|
+
scanner.visit(tree)
|
|
812
|
+
findings.extend(scanner.findings)
|
|
813
|
+
scanned += 1
|
|
575
814
|
if stats is not None:
|
|
576
815
|
stats["files"] = stats.get("files", 0) + scanned
|
|
577
816
|
return findings
|
|
578
817
|
|
|
579
818
|
|
|
580
819
|
def scan_multilang_sources(
|
|
581
|
-
root: Path, max_files: int = 2000, stats: dict[str,
|
|
820
|
+
root: Path, max_files: int = 2000, stats: dict[str, Any] | None = None,
|
|
821
|
+
ignore: PathIgnoreSpec | None = None,
|
|
582
822
|
) -> list[dict[str, Any]]:
|
|
583
|
-
"""使用 UniversalCodeMatcher 与 SASTRuleMatcher
|
|
823
|
+
"""使用 UniversalCodeMatcher 与 SASTRuleMatcher 对多语言源码(含 Python)执行扫描。"""
|
|
584
824
|
matcher = SASTRuleMatcher(BUILTIN_RULES)
|
|
585
825
|
findings: list[dict[str, Any]] = []
|
|
586
826
|
scanned = 0
|
|
587
827
|
|
|
588
|
-
#
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
828
|
+
# 必须覆盖 Python:``BUILTIN_RULES`` 里有 10 条规则声明了 ``python`` 规格
|
|
829
|
+
# (SQLi / 反序列化 / 路径穿越 / SSRF / 弱加密 / 临时文件 / SSTI …),而
|
|
830
|
+
# ``BuiltinAstScanner`` 只覆盖命令注入、动态执行、硬编码凭据三类。早先这里
|
|
831
|
+
# 跳过 ``.py`` 让那 10 条规则的 Python 规格成了永不执行的死代码——靶场种子
|
|
832
|
+
# 「pathlib 拼接式路径穿越」因此完全漏检(F-RSI-20261110-010)。AST 扫描器
|
|
833
|
+
# 与规则引擎对同一处命令注入/eval 的重叠命中由 ``_dedupe_cross_tool`` 合并。
|
|
834
|
+
for ext in EXT_TO_LANG:
|
|
592
835
|
for path in root.rglob(f"*{ext}"):
|
|
593
836
|
if scanned >= max_files:
|
|
594
837
|
break
|
|
@@ -598,24 +841,39 @@ def scan_multilang_sources(
|
|
|
598
841
|
rel = path.relative_to(root).as_posix()
|
|
599
842
|
except ValueError:
|
|
600
843
|
rel = str(path)
|
|
601
|
-
if _skipped(Path(rel)):
|
|
844
|
+
if _skipped(Path(rel), ignore):
|
|
602
845
|
continue
|
|
603
846
|
|
|
604
847
|
try:
|
|
605
848
|
content = path.read_text(encoding="utf-8", errors="replace")
|
|
606
849
|
parsed = UniversalCodeMatcher.parse_file(path, rel_path=rel, content=content)
|
|
850
|
+
# 抑制不在收集期判:清空解析出的抑制表,统一交给 ``run_scan`` 在
|
|
851
|
+
# 去重之后过滤。否则 ``sast_rules`` 会先吃掉多语言命中,同源的
|
|
852
|
+
# AST 规则在去重时无从得知它被合并(``merged_rule_ids`` 为空),
|
|
853
|
+
# 用户按规则目录写 ``# bugx-ignore: SEC-CMD-001`` 就静默失效。
|
|
854
|
+
parsed.suppressions = {}
|
|
607
855
|
file_findings = matcher.match_file(parsed)
|
|
608
856
|
findings.extend(file_findings)
|
|
609
857
|
scanned += 1
|
|
610
|
-
except Exception:
|
|
858
|
+
except Exception as exc: # noqa: BLE001 - 结构化记录,不再静默 continue
|
|
859
|
+
# 逐文件失败不再裸 ``continue``:记录 file+reason 后由 ``run_scan``
|
|
860
|
+
# 汇总为 ``skipped_files``。单文件失败不中断整轮扫描,但必须在
|
|
861
|
+
# 证据上可区分(F-207)。
|
|
862
|
+
_record_skip(stats, rel=rel, stage="multilang", exc=exc)
|
|
611
863
|
continue
|
|
612
864
|
|
|
865
|
+
# Python 文件的 AST 专有规则由 ``matcher._scan_python_specifics`` 内部记录
|
|
866
|
+
# 解析失败(matcher 层维护 parse_error 清单),这里并入同一份聚合结果,
|
|
867
|
+
# 避免只暴露「多语言外壳」抛出的失败而漏掉 AST 规则层的跳过。
|
|
613
868
|
if stats is not None:
|
|
869
|
+
stats.setdefault("skipped_files", []).extend(matcher.parse_errors)
|
|
614
870
|
stats["files"] = stats.get("files", 0) + scanned
|
|
615
871
|
return findings
|
|
616
872
|
|
|
617
873
|
|
|
618
|
-
def scan_external_bandit(
|
|
874
|
+
def scan_external_bandit(
|
|
875
|
+
root: Path, timeout: float = 60.0, ignore: PathIgnoreSpec | None = None,
|
|
876
|
+
) -> list[dict[str, Any]]:
|
|
619
877
|
"""调用外部 Native Bandit 对 Python 源码进行深度安全扫描。
|
|
620
878
|
|
|
621
879
|
``timeout`` 由调用方按**剩余总预算**下发(``run_scan(deadline_seconds=...)``),
|
|
@@ -626,7 +884,11 @@ def scan_external_bandit(root: Path, timeout: float = 60.0) -> list[dict[str, An
|
|
|
626
884
|
if not exe:
|
|
627
885
|
return []
|
|
628
886
|
try:
|
|
629
|
-
|
|
887
|
+
# 外部工具自己遍历磁盘,只能靠 ``-x`` 下发同一份忽略规格(仅字面量前缀)。
|
|
888
|
+
excludes = list(SKIP_DIRS)
|
|
889
|
+
if ignore is not None:
|
|
890
|
+
excludes.extend(str(root / literal) for literal in ignore.literal_excludes())
|
|
891
|
+
cmd = [exe, "-r", str(root), "-f", "json", "-q", "-x", ",".join(excludes)]
|
|
630
892
|
res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
|
|
631
893
|
check=False, env=environment)
|
|
632
894
|
if res.returncode not in (0, 1):
|
|
@@ -667,14 +929,20 @@ def scan_external_bandit(root: Path, timeout: float = 60.0) -> list[dict[str, An
|
|
|
667
929
|
return []
|
|
668
930
|
|
|
669
931
|
|
|
670
|
-
def scan_external_semgrep(
|
|
932
|
+
def scan_external_semgrep(
|
|
933
|
+
root: Path, timeout: float = 60.0, ignore: PathIgnoreSpec | None = None,
|
|
934
|
+
) -> list[dict[str, Any]]:
|
|
671
935
|
"""调用外部 Semgrep 做深度规则扫描;``timeout`` 由调用方的剩余预算下发。"""
|
|
672
936
|
environment = _probe_environment()
|
|
673
937
|
exe = shutil.which("semgrep", path=environment.get("PATH"))
|
|
674
938
|
if not exe:
|
|
675
939
|
return []
|
|
676
940
|
try:
|
|
677
|
-
cmd = [exe, "scan", "--json", "--quiet", "--config", "p/security-audit"
|
|
941
|
+
cmd = [exe, "scan", "--json", "--quiet", "--config", "p/security-audit"]
|
|
942
|
+
if ignore is not None:
|
|
943
|
+
for literal in ignore.literal_excludes():
|
|
944
|
+
cmd.extend(["--exclude", literal])
|
|
945
|
+
cmd.append(str(root))
|
|
678
946
|
res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout,
|
|
679
947
|
check=False, env=environment)
|
|
680
948
|
if res.returncode not in (0, 1):
|
|
@@ -810,8 +1078,78 @@ def _cwe_head(value: Any) -> str:
|
|
|
810
1078
|
return str(value or "").strip().upper().split(":", 1)[0].strip()
|
|
811
1079
|
|
|
812
1080
|
|
|
1081
|
+
def _finding_source_lines(root: Path, rel: str) -> list[str] | None:
|
|
1082
|
+
"""读取 finding 指向的源文件行;越出 ``root`` 或读不到时返回 ``None``。"""
|
|
1083
|
+
candidate = Path(rel)
|
|
1084
|
+
path = candidate if candidate.is_absolute() else root / candidate
|
|
1085
|
+
try:
|
|
1086
|
+
resolved = path.resolve()
|
|
1087
|
+
resolved.relative_to(root)
|
|
1088
|
+
except (OSError, ValueError):
|
|
1089
|
+
return None
|
|
1090
|
+
try:
|
|
1091
|
+
return resolved.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
1092
|
+
except OSError:
|
|
1093
|
+
return None
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
def _apply_suppressions(
|
|
1097
|
+
root: Path, findings: list[dict[str, Any]]
|
|
1098
|
+
) -> tuple[list[dict[str, Any]], int]:
|
|
1099
|
+
"""按行级抑制过滤**去重之后**的最终结果,返回 (保留项, 被抑制数)。
|
|
1100
|
+
|
|
1101
|
+
抑制必须作用在「缺陷」上,而不是各扫描器「原始命中」上。跨规则去重会把
|
|
1102
|
+
同一处的重复命中合并成一条代表(同文件 + 同 CWE + 行距 ≤3),若抑制发生在
|
|
1103
|
+
去重之前,用户抑制掉看得见的那条规则后,被吞掉的同源规则会顶上来——实测
|
|
1104
|
+
``exec`` 被 AST 的 ``SEC-002-DANGEROUS-EVAL`` 与多语言的 ``SEC-EVAL-001``
|
|
1105
|
+
双报,注释只写前者时总数与 critical 纹丝不动,等于抑制静默失效。
|
|
1106
|
+
|
|
1107
|
+
放在这里还有一个好处:抑制口径对 AST / 多语言 / 外部工具一视同仁,不再
|
|
1108
|
+
取决于各扫描器是否记得自己调一次判定。
|
|
1109
|
+
|
|
1110
|
+
匹配时取 ``{rule_id} ∪ merged_rule_ids``:去重把同源的另一条规则(如
|
|
1111
|
+
``SEC-CMD-001``)并进了代表条目,它仍是规则目录里的正式编号,按它写抑制
|
|
1112
|
+
必须同样生效,否则「照文档写注释 → 静默无效果」。
|
|
1113
|
+
"""
|
|
1114
|
+
cache: dict[str, dict[int, set[str]]] = {}
|
|
1115
|
+
kept: list[dict[str, Any]] = []
|
|
1116
|
+
suppressed = 0
|
|
1117
|
+
for item in findings:
|
|
1118
|
+
rel = str(item.get("file") or "")
|
|
1119
|
+
try:
|
|
1120
|
+
lineno = int(item.get("line") or 0)
|
|
1121
|
+
except (TypeError, ValueError):
|
|
1122
|
+
lineno = 0
|
|
1123
|
+
if not rel or lineno <= 0:
|
|
1124
|
+
kept.append(item)
|
|
1125
|
+
continue
|
|
1126
|
+
if rel not in cache:
|
|
1127
|
+
lines = _finding_source_lines(root, rel)
|
|
1128
|
+
cache[rel] = extract_suppressions(lines) if lines is not None else {}
|
|
1129
|
+
rule_ids = {str(item.get("rule_id") or "")}
|
|
1130
|
+
rule_ids.update(str(rule) for rule in (item.get("merged_rule_ids") or ()))
|
|
1131
|
+
rule_ids.discard("")
|
|
1132
|
+
if any(is_suppressed(cache[rel], lineno, rule) for rule in rule_ids):
|
|
1133
|
+
suppressed += 1
|
|
1134
|
+
continue
|
|
1135
|
+
kept.append(item)
|
|
1136
|
+
# ``merged_rule_ids`` 只是抑制判定的中间产物(去重时记下的同源规则身份),
|
|
1137
|
+
# 不是缺陷本身的属性:它不参与指纹/SARIF,留在输出里会变成别人依赖的隐式
|
|
1138
|
+
# 契约,把去重判据锁死。判定用完即摘。
|
|
1139
|
+
for item in kept:
|
|
1140
|
+
item.pop("merged_rule_ids", None)
|
|
1141
|
+
return kept, suppressed
|
|
1142
|
+
|
|
1143
|
+
|
|
813
1144
|
def _dedupe_cross_tool(findings: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
814
|
-
"""合并不同扫描器对同一处缺陷的重复命中(同文件 + 同 CWE + 行号相近)。
|
|
1145
|
+
"""合并不同扫描器对同一处缺陷的重复命中(同文件 + 同 CWE + 行号相近)。
|
|
1146
|
+
|
|
1147
|
+
合并时把被吞掉的 ``rule_id`` 记进代表条目的 ``merged_rule_ids``:规则目录里
|
|
1148
|
+
的正式编号(如 ``SEC-CMD-001``)与去重后输出的编号(``SEC-001-OS-SYSTEM``)
|
|
1149
|
+
不是同一个,用户照文档写抑制注释时必须同样生效,否则抑制静默失效。只在
|
|
1150
|
+
真的合并了**不同** ``rule_id`` 时才写这个字段,代表条目自身的 ``rule_id``
|
|
1151
|
+
与输出口径保持不变。
|
|
1152
|
+
"""
|
|
815
1153
|
kept: list[dict[str, Any]] = []
|
|
816
1154
|
seen: list[tuple[str, str, str, int]] = []
|
|
817
1155
|
for item in findings:
|
|
@@ -822,17 +1160,22 @@ def _dedupe_cross_tool(findings: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
|
822
1160
|
line = int(item.get("line") or 0)
|
|
823
1161
|
except (TypeError, ValueError):
|
|
824
1162
|
line = 0
|
|
825
|
-
|
|
1163
|
+
duplicate_of = -1
|
|
826
1164
|
if path and cwe:
|
|
827
|
-
for seen_path, seen_cwe, seen_rule, seen_line in seen:
|
|
1165
|
+
for index, (seen_path, seen_cwe, seen_rule, seen_line) in enumerate(seen):
|
|
828
1166
|
# 只有**不同规则**命中同一处才算跨工具重复:同一条规则在相邻
|
|
829
1167
|
# 两行命中是两处真实缺陷(实测 src/config.py:5 与 :6 是两个
|
|
830
1168
|
# 独立的硬编码凭据),不能被合并掉。
|
|
831
1169
|
if (seen_path == path and seen_cwe == cwe
|
|
832
1170
|
and seen_rule != rule and abs(seen_line - line) <= 3):
|
|
833
|
-
|
|
1171
|
+
duplicate_of = index
|
|
834
1172
|
break
|
|
835
|
-
if
|
|
1173
|
+
if duplicate_of >= 0:
|
|
1174
|
+
# ``kept`` 与 ``seen`` 同步追加、从不删除,索引一一对应。
|
|
1175
|
+
representative = kept[duplicate_of]
|
|
1176
|
+
merged = representative.setdefault("merged_rule_ids", [])
|
|
1177
|
+
if rule and rule not in merged and rule != representative.get("rule_id"):
|
|
1178
|
+
merged.append(rule)
|
|
836
1179
|
continue
|
|
837
1180
|
seen.append((path, cwe, rule, line))
|
|
838
1181
|
kept.append(item)
|
|
@@ -856,8 +1199,11 @@ def run_scan(
|
|
|
856
1199
|
``budget_exhausted=True``,绝不静默返回 ``COMPLETED`` 冒充完整扫描。
|
|
857
1200
|
"""
|
|
858
1201
|
root = root.resolve()
|
|
1202
|
+
# 忽略规格按本次调用的 root 加载一次,整轮扫描内复用:不同 --root 的调用
|
|
1203
|
+
# 各拿各的 ``.bugxignore``,不会因进程内复用而串味。
|
|
1204
|
+
ignore = PathIgnoreSpec.load(root)
|
|
859
1205
|
findings: list[dict[str, Any]] = []
|
|
860
|
-
file_stats: dict[str,
|
|
1206
|
+
file_stats: dict[str, Any] = {}
|
|
861
1207
|
used_tools: list[str] = []
|
|
862
1208
|
started_at = time.monotonic()
|
|
863
1209
|
deadline = (
|
|
@@ -871,12 +1217,12 @@ def run_scan(
|
|
|
871
1217
|
return deadline - time.monotonic()
|
|
872
1218
|
|
|
873
1219
|
# 1. 执行 Python 原生 AST 扫描 (保持向前兼容)
|
|
874
|
-
builtin_py_results = scan_source_ast(root, stats=file_stats)
|
|
1220
|
+
builtin_py_results = scan_source_ast(root, stats=file_stats, ignore=ignore)
|
|
875
1221
|
findings.extend(builtin_py_results)
|
|
876
1222
|
used_tools.append("builtin-ast")
|
|
877
1223
|
|
|
878
1224
|
# 2. 执行多语言通用结构化模式扫描 (Go, Java, JS/TS, Rust, C/C++, PHP 等)
|
|
879
|
-
multilang_results = scan_multilang_sources(root, stats=file_stats)
|
|
1225
|
+
multilang_results = scan_multilang_sources(root, stats=file_stats, ignore=ignore)
|
|
880
1226
|
if multilang_results:
|
|
881
1227
|
findings.extend(multilang_results)
|
|
882
1228
|
used_tools.append("builtin-multilang-sast")
|
|
@@ -884,7 +1230,13 @@ def run_scan(
|
|
|
884
1230
|
# 3. 执行多语言依赖供应链分析 (SCA)
|
|
885
1231
|
if include_sca:
|
|
886
1232
|
sca = SCAScanner()
|
|
887
|
-
|
|
1233
|
+
# ``SCAScanner`` 自带清单枚举(另一个模块,本次不动),这里按同一份
|
|
1234
|
+
# ``PathIgnoreSpec`` 收口:被忽略的清单不产生 finding。清单解析是毫秒级,
|
|
1235
|
+
# 真正省时间的是上面两条 AST/多语言枚举路径。
|
|
1236
|
+
sca_results = [
|
|
1237
|
+
item for item in sca.scan_project(root)
|
|
1238
|
+
if not ignore.matches(item.get("file", ""))
|
|
1239
|
+
]
|
|
888
1240
|
if sca_results:
|
|
889
1241
|
findings.extend(sca_results)
|
|
890
1242
|
used_tools.append("builtin-sca")
|
|
@@ -900,6 +1252,7 @@ def run_scan(
|
|
|
900
1252
|
else:
|
|
901
1253
|
semgrep_results = scan_external_semgrep(
|
|
902
1254
|
root, timeout=60.0 if remaining is None else min(60.0, remaining),
|
|
1255
|
+
ignore=ignore,
|
|
903
1256
|
)
|
|
904
1257
|
if semgrep_results:
|
|
905
1258
|
findings.extend(semgrep_results)
|
|
@@ -914,6 +1267,7 @@ def run_scan(
|
|
|
914
1267
|
else:
|
|
915
1268
|
bandit_results = scan_external_bandit(
|
|
916
1269
|
root, timeout=60.0 if remaining is None else min(60.0, remaining),
|
|
1270
|
+
ignore=ignore,
|
|
917
1271
|
)
|
|
918
1272
|
if bandit_results:
|
|
919
1273
|
findings.extend(bandit_results)
|
|
@@ -926,9 +1280,13 @@ def run_scan(
|
|
|
926
1280
|
# 行号相近(<=3 行)」,保留首个(内建优先,字段最全)。
|
|
927
1281
|
findings = _dedupe_cross_tool(findings)
|
|
928
1282
|
|
|
1283
|
+
# 行级抑制在**去重之后**统一执行(唯一应用点):先合并同源重复,再按
|
|
1284
|
+
# 「行 + 规则名」压制去重后的代表条目,被吞掉的同源规则不会顶上来。
|
|
1285
|
+
findings, suppressed_by_comment = _apply_suppressions(root, findings)
|
|
1286
|
+
file_stats["suppressed"] = suppressed_by_comment
|
|
1287
|
+
|
|
929
1288
|
# 排序:按严重度及路径排序
|
|
930
|
-
|
|
931
|
-
findings.sort(key=lambda x: (severity_order.get(x.get("severity", "medium"), 2), x.get("file", ""), x.get("line", 0)))
|
|
1289
|
+
findings.sort(key=lambda x: (_SEVERITY_RANK.get(x.get("severity", "medium"), 2), x.get("file", ""), x.get("line", 0)))
|
|
932
1290
|
|
|
933
1291
|
# 保存基线
|
|
934
1292
|
if write_baseline:
|
|
@@ -939,6 +1297,17 @@ def run_scan(
|
|
|
939
1297
|
if baseline:
|
|
940
1298
|
findings, suppressed_baseline = apply_baseline_filter(findings, baseline)
|
|
941
1299
|
|
|
1300
|
+
# 逐文件跳过(含解析失败)的结构化收据:``scanned_files`` 只说明「成功扫了
|
|
1301
|
+
# 多少」,没有这两个字段时「解析失败漏扫」与「文件无缺陷」不可区分(F-207)。
|
|
1302
|
+
skipped_files = _merge_skipped(file_stats.get("skipped_files") or [])
|
|
1303
|
+
parse_errors = sum(
|
|
1304
|
+
1 for item in skipped_files if item.get("reason") in _PARSE_FAILURE_REASONS
|
|
1305
|
+
)
|
|
1306
|
+
skipped_reasons: dict[str, int] = {}
|
|
1307
|
+
for item in skipped_files:
|
|
1308
|
+
reason = str(item.get("reason"))
|
|
1309
|
+
skipped_reasons[reason] = skipped_reasons.get(reason, 0) + 1
|
|
1310
|
+
|
|
942
1311
|
return {
|
|
943
1312
|
"schema_version": 2,
|
|
944
1313
|
"status": "DEGRADED" if budget_exhausted else "COMPLETED",
|
|
@@ -946,6 +1315,18 @@ def run_scan(
|
|
|
946
1315
|
# 报告层需要「扫了多少文件」才能说清楚覆盖范围。此前收据不报这个数,
|
|
947
1316
|
# 调用方只能用命中数顶替,把「命中数」当成「暴露面总量」呈现。
|
|
948
1317
|
"scanned_files": int(file_stats.get("files", 0)),
|
|
1318
|
+
# 解析失败/读取失败的文件数与明细:``reason`` 区分 syntax_error /
|
|
1319
|
+
# parse_error / unreadable / scanner_error,``file``+``line``+``col``
|
|
1320
|
+
# 给出定位,报告层不必再从日志里反推漏扫了什么。
|
|
1321
|
+
"parse_errors": parse_errors,
|
|
1322
|
+
"skipped_files": skipped_files,
|
|
1323
|
+
"skipped_reasons": skipped_reasons,
|
|
1324
|
+
# 路径级忽略是「为什么少扫了」的可解释证据:报告层不该只能看到变小的
|
|
1325
|
+
# 数字却说不清是漏扫还是按规则排除。
|
|
1326
|
+
"path_ignore": ignore.describe(),
|
|
1327
|
+
# 被行级抑制压掉的命中数:抑制生效与否必须可观测,否则「写了不生效」
|
|
1328
|
+
# 只能靠人肉复现。
|
|
1329
|
+
"suppressed_findings": int(file_stats.get("suppressed", 0)),
|
|
949
1330
|
"tools_executed": used_tools,
|
|
950
1331
|
"total_findings": len(findings),
|
|
951
1332
|
"suppressed_by_baseline": suppressed_baseline,
|
|
@@ -955,6 +1336,48 @@ def run_scan(
|
|
|
955
1336
|
}
|
|
956
1337
|
|
|
957
1338
|
|
|
1339
|
+
#: 严重度排序权重(0 最严重)。findings 排序与人读摘要共用同一份口径。
|
|
1340
|
+
_SEVERITY_RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
|
1341
|
+
|
|
1342
|
+
#: 人读输出里「批量命中」的计数阈值:达到该值的规则会得到 --baseline /
|
|
1343
|
+
#: .bugxignore 的可操作提示,而不是让用户逐条复核。
|
|
1344
|
+
_BULK_RULE_THRESHOLD = 20
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
def _rule_summary(findings: list[dict[str, Any]]) -> list[tuple[str, str, int]]:
|
|
1348
|
+
"""按规则聚合 ``(rule_id, 该规则最高严重度, 计数)``。
|
|
1349
|
+
|
|
1350
|
+
严重度取该规则**所有命中**里的最高值,不是第一条命中的——按严重度排序的
|
|
1351
|
+
明细里同一条规则可能散落在多行,用首条会把 306 条 low 的批量规则和 3 条
|
|
1352
|
+
high 的规则显示成同一档。
|
|
1353
|
+
排序:最高严重度从高到低,同档按计数从多到少,再按 rule_id 兜底稳定。
|
|
1354
|
+
"""
|
|
1355
|
+
counts: collections.Counter[str] = collections.Counter()
|
|
1356
|
+
severities: dict[str, str] = {}
|
|
1357
|
+
for item in findings:
|
|
1358
|
+
rule = str(item.get("rule_id") or "")
|
|
1359
|
+
if not rule:
|
|
1360
|
+
continue
|
|
1361
|
+
counts[rule] += 1
|
|
1362
|
+
severity = str(item.get("severity") or "medium").lower()
|
|
1363
|
+
current = severities.get(rule)
|
|
1364
|
+
if current is None or _SEVERITY_RANK.get(severity, 2) < _SEVERITY_RANK.get(current, 2):
|
|
1365
|
+
severities[rule] = severity
|
|
1366
|
+
rows = [(rule, severities[rule], count) for rule, count in counts.items()]
|
|
1367
|
+
rows.sort(key=lambda row: (_SEVERITY_RANK.get(row[1], 2), -row[2], row[0]))
|
|
1368
|
+
return rows
|
|
1369
|
+
|
|
1370
|
+
|
|
1371
|
+
def _print_rule_summary(rows: list[tuple[str, str, int]], total: int) -> None:
|
|
1372
|
+
"""打印规则级摘要(只走人读输出,``--json`` / ``--sarif`` 不经过这里)。"""
|
|
1373
|
+
rule_width = max(len(rule) for rule, _, _ in rows)
|
|
1374
|
+
severity_width = max(len(severity) for _, severity, _ in rows) + 2 # 含方括号
|
|
1375
|
+
print(f" 规则摘要({len(rows)} 条规则 / {total} 项,按最高严重度排序):")
|
|
1376
|
+
for rule, severity, count in rows:
|
|
1377
|
+
tag = f"[{severity.upper()}]".ljust(severity_width)
|
|
1378
|
+
print(f" {tag}{rule.ljust(rule_width)} {count}")
|
|
1379
|
+
|
|
1380
|
+
|
|
958
1381
|
def main(argv: list[str] | None = None) -> int:
|
|
959
1382
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
960
1383
|
parser.add_argument("command", choices=("check", "status", "scan"), nargs="?", default="check")
|
|
@@ -985,13 +1408,36 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
985
1408
|
print(json.dumps(scan_res, ensure_ascii=False, indent=2))
|
|
986
1409
|
else:
|
|
987
1410
|
print(f"[SAST Scan] 执行完成(工具链: {', '.join(scan_res['tools_executed'])}),发现 {scan_res['total_findings']} 个候选漏洞:")
|
|
1411
|
+
if scan_res.get("parse_errors"):
|
|
1412
|
+
reasons = "、".join(
|
|
1413
|
+
f"{reason}×{count}"
|
|
1414
|
+
for reason, count in sorted((scan_res.get("skipped_reasons") or {}).items())
|
|
1415
|
+
)
|
|
1416
|
+
print(
|
|
1417
|
+
f" ⚠️ {scan_res['parse_errors']} 个文件因解析失败被跳过"
|
|
1418
|
+
f"({reasons}),其 AST 级规则未覆盖;明细见 --json 的 skipped_files"
|
|
1419
|
+
)
|
|
988
1420
|
if scan_res.get("suppressed_by_baseline", 0) > 0:
|
|
989
1421
|
print(f" ℹ️ 已基于 Baseline 过滤 {scan_res['suppressed_by_baseline']} 个已知历史问题")
|
|
1422
|
+
truncated = scan_res["total_findings"] > 25
|
|
1423
|
+
rule_rows = _rule_summary(scan_res["findings"])
|
|
1424
|
+
# 摘要只在明细确实被截断时打:小规模扫描打摘要等于把明细抄一遍。
|
|
1425
|
+
if truncated:
|
|
1426
|
+
_print_rule_summary(rule_rows, scan_res["total_findings"])
|
|
990
1427
|
for idx, item in enumerate(scan_res["findings"][:25], 1):
|
|
991
1428
|
cwe_tag = f"[{item.get('cwe', '')}] " if item.get('cwe') else ""
|
|
992
1429
|
print(f" #{idx} [{item['severity'].upper()}] {item['file']}:{item['line']} - {cwe_tag}{item['rule_id']}: {item['message']}")
|
|
993
|
-
if
|
|
1430
|
+
if truncated:
|
|
994
1431
|
print(f" ... 以及另外 {scan_res['total_findings'] - 25} 项(使用 --json 或 --sarif 查看全量)")
|
|
1432
|
+
# 批量命中给可操作出口:这类项逐条复核没有意义,应当固化基线或
|
|
1433
|
+
# 按路径排除。按计数判,不认规则名。
|
|
1434
|
+
bulk = [(rule, count) for rule, _, count in rule_rows if count >= _BULK_RULE_THRESHOLD]
|
|
1435
|
+
if bulk:
|
|
1436
|
+
names = "、".join(f"{rule}({count} 项)" for rule, count in bulk)
|
|
1437
|
+
print(
|
|
1438
|
+
f" 提示:{names}属于批量命中(≥{_BULK_RULE_THRESHOLD} 项),"
|
|
1439
|
+
"建议用 --baseline 固化历史,或用 .bugxignore 排除整类路径,而不是逐条复核。"
|
|
1440
|
+
)
|
|
995
1441
|
return 0
|
|
996
1442
|
|
|
997
1443
|
report = inspect(args.root)
|
|
@@ -1005,5 +1451,60 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
1005
1451
|
return 0 if args.allow_degraded else 2
|
|
1006
1452
|
|
|
1007
1453
|
|
|
1454
|
+
def is_available() -> tuple[bool, str]:
|
|
1455
|
+
"""降级契约:机械探活外部 SAST 工具是否在 PATH(零子进程 which)。
|
|
1456
|
+
|
|
1457
|
+
缺失不阻断:本模块架构契约是非侵入式零依赖,外部工具只做加速通道;
|
|
1458
|
+
但调用方必须据此走 ``run_static_degraded`` 显式标记降级扫描,禁止把
|
|
1459
|
+
纯内置引擎扫描伪装成完整外部工具链扫描。
|
|
1460
|
+
"""
|
|
1461
|
+
environment = _probe_environment()
|
|
1462
|
+
path = environment.get("PATH")
|
|
1463
|
+
found = [name for name in ("semgrep", "codeql", "trivy", "bandit") if shutil.which(name, path=path)]
|
|
1464
|
+
if not found:
|
|
1465
|
+
return False, "无外部 SAST 工具(semgrep/codeql/trivy/bandit);内置多语言引擎兜底"
|
|
1466
|
+
return True, f"外部工具: {', '.join(found)}"
|
|
1467
|
+
|
|
1468
|
+
|
|
1469
|
+
def run_static_degraded(root: Path, *, deadline_seconds: float | None = None) -> dict:
|
|
1470
|
+
"""降级契约:仅执行内置 AST/多语言/SCA 阶段,显式标记降级扫描。
|
|
1471
|
+
|
|
1472
|
+
输出与成功路径(``run_scan`` 的 ``status="COMPLETED"`` 完整工具链扫描)
|
|
1473
|
+
字段级可区分:``status="degraded"`` + ``degraded=True`` + ``degraded_reason``;
|
|
1474
|
+
``tools="builtin"`` 硬性跳过全部外部工具通道,绝不静默混入外部结果。
|
|
1475
|
+
"""
|
|
1476
|
+
available, availability_detail = is_available()
|
|
1477
|
+
result = run_scan(root, tools="builtin", deadline_seconds=deadline_seconds)
|
|
1478
|
+
return {
|
|
1479
|
+
"schema_version": result["schema_version"],
|
|
1480
|
+
"success": True,
|
|
1481
|
+
"status": "degraded",
|
|
1482
|
+
"degraded": True,
|
|
1483
|
+
"degraded_reason": (
|
|
1484
|
+
"static_mode_forced" if available else "external_sast_tools_unavailable"
|
|
1485
|
+
),
|
|
1486
|
+
"probe_mode": "static_degraded",
|
|
1487
|
+
"root": result["root"],
|
|
1488
|
+
"scan_status": result["status"],
|
|
1489
|
+
"scanned_files": result["scanned_files"],
|
|
1490
|
+
"parse_errors": result["parse_errors"],
|
|
1491
|
+
"skipped_files": result["skipped_files"],
|
|
1492
|
+
"skipped_reasons": result["skipped_reasons"],
|
|
1493
|
+
"tools_executed": result["tools_executed"],
|
|
1494
|
+
"total_findings": result["total_findings"],
|
|
1495
|
+
"suppressed_by_baseline": result["suppressed_by_baseline"],
|
|
1496
|
+
"findings": result["findings"],
|
|
1497
|
+
"evidence": {
|
|
1498
|
+
"availability_detail": availability_detail,
|
|
1499
|
+
"external_tools_skipped": ["semgrep", "bandit", "codeql", "trivy"],
|
|
1500
|
+
},
|
|
1501
|
+
"metadata": {
|
|
1502
|
+
"degraded_mode": "builtin_engine_only",
|
|
1503
|
+
"external_channels_executed": False,
|
|
1504
|
+
"fallback": "外部 SAST 工具缺失时由内置多语言引擎完成扫描;加速通道缺失需在准备记录留痕",
|
|
1505
|
+
},
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
|
|
1008
1509
|
if __name__ == "__main__":
|
|
1009
1510
|
raise SystemExit(main())
|