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/publish/pull.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Pull-request steps both forges share: the report, the identity, the sticky comment, the re-check.
|
|
2
|
+
|
|
3
|
+
- :func:`read_checked_report`: load the report and run every untrusted-report
|
|
4
|
+
check against the event, returning the report or a reason it is missing or
|
|
5
|
+
rejected (never raising for those).
|
|
6
|
+
- :func:`identity`: the login of the token's user, so deduplication and the
|
|
7
|
+
sticky comment only ever consider comments this identity wrote.
|
|
8
|
+
- :func:`upsert_sticky`: create or update the one summary comment marked
|
|
9
|
+
:data:`SUMMARY_MARKER` that this identity wrote.
|
|
10
|
+
- :func:`moved`: re-read the pull request; true when it is closed or its head
|
|
11
|
+
or base is no longer the event's (a newer run will publish).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
from collections.abc import Iterable, Mapping
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from codeveto.publish.event import Event
|
|
23
|
+
from codeveto.publish.http import Client, HttpError
|
|
24
|
+
from codeveto.publish.untrusted import ReportRejected, check_report, load_report
|
|
25
|
+
from codeveto.render import safe
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"SUMMARY_MARKER",
|
|
29
|
+
"Checked",
|
|
30
|
+
"author",
|
|
31
|
+
"bot_login",
|
|
32
|
+
"failure_body",
|
|
33
|
+
"identity",
|
|
34
|
+
"is_own",
|
|
35
|
+
"moved",
|
|
36
|
+
"read_checked_report",
|
|
37
|
+
"upsert_sticky",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
SUMMARY_MARKER = "<!-- codeveto:summary -->"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True)
|
|
44
|
+
class Checked:
|
|
45
|
+
"""The outcome of reading the report: ``report`` set, or ``problem`` saying why not.
|
|
46
|
+
|
|
47
|
+
``summarized``: the action's failed prepare step already wrote the reason
|
|
48
|
+
to the job summary, so ``publish`` must not write it again.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
report: dict[str, Any] | None
|
|
52
|
+
problem: str | None
|
|
53
|
+
missing: bool = False
|
|
54
|
+
summarized: bool = False
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def read_checked_report(
|
|
58
|
+
path: str, event: Event, environ: Mapping[str, str] | None = None
|
|
59
|
+
) -> Checked:
|
|
60
|
+
"""The report at ``path`` if it passes every check (SPEC 10.4), else why not.
|
|
61
|
+
|
|
62
|
+
When the action's prepare step did not get to the review
|
|
63
|
+
(``CODEVETO_PREPARE_STATUS`` present and not ``review``), any file at
|
|
64
|
+
``path`` is ignored and the outcome is "did not complete" with the prepare
|
|
65
|
+
step's message (``summarized`` when that step failed: it wrote the job
|
|
66
|
+
summary itself). The outcome is also written as the step output
|
|
67
|
+
``report-status`` (``ok``, ``missing`` or ``rejected``) when
|
|
68
|
+
``$GITHUB_OUTPUT`` is set, so the action's last step can fail a run whose
|
|
69
|
+
report was rejected.
|
|
70
|
+
"""
|
|
71
|
+
env = environ or {}
|
|
72
|
+
if "CODEVETO_PREPARE_STATUS" in env and env["CODEVETO_PREPARE_STATUS"] != "review":
|
|
73
|
+
message = " ".join(env.get("CODEVETO_PREPARE_MESSAGE", "").split())
|
|
74
|
+
checked = Checked(
|
|
75
|
+
None,
|
|
76
|
+
message or "the review was not prepared",
|
|
77
|
+
missing=True,
|
|
78
|
+
summarized=env["CODEVETO_PREPARE_STATUS"] == "fail",
|
|
79
|
+
)
|
|
80
|
+
elif not os.path.isfile(path):
|
|
81
|
+
checked = Checked(None, "the review wrote no report", missing=True)
|
|
82
|
+
else:
|
|
83
|
+
try:
|
|
84
|
+
report = load_report(path)
|
|
85
|
+
check_report(report, head=event.head, base=event.base)
|
|
86
|
+
except ReportRejected as exc:
|
|
87
|
+
checked = Checked(None, f"report rejected: {exc}")
|
|
88
|
+
else:
|
|
89
|
+
checked = Checked(report, None)
|
|
90
|
+
_report_status(env, checked)
|
|
91
|
+
return checked
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _report_status(environ: Mapping[str, str], checked: Checked) -> None:
|
|
95
|
+
output = environ.get("GITHUB_OUTPUT")
|
|
96
|
+
if not output:
|
|
97
|
+
return
|
|
98
|
+
status = "ok" if checked.report is not None else "missing" if checked.missing else "rejected"
|
|
99
|
+
try:
|
|
100
|
+
with open(output, "a", encoding="utf-8") as stream:
|
|
101
|
+
stream.write(f"report-status={status}\n")
|
|
102
|
+
except OSError:
|
|
103
|
+
pass # the last step then falls back to the review's own exit code
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def failure_body(checked: Checked) -> str:
|
|
107
|
+
"""The summary when there is no usable report (trusted text only)."""
|
|
108
|
+
title = "CodeVeto did not complete" if checked.missing else "CodeVeto: report rejected"
|
|
109
|
+
reason = checked.problem or "unknown reason"
|
|
110
|
+
return (
|
|
111
|
+
f"### {title}\n\n{safe.md_code(reason)}\n\n"
|
|
112
|
+
"The check fails as incomplete (exit 2). See the job log.\n"
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def author(item: object) -> str | None:
|
|
117
|
+
"""The login that wrote a comment or review item."""
|
|
118
|
+
if not isinstance(item, Mapping):
|
|
119
|
+
return None
|
|
120
|
+
user = item.get("user")
|
|
121
|
+
login = user.get("login") if isinstance(user, Mapping) else None
|
|
122
|
+
return login if isinstance(login, str) and login else None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
_LOGIN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,98}[A-Za-z0-9])?(?:\[bot\])?")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def bot_login(environ: Mapping[str, str], default: str) -> str:
|
|
129
|
+
"""The identity to assume when the token cannot read ``GET /user``.
|
|
130
|
+
|
|
131
|
+
``CODEVETO_BOT_LOGIN`` (the action's ``bot-login`` input) names it for a
|
|
132
|
+
GitHub App or fine-grained token, such as ``my-app[bot]``; otherwise
|
|
133
|
+
``default`` (the forge's workflow-token bot).
|
|
134
|
+
"""
|
|
135
|
+
value = environ.get("CODEVETO_BOT_LOGIN", "").strip()
|
|
136
|
+
return value if value and _LOGIN.fullmatch(value) else default
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def is_own(item: object, login: str) -> bool:
|
|
140
|
+
"""Did ``login`` write this comment?
|
|
141
|
+
|
|
142
|
+
The author must be ``login``; when the forge also says which GitHub App
|
|
143
|
+
performed it (``performed_via_github_app``), that App's bot must be the
|
|
144
|
+
author too, so a comment is never taken as ours on a mismatched record.
|
|
145
|
+
"""
|
|
146
|
+
if author(item) != login or not isinstance(item, Mapping):
|
|
147
|
+
return False
|
|
148
|
+
app = item.get("performed_via_github_app")
|
|
149
|
+
if isinstance(app, Mapping):
|
|
150
|
+
slug = app.get("slug")
|
|
151
|
+
if isinstance(slug, str) and slug and login.endswith("[bot]"):
|
|
152
|
+
return login == f"{slug}[bot]"
|
|
153
|
+
return True
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def identity(client: Client, fallback: str) -> str:
|
|
157
|
+
"""``GET /user``'s login; ``fallback`` when the token cannot read its own user.
|
|
158
|
+
|
|
159
|
+
An installation token gets 403 here: GitHub's ``GITHUB_TOKEN`` acts as
|
|
160
|
+
``github-actions[bot]``, a GitHub App's token as the login given by
|
|
161
|
+
:func:`bot_login`.
|
|
162
|
+
"""
|
|
163
|
+
try:
|
|
164
|
+
data = client.json("GET", "/user")
|
|
165
|
+
except HttpError as exc:
|
|
166
|
+
if exc.status in (401, 403, 404):
|
|
167
|
+
return fallback
|
|
168
|
+
raise
|
|
169
|
+
login = data.get("login") if isinstance(data, Mapping) else None
|
|
170
|
+
return login if isinstance(login, str) and login else fallback
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def own_sticky(comments: Iterable[Any], login: str) -> Mapping[str, Any] | None:
|
|
174
|
+
"""The first summary comment ``login`` wrote, if any."""
|
|
175
|
+
for comment in comments:
|
|
176
|
+
if not isinstance(comment, Mapping) or not is_own(comment, login):
|
|
177
|
+
continue
|
|
178
|
+
body = comment.get("body")
|
|
179
|
+
number = comment.get("id")
|
|
180
|
+
if (
|
|
181
|
+
isinstance(body, str)
|
|
182
|
+
and body.startswith(SUMMARY_MARKER)
|
|
183
|
+
and isinstance(number, int)
|
|
184
|
+
and not isinstance(number, bool)
|
|
185
|
+
):
|
|
186
|
+
return comment
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def upsert_sticky(
|
|
191
|
+
client: Client,
|
|
192
|
+
*,
|
|
193
|
+
repo: str,
|
|
194
|
+
number: int,
|
|
195
|
+
login: str,
|
|
196
|
+
comments: Iterable[Any],
|
|
197
|
+
body: str,
|
|
198
|
+
) -> str:
|
|
199
|
+
"""Update this identity's summary comment, or create one: ``"updated"`` or ``"created"``."""
|
|
200
|
+
existing = own_sticky(comments, login)
|
|
201
|
+
if existing is not None:
|
|
202
|
+
client.json("PATCH", f"/repos/{repo}/issues/comments/{existing['id']}", body={"body": body})
|
|
203
|
+
return "updated"
|
|
204
|
+
client.json("POST", f"/repos/{repo}/issues/{number}/comments", body={"body": body})
|
|
205
|
+
return "created"
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def moved(client: Client, event: Event) -> bool:
|
|
209
|
+
"""Re-read the pull request: has its head or base moved since the event?"""
|
|
210
|
+
data = client.json("GET", f"/repos/{event.repo}/pulls/{event.number}")
|
|
211
|
+
if not isinstance(data, Mapping):
|
|
212
|
+
raise HttpError("the pull request could not be read")
|
|
213
|
+
head = data.get("head")
|
|
214
|
+
base = data.get("base")
|
|
215
|
+
head_sha = head.get("sha") if isinstance(head, Mapping) else None
|
|
216
|
+
base_sha = base.get("sha") if isinstance(base, Mapping) else None
|
|
217
|
+
state = data.get("state")
|
|
218
|
+
return state != "open" or head_sha != event.head or base_sha != event.base
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""The report is untrusted input to ``publish`` (SPEC 10.4).
|
|
2
|
+
|
|
3
|
+
The review that wrote it read the change under review, so ``publish``
|
|
4
|
+
accepts a report only when all of these hold, and refuses it with a
|
|
5
|
+
:class:`ReportRejected` that names the first failed check otherwise:
|
|
6
|
+
|
|
7
|
+
1. at most :data:`MAX_REPORT_BYTES` bytes, UTF-8, strict JSON (no duplicate
|
|
8
|
+
keys, no ``NaN``/``Infinity``), an object;
|
|
9
|
+
2. valid against ``data/report-v1.schema.json``, every number a JSON integer
|
|
10
|
+
(``1.0`` is not one);
|
|
11
|
+
3. a ``range`` review whose ``target.head`` (and ``target.base`` when the
|
|
12
|
+
event names one) are the event's commit IDs;
|
|
13
|
+
4. consistent: ``exit_code`` matches ``verdict``; ``vetoed`` if and only if a
|
|
14
|
+
finding is blocking; ``clear`` only with no issue or coverage gap that makes
|
|
15
|
+
the review incomplete; the summary counts equal the findings; no
|
|
16
|
+
fingerprint repeats.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from collections import Counter
|
|
22
|
+
from collections.abc import Mapping
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from codeveto import schema
|
|
26
|
+
from codeveto.publish import PublishError
|
|
27
|
+
from codeveto.publish.event import read_capped, strict_json
|
|
28
|
+
from codeveto.report import coverage_incomplete, load_schema, verdict_exit_code
|
|
29
|
+
|
|
30
|
+
__all__ = ["MAX_REPORT_BYTES", "ReportRejected", "check_report", "load_report"]
|
|
31
|
+
|
|
32
|
+
MAX_REPORT_BYTES = 16 * 1024 * 1024
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ReportRejected(PublishError):
|
|
36
|
+
"""The report failed a check; the message names which (never quotes report data)."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_report(path: str, *, cap: int | None = None) -> dict[str, Any]:
|
|
40
|
+
"""Read, parse and schema-validate the report at ``path`` (checks 1 and 2)."""
|
|
41
|
+
try:
|
|
42
|
+
data = read_capped(path, cap or MAX_REPORT_BYTES, "report")
|
|
43
|
+
report = strict_json(data, what="the report")
|
|
44
|
+
except PublishError as exc:
|
|
45
|
+
raise ReportRejected(str(exc)) from None
|
|
46
|
+
if not isinstance(report, dict):
|
|
47
|
+
raise ReportRejected("the report is not a JSON object")
|
|
48
|
+
errors = schema.validate(report, load_schema())
|
|
49
|
+
if errors:
|
|
50
|
+
raise ReportRejected(
|
|
51
|
+
f"the report does not match the report v1 schema ({len(errors)} error(s))"
|
|
52
|
+
)
|
|
53
|
+
if _has_float(report):
|
|
54
|
+
raise ReportRejected("the report has a JSON float where an integer is required")
|
|
55
|
+
return report
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _has_float(value: object) -> bool:
|
|
59
|
+
"""Does ``value`` hold a float anywhere?
|
|
60
|
+
|
|
61
|
+
Every number in the report schema is an integer (a test keeps it so), but
|
|
62
|
+
the schema validator, like JSON Schema, accepts an integral float such as
|
|
63
|
+
``1.0``; an untrusted report must use real integers (``type(x) is int``).
|
|
64
|
+
Booleans are not numbers there, so the schema already rejects them.
|
|
65
|
+
"""
|
|
66
|
+
stack = [value]
|
|
67
|
+
while stack:
|
|
68
|
+
item = stack.pop()
|
|
69
|
+
if isinstance(item, float):
|
|
70
|
+
return True
|
|
71
|
+
if isinstance(item, dict):
|
|
72
|
+
stack.extend(item.values())
|
|
73
|
+
elif isinstance(item, list):
|
|
74
|
+
stack.extend(item)
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def check_report(report: Mapping[str, Any], *, head: str, base: str | None) -> None:
|
|
79
|
+
"""Checks 3 and 4 against the event's ``head`` and ``base`` commit IDs."""
|
|
80
|
+
target = report["target"]
|
|
81
|
+
if target["mode"] != "range":
|
|
82
|
+
raise ReportRejected("the report is not a range review")
|
|
83
|
+
if target["head"] != head:
|
|
84
|
+
raise ReportRejected("the report's head commit is not the event's head")
|
|
85
|
+
if base is not None and target["base"] != base:
|
|
86
|
+
raise ReportRejected("the report's base commit is not the event's base")
|
|
87
|
+
verdict = report["verdict"]
|
|
88
|
+
if report["exit_code"] != verdict_exit_code(verdict):
|
|
89
|
+
raise ReportRejected("the report's exit code does not match its verdict")
|
|
90
|
+
findings = report["findings"]
|
|
91
|
+
blocking = sum(1 for f in findings if f["blocking"])
|
|
92
|
+
if (verdict == "vetoed") != (blocking > 0):
|
|
93
|
+
raise ReportRejected("the report's verdict does not match its blocking findings")
|
|
94
|
+
if verdict == "clear" and (
|
|
95
|
+
any(i["incomplete"] for i in report["issues"])
|
|
96
|
+
or any(coverage_incomplete(c) for c in report["coverage"])
|
|
97
|
+
):
|
|
98
|
+
raise ReportRejected("the report is clear but lists what kept it from completing")
|
|
99
|
+
counts = Counter(f["severity"] for f in findings)
|
|
100
|
+
summary = report["summary"]
|
|
101
|
+
if (
|
|
102
|
+
summary["blocking"] != blocking
|
|
103
|
+
or summary["errors"] != counts["error"]
|
|
104
|
+
or summary["warnings"] != counts["warning"]
|
|
105
|
+
or summary["notes"] != counts["note"]
|
|
106
|
+
):
|
|
107
|
+
raise ReportRejected("the report's summary counts do not match its findings")
|
|
108
|
+
fingerprints = Counter(f["fingerprint"] for f in findings)
|
|
109
|
+
if fingerprints and fingerprints.most_common(1)[0][1] > 1:
|
|
110
|
+
raise ReportRejected("the report repeats a finding fingerprint")
|
codeveto/py.typed
ADDED
|
File without changes
|
codeveto/redact.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Secret redaction for findings (SPEC 5.3, 5.6).
|
|
2
|
+
|
|
3
|
+
A rule marks secret text with ``Hit.redact`` spans ``(line, start_col,
|
|
4
|
+
end_col)``: 1-based columns on the hit's side, ``end_col`` exclusive, ``None``
|
|
5
|
+
meaning to the end of the line. The engine resolves every span to the secret
|
|
6
|
+
substring it covers (:func:`secret_values`) and, before any finding leaves the
|
|
7
|
+
engine, replaces
|
|
8
|
+
|
|
9
|
+
- each span on a snippet's own line, by column (:func:`redact_line`), and
|
|
10
|
+
- every occurrence of every secret substring in snippets, messages and
|
|
11
|
+
evidence (:func:`redact_text`), so a secret quoted by a message or seen by
|
|
12
|
+
another rule on another line is hidden too.
|
|
13
|
+
|
|
14
|
+
Redacted text becomes :data:`MARKER`, which does not reveal the length of
|
|
15
|
+
what it replaces. Occurrences are found one secret at a time, overlapping
|
|
16
|
+
ones included, and merged before replacing, so a marker never contains part
|
|
17
|
+
of a secret and never gets redacted itself.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from collections.abc import Iterable, Sequence
|
|
23
|
+
|
|
24
|
+
from codeveto.rules.base import RedactSpan
|
|
25
|
+
|
|
26
|
+
__all__ = ["MARKER", "SpanError", "redact_line", "redact_text", "secret_values"]
|
|
27
|
+
|
|
28
|
+
MARKER = "[redacted]"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SpanError(ValueError):
|
|
32
|
+
"""A redact span does not lie inside the text it refers to."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _span_range(span: RedactSpan, text: str) -> tuple[int, int]:
|
|
36
|
+
_, start, end = span
|
|
37
|
+
stop = len(text) + 1 if end is None else end
|
|
38
|
+
if start > len(text) + 1 or stop > len(text) + 1:
|
|
39
|
+
raise SpanError("redact span runs past the end of its line")
|
|
40
|
+
return start - 1, stop - 1
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def secret_values(lines: Sequence[str], spans: Iterable[RedactSpan]) -> tuple[str, ...]:
|
|
44
|
+
"""The non-empty substrings the ``spans`` cover in ``lines`` (``lines[n - 1]`` is line ``n``).
|
|
45
|
+
|
|
46
|
+
Raises :class:`SpanError` when a span names a line or column outside
|
|
47
|
+
``lines``, so a wrong span can never leave its secret unredacted silently.
|
|
48
|
+
"""
|
|
49
|
+
values: list[str] = []
|
|
50
|
+
for span in spans:
|
|
51
|
+
line = span[0]
|
|
52
|
+
if line > len(lines):
|
|
53
|
+
raise SpanError("redact span names a line past the end of the file")
|
|
54
|
+
text = lines[line - 1]
|
|
55
|
+
lo, hi = _span_range(span, text)
|
|
56
|
+
if hi > lo:
|
|
57
|
+
values.append(text[lo:hi])
|
|
58
|
+
return tuple(dict.fromkeys(values))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _occurrences(text: str, secrets: Iterable[str]) -> list[tuple[int, int]]:
|
|
62
|
+
found: list[tuple[int, int]] = []
|
|
63
|
+
for secret in secrets:
|
|
64
|
+
if not secret:
|
|
65
|
+
continue
|
|
66
|
+
at = text.find(secret)
|
|
67
|
+
while at >= 0:
|
|
68
|
+
found.append((at, at + len(secret)))
|
|
69
|
+
at = text.find(secret, at + 1)
|
|
70
|
+
return found
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _replace(text: str, ranges: list[tuple[int, int]]) -> str:
|
|
74
|
+
if not ranges:
|
|
75
|
+
return text
|
|
76
|
+
ranges.sort()
|
|
77
|
+
out: list[str] = []
|
|
78
|
+
pos = 0
|
|
79
|
+
cur_lo, cur_hi = ranges[0]
|
|
80
|
+
for lo, hi in ranges[1:]:
|
|
81
|
+
if lo <= cur_hi:
|
|
82
|
+
cur_hi = max(cur_hi, hi)
|
|
83
|
+
continue
|
|
84
|
+
out.append(text[pos:cur_lo])
|
|
85
|
+
out.append(MARKER)
|
|
86
|
+
pos = cur_hi
|
|
87
|
+
cur_lo, cur_hi = lo, hi
|
|
88
|
+
out.append(text[pos:cur_lo])
|
|
89
|
+
out.append(MARKER)
|
|
90
|
+
out.append(text[cur_hi:])
|
|
91
|
+
return "".join(out)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def redact_text(text: str | None, secrets: Iterable[str]) -> str | None:
|
|
95
|
+
"""``text`` with every occurrence of every secret replaced by :data:`MARKER`."""
|
|
96
|
+
if not text:
|
|
97
|
+
return text
|
|
98
|
+
return _replace(text, _occurrences(text, secrets))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def redact_line(
|
|
102
|
+
text: str, line: int, spans: Iterable[RedactSpan], secrets: Iterable[str] = ()
|
|
103
|
+
) -> str:
|
|
104
|
+
"""Line ``line`` of a file with its own spans and every known secret redacted.
|
|
105
|
+
|
|
106
|
+
Spans on other lines are ignored here (their substrings still count when
|
|
107
|
+
they are among ``secrets``). Raises :class:`SpanError` for a span that runs
|
|
108
|
+
past the end of ``text``.
|
|
109
|
+
"""
|
|
110
|
+
ranges = [_span_range(span, text) for span in spans if span[0] == line]
|
|
111
|
+
ranges = [(lo, hi) for lo, hi in ranges if hi > lo]
|
|
112
|
+
ranges.extend(_occurrences(text, secrets))
|
|
113
|
+
return _replace(text, ranges)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Output formats: a registry from ``--format`` name to renderer (SPEC 8).
|
|
2
|
+
|
|
3
|
+
Each format lives in its own module ``codeveto.render.<module>`` with a
|
|
4
|
+
function ``render(report, options) -> str`` that takes the JSON report v1
|
|
5
|
+
dict (:mod:`codeveto.report`) and returns the whole output. The registry
|
|
6
|
+
imports a module only when its format is used, so adding or finishing a
|
|
7
|
+
format touches only its own module: ``sarif``, ``markdown`` and ``github``
|
|
8
|
+
are stubs that raise :class:`NotImplementedError` until they land (C3), and
|
|
9
|
+
the CLI turns that into exit code 2 with a clear message.
|
|
10
|
+
|
|
11
|
+
Every renderer passes repository- and model-derived text through
|
|
12
|
+
:mod:`codeveto.render.safe`, and only renderers emit colour codes or markup.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import importlib
|
|
18
|
+
from collections.abc import Callable, Mapping
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
__all__ = ["FORMATS", "RenderOptions", "Renderer", "get_renderer", "render"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class RenderOptions:
|
|
27
|
+
"""How to draw a report.
|
|
28
|
+
|
|
29
|
+
``color``: emit ANSI colour (the CLI decides from ``--color``, the TTY and
|
|
30
|
+
``NO_COLOR``). ``unicode``: use the Unicode symbols (else the ASCII
|
|
31
|
+
fallback). ``width``: truncate lines to this many columns (the CLI sets
|
|
32
|
+
it only on a TTY), ``None`` for no truncation.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
color: bool = False
|
|
36
|
+
unicode: bool = True
|
|
37
|
+
width: int | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
Renderer = Callable[[Mapping[str, Any], RenderOptions], str]
|
|
41
|
+
|
|
42
|
+
#: ``--format`` name → module under ``codeveto.render``.
|
|
43
|
+
_MODULES: dict[str, str] = {
|
|
44
|
+
"text": "text",
|
|
45
|
+
"json": "json",
|
|
46
|
+
"sarif": "sarif",
|
|
47
|
+
"markdown": "markdown",
|
|
48
|
+
"github": "github",
|
|
49
|
+
"agent": "agent",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
FORMATS: tuple[str, ...] = tuple(_MODULES)
|
|
53
|
+
"""Every ``--format`` value, in the order the CLI lists them."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_renderer(name: str) -> Renderer:
|
|
57
|
+
"""The renderer for ``--format name``; an unknown name raises ``KeyError``."""
|
|
58
|
+
module = importlib.import_module(f"{__name__}.{_MODULES[name]}")
|
|
59
|
+
return module.render # type: ignore[no-any-return]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def render(name: str, report: Mapping[str, Any], options: RenderOptions | None = None) -> str:
|
|
63
|
+
"""Render ``report`` in format ``name`` (stubs raise ``NotImplementedError``)."""
|
|
64
|
+
return get_renderer(name)(report, options or RenderOptions())
|
codeveto/render/agent.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""``--format agent``: a concise, colourless format for agent harness hooks (SPEC 8, 10.3).
|
|
2
|
+
|
|
3
|
+
One finding per line, ``path:line rule severity message`` (``path rule
|
|
4
|
+
severity message`` for a file-level finding; a finding on a removed line
|
|
5
|
+
ends with ``(removed line)``). Then one ``incomplete:`` line per issue or
|
|
6
|
+
not-benign coverage gap that kept the review from completing, one ``note:``
|
|
7
|
+
line per issue that does not affect the verdict, and a last line
|
|
8
|
+
``verdict <verdict> exit <code>``. Exit codes are unchanged. Every
|
|
9
|
+
repository-derived string goes through :func:`codeveto.render.safe.text`.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from codeveto.render import RenderOptions, safe
|
|
18
|
+
from codeveto.report import coverage_incomplete
|
|
19
|
+
|
|
20
|
+
__all__ = ["render"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def render(report: Mapping[str, Any], options: RenderOptions) -> str:
|
|
24
|
+
"""The report in agent format (``options`` do not apply: never coloured or truncated)."""
|
|
25
|
+
lines: list[str] = []
|
|
26
|
+
for f in report["findings"]:
|
|
27
|
+
where = safe.text(f["path"])
|
|
28
|
+
if f["line"] is not None:
|
|
29
|
+
where += f":{f['line']}"
|
|
30
|
+
message = safe.text(f["message"])
|
|
31
|
+
if f["side"] == "old":
|
|
32
|
+
message += " (removed line)"
|
|
33
|
+
lines.append(f"{where} {safe.text(f['rule'])} {f['severity']} {message}")
|
|
34
|
+
for issue in report.get("issues", ()):
|
|
35
|
+
label = "incomplete" if issue.get("incomplete", True) else "note"
|
|
36
|
+
where = f"{safe.text(issue['path'])}: " if issue.get("path") else ""
|
|
37
|
+
lines.append(f"{label}: {where}{safe.text(issue['message'])}")
|
|
38
|
+
for entry in report.get("coverage", ()):
|
|
39
|
+
if coverage_incomplete(entry):
|
|
40
|
+
reason = safe.text(entry.get("reason") or "no reason given")
|
|
41
|
+
lines.append(f"incomplete: {safe.text(entry['path'])}: {entry['status']} ({reason})")
|
|
42
|
+
lines.append(f"verdict {report['verdict']} exit {report['exit_code']}")
|
|
43
|
+
return "\n".join(lines) + "\n"
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""``--format github``: GitHub Actions workflow-command annotations (SPEC 8.1).
|
|
2
|
+
|
|
3
|
+
One command per finding, in report order::
|
|
4
|
+
|
|
5
|
+
::error file=src/a.py,line=2,col=5,title=demo/forbidden-word::Forbidden word%0AFix it.
|
|
6
|
+
|
|
7
|
+
- Command by severity: ``error``, ``warning``, ``notice`` (for notes).
|
|
8
|
+
- A new-side line finding carries ``line`` (and ``endLine``, ``col``); a
|
|
9
|
+
finding on a removed line or a whole file carries only ``file`` (the line
|
|
10
|
+
does not exist in the reviewed revision) and says which removed line it is.
|
|
11
|
+
- The message is the finding's message, a line break and its hint.
|
|
12
|
+
- One ``::warning`` per issue or not-benign coverage gap that made the review
|
|
13
|
+
incomplete, one ``::notice`` per issue that does not affect the verdict.
|
|
14
|
+
- A last plain line ``codeveto: <verdict>, <counts>, exit <code>``.
|
|
15
|
+
|
|
16
|
+
Untrusted text goes through :func:`codeveto.render.safe.workflow_property`
|
|
17
|
+
(properties: ``%``, CR, LF, ``:`` and ``,`` encoded) and
|
|
18
|
+
:func:`codeveto.render.safe.workflow_data` (data: ``%``, CR, LF encoded),
|
|
19
|
+
which also escape every other unsafe character, so a path or message can
|
|
20
|
+
never end a command, start a new one or forge a property.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
from collections.abc import Iterator, Mapping
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from codeveto.render import RenderOptions, safe
|
|
29
|
+
from codeveto.report import coverage_incomplete
|
|
30
|
+
|
|
31
|
+
__all__ = ["annotation", "issue_commands", "render"]
|
|
32
|
+
|
|
33
|
+
_COMMAND = {"error": "error", "warning": "warning", "note": "notice"}
|
|
34
|
+
_MESSAGE_CAP = 4_000
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _command(name: str, properties: Mapping[str, object], data: str) -> str:
|
|
38
|
+
props = ",".join(
|
|
39
|
+
f"{key}={safe.workflow_property(value)}"
|
|
40
|
+
for key, value in properties.items()
|
|
41
|
+
if value is not None
|
|
42
|
+
)
|
|
43
|
+
head = f"{name} {props}" if props else name
|
|
44
|
+
return f"::{head}::{safe.workflow_data(data)}"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def annotation(finding: Mapping[str, Any]) -> str:
|
|
48
|
+
"""The workflow command for one report finding."""
|
|
49
|
+
line = finding["line"]
|
|
50
|
+
message = safe.truncate(str(finding["message"]), _MESSAGE_CAP)
|
|
51
|
+
props: dict[str, object] = {"file": finding["path"]}
|
|
52
|
+
if line is not None and finding["side"] == "new":
|
|
53
|
+
props["line"] = line
|
|
54
|
+
end = finding["end_line"]
|
|
55
|
+
if end is not None and end > line:
|
|
56
|
+
props["endLine"] = end
|
|
57
|
+
elif finding["column"] is not None:
|
|
58
|
+
props["col"] = finding["column"]
|
|
59
|
+
elif line is not None:
|
|
60
|
+
props["file"] = finding.get("old_path") or finding["path"]
|
|
61
|
+
message = f"{message} (removed line {line})"
|
|
62
|
+
props["title"] = finding["rule"]
|
|
63
|
+
hint = safe.truncate(str(finding.get("hint") or ""), _MESSAGE_CAP)
|
|
64
|
+
data = f"{message}\n{hint}" if hint else message
|
|
65
|
+
return _command(_COMMAND[finding["severity"]], props, data)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def issue_commands(report: Mapping[str, Any]) -> Iterator[str]:
|
|
69
|
+
"""One command per issue and per not-benign coverage gap."""
|
|
70
|
+
explained: set[str] = set()
|
|
71
|
+
for issue in report.get("issues", ()):
|
|
72
|
+
incomplete = issue.get("incomplete", True)
|
|
73
|
+
if incomplete and issue.get("path"):
|
|
74
|
+
explained.add(issue["path"])
|
|
75
|
+
props: dict[str, object] = {
|
|
76
|
+
"file": issue.get("path") or None,
|
|
77
|
+
"title": "codeveto incomplete" if incomplete else "codeveto",
|
|
78
|
+
}
|
|
79
|
+
message = safe.truncate(str(issue["message"]), _MESSAGE_CAP)
|
|
80
|
+
yield _command("warning" if incomplete else "notice", props, message)
|
|
81
|
+
for entry in report.get("coverage", ()):
|
|
82
|
+
if coverage_incomplete(entry) and entry["path"] not in explained:
|
|
83
|
+
reason = entry.get("reason") or "no reason given"
|
|
84
|
+
props = {"file": entry["path"], "title": "codeveto incomplete"}
|
|
85
|
+
yield _command("warning", props, f"{entry['status']}: {reason}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _plural(count: int, word: str) -> str:
|
|
89
|
+
return f"{count} {word}" if count == 1 else f"{count} {word}s"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def render(report: Mapping[str, Any], options: RenderOptions) -> str:
|
|
93
|
+
"""The report as workflow commands (``options`` do not apply)."""
|
|
94
|
+
lines = [annotation(f) for f in report["findings"]]
|
|
95
|
+
lines += issue_commands(report)
|
|
96
|
+
summary = report["summary"]
|
|
97
|
+
lines.append(
|
|
98
|
+
f"codeveto: {report['verdict']}, {_plural(summary['blocking'], 'blocking finding')}, "
|
|
99
|
+
f"{_plural(summary['warnings'], 'warning')}, exit {report['exit_code']}"
|
|
100
|
+
)
|
|
101
|
+
return "\n".join(lines) + "\n"
|
codeveto/render/json.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""``--format json``: the JSON report v1 exactly as :mod:`codeveto.report` builds it.
|
|
2
|
+
|
|
3
|
+
Keys keep the report's order, and the document ends with a newline. Text is
|
|
4
|
+
written as UTF-8; every character :mod:`codeveto.render.safe` treats as unsafe
|
|
5
|
+
(C1 controls, bidi and other format characters, line separators, lone
|
|
6
|
+
surrogates) is written as a ``\\uXXXX`` escape, so the data a JSON reader sees
|
|
7
|
+
is unchanged while a terminal showing the raw file sees nothing hidden.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from collections.abc import Mapping
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from codeveto.render import RenderOptions, safe
|
|
17
|
+
|
|
18
|
+
__all__ = ["render"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def render(report: Mapping[str, Any], options: RenderOptions) -> str:
|
|
22
|
+
"""The report as indented JSON (``options`` do not apply: never coloured or truncated)."""
|
|
23
|
+
return safe.json_text(json.dumps(report, indent=2, ensure_ascii=False)) + "\n"
|