codeveto 0.1.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.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/ai/packets.py
ADDED
|
@@ -0,0 +1,855 @@
|
|
|
1
|
+
"""AI review packets (SPEC 9.1): what a model sees of a change, and nothing more.
|
|
2
|
+
|
|
3
|
+
:func:`build` turns a :class:`~codeveto.model.Changeset` into a
|
|
4
|
+
:class:`PacketSet`:
|
|
5
|
+
|
|
6
|
+
1. **Files.** A changed file stays out of the packets, with an
|
|
7
|
+
``ai.coverage`` entry naming the reason, when its path or old path is
|
|
8
|
+
sensitive (``sensitive_path``, see :func:`sensitive_path`), intake did not
|
|
9
|
+
read it (``not_read``) or gave it a placeholder name (``invalid_path``),
|
|
10
|
+
it is not text (``binary``, ``symlink``, ``submodule``, ``lfs_pointer``),
|
|
11
|
+
it is a lockfile (``lockfile``), or the trusted configuration classifies it
|
|
12
|
+
``generated``, ``vendored`` or ``minified``. Files the built-in path
|
|
13
|
+
patterns call generated, vendored or minified are packetized, last. An
|
|
14
|
+
excluded file makes the pass ``partial`` (:func:`coverage_gap`) unless it
|
|
15
|
+
holds no code for a model: non-text kinds, lockfiles, and sensitive files
|
|
16
|
+
whose language is not a code language (a plain ``.env``, credential or key
|
|
17
|
+
file is excluded by design; an ``.env.js`` or a script under ``.ssh/`` is
|
|
18
|
+
a gap). Every excluded file is listed in ``ai.coverage`` either way.
|
|
19
|
+
2. **Secrets.** Before anything is encoded, every line of both sides of every
|
|
20
|
+
packetized file passes the secrets detectors: each registered rule of the
|
|
21
|
+
``secrets`` pack (and any rule tagged ``secrets``) runs on the whole side,
|
|
22
|
+
every line treated as added, regardless of the review policy. Each
|
|
23
|
+
``Hit.redact`` span becomes ``[REDACTED:<rule id>]``; a hit without spans
|
|
24
|
+
redacts its whole lines, a file-level hit its whole side. As a backstop,
|
|
25
|
+
every line from a ``-----BEGIN ... PRIVATE KEY-----`` marker to its END
|
|
26
|
+
marker is redacted whole, whatever comment leaders surround it, even when
|
|
27
|
+
no rule reported it. Sensitive files are scanned the same way, though
|
|
28
|
+
never packetized, so their values are known. A value of at least 8
|
|
29
|
+
characters that a span or a key body covered is also replaced wherever
|
|
30
|
+
else it occurs as a whole token (in any file), never inside a longer
|
|
31
|
+
word. A detector that fails on a file keeps that file out
|
|
32
|
+
(``secret_scan_failed``). Paths are scanned with the secrets pack's
|
|
33
|
+
provider patterns, and a match is redacted in the packet's ``path`` and
|
|
34
|
+
``old_path`` (the report keeps the real path). Lone surrogates (non-UTF-8
|
|
35
|
+
bytes) become U+FFFD.
|
|
36
|
+
3. **Lines.** A packet's ``lines`` are objects ``{"side", "n", "changed",
|
|
37
|
+
"text"}``: removed lines with old numbers, added lines and context lines
|
|
38
|
+
with new numbers, in diff order (a hunk's removed lines just before its
|
|
39
|
+
added lines). Context is up to 20 new-side lines around every changed
|
|
40
|
+
line; ``changed`` is true only for this packet's own anchors (a changed
|
|
41
|
+
line of another packet can appear as context). A deleted file's packets
|
|
42
|
+
hold its removed lines.
|
|
43
|
+
4. **Splitting.** Hunks are packed greedily, with full context, into packets
|
|
44
|
+
of at most :data:`MAX_PACKET_BYTES` (the UTF-8 JSON text sent to the
|
|
45
|
+
model). A hunk that does not fit alone is tried with trimmed context (10,
|
|
46
|
+
5, 2, 0 lines), then split into windows of its changed lines; a single
|
|
47
|
+
changed line that does not fit even without context is skipped and
|
|
48
|
+
recorded (``line_too_long``). Each changed line is an eligible anchor in
|
|
49
|
+
exactly one packet.
|
|
50
|
+
5. **Order and cap.** Packets are ordered by risk (:func:`risk_tier`: source,
|
|
51
|
+
workflow, agent config, config and manifests; then tests; then docs and
|
|
52
|
+
text; then built-in generated, vendored and minified files), deleted files
|
|
53
|
+
after the others of their tier, then by the change's file order and
|
|
54
|
+
position; only the first ``max_packets`` are kept and the files that lost
|
|
55
|
+
packets get ``max_packets`` coverage entries.
|
|
56
|
+
6. **IDs.** ``packet_id = sha256(canonical([PROTOCOL, prompt sha256,
|
|
57
|
+
wire-schema sha256, packet body]))`` where the body is the packet without
|
|
58
|
+
its ID; ``run_id = sha256(canonical([version, mode, base, head or the
|
|
59
|
+
snapshot tree, [packet_id, ...]]))``. Canonical JSON is sorted, compact,
|
|
60
|
+
UTF-8 (:func:`codeveto.ai.prompt.canonical`).
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
from __future__ import annotations
|
|
64
|
+
|
|
65
|
+
import contextlib
|
|
66
|
+
import hashlib
|
|
67
|
+
import json
|
|
68
|
+
import re
|
|
69
|
+
import time
|
|
70
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
71
|
+
from dataclasses import dataclass, field
|
|
72
|
+
from functools import cache
|
|
73
|
+
from pathlib import PurePosixPath
|
|
74
|
+
from types import MappingProxyType, ModuleType
|
|
75
|
+
|
|
76
|
+
from codeveto import __version__, languages
|
|
77
|
+
from codeveto.ai import prompt
|
|
78
|
+
from codeveto.git import FLAG_INVALID_PATH, SKIPPED_PREFIX
|
|
79
|
+
from codeveto.model import Changeset, FileChange, FileKind, FileStatus, git_lines
|
|
80
|
+
from codeveto.rules.base import FileContext, Registry, Rule, Scope
|
|
81
|
+
|
|
82
|
+
__all__ = [
|
|
83
|
+
"BUILTIN_LAST_CLASSES",
|
|
84
|
+
"CONTEXT_LINES",
|
|
85
|
+
"DEFAULT_MAX_PACKETS",
|
|
86
|
+
"MAX_PACKETS_CEILING",
|
|
87
|
+
"MAX_PACKET_BYTES",
|
|
88
|
+
"MIN_PROPAGATED_SECRET",
|
|
89
|
+
"NON_TEXT_REASONS",
|
|
90
|
+
"REASON_INVALID_PATH",
|
|
91
|
+
"REASON_LINE_TOO_LONG",
|
|
92
|
+
"REASON_LOCKFILE",
|
|
93
|
+
"REASON_MAX_PACKETS",
|
|
94
|
+
"REASON_NOT_READ",
|
|
95
|
+
"REASON_SCAN_FAILED",
|
|
96
|
+
"REASON_SENSITIVE",
|
|
97
|
+
"TRUSTED_EXCLUDED_CLASSES",
|
|
98
|
+
"Packet",
|
|
99
|
+
"PacketSet",
|
|
100
|
+
"build",
|
|
101
|
+
"coverage_gap",
|
|
102
|
+
"has_secret_detectors",
|
|
103
|
+
"marker",
|
|
104
|
+
"redact_path",
|
|
105
|
+
"risk_tier",
|
|
106
|
+
"sensitive_path",
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
MAX_PACKET_BYTES = 24 * 1024
|
|
110
|
+
"""Largest packet: the UTF-8 JSON text of the user turn."""
|
|
111
|
+
CONTEXT_LINES = 20
|
|
112
|
+
DEFAULT_MAX_PACKETS = 40
|
|
113
|
+
MAX_PACKETS_CEILING = 100
|
|
114
|
+
SECRET_SCAN_BUDGET_S = 60.0
|
|
115
|
+
"""Total time the secrets detectors may take; files left after it are kept out."""
|
|
116
|
+
MIN_PROPAGATED_SECRET = 8
|
|
117
|
+
"""Shortest secret value that is redacted where no detector reported it."""
|
|
118
|
+
_TRIMMED = (10, 5, 2, 0)
|
|
119
|
+
_MAX_HITS = 10_000
|
|
120
|
+
_KEY_MAX_LINES = 400
|
|
121
|
+
_KEY_RULE = "secrets/private-key"
|
|
122
|
+
|
|
123
|
+
REASON_SENSITIVE = "sensitive_path"
|
|
124
|
+
REASON_INVALID_PATH = "invalid_path"
|
|
125
|
+
REASON_NOT_READ = "not_read"
|
|
126
|
+
REASON_LOCKFILE = "lockfile"
|
|
127
|
+
REASON_SCAN_FAILED = "secret_scan_failed"
|
|
128
|
+
REASON_LINE_TOO_LONG = "line_too_long"
|
|
129
|
+
REASON_MAX_PACKETS = "max_packets"
|
|
130
|
+
NON_TEXT_REASONS = frozenset(str(kind) for kind in FileKind if kind is not FileKind.TEXT)
|
|
131
|
+
"""Coverage reasons that do not make a pass partial: no model reads these files."""
|
|
132
|
+
TRUSTED_EXCLUDED_CLASSES = frozenset({"generated", "vendored", "minified"})
|
|
133
|
+
"""Classes that keep a file out when the trusted configuration assigns them."""
|
|
134
|
+
BUILTIN_LAST_CLASSES = TRUSTED_EXCLUDED_CLASSES
|
|
135
|
+
"""Classes that the built-in path patterns assign: packetized, but sent last."""
|
|
136
|
+
|
|
137
|
+
_TIERS = {"source": 0, "workflow": 0, "agent-config": 0, "config": 0, "manifest": 0, "test": 1}
|
|
138
|
+
_SECRETS_PACK = "secrets"
|
|
139
|
+
_REPLACEMENT = chr(0xFFFD)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def risk_tier(file_class: str) -> int:
|
|
143
|
+
"""Packet order by class: 0 code and config, 1 tests, 2 docs and text, 3 generated."""
|
|
144
|
+
if file_class in BUILTIN_LAST_CLASSES:
|
|
145
|
+
return 3
|
|
146
|
+
return _TIERS.get(file_class, 2)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def marker(rule_id: str) -> str:
|
|
150
|
+
"""The text that replaces a secret found by ``rule_id``."""
|
|
151
|
+
return f"[REDACTED:{rule_id}]"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def coverage_gap(reason: str, language: str | None = None) -> bool:
|
|
155
|
+
"""Does leaving a file out for ``reason`` make the pass ``partial``?
|
|
156
|
+
|
|
157
|
+
Not for non-text kinds and lockfiles (no code a model could review), nor
|
|
158
|
+
for a sensitive file unless ``language`` is a code language
|
|
159
|
+
(:data:`codeveto.languages.CODE_LANGUAGES`). Every other reason is a gap.
|
|
160
|
+
"""
|
|
161
|
+
token = reason.split(":", 1)[0]
|
|
162
|
+
if token in NON_TEXT_REASONS or token == REASON_LOCKFILE:
|
|
163
|
+
return False
|
|
164
|
+
if token == REASON_SENSITIVE:
|
|
165
|
+
return language in languages.CODE_LANGUAGES
|
|
166
|
+
return True
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@cache
|
|
170
|
+
def _secrets_pack() -> ModuleType | None:
|
|
171
|
+
"""The secrets pack module for its path helpers and provider patterns, if importable."""
|
|
172
|
+
try:
|
|
173
|
+
from codeveto.rules import secrets
|
|
174
|
+
except Exception: # the pack is optional here: built-in lists still apply
|
|
175
|
+
return None
|
|
176
|
+
return secrets
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# --- sensitive paths (legacy reviewgate.model._sensitive_path, widened) ---------------
|
|
180
|
+
|
|
181
|
+
# Paths that themselves look like credentials (the legacy model-transport guard).
|
|
182
|
+
_SECRET_IN_PATH = re.compile(
|
|
183
|
+
r"-----BEGIN (?:[A-Z0-9 ]*PRIVATE KEY|PGP PRIVATE KEY BLOCK)-----|"
|
|
184
|
+
r"\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bgh[pousr]_[A-Za-z0-9]{20,}|"
|
|
185
|
+
r"\bgithub_pat_[A-Za-z0-9_]{25,}|\bsk-(?:proj-)?[A-Za-z0-9_-]{24,}|"
|
|
186
|
+
r"\bxox[baprs]-[A-Za-z0-9-]{10,}|"
|
|
187
|
+
r"\beyJ[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}|"
|
|
188
|
+
r"(?i:\bAuthorization[\x22\x27]?\s*[:=]\s*[\x22\x27]?Bearer\s+[A-Za-z0-9._~+/=-]{12,})|"
|
|
189
|
+
r"(?i:\b(?:api[_-]?key|(?:access[_-]?|auth[_-]?)?token|password|passwd|client[_-]?secret"
|
|
190
|
+
r"|secret[_-]?key)\b[\x22\x27]?\s*[:=]\s*[\x22\x27][^\x22\x27\s]{12,})"
|
|
191
|
+
)
|
|
192
|
+
_CREDENTIAL_NAMES = frozenset(
|
|
193
|
+
{
|
|
194
|
+
".env",
|
|
195
|
+
".envrc",
|
|
196
|
+
".netrc",
|
|
197
|
+
"_netrc",
|
|
198
|
+
".npmrc",
|
|
199
|
+
".pypirc",
|
|
200
|
+
".git-credentials",
|
|
201
|
+
"credentials.json",
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
_ENV_TEMPLATES = (".example", ".sample", ".template", ".dist")
|
|
205
|
+
_KEY_SUFFIXES = (".p12", ".pfx", ".pem", ".key", ".ppk")
|
|
206
|
+
_SSH_KEY_NAMES = frozenset(
|
|
207
|
+
{"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "id_ecdsa_sk", "id_ed25519_sk"}
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _own_sensitive(path: str) -> bool:
|
|
212
|
+
parts = PurePosixPath(path.lower()).parts
|
|
213
|
+
name = parts[-1] if parts else ""
|
|
214
|
+
env_like = name.startswith(".env.") or (name.endswith(".env") and name != ".env")
|
|
215
|
+
return (
|
|
216
|
+
name in _CREDENTIAL_NAMES
|
|
217
|
+
or (env_like and not name.endswith(_ENV_TEMPLATES))
|
|
218
|
+
or name.endswith(_KEY_SUFFIXES)
|
|
219
|
+
or (name.startswith("client_secret") and name.endswith(".json"))
|
|
220
|
+
or name.removesuffix(".pub") in _SSH_KEY_NAMES
|
|
221
|
+
or ".ssh" in parts[:-1]
|
|
222
|
+
or (".aws" in parts[:-1] and name == "credentials")
|
|
223
|
+
or bool(_SECRET_IN_PATH.search(path))
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def sensitive_path(path: str) -> bool:
|
|
228
|
+
"""Is ``path`` a file whose content must never reach a model?
|
|
229
|
+
|
|
230
|
+
The legacy list (``.env``, ``.env.*`` except templates, ``*.pem``,
|
|
231
|
+
``*.key``, ``*.p12``, ``*.pfx``, ``.npmrc``, ``.pypirc``, ``.netrc``,
|
|
232
|
+
``.git-credentials``, ``.aws/credentials``, a path that looks like a
|
|
233
|
+
credential), widened with ``.envrc``, ``*.env``, ``_netrc``, ``*.ppk``,
|
|
234
|
+
``credentials.json``, ``client_secret*.json``, SSH key names (``id_rsa``,
|
|
235
|
+
``id_dsa``, ``id_ecdsa``, ``id_ed25519`` and their ``_sk`` and ``.pub``
|
|
236
|
+
forms), anything under a ``.ssh/`` directory, and whatever the secrets
|
|
237
|
+
pack's ``is_env_file`` and ``credential_kind`` recognise.
|
|
238
|
+
"""
|
|
239
|
+
if _own_sensitive(path):
|
|
240
|
+
return True
|
|
241
|
+
pack = _secrets_pack()
|
|
242
|
+
if pack is None:
|
|
243
|
+
return False
|
|
244
|
+
try:
|
|
245
|
+
return bool(pack.is_env_file(path) or pack.credential_kind(path) is not None)
|
|
246
|
+
except Exception: # a helper that fails is no reason to send the file
|
|
247
|
+
return True
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@cache
|
|
251
|
+
def _path_patterns() -> tuple[tuple[str, re.Pattern[str], str | int], ...]:
|
|
252
|
+
pack = _secrets_pack()
|
|
253
|
+
providers = getattr(pack, "PROVIDERS", None) if pack is not None else None
|
|
254
|
+
if not isinstance(providers, Mapping):
|
|
255
|
+
return ()
|
|
256
|
+
return tuple(
|
|
257
|
+
(rule_id, provider.pattern, provider.group)
|
|
258
|
+
for rule_id, group in providers.items()
|
|
259
|
+
for provider in group
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def redact_path(path: str) -> str:
|
|
264
|
+
"""``path`` with every secrets-pack provider token in it replaced by its marker."""
|
|
265
|
+
ranges: list[tuple[int, int, str]] = []
|
|
266
|
+
for rule_id, pattern, group in _path_patterns():
|
|
267
|
+
for match in pattern.finditer(path):
|
|
268
|
+
lo, hi = match.span(group)
|
|
269
|
+
if hi > lo:
|
|
270
|
+
ranges.append((lo, hi, rule_id))
|
|
271
|
+
return _no_surrogates(_replace(path, ranges))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# --- secret detection ------------------------------------------------------------------
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _detectors(registry: Registry) -> tuple[Rule, ...]:
|
|
278
|
+
return tuple(
|
|
279
|
+
r
|
|
280
|
+
for r in registry.all()
|
|
281
|
+
if (r.meta.pack == _SECRETS_PACK or _SECRETS_PACK in r.meta.tags)
|
|
282
|
+
and r.meta.scope is not Scope.CHANGE
|
|
283
|
+
and FileKind.TEXT in r.meta.kinds
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def has_secret_detectors(registry: Registry) -> bool:
|
|
288
|
+
"""Is the secrets pack registered (so packets are redacted before they leave)?"""
|
|
289
|
+
return any(r.meta.pack == _SECRETS_PACK for r in registry.all())
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class _ScanError(Exception):
|
|
293
|
+
pass
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
@dataclass(slots=True)
|
|
297
|
+
class _Secrets:
|
|
298
|
+
"""Secret locations on one side: per-line spans (0-based, end exclusive) and whole lines."""
|
|
299
|
+
|
|
300
|
+
spans: dict[int, list[tuple[int, int, str]]] = field(default_factory=dict)
|
|
301
|
+
whole: dict[int, str] = field(default_factory=dict)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
_KEY_BEGIN = re.compile(r"-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----")
|
|
305
|
+
_KEY_END = re.compile(r"-----END [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----")
|
|
306
|
+
_KEY_BODY = re.compile(r"[A-Za-z0-9+/=]{16,}")
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _key_blocks(lines: Sequence[str], found: _Secrets, values: dict[str, str]) -> None:
|
|
310
|
+
"""Redact every private key block whole: BEGIN marker line through its END marker line.
|
|
311
|
+
|
|
312
|
+
Without an END marker the block runs for at most :data:`_KEY_MAX_LINES`
|
|
313
|
+
lines. Base64 runs of 16 or more characters inside a block are recorded as
|
|
314
|
+
secret values, so a copy of the key elsewhere is redacted too.
|
|
315
|
+
"""
|
|
316
|
+
index = 0
|
|
317
|
+
while index < len(lines):
|
|
318
|
+
begin = _KEY_BEGIN.search(lines[index])
|
|
319
|
+
if begin is None:
|
|
320
|
+
index += 1
|
|
321
|
+
continue
|
|
322
|
+
last = min(len(lines), index + _KEY_MAX_LINES) - 1
|
|
323
|
+
stop = last
|
|
324
|
+
for probe in range(index, last + 1):
|
|
325
|
+
start = begin.end() if probe == index else 0
|
|
326
|
+
if _KEY_END.search(lines[probe], start):
|
|
327
|
+
stop = probe
|
|
328
|
+
break
|
|
329
|
+
for n in range(index, stop + 1):
|
|
330
|
+
found.whole.setdefault(n + 1, _KEY_RULE)
|
|
331
|
+
for body in _KEY_BODY.finditer(lines[n]):
|
|
332
|
+
values.setdefault(body.group(), _KEY_RULE)
|
|
333
|
+
index = stop + 1
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _scan_side(
|
|
337
|
+
path: str,
|
|
338
|
+
text: str,
|
|
339
|
+
mode: str | None,
|
|
340
|
+
language: str,
|
|
341
|
+
file_class: str,
|
|
342
|
+
detectors: Sequence[Rule],
|
|
343
|
+
values: dict[str, str],
|
|
344
|
+
) -> _Secrets:
|
|
345
|
+
found = _Secrets()
|
|
346
|
+
lines = git_lines(text)
|
|
347
|
+
if not lines:
|
|
348
|
+
return found
|
|
349
|
+
_key_blocks(lines, found, values)
|
|
350
|
+
if not detectors:
|
|
351
|
+
return found
|
|
352
|
+
change = FileChange.from_texts(path, None, text, new_mode=mode)
|
|
353
|
+
ctx = FileContext(
|
|
354
|
+
change,
|
|
355
|
+
language,
|
|
356
|
+
file_class,
|
|
357
|
+
Changeset("range", None, None, None, None, "base", files=(change,)),
|
|
358
|
+
)
|
|
359
|
+
for rule in detectors:
|
|
360
|
+
meta = rule.meta
|
|
361
|
+
if meta.languages is not None and language not in meta.languages:
|
|
362
|
+
continue
|
|
363
|
+
if meta.classes is not None and file_class not in meta.classes:
|
|
364
|
+
continue
|
|
365
|
+
try:
|
|
366
|
+
hits = list(_bounded(rule.func(ctx))) # type: ignore[arg-type]
|
|
367
|
+
except _ScanError:
|
|
368
|
+
raise
|
|
369
|
+
except Exception: # a broken detector must not let a secret through
|
|
370
|
+
raise _ScanError from None
|
|
371
|
+
for hit in hits:
|
|
372
|
+
if hit.line is None:
|
|
373
|
+
for n in range(1, len(lines) + 1):
|
|
374
|
+
found.whole.setdefault(n, rule.id)
|
|
375
|
+
continue
|
|
376
|
+
if not hit.redact:
|
|
377
|
+
last = hit.end_line or hit.line
|
|
378
|
+
for n in range(hit.line, min(last, len(lines)) + 1):
|
|
379
|
+
found.whole.setdefault(n, rule.id)
|
|
380
|
+
continue
|
|
381
|
+
for line, start, end in hit.redact:
|
|
382
|
+
if line > len(lines):
|
|
383
|
+
raise _ScanError
|
|
384
|
+
row = lines[line - 1]
|
|
385
|
+
stop = len(row) + 1 if end is None else end
|
|
386
|
+
if start > len(row) + 1 or stop > len(row) + 1:
|
|
387
|
+
raise _ScanError
|
|
388
|
+
lo, hi = start - 1, stop - 1
|
|
389
|
+
if hi > lo:
|
|
390
|
+
found.spans.setdefault(line, []).append((lo, hi, rule.id))
|
|
391
|
+
values.setdefault(row[lo:hi], rule.id)
|
|
392
|
+
return found
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _bounded(hits: Iterable[object]) -> Iterable[object]:
|
|
396
|
+
for count, hit in enumerate(hits, 1):
|
|
397
|
+
if count > _MAX_HITS:
|
|
398
|
+
raise _ScanError
|
|
399
|
+
yield hit
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _no_surrogates(text: str) -> str:
|
|
403
|
+
if not any(0xD800 <= ord(c) <= 0xDFFF for c in text):
|
|
404
|
+
return text
|
|
405
|
+
return "".join(_REPLACEMENT if 0xD800 <= ord(c) <= 0xDFFF else c for c in text)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _word(char: str) -> bool:
|
|
409
|
+
return char.isalnum() or char == "_"
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _token_occurrences(text: str, value: str) -> Iterable[int]:
|
|
413
|
+
"""Starts of ``value`` in ``text`` that are whole tokens (no word character either side)."""
|
|
414
|
+
at = text.find(value)
|
|
415
|
+
while at >= 0:
|
|
416
|
+
end = at + len(value)
|
|
417
|
+
if (at == 0 or not _word(text[at - 1])) and (end == len(text) or not _word(text[end])):
|
|
418
|
+
yield at
|
|
419
|
+
at = text.find(value, at + 1)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _replace(text: str, ranges: list[tuple[int, int, str]]) -> str:
|
|
423
|
+
if not ranges:
|
|
424
|
+
return text
|
|
425
|
+
ranges.sort()
|
|
426
|
+
out: list[str] = []
|
|
427
|
+
pos = 0
|
|
428
|
+
lo, hi, rule_id = ranges[0]
|
|
429
|
+
for start, end, rid in ranges[1:]:
|
|
430
|
+
if start <= hi:
|
|
431
|
+
hi = max(hi, end)
|
|
432
|
+
continue
|
|
433
|
+
out += (text[pos:lo], marker(rule_id))
|
|
434
|
+
pos, (lo, hi, rule_id) = hi, (start, end, rid)
|
|
435
|
+
out += (text[pos:lo], marker(rule_id), text[hi:])
|
|
436
|
+
return "".join(out)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _redact(
|
|
440
|
+
text: str, own: Sequence[tuple[int, int, str]], values: Sequence[tuple[str, str]]
|
|
441
|
+
) -> str:
|
|
442
|
+
ranges = list(own)
|
|
443
|
+
for value, rule_id in values:
|
|
444
|
+
ranges += ((at, at + len(value), rule_id) for at in _token_occurrences(text, value))
|
|
445
|
+
return _replace(text, ranges)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
# --- packets ---------------------------------------------------------------------------
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
@dataclass(frozen=True, slots=True)
|
|
452
|
+
class Packet:
|
|
453
|
+
"""One packet: ``message`` is the exact JSON text a model receives as the user turn.
|
|
454
|
+
|
|
455
|
+
``path``/``old_path`` are the real paths (for the report);
|
|
456
|
+
``wire_path``/``wire_old_path`` are what the packet shows (secrets in a
|
|
457
|
+
path redacted) and what a finding must name. ``anchors`` maps each
|
|
458
|
+
eligible ``(side, line)`` to its redacted text, the text a quote must match.
|
|
459
|
+
"""
|
|
460
|
+
|
|
461
|
+
packet_id: str
|
|
462
|
+
path: str
|
|
463
|
+
old_path: str | None
|
|
464
|
+
wire_path: str
|
|
465
|
+
wire_old_path: str | None
|
|
466
|
+
file_class: str
|
|
467
|
+
message: str
|
|
468
|
+
anchors: Mapping[tuple[str, int], str]
|
|
469
|
+
|
|
470
|
+
def path_for(self, side: str) -> str:
|
|
471
|
+
"""The path a finding on ``side`` must name (old side: the old path of a rename)."""
|
|
472
|
+
return (self.wire_old_path or self.wire_path) if side == "old" else self.wire_path
|
|
473
|
+
|
|
474
|
+
def document(self) -> dict[str, object]:
|
|
475
|
+
"""The packet as a JSON object (a fresh copy)."""
|
|
476
|
+
return json.loads(self.message)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
@dataclass(frozen=True, slots=True)
|
|
480
|
+
class PacketSet:
|
|
481
|
+
"""The packets of one change, in send order, and what was left out."""
|
|
482
|
+
|
|
483
|
+
run_id: str
|
|
484
|
+
mode: str
|
|
485
|
+
base: str | None
|
|
486
|
+
head: str | None
|
|
487
|
+
snapshot: str | None
|
|
488
|
+
packets: tuple[Packet, ...]
|
|
489
|
+
coverage: tuple[tuple[str, str], ...]
|
|
490
|
+
secrets: tuple[str, ...]
|
|
491
|
+
redaction: bool
|
|
492
|
+
gaps: tuple[tuple[str, str], ...] = ()
|
|
493
|
+
"""The ``coverage`` entries that make the pass partial (:func:`coverage_gap`)."""
|
|
494
|
+
|
|
495
|
+
def get(self, packet_id: object) -> Packet | None:
|
|
496
|
+
for packet in self.packets:
|
|
497
|
+
if packet.packet_id == packet_id:
|
|
498
|
+
return packet
|
|
499
|
+
return None
|
|
500
|
+
|
|
501
|
+
@property
|
|
502
|
+
def partial(self) -> bool:
|
|
503
|
+
"""Did a file with code for the model stay out of the packets (:func:`coverage_gap`)?"""
|
|
504
|
+
return bool(self.gaps)
|
|
505
|
+
|
|
506
|
+
def document(self) -> dict[str, object]:
|
|
507
|
+
"""The ``codeveto packets`` document (SPEC 9.4 harness)."""
|
|
508
|
+
return {
|
|
509
|
+
"protocol": prompt.PROTOCOL,
|
|
510
|
+
"run_id": self.run_id,
|
|
511
|
+
"base": self.base,
|
|
512
|
+
"head": self.head,
|
|
513
|
+
"snapshot": self.snapshot,
|
|
514
|
+
"instructions": prompt.system_prompt(),
|
|
515
|
+
"wire_schema": prompt.wire_schema(),
|
|
516
|
+
"packets": [p.document() for p in self.packets],
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
@dataclass(frozen=True, slots=True)
|
|
521
|
+
class _Item:
|
|
522
|
+
side: str
|
|
523
|
+
n: int
|
|
524
|
+
pos: int # new-side position: the line itself, or where a removed block sat
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
class _File:
|
|
528
|
+
def __init__(
|
|
529
|
+
self,
|
|
530
|
+
index: int,
|
|
531
|
+
change: FileChange,
|
|
532
|
+
language: str,
|
|
533
|
+
file_class: str,
|
|
534
|
+
secrets: dict[str, _Secrets],
|
|
535
|
+
values: Sequence[tuple[str, str]],
|
|
536
|
+
) -> None:
|
|
537
|
+
self.index = index
|
|
538
|
+
self.change = change
|
|
539
|
+
self.language = language
|
|
540
|
+
self.file_class = file_class
|
|
541
|
+
self.lines = {"new": git_lines(change.new_text), "old": git_lines(change.old_text)}
|
|
542
|
+
self.secrets = secrets
|
|
543
|
+
self.values = values
|
|
544
|
+
self.wire_path = redact_path(change.path)
|
|
545
|
+
self.wire_old_path = redact_path(change.old_path) if change.old_path else None
|
|
546
|
+
self._text: dict[tuple[str, int], str] = {}
|
|
547
|
+
self._size: dict[tuple[str, int, bool], int] = {}
|
|
548
|
+
self.base_size = len(prompt.canonical(self.body([], "0" * 64)))
|
|
549
|
+
|
|
550
|
+
def body(self, lines: list[dict[str, object]], packet_id: str | None) -> dict[str, object]:
|
|
551
|
+
body: dict[str, object] = {
|
|
552
|
+
"file_class": self.file_class,
|
|
553
|
+
"language": self.language,
|
|
554
|
+
"lines": lines,
|
|
555
|
+
"old_path": self.wire_old_path,
|
|
556
|
+
"path": self.wire_path,
|
|
557
|
+
"status": str(self.change.status),
|
|
558
|
+
}
|
|
559
|
+
if packet_id is not None:
|
|
560
|
+
body["packet_id"] = packet_id
|
|
561
|
+
return body
|
|
562
|
+
|
|
563
|
+
def text(self, side: str, n: int) -> str:
|
|
564
|
+
key = (side, n)
|
|
565
|
+
cached = self._text.get(key)
|
|
566
|
+
if cached is None:
|
|
567
|
+
raw = self.lines[side][n - 1]
|
|
568
|
+
found = self.secrets[side]
|
|
569
|
+
rule_id = found.whole.get(n)
|
|
570
|
+
redacted = (
|
|
571
|
+
marker(rule_id)
|
|
572
|
+
if rule_id is not None
|
|
573
|
+
else _redact(raw, found.spans.get(n, ()), self.values)
|
|
574
|
+
)
|
|
575
|
+
cached = self._text[key] = _no_surrogates(redacted)
|
|
576
|
+
return cached
|
|
577
|
+
|
|
578
|
+
def row(self, side: str, n: int, changed: bool) -> dict[str, object]:
|
|
579
|
+
return {"changed": changed, "n": n, "side": side, "text": self.text(side, n)}
|
|
580
|
+
|
|
581
|
+
def row_size(self, side: str, n: int, changed: bool) -> int:
|
|
582
|
+
key = (side, n, changed)
|
|
583
|
+
size = self._size.get(key)
|
|
584
|
+
if size is None:
|
|
585
|
+
size = self._size[key] = len(prompt.canonical(self.row(side, n, changed)))
|
|
586
|
+
return size
|
|
587
|
+
|
|
588
|
+
def items(self) -> list[list[_Item]]:
|
|
589
|
+
change = self.change
|
|
590
|
+
groups: list[list[_Item]] = []
|
|
591
|
+
for hunk in change.hunks:
|
|
592
|
+
pos = hunk.new_start if hunk.new_count else hunk.new_start + 1
|
|
593
|
+
group = [_Item("old", o, pos) for o in hunk.old_lines if o in change.removed_lines]
|
|
594
|
+
group += [_Item("new", n, n) for n in hunk.new_lines if n in change.added_lines]
|
|
595
|
+
if group:
|
|
596
|
+
groups.append(group)
|
|
597
|
+
return groups
|
|
598
|
+
|
|
599
|
+
def rows(self, items: Sequence[_Item], radius: int) -> dict[tuple[str, int], bool]:
|
|
600
|
+
rows = {(i.side, i.n): True for i in items}
|
|
601
|
+
if radius:
|
|
602
|
+
last = len(self.lines["new"])
|
|
603
|
+
for i in items:
|
|
604
|
+
if i.side == "old":
|
|
605
|
+
lo, hi = i.pos - radius, i.pos + radius - 1
|
|
606
|
+
else:
|
|
607
|
+
lo, hi = i.n - radius, i.n + radius
|
|
608
|
+
for n in range(max(1, lo), min(last, hi) + 1):
|
|
609
|
+
rows.setdefault(("new", n), False)
|
|
610
|
+
return rows
|
|
611
|
+
|
|
612
|
+
def size(self, items: Sequence[_Item], radius: int) -> int:
|
|
613
|
+
rows = self.rows(items, radius)
|
|
614
|
+
total = self.base_size + max(0, len(rows) - 1)
|
|
615
|
+
for (side, n), changed in rows.items():
|
|
616
|
+
total += self.row_size(side, n, changed)
|
|
617
|
+
if total > MAX_PACKET_BYTES:
|
|
618
|
+
break
|
|
619
|
+
return total
|
|
620
|
+
|
|
621
|
+
def fits(self, items: Sequence[_Item], radius: int) -> bool:
|
|
622
|
+
return self.size(items, radius) <= MAX_PACKET_BYTES
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
@dataclass(frozen=True, slots=True)
|
|
626
|
+
class _Draft:
|
|
627
|
+
file: _File
|
|
628
|
+
items: tuple[_Item, ...]
|
|
629
|
+
radius: int
|
|
630
|
+
order: int
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _split(f: _File) -> tuple[list[_Draft], list[_Item]]:
|
|
634
|
+
drafts: list[_Draft] = []
|
|
635
|
+
skipped: list[_Item] = []
|
|
636
|
+
|
|
637
|
+
def emit(items: Sequence[_Item], radius: int) -> None:
|
|
638
|
+
drafts.append(_Draft(f, tuple(items), radius, len(drafts)))
|
|
639
|
+
|
|
640
|
+
def alone(items: Sequence[_Item]) -> bool:
|
|
641
|
+
for radius in _TRIMMED:
|
|
642
|
+
if f.fits(items, radius):
|
|
643
|
+
emit(items, radius)
|
|
644
|
+
return True
|
|
645
|
+
return False
|
|
646
|
+
|
|
647
|
+
current: list[_Item] = []
|
|
648
|
+
for group in f.items():
|
|
649
|
+
if current and f.fits(current + group, CONTEXT_LINES):
|
|
650
|
+
current += group
|
|
651
|
+
continue
|
|
652
|
+
if current:
|
|
653
|
+
emit(current, CONTEXT_LINES)
|
|
654
|
+
current = []
|
|
655
|
+
if f.fits(group, CONTEXT_LINES):
|
|
656
|
+
current = list(group)
|
|
657
|
+
continue
|
|
658
|
+
if alone(group):
|
|
659
|
+
continue
|
|
660
|
+
window: list[_Item] = []
|
|
661
|
+
for item in group:
|
|
662
|
+
if window and f.fits([*window, item], CONTEXT_LINES):
|
|
663
|
+
window.append(item)
|
|
664
|
+
continue
|
|
665
|
+
if window:
|
|
666
|
+
emit(window, CONTEXT_LINES)
|
|
667
|
+
window = []
|
|
668
|
+
if f.fits([item], CONTEXT_LINES):
|
|
669
|
+
window = [item]
|
|
670
|
+
elif not alone([item]):
|
|
671
|
+
skipped.append(item)
|
|
672
|
+
if window:
|
|
673
|
+
emit(window, CONTEXT_LINES)
|
|
674
|
+
if current:
|
|
675
|
+
emit(current, CONTEXT_LINES)
|
|
676
|
+
return drafts, skipped
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _packet(draft: _Draft, protocol_digest: tuple[str, str, str]) -> Packet:
|
|
680
|
+
f = draft.file
|
|
681
|
+
rows = f.rows(draft.items, draft.radius)
|
|
682
|
+
position = {
|
|
683
|
+
(i.side, i.n): (i.pos, 0, i.n) if i.side == "old" else (i.n, 1, 0) for i in draft.items
|
|
684
|
+
}
|
|
685
|
+
ordered = sorted(rows, key=lambda key: position.get(key, (key[1], 1, 0)))
|
|
686
|
+
body = f.body([f.row(side, n, rows[(side, n)]) for side, n in ordered], None)
|
|
687
|
+
digest = hashlib.sha256(prompt.canonical([*protocol_digest, body])).hexdigest()
|
|
688
|
+
message = prompt.canonical({**body, "packet_id": digest}).decode("utf-8")
|
|
689
|
+
anchors = {(i.side, i.n): f.text(i.side, i.n) for i in draft.items}
|
|
690
|
+
return Packet(
|
|
691
|
+
packet_id=digest,
|
|
692
|
+
path=f.change.path,
|
|
693
|
+
old_path=f.change.old_path,
|
|
694
|
+
wire_path=f.wire_path,
|
|
695
|
+
wire_old_path=f.wire_old_path,
|
|
696
|
+
file_class=f.file_class,
|
|
697
|
+
message=message,
|
|
698
|
+
anchors=MappingProxyType(anchors),
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _classify(
|
|
703
|
+
change: FileChange, file_class: Callable[[str], str | None] | None
|
|
704
|
+
) -> tuple[str, str, bool]:
|
|
705
|
+
"""(language, class, whether the trusted configuration chose the class)."""
|
|
706
|
+
text = change.new_text if change.new_text is not None else change.old_text
|
|
707
|
+
mode = change.new_mode if change.new_mode is not None else change.old_mode
|
|
708
|
+
info = languages.classify(change.path, text=text, executable=mode == "100755")
|
|
709
|
+
trusted = file_class(change.path) if file_class is not None else None
|
|
710
|
+
if trusted is not None and trusted in languages.FILE_CLASSES:
|
|
711
|
+
return info.language, trusted, True
|
|
712
|
+
return info.language, info.file_class, False
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def _excluded(change: FileChange, file_class: str, trusted: bool) -> str | None:
|
|
716
|
+
if FLAG_INVALID_PATH in change.flags:
|
|
717
|
+
return REASON_INVALID_PATH
|
|
718
|
+
if any(sensitive_path(p) for p in (change.path, change.old_path) if p):
|
|
719
|
+
return REASON_SENSITIVE
|
|
720
|
+
if any(flag.startswith(SKIPPED_PREFIX) for flag in change.flags):
|
|
721
|
+
return REASON_NOT_READ
|
|
722
|
+
if change.kind is not FileKind.TEXT:
|
|
723
|
+
return str(change.kind)
|
|
724
|
+
if file_class == REASON_LOCKFILE:
|
|
725
|
+
return REASON_LOCKFILE
|
|
726
|
+
if trusted and file_class in TRUSTED_EXCLUDED_CLASSES:
|
|
727
|
+
return file_class
|
|
728
|
+
if change.new_text is None and change.old_text is None:
|
|
729
|
+
return REASON_NOT_READ
|
|
730
|
+
return None
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def _line_list(items: Iterable[_Item]) -> str:
|
|
734
|
+
return ", ".join(f"{i.side} {i.n}" for i in items)
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _scan_both(
|
|
738
|
+
change: FileChange,
|
|
739
|
+
language: str,
|
|
740
|
+
file_class: str,
|
|
741
|
+
detectors: Sequence[Rule],
|
|
742
|
+
values: dict[str, str],
|
|
743
|
+
) -> dict[str, _Secrets]:
|
|
744
|
+
return {
|
|
745
|
+
"new": _scan_side(
|
|
746
|
+
change.path,
|
|
747
|
+
change.new_text or "",
|
|
748
|
+
change.new_mode,
|
|
749
|
+
language,
|
|
750
|
+
file_class,
|
|
751
|
+
detectors,
|
|
752
|
+
values,
|
|
753
|
+
),
|
|
754
|
+
"old": _scan_side(
|
|
755
|
+
change.old_path or change.path,
|
|
756
|
+
change.old_text or "",
|
|
757
|
+
change.old_mode,
|
|
758
|
+
language,
|
|
759
|
+
file_class,
|
|
760
|
+
detectors,
|
|
761
|
+
values,
|
|
762
|
+
),
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def build(
|
|
767
|
+
changeset: Changeset,
|
|
768
|
+
*,
|
|
769
|
+
registry: Registry,
|
|
770
|
+
file_class: Callable[[str], str | None] | None = None,
|
|
771
|
+
max_packets: int = DEFAULT_MAX_PACKETS,
|
|
772
|
+
clock: Callable[[], float] = time.monotonic,
|
|
773
|
+
scan_budget_s: float = SECRET_SCAN_BUDGET_S,
|
|
774
|
+
) -> PacketSet:
|
|
775
|
+
"""The packets of ``changeset`` (see the module docstring).
|
|
776
|
+
|
|
777
|
+
``file_class`` is the trusted class override (``Policy.file_class``);
|
|
778
|
+
``max_packets`` is clamped to 1..:data:`MAX_PACKETS_CEILING`.
|
|
779
|
+
"""
|
|
780
|
+
limit = max(1, min(int(max_packets), MAX_PACKETS_CEILING))
|
|
781
|
+
detectors = _detectors(registry)
|
|
782
|
+
coverage: list[tuple[str, str]] = []
|
|
783
|
+
gaps: list[tuple[str, str]] = []
|
|
784
|
+
|
|
785
|
+
def leave_out(path: str, reason: str, language: str | None = None) -> None:
|
|
786
|
+
coverage.append((path, reason))
|
|
787
|
+
if coverage_gap(reason, language):
|
|
788
|
+
gaps.append((path, reason))
|
|
789
|
+
|
|
790
|
+
values: dict[str, str] = {}
|
|
791
|
+
candidates: list[tuple[int, FileChange, str, str, dict[str, _Secrets]]] = []
|
|
792
|
+
started = clock()
|
|
793
|
+
for index, change in enumerate(changeset.files):
|
|
794
|
+
language, cls, trusted = _classify(change, file_class)
|
|
795
|
+
reason = _excluded(change, cls, trusted)
|
|
796
|
+
if reason == REASON_SENSITIVE and change.kind is FileKind.TEXT:
|
|
797
|
+
# Never packetized, but its values must be redacted wherever else they appear.
|
|
798
|
+
with contextlib.suppress(_ScanError):
|
|
799
|
+
_scan_both(change, language, cls, detectors, values)
|
|
800
|
+
if reason is not None:
|
|
801
|
+
leave_out(change.path, reason, language)
|
|
802
|
+
continue
|
|
803
|
+
if not change.hunks:
|
|
804
|
+
continue # nothing changed in the text (a pure rename or mode change)
|
|
805
|
+
if clock() - started > scan_budget_s:
|
|
806
|
+
leave_out(change.path, REASON_SCAN_FAILED)
|
|
807
|
+
continue
|
|
808
|
+
try:
|
|
809
|
+
found = _scan_both(change, language, cls, detectors, values)
|
|
810
|
+
except _ScanError:
|
|
811
|
+
leave_out(change.path, REASON_SCAN_FAILED)
|
|
812
|
+
continue
|
|
813
|
+
candidates.append((index, change, language, cls, found))
|
|
814
|
+
ordered_values = sorted(
|
|
815
|
+
((v, r) for v, r in values.items() if len(v) >= MIN_PROPAGATED_SECRET),
|
|
816
|
+
key=lambda kv: (-len(kv[0]), kv[0]),
|
|
817
|
+
)
|
|
818
|
+
drafts: list[_Draft] = []
|
|
819
|
+
for index, change, language, cls, found in candidates:
|
|
820
|
+
f = _File(index, change, language, cls, found, ordered_values)
|
|
821
|
+
file_drafts, skipped = _split(f)
|
|
822
|
+
drafts += file_drafts
|
|
823
|
+
if skipped:
|
|
824
|
+
leave_out(change.path, f"{REASON_LINE_TOO_LONG}: {_line_list(skipped)}")
|
|
825
|
+
drafts.sort(
|
|
826
|
+
key=lambda d: (
|
|
827
|
+
risk_tier(d.file.file_class),
|
|
828
|
+
d.file.change.status is FileStatus.DELETED,
|
|
829
|
+
d.file.index,
|
|
830
|
+
d.order,
|
|
831
|
+
)
|
|
832
|
+
)
|
|
833
|
+
kept, dropped = drafts[:limit], drafts[limit:]
|
|
834
|
+
for path in dict.fromkeys(d.file.change.path for d in dropped):
|
|
835
|
+
leave_out(path, REASON_MAX_PACKETS)
|
|
836
|
+
digest = (prompt.PROTOCOL, prompt.prompt_sha256(), prompt.schema_sha256())
|
|
837
|
+
packets = tuple(_packet(d, digest) for d in kept)
|
|
838
|
+
head = changeset.head if changeset.head is not None else changeset.snapshot
|
|
839
|
+
run_id = hashlib.sha256(
|
|
840
|
+
prompt.canonical(
|
|
841
|
+
[__version__, changeset.mode, changeset.base, head, [p.packet_id for p in packets]]
|
|
842
|
+
)
|
|
843
|
+
).hexdigest()
|
|
844
|
+
return PacketSet(
|
|
845
|
+
run_id=run_id,
|
|
846
|
+
mode=changeset.mode,
|
|
847
|
+
base=changeset.base,
|
|
848
|
+
head=changeset.head,
|
|
849
|
+
snapshot=changeset.snapshot,
|
|
850
|
+
packets=packets,
|
|
851
|
+
coverage=tuple(coverage),
|
|
852
|
+
gaps=tuple(gaps),
|
|
853
|
+
secrets=tuple(v for v, _ in ordered_values),
|
|
854
|
+
redaction=has_secret_detectors(registry),
|
|
855
|
+
)
|