aicaudit 0.2.0__py3-none-any.whl
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.
- aicaudit/__init__.py +1 -0
- aicaudit/__main__.py +3 -0
- aicaudit/audit.py +167 -0
- aicaudit/cli.py +256 -0
- aicaudit/config.py +120 -0
- aicaudit/fix.py +213 -0
- aicaudit/graph.py +168 -0
- aicaudit/llm/__init__.py +1 -0
- aicaudit/llm/client.py +249 -0
- aicaudit/llm/prompts.py +195 -0
- aicaudit/output/__init__.py +1 -0
- aicaudit/output/json_output.py +34 -0
- aicaudit/output/markdown_output.py +52 -0
- aicaudit/output/sarif_output.py +121 -0
- aicaudit/rules/__init__.py +1 -0
- aicaudit/rules/base.py +90 -0
- aicaudit/rules/performance/__init__.py +1 -0
- aicaudit/rules/performance/complexity.py +57 -0
- aicaudit/rules/performance/nesting_depth.py +49 -0
- aicaudit/rules/quality/__init__.py +1 -0
- aicaudit/rules/quality/bare_except.py +30 -0
- aicaudit/rules/quality/magic_numbers.py +85 -0
- aicaudit/rules/quality/todo_comment.py +29 -0
- aicaudit/rules/quality/undefined_name.py +80 -0
- aicaudit/rules/quality/unused_variable.py +55 -0
- aicaudit/rules/security/__init__.py +1 -0
- aicaudit/rules/security/dangerous_functions.py +89 -0
- aicaudit/rules/security/insecure_random.py +58 -0
- aicaudit/rules/security/path_traversal.py +107 -0
- aicaudit/rules/security/secret_leak.py +71 -0
- aicaudit/rules/security/sql_injection.py +114 -0
- aicaudit/rules/security/ssrf.py +66 -0
- aicaudit/rules/security/weak_crypto.py +57 -0
- aicaudit/rules/security/xml_xxe.py +132 -0
- aicaudit/scan.py +266 -0
- aicaudit/web/__init__.py +5 -0
- aicaudit/web/server.py +495 -0
- aicaudit/web/static/app.css +416 -0
- aicaudit/web/static/app.js +440 -0
- aicaudit/web/templates/base.html +52 -0
- aicaudit/web/templates/config.html +48 -0
- aicaudit/web/templates/index.html +33 -0
- aicaudit/web/templates/results.html +34 -0
- aicaudit/web/templates/rules.html +29 -0
- aicaudit/web/templates/scan.html +48 -0
- aicaudit-0.2.0.dist-info/METADATA +461 -0
- aicaudit-0.2.0.dist-info/RECORD +51 -0
- aicaudit-0.2.0.dist-info/WHEEL +5 -0
- aicaudit-0.2.0.dist-info/entry_points.txt +2 -0
- aicaudit-0.2.0.dist-info/licenses/LICENSE +21 -0
- aicaudit-0.2.0.dist-info/top_level.txt +1 -0
aicaudit/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
aicaudit/__main__.py
ADDED
aicaudit/audit.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""AI deep audit: static scan + taint evidence + AI verdicts.
|
|
2
|
+
|
|
3
|
+
Orchestrates:
|
|
4
|
+
1. Static scan (rules + taint engine) to find suspicious code
|
|
5
|
+
2. Evidence assembly: taint paths, enclosing functions, entry points
|
|
6
|
+
3. AI verdicts grounded in that evidence (three-state, fail-safe)
|
|
7
|
+
4. Structured audit report with evidence and confidence
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import time
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from aicaudit.graph import CodeGraph
|
|
17
|
+
from aicaudit.llm.client import load_ai_config, verify_findings
|
|
18
|
+
from aicaudit.llm.prompts import (
|
|
19
|
+
FindingEvidence,
|
|
20
|
+
enclosing_function_source,
|
|
21
|
+
imports_block,
|
|
22
|
+
)
|
|
23
|
+
from aicaudit.scan import scan
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class AuditIssue:
|
|
28
|
+
rule_id: str
|
|
29
|
+
message: str
|
|
30
|
+
message_zh: str
|
|
31
|
+
file: str
|
|
32
|
+
line: int
|
|
33
|
+
static_severity: str
|
|
34
|
+
snippet: str = ""
|
|
35
|
+
cwe: str | None = None
|
|
36
|
+
# AI verdict fields (three-state status + confidence)
|
|
37
|
+
ai_status: str = "" # "" = AI not used; confirmed/false_positive/unverified
|
|
38
|
+
ai_confidence: float = 0.0
|
|
39
|
+
ai_reason: str = ""
|
|
40
|
+
ai_severity: str = ""
|
|
41
|
+
ai_cwe: str = ""
|
|
42
|
+
ai_vuln_type: str = ""
|
|
43
|
+
ai_suggested_fix: str = ""
|
|
44
|
+
evidence_chain: list = field(default_factory=list) # [(file,line,desc),...]
|
|
45
|
+
entry_point: str = ""
|
|
46
|
+
taint_paths: list = field(default_factory=list) # rendered source->sink paths
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def run_audit(paths, lang="en", use_ai=True) -> dict:
|
|
50
|
+
"""Run a full AI deep audit. Returns structured report dict."""
|
|
51
|
+
start = time.time()
|
|
52
|
+
root = Path(paths[0]) if paths else Path(".")
|
|
53
|
+
|
|
54
|
+
# 1. Static scan (taint-aware: findings may carry taint_path + cwe)
|
|
55
|
+
findings = scan([Path(p) for p in paths], lang=lang)
|
|
56
|
+
|
|
57
|
+
# 2. Code graph for entry points / containing functions
|
|
58
|
+
graph = CodeGraph(root)
|
|
59
|
+
graph.build()
|
|
60
|
+
|
|
61
|
+
# 3. Assemble issues with evidence
|
|
62
|
+
sources: dict[str, str] = {}
|
|
63
|
+
audit_issues: list[AuditIssue] = []
|
|
64
|
+
for f in findings:
|
|
65
|
+
if f.file not in sources:
|
|
66
|
+
try:
|
|
67
|
+
with open(f.file, encoding="utf-8-sig", errors="replace") as fh:
|
|
68
|
+
sources[f.file] = fh.read()
|
|
69
|
+
except OSError:
|
|
70
|
+
sources[f.file] = ""
|
|
71
|
+
|
|
72
|
+
containing_func = _find_containing_func(graph, f.file, f.line)
|
|
73
|
+
chain_path = [(f.file, containing_func.line, containing_func.name)] if containing_func else []
|
|
74
|
+
ep = ""
|
|
75
|
+
for entry in graph.entry_points:
|
|
76
|
+
if _entry_in_file(entry, f.file):
|
|
77
|
+
ep = f'{entry.kind}: {entry.pattern or entry.location}'
|
|
78
|
+
break
|
|
79
|
+
|
|
80
|
+
audit_issues.append(AuditIssue(
|
|
81
|
+
rule_id=f.rule_id, message=f.message, message_zh=getattr(f, "message_zh", ""),
|
|
82
|
+
file=f.file, line=f.line, static_severity=f.severity.value,
|
|
83
|
+
snippet=f.snippet or "", cwe=f.cwe, entry_point=ep, evidence_chain=chain_path,
|
|
84
|
+
taint_paths=[p.render() for p in (f.taint_path or [])],
|
|
85
|
+
))
|
|
86
|
+
|
|
87
|
+
# 4. AI verdicts grounded in taint paths + enclosing functions
|
|
88
|
+
ai_summary = {"provider": "disabled", "model": "",
|
|
89
|
+
"confirmed": 0, "false_positive": 0, "unverified": 0, "total": 0}
|
|
90
|
+
if use_ai:
|
|
91
|
+
cfg = load_ai_config()
|
|
92
|
+
if cfg.provider != "mock":
|
|
93
|
+
evidences = []
|
|
94
|
+
for issue, f in zip(audit_issues, findings):
|
|
95
|
+
src = sources.get(issue.file, "")
|
|
96
|
+
evidences.append(FindingEvidence(
|
|
97
|
+
rule_id=issue.rule_id, cwe=f.cwe, severity=issue.static_severity,
|
|
98
|
+
message=issue.message, file=issue.file, line=issue.line,
|
|
99
|
+
snippet=issue.snippet, fix=f.fix,
|
|
100
|
+
function_source=enclosing_function_source(src, issue.line),
|
|
101
|
+
imports=imports_block(src),
|
|
102
|
+
taint_paths=list(f.taint_path or []),
|
|
103
|
+
))
|
|
104
|
+
verdicts = verify_findings(evidences, cfg)
|
|
105
|
+
for issue, v in zip(audit_issues, verdicts):
|
|
106
|
+
issue.ai_status = v.get("ai_status", "unverified")
|
|
107
|
+
issue.ai_confidence = v.get("ai_confidence", 0.0)
|
|
108
|
+
issue.ai_reason = v.get("ai_reason", "")
|
|
109
|
+
issue.ai_severity = v.get("ai_severity", "")
|
|
110
|
+
issue.ai_cwe = v.get("ai_cwe", "")
|
|
111
|
+
issue.ai_vuln_type = v.get("ai_vuln_type", "")
|
|
112
|
+
issue.ai_suggested_fix = v.get("ai_suggested_fix", "")
|
|
113
|
+
ai_summary = {
|
|
114
|
+
"provider": cfg.provider, "model": cfg.model,
|
|
115
|
+
"confirmed": sum(1 for i in audit_issues if i.ai_status == "confirmed"),
|
|
116
|
+
"false_positive": sum(1 for i in audit_issues if i.ai_status == "false_positive"),
|
|
117
|
+
"unverified": sum(1 for i in audit_issues if i.ai_status == "unverified"),
|
|
118
|
+
"total": len(audit_issues),
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
elapsed = time.time() - start
|
|
122
|
+
return {
|
|
123
|
+
"tool": "aicaudit",
|
|
124
|
+
"version": "0.1.0",
|
|
125
|
+
"paths": [str(p) for p in paths],
|
|
126
|
+
"scan": {"findings": len(audit_issues), "files": len(graph.files),
|
|
127
|
+
"duration_s": round(elapsed, 2),
|
|
128
|
+
"taint_paths_traced": sum(1 for i in audit_issues if i.taint_paths)},
|
|
129
|
+
"ai": ai_summary,
|
|
130
|
+
"issues": [
|
|
131
|
+
{
|
|
132
|
+
"rule_id": i.rule_id, "message": i.message,
|
|
133
|
+
"message_zh": i.message_zh, "file": i.file, "line": i.line,
|
|
134
|
+
"static_severity": i.static_severity, "snippet": i.snippet,
|
|
135
|
+
"cwe": i.cwe, "entry_point": i.entry_point,
|
|
136
|
+
"evidence_chain": i.evidence_chain, "taint_paths": i.taint_paths,
|
|
137
|
+
"ai": {
|
|
138
|
+
"status": i.ai_status or None,
|
|
139
|
+
"confidence": i.ai_confidence,
|
|
140
|
+
"reason": i.ai_reason,
|
|
141
|
+
"severity": i.ai_severity, "cwe": i.ai_cwe,
|
|
142
|
+
"vuln_type": i.ai_vuln_type, "suggested_fix": i.ai_suggested_fix,
|
|
143
|
+
},
|
|
144
|
+
}
|
|
145
|
+
for i in audit_issues
|
|
146
|
+
],
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _find_containing_func(graph, file_path, line):
|
|
151
|
+
"""Find the function that contains the given line in a file."""
|
|
152
|
+
target = file_path.replace('\\', '/')
|
|
153
|
+
target_base = target.split('/')[-1]
|
|
154
|
+
best = None
|
|
155
|
+
for funcs in graph.funcs.values():
|
|
156
|
+
for fd in funcs:
|
|
157
|
+
fd_base = fd.file.replace('\\', '/').split('/')[-1]
|
|
158
|
+
if fd_base == target_base and fd.line <= line and (best is None or fd.line > best.line):
|
|
159
|
+
best = fd
|
|
160
|
+
return best
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _entry_in_file(entry, file_path):
|
|
164
|
+
"""Check if an entry point is in the given file (basename match)."""
|
|
165
|
+
entry_f = entry.location.split(':')[0].replace('\\', '/').split('/')[-1]
|
|
166
|
+
target = file_path.replace('\\', '/').split('/')[-1]
|
|
167
|
+
return entry_f == target
|
aicaudit/cli.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Command-line interface for AICAudit."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from aicaudit.config import find_project_root, merge_config
|
|
8
|
+
from aicaudit.output.json_output import dump_json
|
|
9
|
+
from aicaudit.output.markdown_output import dump_markdown
|
|
10
|
+
from aicaudit.output.sarif_output import dump_sarif
|
|
11
|
+
from aicaudit.scan import _import_all_rules, scan
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@click.group()
|
|
15
|
+
@click.version_option("0.2.0")
|
|
16
|
+
def main():
|
|
17
|
+
"""AICAudit — AI-powered code audit for Python projects."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@main.command()
|
|
21
|
+
@click.option("--host", default="127.0.0.1", help="Host to bind")
|
|
22
|
+
@click.option("--port", default=8080, help="Port to bind")
|
|
23
|
+
@click.option("--reload", is_flag=True, help="Auto-reload on changes")
|
|
24
|
+
def web(host, port, reload):
|
|
25
|
+
"""Start AICAudit Web UI."""
|
|
26
|
+
from aicaudit.web.server import run_server
|
|
27
|
+
run_server(host=host, port=port, reload=reload)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@main.command()
|
|
32
|
+
@click.argument("paths", nargs=-1, type=click.Path(exists=True))
|
|
33
|
+
@click.option("--output", "-o", type=click.Choice(["json", "markdown", "sarif"]), default="markdown",
|
|
34
|
+
help="Output format: json, markdown, or sarif")
|
|
35
|
+
@click.option("--lang", type=click.Choice(["en", "zh"]), default="en",
|
|
36
|
+
help="Output language: en or zh")
|
|
37
|
+
@click.option("--ai", is_flag=True, help="Attach AI verdicts to findings (marks, never hides)")
|
|
38
|
+
@click.option("--ai-strict", is_flag=True,
|
|
39
|
+
help="With --ai: keep only AI-confirmed findings (can suppress true positives)")
|
|
40
|
+
@click.option("--rules", default=None,
|
|
41
|
+
help="Comma-separated rule IDs to run, e.g. --rules S001,Q001")
|
|
42
|
+
@click.option("--min-severity", type=click.Choice(["info", "warning", "error", "critical"]),
|
|
43
|
+
default=None, help="Minimum severity to report")
|
|
44
|
+
@click.option("--fail-on", "fail_on", type=click.Choice(["info", "warning", "error", "critical"]),
|
|
45
|
+
default=None,
|
|
46
|
+
help="CI gate: exit 1 when any finding is at or above this severity "
|
|
47
|
+
"(exit 0 = clean, 1 = threshold exceeded, 2 = usage error)")
|
|
48
|
+
def scan_cmd(paths, output, lang, ai, ai_strict, rules, min_severity, fail_on):
|
|
49
|
+
"""Scan Python files for code issues."""
|
|
50
|
+
if not paths:
|
|
51
|
+
paths = ["."]
|
|
52
|
+
|
|
53
|
+
start = Path(paths[0])
|
|
54
|
+
# Load config (file + CLI overrides)
|
|
55
|
+
cfg = merge_config(rules, min_severity, start)
|
|
56
|
+
|
|
57
|
+
click.echo(f"Scanning {len(paths)} path(s)...", err=True)
|
|
58
|
+
findings = scan(
|
|
59
|
+
[Path(p) for p in paths],
|
|
60
|
+
lang=lang,
|
|
61
|
+
rules=cfg.rules or None,
|
|
62
|
+
min_severity=cfg.min_severity,
|
|
63
|
+
ignore_patterns=cfg.ignore_patterns,
|
|
64
|
+
base_root=find_project_root(start),
|
|
65
|
+
ai_verify=ai,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
if ai and ai_strict:
|
|
69
|
+
before = len(findings)
|
|
70
|
+
findings = [f for f in findings if (f.ai or {}).get("ai_status") == "confirmed"]
|
|
71
|
+
click.echo(f"--ai-strict: {before} findings -> {len(findings)} AI-confirmed", err=True)
|
|
72
|
+
|
|
73
|
+
if not findings:
|
|
74
|
+
click.echo("No issues found.", err=True)
|
|
75
|
+
_exit_code(findings, fail_on)
|
|
76
|
+
return
|
|
77
|
+
|
|
78
|
+
if output == "json":
|
|
79
|
+
click.echo(dump_json(findings, lang=lang))
|
|
80
|
+
elif output == "sarif":
|
|
81
|
+
click.echo(dump_sarif(findings, lang=lang))
|
|
82
|
+
else:
|
|
83
|
+
click.echo(dump_markdown(findings, lang=lang))
|
|
84
|
+
|
|
85
|
+
# AI mode: show fix previews (dry-run only)
|
|
86
|
+
if ai:
|
|
87
|
+
from aicaudit.fix import fix_file
|
|
88
|
+
seen = set()
|
|
89
|
+
for f in findings:
|
|
90
|
+
if f.file in seen or not f.fix:
|
|
91
|
+
continue
|
|
92
|
+
seen.add(f.file)
|
|
93
|
+
p = Path(f.file)
|
|
94
|
+
if p.exists():
|
|
95
|
+
result = fix_file(str(p), [f], dry_run=True, backup=False)
|
|
96
|
+
if result.after and result.after != result.before:
|
|
97
|
+
_print_fix_diff(result)
|
|
98
|
+
click.echo("", err=True)
|
|
99
|
+
click.echo("Fix previews above are dry-run only; nothing was written.", err=True)
|
|
100
|
+
|
|
101
|
+
_exit_code(findings, fail_on)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _exit_code(findings, fail_on):
|
|
105
|
+
"""CI gate: exit 1 when findings reach the threshold (click ctx.exit)."""
|
|
106
|
+
if not fail_on:
|
|
107
|
+
return
|
|
108
|
+
rank = {"info": 0, "warning": 1, "error": 2, "critical": 3}
|
|
109
|
+
threshold = rank[fail_on]
|
|
110
|
+
exceeded = [f for f in findings if rank.get(f.severity.value, 0) >= threshold]
|
|
111
|
+
if exceeded:
|
|
112
|
+
click.echo(f"fail-on {fail_on}: {len(exceeded)} finding(s) at or above threshold", err=True)
|
|
113
|
+
click.get_current_context().exit(1)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@main.command()
|
|
117
|
+
def rules():
|
|
118
|
+
"""List all registered audit rules."""
|
|
119
|
+
_import_all_rules()
|
|
120
|
+
from aicaudit.rules.base import all_rules
|
|
121
|
+
for cls in all_rules():
|
|
122
|
+
r = cls()
|
|
123
|
+
click.echo(f" {r.id:6s} {r.severity.value:8s} {r.name}")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@main.command()
|
|
127
|
+
@click.option("--min-severity", type=click.Choice(["info", "warning", "error", "critical"]),
|
|
128
|
+
default=None, help="Minimum severity to report (skip the prompt)")
|
|
129
|
+
@click.option("--ignore", default=None,
|
|
130
|
+
help="Comma-separated glob patterns to ignore (skip the prompt)")
|
|
131
|
+
@click.option("--yes", "-y", is_flag=True, help="Accept defaults without prompting")
|
|
132
|
+
def init_cmd(min_severity, ignore, yes):
|
|
133
|
+
"""Create or update the [tool.aicaudit] section in pyproject.toml."""
|
|
134
|
+
root = find_project_root(Path.cwd())
|
|
135
|
+
pyproject = root / "pyproject.toml"
|
|
136
|
+
|
|
137
|
+
default_sev = "warning"
|
|
138
|
+
if min_severity:
|
|
139
|
+
sev = min_severity
|
|
140
|
+
elif yes:
|
|
141
|
+
sev = default_sev
|
|
142
|
+
else:
|
|
143
|
+
sev = click.prompt("Minimum severity to report", default=default_sev,
|
|
144
|
+
type=click.Choice(["info", "warning", "error", "critical"]))
|
|
145
|
+
|
|
146
|
+
if ignore is not None:
|
|
147
|
+
ignores = [p.strip() for p in ignore.split(",") if p.strip()]
|
|
148
|
+
elif yes:
|
|
149
|
+
ignores = []
|
|
150
|
+
else:
|
|
151
|
+
raw = click.prompt("Ignore patterns (comma-separated globs, empty for none)", default="")
|
|
152
|
+
ignores = [p.strip() for p in raw.split(",") if p.strip()]
|
|
153
|
+
|
|
154
|
+
section = _render_aicaudit_section(sev, ignores)
|
|
155
|
+
|
|
156
|
+
if pyproject.exists():
|
|
157
|
+
text = pyproject.read_text(encoding="utf-8")
|
|
158
|
+
if "[tool.aicaudit]" in text:
|
|
159
|
+
text = _replace_section(text, section)
|
|
160
|
+
action = "updated"
|
|
161
|
+
else:
|
|
162
|
+
text = text.rstrip("\n") + "\n\n" + section
|
|
163
|
+
action = "updated"
|
|
164
|
+
else:
|
|
165
|
+
text = section
|
|
166
|
+
action = "created"
|
|
167
|
+
pyproject.write_text(text, encoding="utf-8")
|
|
168
|
+
|
|
169
|
+
click.echo(f"{action}: {pyproject}")
|
|
170
|
+
click.echo(section.rstrip())
|
|
171
|
+
click.echo("Custom rules: drop .py rule files into .aicaudit/rules/ "
|
|
172
|
+
"or set rule-dirs in the section above.", err=True)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _render_aicaudit_section(min_severity, ignores):
|
|
176
|
+
lines = ["[tool.aicaudit]", f'min-severity = "{min_severity}"']
|
|
177
|
+
if ignores:
|
|
178
|
+
joined = ", ".join(f'"{g}"' for g in ignores)
|
|
179
|
+
lines.append(f"ignore = [{joined}]")
|
|
180
|
+
lines.append('# rule-dirs = ["custom_rules"] # extra dirs with Python rule files')
|
|
181
|
+
return "\n".join(lines) + "\n"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _replace_section(text, new_section):
|
|
185
|
+
"""Replace an existing [tool.aicaudit] section (until the next [section])."""
|
|
186
|
+
import re
|
|
187
|
+
pattern = re.compile(r"\[tool\.aicaudit\][^\[]*", re.DOTALL)
|
|
188
|
+
if pattern.search(text):
|
|
189
|
+
return pattern.sub(new_section, text, count=1)
|
|
190
|
+
return text.rstrip("\n") + "\n\n" + new_section
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
if __name__ == "__main__":
|
|
194
|
+
main()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _print_fix_diff(result):
|
|
198
|
+
"""Print a unified diff for a proposed fix."""
|
|
199
|
+
import difflib
|
|
200
|
+
import sys
|
|
201
|
+
if result.before == result.after:
|
|
202
|
+
return
|
|
203
|
+
diff = difflib.unified_diff(
|
|
204
|
+
result.before.splitlines(keepends=True),
|
|
205
|
+
result.after.splitlines(keepends=True),
|
|
206
|
+
fromfile=result.path, tofile=result.path + " (fixed)", n=2,
|
|
207
|
+
)
|
|
208
|
+
print("".join(diff), file=sys.stderr)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@main.command()
|
|
212
|
+
@click.argument("paths", nargs=-1, type=click.Path(exists=True))
|
|
213
|
+
@click.option("--lang", type=click.Choice(["en", "zh"]), default="en")
|
|
214
|
+
@click.option("--no-ai", is_flag=True, help="Disable AI deep-audit")
|
|
215
|
+
@click.option("--output", "-o", type=click.Choice(["json", "markdown"]), default="markdown")
|
|
216
|
+
def audit_cmd(paths, lang, no_ai, output):
|
|
217
|
+
"""AI deep audit: static + graph + AI verdict with evidence chains."""
|
|
218
|
+
if not paths:
|
|
219
|
+
paths = ["."]
|
|
220
|
+
from aicaudit.audit import run_audit
|
|
221
|
+
report = run_audit(paths, lang=lang, use_ai=not no_ai)
|
|
222
|
+
import json
|
|
223
|
+
if output == "json":
|
|
224
|
+
click.echo(json.dumps(report, indent=2, ensure_ascii=False))
|
|
225
|
+
else:
|
|
226
|
+
click.echo(_format_audit_markdown(report, lang))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _format_audit_markdown(report, lang):
|
|
230
|
+
lines = ['# AICAudit Deep Audit', '']
|
|
231
|
+
scan = report['scan']
|
|
232
|
+
ai = report['ai']
|
|
233
|
+
lines.append('**Scan**: {} findings / {} files / {}s'.format(scan['findings'], scan['files'], scan['duration_s']))
|
|
234
|
+
lines.append('**Evidence chains**: {} paths traced'.format(scan['evidence_chains_traced']))
|
|
235
|
+
lines.append('**AI**: provider={} confirmed {}/{}'.format(ai['provider'], ai['confirmed'], ai['total']))
|
|
236
|
+
lines.append('')
|
|
237
|
+
for issue in report['issues']:
|
|
238
|
+
lines.append('### {}: {}'.format(issue['rule_id'], issue['message']))
|
|
239
|
+
mark = '' + issue['file'] + ':' + str(issue['line']) + ''
|
|
240
|
+
lines.append('- **File**: ' + mark)
|
|
241
|
+
lines.append('- **Static severity**: ' + issue['static_severity'])
|
|
242
|
+
if issue.get('entry_point'):
|
|
243
|
+
lines.append('- **Entry point**: ' + issue['entry_point'])
|
|
244
|
+
if issue.get('evidence_chain'):
|
|
245
|
+
ps = ' -> '.join(f'{fp}:{ln}({fn})' for fp, ln, fn in issue['evidence_chain'])
|
|
246
|
+
lines.append('- **Evidence chain**: ' + ps)
|
|
247
|
+
ai_issue = issue.get('ai') or {}
|
|
248
|
+
if ai_issue.get('confirmed') is not None:
|
|
249
|
+
verdict = 'confirmed' if ai_issue['confirmed'] else 'false positive'
|
|
250
|
+
lines.append('- **AI verdict**: ' + verdict)
|
|
251
|
+
if ai_issue.get('reason'):
|
|
252
|
+
lines.append('- **AI reason**: ' + ai_issue['reason'])
|
|
253
|
+
if ai_issue.get('suggested_fix'):
|
|
254
|
+
lines.append('- **Suggested fix**: ' + ai_issue['suggested_fix'])
|
|
255
|
+
lines.append('')
|
|
256
|
+
return chr(10).join(lines)
|
aicaudit/config.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Configuration loading for AICAudit.
|
|
2
|
+
|
|
3
|
+
Reads settings from:
|
|
4
|
+
1. pyproject.toml [tool.aicaudit] section (project level)
|
|
5
|
+
2. .aicauditignore file (path exclusions)
|
|
6
|
+
3. CLI arguments (highest priority, overrides config)
|
|
7
|
+
|
|
8
|
+
Design notes:
|
|
9
|
+
- Never crash on bad config — fall back to sane defaults
|
|
10
|
+
- Rule filters use closed sets, validated against the registry
|
|
11
|
+
- Path ignores support glob patterns
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class AuditConfig:
|
|
23
|
+
rules: set[str] = field(default_factory=set) # empty = run all
|
|
24
|
+
min_severity: str | None = None # None = no filter
|
|
25
|
+
ignore_patterns: list[str] = field(default_factory=list)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def find_project_root(start: Path) -> Path:
|
|
29
|
+
"""Walk up to find the directory containing pyproject.toml or setup.py."""
|
|
30
|
+
for current in [start, *start.parents]:
|
|
31
|
+
if (current / "pyproject.toml").exists() or (current / "setup.py").exists():
|
|
32
|
+
return current
|
|
33
|
+
return start
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_pyproject(root: Path) -> dict:
|
|
37
|
+
"""Load [tool.aicaudit] from pyproject.toml. Never raises."""
|
|
38
|
+
# Python 3.10 uses tomli; 3.11+ has tomllib built in
|
|
39
|
+
try:
|
|
40
|
+
import tomllib
|
|
41
|
+
except ImportError: # pragma: no cover - py3.10 compat
|
|
42
|
+
import tomli as tomllib # type: ignore
|
|
43
|
+
|
|
44
|
+
pyproject = root / "pyproject.toml"
|
|
45
|
+
if not pyproject.exists():
|
|
46
|
+
return {}
|
|
47
|
+
try:
|
|
48
|
+
with open(pyproject, "rb") as f:
|
|
49
|
+
data = tomllib.load(f)
|
|
50
|
+
return data.get("tool", {}).get("aicaudit", {})
|
|
51
|
+
except Exception: # noqa: BLE001 - broken config should not crash the tool
|
|
52
|
+
return {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load_ignore_file(root: Path) -> list[str]:
|
|
56
|
+
"""Read .aicauditignore (one glob per line, empty/comment lines skipped)."""
|
|
57
|
+
path = root / ".aicauditignore"
|
|
58
|
+
if not path.exists():
|
|
59
|
+
return []
|
|
60
|
+
patterns = []
|
|
61
|
+
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
62
|
+
line = line.strip()
|
|
63
|
+
if line and not line.startswith("#"):
|
|
64
|
+
patterns.append(line)
|
|
65
|
+
return patterns
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def merge_config(cli_rules, cli_min_severity, start: Path | None = None) -> AuditConfig:
|
|
69
|
+
"""Merge config file + .aicauditignore + CLI overrides."""
|
|
70
|
+
root = find_project_root(start or Path.cwd())
|
|
71
|
+
file_cfg = load_pyproject(root)
|
|
72
|
+
ignore_patterns = load_ignore_file(root)
|
|
73
|
+
|
|
74
|
+
# rules: CLI wins, else config
|
|
75
|
+
rules: set[str] = set()
|
|
76
|
+
if cli_rules:
|
|
77
|
+
rules = {r.strip().upper() for r in cli_rules.split(",") if r.strip()}
|
|
78
|
+
elif file_cfg.get("rules"):
|
|
79
|
+
rules = {str(r).strip().upper() for r in file_cfg["rules"] if str(r).strip()}
|
|
80
|
+
|
|
81
|
+
# min-severity: CLI wins, else config
|
|
82
|
+
min_sev = cli_min_severity or file_cfg.get("min-severity") or file_cfg.get("min_severity")
|
|
83
|
+
|
|
84
|
+
# ignore: config file patterns + .aicauditignore patterns
|
|
85
|
+
ignore = list(file_cfg.get("ignore", []))
|
|
86
|
+
ignore.extend(ignore_patterns)
|
|
87
|
+
|
|
88
|
+
return AuditConfig(
|
|
89
|
+
rules=rules,
|
|
90
|
+
min_severity=str(min_sev) if min_sev else None,
|
|
91
|
+
ignore_patterns=[str(p) for p in ignore],
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def matches_ignore(path: Path, patterns: list[str], root: Path | None = None) -> bool:
|
|
96
|
+
"""Check if path matches any ignore pattern (glob)."""
|
|
97
|
+
if not patterns:
|
|
98
|
+
return False
|
|
99
|
+
base = root or Path.cwd()
|
|
100
|
+
try:
|
|
101
|
+
rel = path.relative_to(base)
|
|
102
|
+
except ValueError:
|
|
103
|
+
rel = path
|
|
104
|
+
rel_str = str(rel).replace(os.sep, "/")
|
|
105
|
+
for pat in patterns:
|
|
106
|
+
p = pat.replace(os.sep, "/").strip("/")
|
|
107
|
+
if p and (rel_str == p or rel_str.startswith(p + "/") or _fnmatch(rel_str, p)):
|
|
108
|
+
return True
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _fnmatch(name: str, pattern: str) -> bool:
|
|
113
|
+
"""Minimal glob matcher: * matches any chars, ** matches across /"""
|
|
114
|
+
import fnmatch
|
|
115
|
+
if "**" in pattern:
|
|
116
|
+
parts = pattern.split("**")
|
|
117
|
+
if len(parts) == 2:
|
|
118
|
+
prefix, suffix = parts
|
|
119
|
+
return name.startswith(prefix) and name.endswith(suffix)
|
|
120
|
+
return fnmatch.fnmatch(name, pattern)
|