|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import ast |
| 4 | +from datetime import datetime, timezone |
| 5 | +import hashlib |
| 6 | +from importlib.metadata import PackageNotFoundError, version |
| 7 | +import json |
| 8 | +import platform |
| 9 | +from pathlib import Path |
| 10 | +from typing import Any |
| 11 | + |
| 12 | + |
| 13 | +SENSITIVE_IMPORTS = { |
| 14 | + "ctypes", |
| 15 | + "marshal", |
| 16 | + "mmap", |
| 17 | + "pickle", |
| 18 | + "socket", |
| 19 | + "subprocess", |
| 20 | + "winreg", |
| 21 | +} |
| 22 | + |
| 23 | +SENSITIVE_CALLS = { |
| 24 | + "__import__", |
| 25 | + "compile", |
| 26 | + "eval", |
| 27 | + "exec", |
| 28 | + "marshal.loads", |
| 29 | + "os.execl", |
| 30 | + "os.execle", |
| 31 | + "os.execlp", |
| 32 | + "os.execlpe", |
| 33 | + "os.execv", |
| 34 | + "os.execve", |
| 35 | + "os.execvp", |
| 36 | + "os.execvpe", |
| 37 | + "os.popen", |
| 38 | + "os.spawnl", |
| 39 | + "os.spawnle", |
| 40 | + "os.spawnlp", |
| 41 | + "os.spawnlpe", |
| 42 | + "os.spawnv", |
| 43 | + "os.spawnve", |
| 44 | + "os.spawnvp", |
| 45 | + "os.spawnvpe", |
| 46 | + "os.system", |
| 47 | + "pickle.loads", |
| 48 | + "subprocess.call", |
| 49 | + "subprocess.check_call", |
| 50 | + "subprocess.check_output", |
| 51 | + "subprocess.Popen", |
| 52 | + "subprocess.run", |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +def sha256_text(value: str) -> str: |
| 57 | + return hashlib.sha256(value.encode("utf-8")).hexdigest() |
| 58 | + |
| 59 | + |
| 60 | +def _utc_now() -> str: |
| 61 | + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 62 | + |
| 63 | + |
| 64 | +def _tool_version() -> str: |
| 65 | + try: |
| 66 | + return version("patchwork") |
| 67 | + except PackageNotFoundError: |
| 68 | + return "0.2.0" |
| 69 | + |
| 70 | + |
| 71 | +def _call_name(node: ast.AST) -> str | None: |
| 72 | + if isinstance(node, ast.Name): |
| 73 | + return node.id |
| 74 | + if isinstance(node, ast.Attribute): |
| 75 | + parent = _call_name(node.value) |
| 76 | + if parent: |
| 77 | + return f"{parent}.{node.attr}" |
| 78 | + return node.attr |
| 79 | + return None |
| 80 | + |
| 81 | + |
| 82 | +class AuditVisitor(ast.NodeVisitor): |
| 83 | + def __init__(self) -> None: |
| 84 | + self.imports: set[str] = set() |
| 85 | + self.functions: list[str] = [] |
| 86 | + self.classes: list[str] = [] |
| 87 | + self.review_indicators: list[dict[str, object]] = [] |
| 88 | + self.node_count = 0 |
| 89 | + |
| 90 | + def generic_visit(self, node: ast.AST) -> None: |
| 91 | + self.node_count += 1 |
| 92 | + super().generic_visit(node) |
| 93 | + |
| 94 | + def visit_Import(self, node: ast.Import) -> None: |
| 95 | + for alias in node.names: |
| 96 | + top_level = alias.name.split(".", 1)[0] |
| 97 | + self.imports.add(alias.name) |
| 98 | + if top_level in SENSITIVE_IMPORTS: |
| 99 | + self.review_indicators.append( |
| 100 | + { |
| 101 | + "kind": "import", |
| 102 | + "name": alias.name, |
| 103 | + "line": node.lineno, |
| 104 | + "reason": "sensitive standard-library capability", |
| 105 | + } |
| 106 | + ) |
| 107 | + self.generic_visit(node) |
| 108 | + |
| 109 | + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: |
| 110 | + module = node.module or "" |
| 111 | + if module: |
| 112 | + self.imports.add(module) |
| 113 | + top_level = module.split(".", 1)[0] |
| 114 | + if top_level in SENSITIVE_IMPORTS: |
| 115 | + self.review_indicators.append( |
| 116 | + { |
| 117 | + "kind": "import", |
| 118 | + "name": module, |
| 119 | + "line": node.lineno, |
| 120 | + "reason": "sensitive standard-library capability", |
| 121 | + } |
| 122 | + ) |
| 123 | + self.generic_visit(node) |
| 124 | + |
| 125 | + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: |
| 126 | + self.functions.append(node.name) |
| 127 | + self.generic_visit(node) |
| 128 | + |
| 129 | + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: |
| 130 | + self.functions.append(node.name) |
| 131 | + self.generic_visit(node) |
| 132 | + |
| 133 | + def visit_ClassDef(self, node: ast.ClassDef) -> None: |
| 134 | + self.classes.append(node.name) |
| 135 | + self.generic_visit(node) |
| 136 | + |
| 137 | + def visit_Call(self, node: ast.Call) -> None: |
| 138 | + name = _call_name(node.func) |
| 139 | + if name in SENSITIVE_CALLS: |
| 140 | + self.review_indicators.append( |
| 141 | + { |
| 142 | + "kind": "call", |
| 143 | + "name": name, |
| 144 | + "line": node.lineno, |
| 145 | + "reason": "dynamic execution or process capability", |
| 146 | + } |
| 147 | + ) |
| 148 | + self.generic_visit(node) |
| 149 | + |
| 150 | + |
| 151 | +def analyze_source(source: str, *, path: str | Path | None = None) -> dict[str, Any]: |
| 152 | + tree = ast.parse(source, filename=str(path or "<memory>")) |
| 153 | + visitor = AuditVisitor() |
| 154 | + visitor.visit(tree) |
| 155 | + review_indicators = sorted(visitor.review_indicators, key=lambda item: (int(item["line"]), str(item["name"]))) |
| 156 | + return { |
| 157 | + "path": str(path) if path else None, |
| 158 | + "sha256": sha256_text(source), |
| 159 | + "lines": source.count("\n") + (1 if source else 0), |
| 160 | + "bytes_utf8": len(source.encode("utf-8")), |
| 161 | + "ast_nodes": visitor.node_count, |
| 162 | + "imports": sorted(visitor.imports), |
| 163 | + "functions": sorted(visitor.functions), |
| 164 | + "classes": sorted(visitor.classes), |
| 165 | + "review": { |
| 166 | + "indicator_count": len(review_indicators), |
| 167 | + "requires_human_review": bool(review_indicators), |
| 168 | + "indicators": review_indicators, |
| 169 | + }, |
| 170 | + } |
| 171 | + |
| 172 | + |
| 173 | +def build_manifest( |
| 174 | + *, |
| 175 | + input_path: str | Path, |
| 176 | + output_path: str | Path, |
| 177 | + input_source: str, |
| 178 | + output_source: str, |
| 179 | + seed: int, |
| 180 | + options: dict[str, object], |
| 181 | + audit: dict[str, Any], |
| 182 | +) -> dict[str, Any]: |
| 183 | + return { |
| 184 | + "schema": "patchwork.manifest.v1", |
| 185 | + "generated_at": _utc_now(), |
| 186 | + "tool": { |
| 187 | + "name": "patchwork", |
| 188 | + "version": _tool_version(), |
| 189 | + "python": platform.python_version(), |
| 190 | + "platform": platform.platform(), |
| 191 | + }, |
| 192 | + "input": { |
| 193 | + "path": str(input_path), |
| 194 | + "sha256": sha256_text(input_source), |
| 195 | + "bytes_utf8": len(input_source.encode("utf-8")), |
| 196 | + }, |
| 197 | + "output": { |
| 198 | + "path": str(output_path), |
| 199 | + "sha256": sha256_text(output_source), |
| 200 | + "bytes_utf8": len(output_source.encode("utf-8")), |
| 201 | + }, |
| 202 | + "build": { |
| 203 | + "seed": seed, |
| 204 | + "options": options, |
| 205 | + }, |
| 206 | + "audit": audit, |
| 207 | + } |
| 208 | + |
| 209 | + |
| 210 | +def write_json(path: str | Path, data: dict[str, Any]) -> Path: |
| 211 | + output_path = Path(path) |
| 212 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 213 | + output_path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8") |
| 214 | + return output_path |
0 commit comments