git-finalizer 2.0.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.
@@ -0,0 +1,165 @@
1
+ """Exact unified-diff `.patch` single-space empty-context whitespace classifier."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from git_finalizer.errors import ErrorCode, FinalizerError
8
+ from git_finalizer.git_io import clean_git_env, run_git
9
+
10
+ MAX_PATCH_BYTES = 1_048_576
11
+ HUNK_HEADER_RE = re.compile(
12
+ rb"^@@ -(?P<old_start>[0-9]+)(?:,(?P<old_count>[0-9]+))? "
13
+ rb"\+(?P<new_start>[0-9]+)(?:,(?P<new_count>[0-9]+))? @@"
14
+ )
15
+
16
+
17
+ def parse_counted_patch_empty_context_lines(raw: bytes) -> tuple[bool, set[int], int]:
18
+ """Verify `.patch` structure and return (valid, empty_context_1_based_lines, line_count)."""
19
+ if len(raw) > MAX_PATCH_BYTES or b"\0" in raw:
20
+ return False, set(), 0
21
+ lines = raw.splitlines(keepends=True)
22
+ if not lines or not lines[-1].endswith(b"\n"):
23
+ return False, set(), 0
24
+
25
+ in_hunk = False
26
+ old_left = 0
27
+ new_left = 0
28
+ saw_hunk = False
29
+ empty_context_lines: set[int] = set()
30
+
31
+ for lineno, line_with_nl in enumerate(lines, start=1):
32
+ line = line_with_nl[:-1]
33
+ if line.endswith(b"\r"):
34
+ return False, set(), 0
35
+ if in_hunk:
36
+ if line == b"\":
37
+ continue
38
+ if line.startswith(b" "):
39
+ if line == b" ":
40
+ empty_context_lines.add(lineno)
41
+ elif line.endswith((b" ", b"\t")):
42
+ return False, set(), 0
43
+ old_left -= 1
44
+ new_left -= 1
45
+ elif line.startswith(b"-"):
46
+ old_left -= 1
47
+ elif line.startswith(b"+"):
48
+ if line.endswith((b" ", b"\t")):
49
+ return False, set(), 0
50
+ new_left -= 1
51
+ else:
52
+ return False, set(), 0
53
+ if old_left < 0 or new_left < 0:
54
+ return False, set(), 0
55
+ if old_left == 0 and new_left == 0:
56
+ in_hunk = False
57
+ continue
58
+
59
+ match = HUNK_HEADER_RE.match(line)
60
+ if match:
61
+ saw_hunk = True
62
+ old_left = int(match.group("old_count") or b"1")
63
+ new_left = int(match.group("new_count") or b"1")
64
+ in_hunk = old_left > 0 or new_left > 0
65
+ continue
66
+ if line.endswith((b" ", b"\t")):
67
+ return False, set(), 0
68
+
69
+ if in_hunk or not saw_hunk:
70
+ return False, set(), 0
71
+ return True, empty_context_lines, len(lines)
72
+
73
+
74
+ def allow_patch_context_whitespace_only(
75
+ repo,
76
+ path: str,
77
+ raw: bytes,
78
+ diff_check_output: str,
79
+ *,
80
+ env: dict[str, str] | None = None,
81
+ ) -> bool:
82
+ """Return True iff every whitespace diagnostic in `diff_check_output` is a valid counted-hunk empty context space."""
83
+ if not path.endswith(".patch"):
84
+ return False
85
+ valid, allowed_lines, total_lines = parse_counted_patch_empty_context_lines(raw)
86
+ if not valid or not allowed_lines:
87
+ return False
88
+
89
+ # Confirm Git itself parses the patch cleanly with apply --numstat without applying it.
90
+ try:
91
+ applied = run_git(
92
+ repo,
93
+ "apply",
94
+ "--numstat",
95
+ "-",
96
+ timeout=15.0,
97
+ env=clean_git_env(env),
98
+ input_data=raw,
99
+ )
100
+ except FinalizerError:
101
+ return False
102
+ if applied.returncode != 0:
103
+ return False
104
+
105
+ for raw_diag in diff_check_output.splitlines():
106
+ diag = raw_diag.strip()
107
+ if not diag:
108
+ continue
109
+ # Formats emitted by git diff --check:
110
+ # <path>:<lineno>: trailing whitespace.
111
+ # <path>:<lineno>: new blank line at EOF.
112
+ prefix = f"{path}:"
113
+ if not diag.startswith(prefix):
114
+ return False
115
+ rest = diag[len(prefix) :]
116
+ line_str, sep, message = rest.partition(":")
117
+ if not sep or not line_str.isdigit():
118
+ return False
119
+ lineno = int(line_str)
120
+ msg = message.strip()
121
+ if msg == "trailing whitespace.":
122
+ if lineno not in allowed_lines:
123
+ return False
124
+ elif msg == "new blank line at EOF.":
125
+ # Only exact final context line may trigger EOF blank line.
126
+ if lineno not in allowed_lines or lineno != total_lines:
127
+ return False
128
+ else:
129
+ return False
130
+ return True
131
+
132
+
133
+ def check_patch_bytes(
134
+ repo,
135
+ path: str,
136
+ raw: bytes,
137
+ *,
138
+ env: dict[str, str] | None = None,
139
+ ) -> bool:
140
+ """Validate whitespace in a standalone `.patch` blob without polluting repository state."""
141
+ valid, allowed_lines, _ = parse_counted_patch_empty_context_lines(raw)
142
+ if not valid:
143
+ # Check if there is any trailing whitespace at all; ordinary non-whitespace lines pass.
144
+ return not any(
145
+ line.rstrip(b"\r\n").endswith((b" ", b"\t")) for line in raw.splitlines()
146
+ )
147
+ if not allowed_lines:
148
+ return True
149
+ try:
150
+ applied = run_git(
151
+ repo,
152
+ "apply",
153
+ "--numstat",
154
+ "-",
155
+ timeout=15.0,
156
+ env=clean_git_env(env),
157
+ input_data=raw,
158
+ )
159
+ except FinalizerError as exc:
160
+ raise FinalizerError(
161
+ ErrorCode.WHITESPACE_VIOLATION,
162
+ f"补丁文件验证失败: {path}",
163
+ final_phase="local_validation",
164
+ ) from exc
165
+ return applied.returncode == 0
@@ -0,0 +1,311 @@
1
+ """Declarative delivery policy (`.agents/delivery-policy.toml`) and optional OPA/Rego hook."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import fnmatch
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import shutil
11
+ import subprocess
12
+ import tomllib
13
+ from typing import Any
14
+
15
+ from git_finalizer.errors import ErrorCode, FinalizerError
16
+
17
+ POLICY_REL_PATH = Path(".agents/delivery-policy.toml")
18
+ DEFAULT_LARGE_BINARY_BYTES = 5 * 1024 * 1024
19
+ DEFAULT_MAX_ALLOWED_BINARY_BYTES = 25 * 1024 * 1024
20
+ ALLOWED_POLICY_KEYS = frozenset(
21
+ {
22
+ "schema_version",
23
+ "protected_branches",
24
+ "extra_protected_branches",
25
+ "max_file_bytes",
26
+ "max_large_binary_bytes",
27
+ "require_trailers",
28
+ "require_scanners",
29
+ "forbid_paths",
30
+ "allow_reviewed_extensions",
31
+ "scanners",
32
+ }
33
+ )
34
+
35
+
36
+ @dataclasses.dataclass(frozen=True)
37
+ class DeliveryPolicy:
38
+ source: str | None = None
39
+ extra_protected_branches: tuple[str, ...] = ()
40
+ max_file_bytes: int = DEFAULT_LARGE_BINARY_BYTES
41
+ max_large_binary_bytes: int = DEFAULT_MAX_ALLOWED_BINARY_BYTES
42
+ require_trailers: tuple[str, ...] = ()
43
+ require_scanners: tuple[str, ...] = ()
44
+ forbid_paths: tuple[str, ...] = ()
45
+ allow_reviewed_extensions: tuple[str, ...] = (".py", ".css", ".json")
46
+ sarif_cmd_argv: tuple[str, ...] = ()
47
+
48
+
49
+ def _string_list(data: dict[str, Any], key: str) -> tuple[str, ...]:
50
+ if key not in data:
51
+ return ()
52
+ value = data[key]
53
+ if not isinstance(value, list) or not all(isinstance(item, str) and item.strip() for item in value):
54
+ raise FinalizerError(
55
+ ErrorCode.POLICY_DENIED,
56
+ f"delivery-policy.toml 字段 {key} 必须是非空字符串数组",
57
+ final_phase="preflight",
58
+ )
59
+ return tuple(item.strip() for item in value)
60
+
61
+
62
+ def _positive_int(data: dict[str, Any], key: str, default: int, *, maximum: int) -> int:
63
+ if key not in data:
64
+ return default
65
+ value = data[key]
66
+ if type(value) is not int or value <= 0 or value > maximum:
67
+ raise FinalizerError(
68
+ ErrorCode.POLICY_DENIED,
69
+ f"delivery-policy.toml 字段 {key} 必须是 1..{maximum} 整数",
70
+ final_phase="preflight",
71
+ )
72
+ return value
73
+
74
+
75
+ def load_delivery_policy(repo: Path) -> DeliveryPolicy:
76
+ """Load `.agents/delivery-policy.toml` when present, failing closed on invalid syntax/types."""
77
+ policy_path = repo / POLICY_REL_PATH
78
+ if not policy_path.exists() and not policy_path.is_symlink():
79
+ return DeliveryPolicy()
80
+ if policy_path.is_symlink() or not policy_path.is_file():
81
+ raise FinalizerError(
82
+ ErrorCode.POLICY_DENIED,
83
+ ".agents/delivery-policy.toml 必须是普通文件",
84
+ final_phase="preflight",
85
+ )
86
+ try:
87
+ raw = policy_path.read_bytes()
88
+ if len(raw) > 256 * 1024:
89
+ raise ValueError("policy file exceeds 256 KiB")
90
+ data = tomllib.loads(raw.decode("utf-8"))
91
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError, ValueError) as exc:
92
+ raise FinalizerError(
93
+ ErrorCode.POLICY_DENIED,
94
+ f"无法解析 .agents/delivery-policy.toml: {exc}",
95
+ final_phase="preflight",
96
+ ) from exc
97
+ if not isinstance(data, dict):
98
+ raise FinalizerError(
99
+ ErrorCode.POLICY_DENIED,
100
+ ".agents/delivery-policy.toml 顶层必须是 TOML table",
101
+ final_phase="preflight",
102
+ )
103
+ unknown = set(data) - ALLOWED_POLICY_KEYS
104
+ if unknown:
105
+ raise FinalizerError(
106
+ ErrorCode.POLICY_DENIED,
107
+ f".agents/delivery-policy.toml 包含未识别字段: {', '.join(sorted(unknown))}",
108
+ final_phase="preflight",
109
+ )
110
+ schema_version = data.get("schema_version")
111
+ if type(schema_version) is not int or schema_version != 1:
112
+ raise FinalizerError(
113
+ ErrorCode.POLICY_DENIED,
114
+ ".agents/delivery-policy.toml 需要 schema_version = 1",
115
+ final_phase="preflight",
116
+ )
117
+ extra_branches = _string_list(data, "protected_branches") + _string_list(
118
+ data, "extra_protected_branches"
119
+ )
120
+ max_file_bytes = _positive_int(
121
+ data, "max_file_bytes", DEFAULT_LARGE_BINARY_BYTES, maximum=DEFAULT_MAX_ALLOWED_BINARY_BYTES
122
+ )
123
+ max_large_binary_bytes = _positive_int(
124
+ data,
125
+ "max_large_binary_bytes",
126
+ DEFAULT_MAX_ALLOWED_BINARY_BYTES,
127
+ maximum=DEFAULT_MAX_ALLOWED_BINARY_BYTES,
128
+ )
129
+ if max_large_binary_bytes < max_file_bytes:
130
+ raise FinalizerError(
131
+ ErrorCode.POLICY_DENIED,
132
+ "delivery-policy.toml 的 max_large_binary_bytes 不得小于 max_file_bytes",
133
+ final_phase="preflight",
134
+ )
135
+ extensions = _string_list(data, "allow_reviewed_extensions") or (".py", ".css", ".json")
136
+ for ext in extensions:
137
+ if not ext.startswith(".") or len(ext) < 2:
138
+ raise FinalizerError(
139
+ ErrorCode.POLICY_DENIED,
140
+ f"delivery-policy.toml 非法扩展名配置: {ext!r}",
141
+ final_phase="preflight",
142
+ )
143
+ sarif_cmd_argv: tuple[str, ...] = ()
144
+ scanners_cfg = data.get("scanners")
145
+ if scanners_cfg is not None:
146
+ if not isinstance(scanners_cfg, dict):
147
+ raise FinalizerError(
148
+ ErrorCode.POLICY_DENIED,
149
+ "delivery-policy.toml [scanners] 必须是 table",
150
+ final_phase="preflight",
151
+ )
152
+ sarif_cfg = scanners_cfg.get("sarif_cmd")
153
+ if sarif_cfg is not None:
154
+ if not isinstance(sarif_cfg, dict):
155
+ raise FinalizerError(
156
+ ErrorCode.POLICY_DENIED,
157
+ "delivery-policy.toml [scanners.sarif_cmd] 必须是 table",
158
+ final_phase="preflight",
159
+ )
160
+ sarif_cmd_argv = _string_list(sarif_cfg, "argv")
161
+
162
+ return DeliveryPolicy(
163
+ source=str(POLICY_REL_PATH),
164
+ extra_protected_branches=extra_branches,
165
+ max_file_bytes=max_file_bytes,
166
+ max_large_binary_bytes=max_large_binary_bytes,
167
+ require_trailers=_string_list(data, "require_trailers"),
168
+ require_scanners=_string_list(data, "require_scanners"),
169
+ forbid_paths=_string_list(data, "forbid_paths"),
170
+ allow_reviewed_extensions=extensions,
171
+ sarif_cmd_argv=sarif_cmd_argv,
172
+ )
173
+
174
+
175
+ def enforce_declarative_policy(
176
+ policy: DeliveryPolicy,
177
+ *,
178
+ branch: str | None,
179
+ requested_paths: list[str],
180
+ trailers: list[tuple[str, str]],
181
+ active_scanners: list[str],
182
+ mutating_commit: bool,
183
+ ) -> None:
184
+ """Enforce declarative TOML rules deterministically before index/repo writes."""
185
+ if branch:
186
+ for pattern in policy.extra_protected_branches:
187
+ if fnmatch.fnmatchcase(branch, pattern):
188
+ raise FinalizerError(
189
+ ErrorCode.BRANCH_PROTECTED,
190
+ f"delivery-policy.toml 禁止操作受保护分支: {branch}",
191
+ final_phase="preflight",
192
+ )
193
+ for rel in requested_paths:
194
+ for pattern in policy.forbid_paths:
195
+ if fnmatch.fnmatchcase(rel, pattern):
196
+ raise FinalizerError(
197
+ ErrorCode.POLICY_DENIED,
198
+ f"delivery-policy.toml 禁止提交路径: {rel}",
199
+ final_phase="local_validation",
200
+ )
201
+ if mutating_commit and policy.require_trailers:
202
+ present = {key for key, _ in trailers}
203
+ missing = [req for req in policy.require_trailers if req not in present]
204
+ if missing:
205
+ raise FinalizerError(
206
+ ErrorCode.POLICY_DENIED,
207
+ f"delivery-policy.toml 要求提供 trailers: {', '.join(missing)}",
208
+ final_phase="preflight",
209
+ )
210
+ if policy.require_scanners:
211
+ missing_scanners = [s for s in policy.require_scanners if s not in active_scanners]
212
+ if missing_scanners:
213
+ raise FinalizerError(
214
+ ErrorCode.POLICY_DENIED,
215
+ f"delivery-policy.toml 要求启用扫描器: {', '.join(missing_scanners)}",
216
+ final_phase="preflight",
217
+ )
218
+
219
+
220
+ def evaluate_opa_policy(
221
+ opa_policy_path: Path,
222
+ *,
223
+ input_document: dict[str, Any],
224
+ query: str = "data.git_finalizer.delivery.deny",
225
+ timeout: float = 15.0,
226
+ ) -> dict[str, Any]:
227
+ """Invoke `opa eval` fail-closed when `--opa-policy` is explicitly requested."""
228
+ if not opa_policy_path.exists():
229
+ raise FinalizerError(
230
+ ErrorCode.POLICY_DENIED,
231
+ f"OPA policy 路径不存在: {opa_policy_path}",
232
+ final_phase="preflight",
233
+ )
234
+ opa_bin = shutil.which("opa")
235
+ if not opa_bin:
236
+ raise FinalizerError(
237
+ ErrorCode.POLICY_DENIED,
238
+ "已指定 --opa-policy,但 PATH 中未找到 opa 可执行文件",
239
+ final_phase="preflight",
240
+ )
241
+ # Keep deterministic JSON eval and parse result directly.
242
+ cmd = [
243
+ opa_bin,
244
+ "eval",
245
+ "--format",
246
+ "json",
247
+ "--data",
248
+ str(opa_policy_path),
249
+ "--stdin-input",
250
+ query,
251
+ ]
252
+ payload = json.dumps(input_document, ensure_ascii=False, sort_keys=True)
253
+ try:
254
+ completed = subprocess.run(
255
+ cmd,
256
+ input=payload,
257
+ capture_output=True,
258
+ text=True,
259
+ timeout=timeout,
260
+ env={**os.environ, "LC_ALL": "C"},
261
+ close_fds=True,
262
+ check=False,
263
+ )
264
+ except (OSError, subprocess.SubprocessError) as exc:
265
+ raise FinalizerError(
266
+ ErrorCode.POLICY_DENIED,
267
+ f"OPA policy 执行失败: {exc}",
268
+ final_phase="preflight",
269
+ status="failed",
270
+ ) from exc
271
+ if completed.returncode != 0:
272
+ raise FinalizerError(
273
+ ErrorCode.POLICY_DENIED,
274
+ f"OPA policy 评估返回非零退出码 ({completed.returncode})",
275
+ final_phase="preflight",
276
+ status="failed",
277
+ )
278
+ try:
279
+ parsed = json.loads(completed.stdout)
280
+ expressions = parsed["result"][0]["expressions"]
281
+ value = expressions[0]["value"]
282
+ except (ValueError, KeyError, IndexError, TypeError) as exc:
283
+ raise FinalizerError(
284
+ ErrorCode.POLICY_DENIED,
285
+ "OPA policy 输出不是有效判定 JSON",
286
+ final_phase="preflight",
287
+ status="failed",
288
+ ) from exc
289
+ if isinstance(value, bool):
290
+ if not value:
291
+ raise FinalizerError(
292
+ ErrorCode.POLICY_DENIED,
293
+ "OPA policy 拒绝了本次交付",
294
+ final_phase="local_validation",
295
+ )
296
+ elif isinstance(value, (list, set)):
297
+ denials = [str(item) for item in value if item]
298
+ if denials:
299
+ raise FinalizerError(
300
+ ErrorCode.POLICY_DENIED,
301
+ f"OPA policy 拒绝了本次交付: {'; '.join(denials[:3])}",
302
+ final_phase="local_validation",
303
+ )
304
+ else:
305
+ raise FinalizerError(
306
+ ErrorCode.POLICY_DENIED,
307
+ "OPA policy 判定值必须是布尔值或拒绝消息列表",
308
+ final_phase="local_validation",
309
+ status="failed",
310
+ )
311
+ return {"policy_path": str(opa_policy_path), "decision": "allow"}