daedalus/ImpactGuard

GitHub: daedalus/ImpactGuard

ImpactGuard是一款多语言API影响分析器,用于自动化检测代码变更带来的风险。

Stars: 113 | Forks: 19

# **ImpactGuard** — 轻量级多语言API影响分析器 ## CLI参考 `impactguard`命令行工具是开发人员和自动化脚本的入口点。 ### 使用方法 ``` impactguard [-h] [--version] {extract,compare,analyze,risk,report,report-sarif,enforce,suggest,patch,extract-calls,trace,check,check-diff,check-commit,check-commits,install-hooks,generate-changelog,baseline,semver,report-markdown,feedback,history} ... ImpactGuard - API impact analyzer for Python positional arguments: {extract,compare,analyze,risk,report,report-sarif,enforce,suggest,patch,extract-calls,trace,check,check-diff,check-commit,check-commits,install-hooks,generate-changelog,baseline,semver,report-markdown,feedback,history} Available commands extract Extract function signatures from source files compare Compare signature snapshots or source files directly analyze Analyze impact on call sites risk Run risk analysis report Generate HTML report report-sarif Generate SARIF v2.1.0 report from risk report JSON enforce Enforce gate - block on HIGH risk suggest Generate fix suggestions from risk report patch Generate CST-based patches extract-calls Extract call sites from source files trace Runtime tracing check Run full ImpactGuard pipeline check check-diff Run full pipeline on a unified diff / patch file check-commit Run full pipeline on a single git commit vs its parent check-commits Compare two git commits install-hooks Install git hooks for ImpactGuard generate-changelog Generate changelog from signature diffs baseline Manage ImpactGuard signature baselines semver Suggest semver bump from two signature snapshots report-markdown Generate markdown PR comment from risk report JSON feedback Manage patch-outcome feedback for confidence calibration history Manage tagged release-history baselines options: -h, --help show this help message and exit --version show program's version number and exit ``` ### 管道模式(推荐) ``` # 比较代码的两个版本 impactguard old_version/ new_version/ # 直接比较两个git提交 impactguard check-commits HEAD~1 HEAD # 在提交之间比较特定文件 impactguard check-commits HEAD~1 HEAD --files src/module.py src/utils.py # 为建议的修复生成补丁文件 impactguard check --suggest-patch old.py new.py # 显示修补后旧文件的外观(需要 --suggest-patch) impactguard check --suggest-patch --show-patch old.py new.py ``` **补丁生成标志:** - `--suggest-patch`:生成并保存补丁文件到`patches/`目录 - `--show-patch`:显示补丁内容(取决于`--suggest-patch`) **SARIF输出:** 所有检查子命令都接受`--report-sarif PATH`以将SARIF v2.1.0报告写入常规输出旁边: ``` impactguard check old/ new/ --report-sarif results.sarif impactguard check-diff --pipe --runtime runtime.json --report-sarif results.sarif impactguard check-commit HEAD --report-sarif results.sarif impactguard check-commits HEAD~1 HEAD --report-sarif results.sarif ``` 将现有风险报告JSON转换为SARIF的独立子命令: ``` impactguard report-sarif report.json -o results.sarif ``` **补丁生成标志:** - `--suggest-patch`:生成并保存补丁文件到`patches/`目录 - `--show-patch`:显示补丁内容(取决于`--suggest-patch`) ### 单个命令(高级) ``` impactguard extract file1.py file2.py impactguard compare old_sigs.json new_sigs.json # 或直接比较源文件(自动提取签名): impactguard compare old.py new.py impactguard analyze signatures.json calls.json runtime.json impactguard risk diff.txt runtime.json output.json impactguard report risk.json output.html impactguard trace install mypackage impactguard trace dump runtime.json impactguard install-hooks . --both # Install git hooks ``` ### Git钩子安装 ImpactGuard使用`pre-commit`框架来管理git钩子,并使用适当的YAML配置。 ``` # 安装 pre-commit 和 post-commit 钩子 impactguard install-hooks . # 仅安装 pre-commit 钩子 impactguard install-hooks . --pre # 仅安装 post-commit 钩子 impactguard install-hooks . --post # 安装钩子 + GitHub Actions 工作流程 impactguard install-hooks . --install-github-workflow ``` `install-hooks`命令: 1. 创建/更新`.pre-commit-config.yaml`以包含ImpactGuard钩子(使用PyYAML进行适当的格式化) 2. 运行`pre-commit install`和`pre-commit install --hook-type post-commit` 3. 可选地生成`.github/workflows/impactguard.yml`以用于CI/CD **钩子行为:** - **Pre-commit**:在提交之前运行完整的ImpactGuard管道(`check-diff --pipe`)对暂存更改 - **Post-commit**:运行`check-commit HEAD` + 更新签名跟踪 ## Python库API `impactguard`包导出其核心功能以进行程序集成。 ### 管道(推荐) ``` from impactguard import run_pipeline, quick_check, run_pipeline_git, ImpactGuard # 完整管道 - 提取、比较、分析、风险、报告 result = run_pipeline( old_files=["src/"], new_files=["src/"], runtime_path="runtime.json", output_dir="report.html", suggest_patch=True, # Generate patch files show_patch=True, # Display patched content inline ) # 仅快速比较(提取 + 比较) changes = quick_check("old/", "new/") print(f"Breaking: {len(changes['comparison']['breaking'])}") # 比较git提交 result = run_pipeline_git( old_ref="HEAD~1", new_ref="HEAD", files=["src/module.py"], suggest_patch=True, show_patch=True, ) # 使用 ImpactGuard 类进行更多控制 guard = ImpactGuard() report = guard.check("old/", "new/", output="report.html") ``` **补丁生成参数:** - `suggest_patch=True`:生成并保存补丁文件到`patches/`目录 - `show_patch=True`:显示修补后旧文件的外观(需要`suggest_patch=True`) ### 单个组件(高级) ``` from impactguard import extract, compare, analyze_impact # 从Python文件中提取签名 signatures = extract(["src/module.py", "src/other.py"]) # 从其他支持的语言中提取(tree-sitter 后端) signatures = extract(["src/main.go", "src/utils.go"]) signatures = extract(["src/lib.rs", "src/main.rs"]) # 比较两个签名快照或直接比较源文件 result = compare("old_sigs.json", "new_sigs.json") # 或直接比较源文件(自动提取签名): result = compare("old.py", "new.py") print(f"Breaking changes: {len(result['breaking'])}") # 分析对调用站点的影响 issues = analyze_impact("signatures.json", "calls.json", "runtime.json") ``` ## Git钩子和工作流程集成 ImpactGuard使用`pre-commit`框架深度集成到标准的Git开发工作流程。 ### Pre-Commit钩子(完整管道检查) 在允许提交之前,在暂存更改上运行完整的ImpactGuard管道: ``` impactguard check-diff --pipe --runtime .runtime_calls.json ``` **性能**:预提交钩子故意是增量式的——它仅处理**暂存文件**(当前提交中修改的文件),使用`git diff --cached --diff-filter=ACMR`。在一个包含500k+行的代码库中,典型的提交仅触及少数文件,因此提取完成在毫秒内。这避免了每次提交重新扫描每个文件的启动成本。 这可以提前捕获破坏性更改,在它们进入提交历史之前。 ### Post-Commit钩子(签名跟踪) 每次提交后,post-commit钩子: 1. 运行`check-commit HEAD`以分析提交的更改 2. 重新扫描**所有跟踪的Python文件**(通过`git ls-files '*.py'`)并使用`.signatures.txt`更新完整快照 post-commit钩子故意**不是**增量式的——它在每次提交时替换整个基线,以确保存储的快照始终反映完整的代码库。这保证了`check-diff`(在*下一个*提交上由预提交钩子使用)有一个完整的图像来与之比较,但这在每次提交后都需要进行完整的扫描。对于一个500k行的代码库,这可能会花费几秒钟;钩子异步运行,不会阻塞开发者。 ### GitHub Actions工作流程 使用以下命令生成可用的CI工作流程: ``` impactguard install-hooks . --install-github-workflow ``` 这创建`.github/workflows/impactguard.yml`,其中: - 在推送到`main`/`master`时触发 - 为拉取请求运行`check-commits` - 为直接推送运行`check-commit` - 使用`impactguard[all]`进行完整语言支持 ### 控制台脚本 钩子使用以下入口点(自动配置): - `impactguard-check-staged` → 在暂存差异上运行管道 - `impactguard-post-commit-hook` → 运行提交后分析 ## CI/CD和发布基础设施 ### CI管道 CI管道在`.github/workflows/ci.yml`中定义,并在针对`master`分支的所有推送和拉取请求上执行。它由三个并行作业组成: - **测试矩阵**:在Python版本3.11、3.12和3.13上执行`pytest` - **静态分析(代码审查)**:运行`ruff`、`prospector`、`semgrep`和`mypy` - **构建验证**:确保可以通过`twine check`成功构建包 ### 打包和发布 ImpactGuard使用现代Python打包标准,使用`hatchling`作为构建后端。 **依赖组:** | 组 | 目的 | 关键工具 | |-------|---------|-----------| | `dev` | 通用开发 | `hatch`、`pip-api` | | `test` | 自动化测试 | `pytest`、`hypothesis` | | `lint` | 静态分析 | `ruff`、`mypy`、`semgrep` | **发布自动化:** - **版本管理**:使用`bumpversion`来维护`pyproject.toml`和`src/impactguard/__init__.py`之间的一致性 - **自动化发布**:`pypi-publish.yml`工作流程在GitHub发布事件上触发,使用受信任的发布者(OIDC)构建和发布到PyPI ## 测试 ImpactGuard测试套件确保签名提取管道的可靠性、风险模型的准确性以及CLI的稳定性。项目维护一个严格的质量门,要求至少80%的代码覆盖率。 ### 测试架构 1. **单元测试**:对单个模块(提取、比较、修补)进行隔离测试 2. **集成测试**:端到端CLI流程和公共API表面验证 3. **覆盖率强制**:自动检查以确保代码库达到80%的阈值 ### 测试夹具 | 夹具 | 描述 | |---------|-------------| | `sample_signature_data` | 返回表示序列化函数签名的字典列表 | | `sample_signatures_file` | 创建包含签名数据的临时`.json`文件 | | `sample_python_file` | 生成包含函数和类的临时`.py`文件 | | `runtime_data_file` | 提供模拟跟踪器输出的临时JSON文件 | ## 工作原理 1. **签名提取** — 解析Python AST(stdlib)或tree-sitter语法(TypeScript、JavaScript、Java、Kotlin、Go、Rust、Swift、C、C++、C#、Ruby、Haskell、Zig)以提取具有完整结构信息的函数签名 2. **API差异** — 将签名快照进行比较以检测删除的函数、添加的必需参数、位置重排和其他破坏性更改 3. **调用站点分析** — 将签名数据与调用站点提取相结合以预测哪些调用者将中断 4. **运行时验证** — 在测试运行期间对函数进行仪器化以记录实际的调用模式 5. **管道协调器** — 将所有组件连接到一个统一的流程(`run_pipeline()`) 6. **Git集成** — 直接比较任何两个git提交(`run_pipeline_git()`) ## 中间工件 管道依赖于标准化的JSON模式来在过滤器之间传递数据: | 工件 | 生产者 | 消费者 | 描述 | |----------|-----------|----------|-------------| | `.signatures.json` | `extract_signatures.py` | `compare_signatures.py`、`impact_analysis.py` | 函数元数据,包括参数、默认值和行号 | | `.calls.json` | `extract_calls.py` | `impact_analysis.py` | 静态调用站点映射,按调用者和被调用者划分 | | `.runtime_calls.json` | `trace_calls.py` | `impact_analysis.py`、`risk_gate.py` | 从执行中获取的频率和参数数据 | | `report.json` | `risk_gate.py` | `generate_report.py`、`suggest_fixes.py`、`sarif.py` | 最终风险分类(高/中/低) | | `*.sarif` | `sarif.py` | SARIF兼容的SAST工具 | SARIF v2.1.0输出,用于IDE/CI集成 | ## 自测试(Dogfooding) ImpactGuard已经在其自身上进行了**测试**以验证其API更改: ``` # 从自己的代码库中提取签名 $ impactguard extract src/impactguard/*.py ✓ Extracted 98 function signatures # 检测非破坏性更改(添加可选参数) ✓ Correctly classified as "Non-breaking changes: 1" # 检测破坏性更改(删除必需参数) ✓ Correctly classified as "Breaking changes: 1" # 在其自身上运行完整管道 $ impactguard check-commits HEAD~5 HEAD ✓ Pipeline orchestrator completed successfully ✓ Generated HTML report with risk analysis ``` ## 质量标准 ImpactGuard遵循严格的质量门: - **Ruff** — 0问题(格式化+代码审查) - **MyPy** — 0错误(严格模式) - **Prospector** — 0警告 - **Semgrep** — 0发现 - **覆盖率** — ≥80%(目标) - **测试** — 所有通过 ## 术语表 ### 核心概念 - **签名**:可调用接口的结构化表示,包括位置参数、关键字参数、可变参数和返回类型。支持Python、TypeScript、JavaScript、Java、Kotlin、Go、Rust、Swift、C、C++、C#、Ruby、Haskell和Zig。 - **FQName(完全限定名)**:`file_path:function_name`格式的唯一标识符(例如,`src/auth.py:login`) - **破坏性更改**:防止现有调用者正确执行的修改(例如,`REMOVED`、`REQUIRED_POSITIONAL_ADDED`、`POSITIONAL_REORDER`) ### 风险框架(S × E × C × λ) - **严重性(S)**:更改类型的技术影响(0.1到1.0) - **暴露(E)**:函数被调用的频率,按对数计算 - **置信度(C)**:基于样本大小的运行时数据的可靠性 - **Lambda(λ)**:灵敏度乘数(默认1.0);通过`--lambda-factor`调整 ### 修补 - **CST(具体语法树)**:与AST不同,保留格式、注释和空白 - **修补置信度**:从0.0到1.0的分数,表示自动修复正确的可能性 ## 直接竞争对手(Python API分析空间) 下表比较了ImpactGuard与最常用于Python API更改管理、静态分析和发布自动化的工具。截至2026-05,据我们所知: | 功能 | **ImpactGuard** | **griffe** | **python-semantic-release** | **commitizen** | **pyright / mypy** | |---|---|---|---|---|---| | AST-based signature extraction | ✅ 全部 — Python (`ast`), TypeScript/JavaScript/Java/Kotlin/Go/Rust/Swift/C/C++/C#/Ruby/Haskell/Zig (tree-sitter) | ✅ 全部(Python) | ❌ | ❌ | ✅(内部仅限) | | Breaking-change detection | ✅ 语义差异(添加/删除/修改) | ✅ | ❌ 代码无关 | ❌ 代码无关 | ⚠️ 仅类型错误 | | Call-site impact analysis | ✅ 静态调用站点遍历 | ❌ | ❌ | ❌ | ❌ | | Runtime call tracing | ✅(测试+生产采样) | ❌ | ❌ | ❌ | ❌ | | Risk scoring (S × E × C × λ model) | ✅ | ❌ | ❌ | ❌ | ❌ | | Transitive impact tracking | ✅ | ❌ | ❌ | ❌ | ❌ | | Semver bump recommendation | ✅ 从代码差异 | ⚠️ 部分通过griffe-diff | ✅ 从提交消息 | ✅ 从提交消息 | ❌ | | Changelog generation | ✅ 从签名差异 | ⚠️ 通过mkdocs插件 | ✅ 从提交消息 | ✅ 从提交消息 | ❌ | | HTML report | ✅ | ❌ | ❌ | ❌ | ❌ | | Patch generation (CST-based) | ✅ 保留格式 | ❌ | ❌ | ❌ | ⚠️ 快速修复 | | Patch confidence scoring | ✅ | ❌ | ❌ | ❌ | ❌ | | Baseline management | ✅ 保存/比较/差异 | ⚠️ 通过快照 | ❌ | ❌ | ❌ | | CI enforcement gate | ✅ 在HIGH / UNKNOWN上阻止 | ❌ | ✅(发布门) | ✅(代码审查门) | ✅(类型门) | | Git hook integration | ✅ Pre + post commit | ❌ | ❌ | ✅ | ❌ | | Config file (TOML) | ✅ `impactguard.toml` | ✅ | ✅ | ✅ | ✅ | | Watch mode (live re-run) | ✅ `--watch` | ❌ | ❌ | ❌ | ✅ | | No network required | ✅ | ✅ | ❌(PyPI / git) | ❌(git) | ✅ | | SARIF v2.1.0 report | ✅ `report-sarif`、`--report-sarif` | ❌ | ❌ | ❌ | ❌ | ### 生态系统相关工具 | 工具 | 领域 | 与ImpactGuard的重叠 | ImpactGuard添加的内容 | |---|---|---|---| | **griffe** | Python API文档+差异 | 最接近的替代品——提取签名,检测破坏性更改 | 调用站点分析、运行时跟踪、风险模型、修补生成 | | **python-semantic-release** | 自动化发布+semver | Semver bumps来自常规提交 | 代码级别的证明,而不仅仅是提交消息约定 | | **commitizen** | 习惯性提交+更改日志 | 更改日志生成、git钩子 | 实际的API级别分析和强制 | | **bump2version / bumpversion** | 版本字符串管理 | 版本提升 | 所有分析功能 | | **mypy / pyright** | 静态类型检查 | 检测类型不兼容的更改 | 调用站点影响、风险评分、运行时数据集成 | | **japicmp / apidiff (Go/Java)** | Java / Go中的API兼容性 | 直接在其他语言中的概念类似物 | Python + TypeScript + Java + Go + Rust + C/C++ + Ruby支持、运行时跟踪、修补生成 | ### ImpactGuard的独特差异化 1. **风险评分(S × E × C × λ)** — 没有将严重性、暴露(调用次数)和置信度结合成一个单一的风险评分。 2. **运行时+静态融合** — 将静态调用站点分析与实际测试运行中的实际调用次数合并,以提供经验证的风险级别。 3. **传递影响** — 跟踪调用者的调用者,而不仅仅是直接调用站点。 4. **基于CST的修补生成** — 建议并预览保留原始格式的源修补;在API更改领域没有竞争对手这样做。 5. **修补置信度评分** — 在应用之前量化自动修复的安全性。 6. **完全离线** — 无网络访问,无数据库;完全嵌入在Python项目中。 ## 坚韧性评估器(`tools/robustness_evaluator.py`) **坚韧性评估器**从测试套件指标计算项目级别的**坚韧性评分(R)**,并额外强调对抗性测试性能。它还报告一个**对抗性脆弱性指数(F)**,以隔离对抗性输入如何具体降低系统。 ### 指标 | 指标 | 公式 | 描述 | |--------|---------|-------------| | **R** | `C × (α × P_a + (1−α) × P_n) × S` | 综合坚韧性评分——整体健康在[0, 1] | | **R_d** | `C × D × (α × P_a + (1−α) × P_n) × S` | R与类别多样性惩罚 | | **F** | `max(0, (P_n - P_a) / P_n)` | 脆弱性指数——限制在[0, 1] | | **D** | `mean(pass_rate_i)` | 加权多样性(跨类别的平均通过率) | | **S** | `sample_penalty` | 样本大小惩罚(当n ≥ 10时为1.0,对于小样本减少) | **输入符号:** | 符号 | 含义 | |--------|---------| | `C` | 覆盖率比(0 – 1) | | `α` | 对抗性权重;建议0.5(通用)、0.65(安全)、0.75(红队) | | `P_a` | 对抗性通过率(`passing_adv / n_adversarial`) | | `P_n` | 正常通过率(`passing_norm / n_normal`) | **坚韧性标签:**优秀(≥ 0.80)·良好(≥ 0.65)·合格(≥ 0.45)·较差(< 0.45) - **地板**:如果`P_a < 0.3`,坚韧性标签将被限制为**较差**,无论分数如何 **脆弱性标签:**健壮(F ≤ 0.10)·适度(≤ 0.25)·脆弱(≤ 0.50)·非常脆弱(> 0.50) - **限制**:F被限制在[0, 1];当`P_a ≥ P_n`时,F = 0.0(不是脆弱的) **样本大小惩罚**:当对抗性或正常样本小于10个测试时应用(从0.3到1.0的线性斜率) 该工具强制执行**至少25%的对抗性覆盖率**要求(以代码0退出,将警告输出到stderr)。 ### 对抗性预算分配 | 类别 | 目标%的对抗性预算 | 示例 | |----------|--------------------------------|---------| | 边界/边缘情况 | 30% | 决策边界的输入 | | 语义扰动 | 25% | 相同意义,不同形式 | | 避免和混淆 | 25% | 编码技巧,重新表述 | | 组合攻击 | 20% | 多步骤,链式输入 | ### 使用方法 **Python API:** ``` from tools.robustness_evaluator import evaluate_robustness, CategoryStats result = evaluate_robustness( n_total=1054, n_adversarial=425, passing_adv=424, passing_norm=629, coverage=0.57, alpha=0.65, # security context categories=[ CategoryStats("boundary", 28, 28, difficulty=1.0), # hard CategoryStats("semantic", 22, 22, difficulty=0.5), # medium CategoryStats("evasion", 24, 24, difficulty=1.0), # hard CategoryStats("compositional", 19, 19, difficulty=0.8), # hard ], ) print(f"R = {result.robustness_score:.4f} [{result.robustness_label}]") print(f"F = {result.fragility_index:.4f} [{result.fragility_label}]") print(f"R_d = {result.robustness_score_with_diversity:.4f} (with diversity)") print(f"S = {result.sample_penalty:.2f} (sample penalty)") ``` **CLI(人类可读的报告)——
标签:AI红队测试, API分析, Git集成, Homebrew安装, HTML报告, Python, SARIF报告, 代码分析, 代码补丁, 代码追踪, 凭证管理, 历史记录, 反馈系统, 变更日志, 基线管理, 多语言支持, 安全可观测性, 安全测试框架, 数字取证, 无后门, 版本控制, 网络安全研究, 自动化脚本, 语义版本控制, 逆向工具, 风险分析