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
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""``codeveto publish github``: annotations, job summary, sticky comment and one review (SPEC 10.4).
|
|
2
|
+
|
|
3
|
+
Order of work:
|
|
4
|
+
|
|
5
|
+
1. The event (:mod:`.event`) and the report, checked as untrusted
|
|
6
|
+
(:mod:`.untrusted`). Without a usable report the job summary says why and,
|
|
7
|
+
on a pull request, the sticky comment is updated to say so too (after the
|
|
8
|
+
head re-check), so it never keeps showing an older verdict.
|
|
9
|
+
2. The text rendering goes to the job log with workflow commands stopped.
|
|
10
|
+
3. ``pull_request_target``: the pull request's files (``GET /pulls/{n}/files``,
|
|
11
|
+
every page up to GitHub's 3,000-file limit) decide which findings are on
|
|
12
|
+
lines it changes (:mod:`.diff`); the others are dropped and counted. The
|
|
13
|
+
token's identity, the existing issue comments and review comments are
|
|
14
|
+
read; the pull request is re-read and nothing is posted if its head or
|
|
15
|
+
base moved. Then: annotations, the sticky summary comment
|
|
16
|
+
(``<!-- codeveto:summary -->``, created or updated, only this identity's)
|
|
17
|
+
and at most one review per run (``event: COMMENT``, ``commit_id`` the head,
|
|
18
|
+
``side`` ``RIGHT`` or ``LEFT``) with at most :data:`MAX_INLINE` inline
|
|
19
|
+
comments that this identity has not already posted (fingerprint marker;
|
|
20
|
+
outdated comments count as absent). The rest are only in the summary.
|
|
21
|
+
4. ``merge_group`` and ``push``: annotations and the job summary, no comments.
|
|
22
|
+
5. ``CODEVETO_SARIF=true``: the SARIF of the published findings is uploaded
|
|
23
|
+
to code scanning (needs ``security-events: write``).
|
|
24
|
+
|
|
25
|
+
``CODEVETO_COMMENT=false`` turns off the comment and the review. Annotations
|
|
26
|
+
are capped at :data:`MAX_ANNOTATIONS` per level (GitHub shows no more per
|
|
27
|
+
step), blocking findings first. The token is ``GITHUB_TOKEN``.
|
|
28
|
+
|
|
29
|
+
The exit code is 0 when everything was published (or skipped because the
|
|
30
|
+
pull request moved) and 2 when something could not be; it never affects the
|
|
31
|
+
review's own exit code, which the action takes from the review step.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import base64
|
|
37
|
+
import gzip
|
|
38
|
+
import json
|
|
39
|
+
import re
|
|
40
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
41
|
+
from typing import Any, TextIO
|
|
42
|
+
|
|
43
|
+
from codeveto.publish import PublishError
|
|
44
|
+
from codeveto.publish.common import Output
|
|
45
|
+
from codeveto.publish.diff import FileLines, from_github_files, placement
|
|
46
|
+
from codeveto.publish.event import Event, read_event
|
|
47
|
+
from codeveto.publish.http import Client, HttpError
|
|
48
|
+
from codeveto.publish.pull import (
|
|
49
|
+
SUMMARY_MARKER,
|
|
50
|
+
bot_login,
|
|
51
|
+
failure_body,
|
|
52
|
+
identity,
|
|
53
|
+
is_own,
|
|
54
|
+
moved,
|
|
55
|
+
read_checked_report,
|
|
56
|
+
upsert_sticky,
|
|
57
|
+
)
|
|
58
|
+
from codeveto.render import github as annotations
|
|
59
|
+
from codeveto.render import markdown, safe
|
|
60
|
+
from codeveto.render import sarif as sarif_renderer
|
|
61
|
+
|
|
62
|
+
Sleep = Callable[[float], None] | None
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"BOT_LOGIN",
|
|
66
|
+
"MAX_ANNOTATIONS",
|
|
67
|
+
"MAX_INLINE",
|
|
68
|
+
"REVIEW_MARKER",
|
|
69
|
+
"inline_body",
|
|
70
|
+
"publish",
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
MAX_INLINE = 25
|
|
74
|
+
MAX_ANNOTATIONS = 10
|
|
75
|
+
MAX_FILE_PAGES = 30 # GitHub lists at most 3,000 files
|
|
76
|
+
MAX_COMMENT_PAGES = 50
|
|
77
|
+
BOT_LOGIN = "github-actions[bot]"
|
|
78
|
+
REVIEW_MARKER = "<!-- codeveto:review -->"
|
|
79
|
+
_FP = re.compile(r"<!-- codeveto:fp=([0-9a-f]{16}) -->") # the whole first line, exactly
|
|
80
|
+
_RANK = {"error": 0, "warning": 1, "note": 2}
|
|
81
|
+
_SYMBOL = {"error": "✕", "warning": "▲", "note": "·"}
|
|
82
|
+
_HEADERS = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _order(findings: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
|
|
86
|
+
return sorted(findings, key=lambda f: (not f["blocking"], _RANK[f["severity"]]))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def inline_body(finding: Mapping[str, Any]) -> str:
|
|
90
|
+
"""The body of one inline review comment (fingerprint marker first)."""
|
|
91
|
+
severity = finding["severity"]
|
|
92
|
+
label = f"{_SYMBOL[severity]} {severity}"
|
|
93
|
+
if finding["blocking"]:
|
|
94
|
+
label = f"**{label}** (blocking)"
|
|
95
|
+
lines = [
|
|
96
|
+
f"<!-- codeveto:fp={finding['fingerprint']} -->",
|
|
97
|
+
f"{label} · {safe.md_code(finding['rule'])}",
|
|
98
|
+
"",
|
|
99
|
+
safe.md_code(finding["message"]),
|
|
100
|
+
]
|
|
101
|
+
if finding.get("hint"):
|
|
102
|
+
lines += ["", f"Fix: {safe.md_code(finding['hint'])}"]
|
|
103
|
+
return "\n".join(lines)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _annotate(out: Output, findings: Sequence[Mapping[str, Any]]) -> int:
|
|
107
|
+
"""Print capped annotations, blocking first; return how many were left out."""
|
|
108
|
+
shown = {"error": 0, "warning": 0, "note": 0}
|
|
109
|
+
left = 0
|
|
110
|
+
for finding in _order(findings):
|
|
111
|
+
level = finding["severity"]
|
|
112
|
+
if shown[level] >= MAX_ANNOTATIONS:
|
|
113
|
+
left += 1
|
|
114
|
+
continue
|
|
115
|
+
shown[level] += 1
|
|
116
|
+
out.command(annotations.annotation(finding))
|
|
117
|
+
return left
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _posted(comments: Sequence[Any], login: str) -> set[str]:
|
|
121
|
+
"""Fingerprints this identity already has as current (not outdated) inline comments."""
|
|
122
|
+
seen: set[str] = set()
|
|
123
|
+
for comment in comments:
|
|
124
|
+
if not isinstance(comment, Mapping) or not is_own(comment, login):
|
|
125
|
+
continue
|
|
126
|
+
if comment.get("line") is None: # outdated: treated as absent
|
|
127
|
+
continue
|
|
128
|
+
body = comment.get("body")
|
|
129
|
+
if not isinstance(body, str):
|
|
130
|
+
continue
|
|
131
|
+
# Only the first line, exactly as inline_body writes it: a marker quoted in a
|
|
132
|
+
# message (Markdown code breaks "<!--" anyway) never counts.
|
|
133
|
+
match = _FP.fullmatch(body.split("\n", 1)[0])
|
|
134
|
+
if match:
|
|
135
|
+
seen.add(match.group(1))
|
|
136
|
+
return seen
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _review_comment(finding: Mapping[str, Any]) -> dict[str, Any]:
|
|
140
|
+
return {
|
|
141
|
+
"path": finding["path"],
|
|
142
|
+
"line": finding["line"],
|
|
143
|
+
"side": "LEFT" if finding["side"] == "old" else "RIGHT",
|
|
144
|
+
"body": inline_body(finding),
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _upload_sarif(
|
|
149
|
+
client: Client, event: Event, report: Mapping[str, Any], findings: Sequence[Any]
|
|
150
|
+
) -> None:
|
|
151
|
+
if event.ref is None:
|
|
152
|
+
raise PublishError("SARIF upload needs a ref, and this event has none")
|
|
153
|
+
log = sarif_renderer.build({**report, "findings": list(findings)})
|
|
154
|
+
payload = base64.b64encode(gzip.compress(json.dumps(log).encode("utf-8"), mtime=0))
|
|
155
|
+
client.json(
|
|
156
|
+
"POST",
|
|
157
|
+
f"/repos/{event.repo}/code-scanning/sarifs",
|
|
158
|
+
body={
|
|
159
|
+
"commit_sha": event.head,
|
|
160
|
+
"ref": event.ref,
|
|
161
|
+
"sarif": payload.decode("ascii"),
|
|
162
|
+
"tool_name": "codeveto",
|
|
163
|
+
},
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _plural(count: int, word: str) -> str:
|
|
168
|
+
return f"{count} {word}" if count == 1 else f"{count} {word}s"
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def publish(
|
|
172
|
+
environ: Mapping[str, str],
|
|
173
|
+
report_path: str,
|
|
174
|
+
*,
|
|
175
|
+
sleep: Sleep = None,
|
|
176
|
+
stdout: TextIO | None = None,
|
|
177
|
+
stderr: TextIO | None = None,
|
|
178
|
+
) -> int:
|
|
179
|
+
"""Publish the report at ``report_path`` for this GitHub Actions run (see module docstring)."""
|
|
180
|
+
out = Output(environ, stdout=stdout, stderr=stderr)
|
|
181
|
+
try:
|
|
182
|
+
return _publish(environ, report_path, out, sleep)
|
|
183
|
+
finally:
|
|
184
|
+
out.finish()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _client(environ: Mapping[str, str], event: Event, sleep: Sleep) -> Client:
|
|
188
|
+
return Client(
|
|
189
|
+
event.api_url, environ.get("GITHUB_TOKEN", ""), auth="Bearer", headers=_HEADERS, sleep=sleep
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _publish(environ: Mapping[str, str], report_path: str, out: Output, sleep: Sleep) -> int:
|
|
194
|
+
try:
|
|
195
|
+
event = read_event(environ, "github")
|
|
196
|
+
except PublishError as exc:
|
|
197
|
+
out.body = "### CodeVeto: not published\n\nThe workflow event could not be used.\n"
|
|
198
|
+
out.warn(str(exc))
|
|
199
|
+
return 2
|
|
200
|
+
comment = environ.get("CODEVETO_COMMENT", "true").strip().lower() != "false"
|
|
201
|
+
checked = read_checked_report(report_path, event, environ)
|
|
202
|
+
if checked.report is None:
|
|
203
|
+
out.body = failure_body(checked)
|
|
204
|
+
out.body_in_summary = not checked.summarized
|
|
205
|
+
out.warn(checked.problem or "no report")
|
|
206
|
+
if event.is_pull_request and comment:
|
|
207
|
+
_sticky_failure(environ, event, out, sleep)
|
|
208
|
+
return 2
|
|
209
|
+
report = checked.report
|
|
210
|
+
out.log_report(report)
|
|
211
|
+
findings: list[Mapping[str, Any]] = list(report["findings"])
|
|
212
|
+
if not event.is_pull_request:
|
|
213
|
+
left = _annotate(out, findings)
|
|
214
|
+
notes = [f"{_plural(left, 'annotation')} not shown (GitHub's limit)."] if left else []
|
|
215
|
+
out.body = markdown.summary(report, notes=notes)
|
|
216
|
+
_maybe_sarif(environ, event, report, findings, out, sleep)
|
|
217
|
+
return 2 if out.warnings else 0
|
|
218
|
+
return _publish_pull(environ, event, report, findings, comment, out, sleep)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _sticky_failure(environ: Mapping[str, str], event: Event, out: Output, sleep: Sleep) -> None:
|
|
222
|
+
try:
|
|
223
|
+
client = _client(environ, event, sleep)
|
|
224
|
+
login = identity(client, bot_login(environ, BOT_LOGIN))
|
|
225
|
+
comments, _ = client.paginate(
|
|
226
|
+
f"/repos/{event.repo}/issues/{event.number}/comments", max_pages=MAX_COMMENT_PAGES
|
|
227
|
+
)
|
|
228
|
+
if moved(client, event):
|
|
229
|
+
return
|
|
230
|
+
body = f"{SUMMARY_MARKER}\n{out.body or ''}"
|
|
231
|
+
upsert_sticky(
|
|
232
|
+
client,
|
|
233
|
+
repo=event.repo,
|
|
234
|
+
number=event.number or 0,
|
|
235
|
+
login=login,
|
|
236
|
+
comments=comments,
|
|
237
|
+
body=body,
|
|
238
|
+
)
|
|
239
|
+
except PublishError as exc:
|
|
240
|
+
out.warn(f"summary comment not updated: {exc}")
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _maybe_sarif(
|
|
244
|
+
environ: Mapping[str, str],
|
|
245
|
+
event: Event,
|
|
246
|
+
report: Mapping[str, Any],
|
|
247
|
+
findings: Sequence[Any],
|
|
248
|
+
out: Output,
|
|
249
|
+
sleep: Sleep,
|
|
250
|
+
) -> None:
|
|
251
|
+
if environ.get("CODEVETO_SARIF", "false").strip().lower() != "true":
|
|
252
|
+
return
|
|
253
|
+
try:
|
|
254
|
+
_upload_sarif(_client(environ, event, sleep), event, report, findings)
|
|
255
|
+
except PublishError as exc:
|
|
256
|
+
out.warn(f"SARIF not uploaded: {exc}")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _publish_pull(
|
|
260
|
+
environ: Mapping[str, str],
|
|
261
|
+
event: Event,
|
|
262
|
+
report: dict[str, Any],
|
|
263
|
+
findings: list[Mapping[str, Any]],
|
|
264
|
+
comment: bool,
|
|
265
|
+
out: Output,
|
|
266
|
+
sleep: Sleep,
|
|
267
|
+
) -> int:
|
|
268
|
+
notes: list[str] = []
|
|
269
|
+
try:
|
|
270
|
+
client = _client(environ, event, sleep)
|
|
271
|
+
entries, complete = client.paginate(
|
|
272
|
+
f"/repos/{event.repo}/pulls/{event.number}/files", max_pages=MAX_FILE_PAGES
|
|
273
|
+
)
|
|
274
|
+
except PublishError as exc:
|
|
275
|
+
out.warn(f"the pull request's files could not be read: {exc}")
|
|
276
|
+
left = _annotate(out, findings)
|
|
277
|
+
if left:
|
|
278
|
+
notes.append(f"{_plural(left, 'annotation')} not shown (GitHub's limit).")
|
|
279
|
+
out.body = markdown.summary(report, notes=notes)
|
|
280
|
+
return 2
|
|
281
|
+
files: dict[str, FileLines] = from_github_files(entries)
|
|
282
|
+
placed = [(f, placement(f, files)) for f in findings]
|
|
283
|
+
kept = [f for f, where in placed if where is not None]
|
|
284
|
+
inline = [f for f, where in placed if where == "inline"]
|
|
285
|
+
dropped = len(findings) - len(kept)
|
|
286
|
+
if dropped:
|
|
287
|
+
notes.append(
|
|
288
|
+
f"{_plural(dropped, 'finding')} not on a line this pull request changes "
|
|
289
|
+
"(as GitHub shows it) not published here; the job log lists every finding."
|
|
290
|
+
)
|
|
291
|
+
if not complete:
|
|
292
|
+
notes.append("The pull request has more files than GitHub lists (3,000).")
|
|
293
|
+
|
|
294
|
+
login = BOT_LOGIN
|
|
295
|
+
issue_comments: list[Any] = []
|
|
296
|
+
new_inline: list[Mapping[str, Any]] = []
|
|
297
|
+
if comment:
|
|
298
|
+
try:
|
|
299
|
+
login = identity(client, bot_login(environ, BOT_LOGIN))
|
|
300
|
+
issue_comments, _ = client.paginate(
|
|
301
|
+
f"/repos/{event.repo}/issues/{event.number}/comments",
|
|
302
|
+
max_pages=MAX_COMMENT_PAGES,
|
|
303
|
+
)
|
|
304
|
+
review_comments, _ = client.paginate(
|
|
305
|
+
f"/repos/{event.repo}/pulls/{event.number}/comments",
|
|
306
|
+
max_pages=MAX_COMMENT_PAGES,
|
|
307
|
+
)
|
|
308
|
+
except PublishError as exc:
|
|
309
|
+
out.warn(f"existing comments could not be read; nothing was commented: {exc}")
|
|
310
|
+
comment = False
|
|
311
|
+
else:
|
|
312
|
+
posted = _posted(review_comments, login)
|
|
313
|
+
fresh = [f for f in _order(inline) if f["fingerprint"] not in posted]
|
|
314
|
+
new_inline = fresh[:MAX_INLINE]
|
|
315
|
+
if len(fresh) > MAX_INLINE:
|
|
316
|
+
notes.append(
|
|
317
|
+
f"{_plural(len(fresh) - MAX_INLINE, 'finding')} beyond the "
|
|
318
|
+
f"{MAX_INLINE} inline comments per run are listed here only."
|
|
319
|
+
)
|
|
320
|
+
try:
|
|
321
|
+
if moved(client, event):
|
|
322
|
+
out.body = markdown.summary(
|
|
323
|
+
report,
|
|
324
|
+
findings=kept,
|
|
325
|
+
notes=[
|
|
326
|
+
*notes,
|
|
327
|
+
"The pull request moved (closed, or a new head or base) while this run "
|
|
328
|
+
"reviewed it: nothing was posted to it. A newer run reviews the new state.",
|
|
329
|
+
],
|
|
330
|
+
)
|
|
331
|
+
return 0
|
|
332
|
+
except PublishError as exc:
|
|
333
|
+
out.warn(f"the pull request could not be re-read; nothing was posted: {exc}")
|
|
334
|
+
out.body = markdown.summary(report, findings=kept, notes=notes)
|
|
335
|
+
return 2
|
|
336
|
+
|
|
337
|
+
left = _annotate(out, kept)
|
|
338
|
+
if left:
|
|
339
|
+
notes.append(f"{_plural(left, 'annotation')} not shown (GitHub's limit).")
|
|
340
|
+
out.body = markdown.summary(report, findings=kept, notes=notes)
|
|
341
|
+
if comment:
|
|
342
|
+
body = markdown.summary(report, findings=kept, prefix=[SUMMARY_MARKER], notes=notes)
|
|
343
|
+
try:
|
|
344
|
+
upsert_sticky(
|
|
345
|
+
client,
|
|
346
|
+
repo=event.repo,
|
|
347
|
+
number=event.number or 0,
|
|
348
|
+
login=login,
|
|
349
|
+
comments=issue_comments,
|
|
350
|
+
body=body,
|
|
351
|
+
)
|
|
352
|
+
except PublishError as exc:
|
|
353
|
+
out.warn(f"summary comment not posted: {exc}")
|
|
354
|
+
if new_inline:
|
|
355
|
+
_post_review(client, event, new_inline, out)
|
|
356
|
+
_maybe_sarif(environ, event, report, kept, out, sleep)
|
|
357
|
+
return 2 if out.warnings else 0
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _post_review(
|
|
361
|
+
client: Client, event: Event, findings: Sequence[Mapping[str, Any]], out: Output
|
|
362
|
+
) -> None:
|
|
363
|
+
count = len(findings)
|
|
364
|
+
body = (
|
|
365
|
+
f"{REVIEW_MARKER}\nCodeVeto: {_plural(count, 'new finding')} on lines this "
|
|
366
|
+
"pull request changes. The summary comment lists every finding."
|
|
367
|
+
)
|
|
368
|
+
try:
|
|
369
|
+
client.json(
|
|
370
|
+
"POST",
|
|
371
|
+
f"/repos/{event.repo}/pulls/{event.number}/reviews",
|
|
372
|
+
body={
|
|
373
|
+
"commit_id": event.head,
|
|
374
|
+
"event": "COMMENT",
|
|
375
|
+
"body": body,
|
|
376
|
+
"comments": [_review_comment(f) for f in findings],
|
|
377
|
+
},
|
|
378
|
+
)
|
|
379
|
+
except HttpError as exc:
|
|
380
|
+
out.warn(f"review not posted: {exc}")
|
codeveto/publish/http.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""A small JSON-over-HTTPS client for forge APIs, standard library only (``urllib``).
|
|
2
|
+
|
|
3
|
+
- Base URLs must be ``https`` (plain ``http`` only to a loopback host, for
|
|
4
|
+
tests and local forges), with no credentials, query or fragment.
|
|
5
|
+
- Every request has a timeout. Redirects are never followed (a redirect could
|
|
6
|
+
carry the token to another host); the ``Authorization`` header is also
|
|
7
|
+
added as an unredirected header.
|
|
8
|
+
- Retries with bounded backoff: rate limits (429, or 403 with
|
|
9
|
+
``Retry-After`` or ``X-RateLimit-Remaining: 0``) for every method; server
|
|
10
|
+
errors (500, 502, 503, 504) and connection failures only for ``GET``,
|
|
11
|
+
``PUT`` and ``PATCH``, since a ``POST`` that failed late may already have
|
|
12
|
+
created its comment. Waits honour ``Retry-After`` and
|
|
13
|
+
``X-RateLimit-Reset`` but never exceed :data:`MAX_WAIT` seconds each.
|
|
14
|
+
- Responses are capped at :data:`MAX_RESPONSE_BYTES` and decoded as strict
|
|
15
|
+
JSON (no ``NaN``).
|
|
16
|
+
- Errors are :class:`HttpError` with the method, the path and the status
|
|
17
|
+
only: never the token, a header, a response body or a URL query.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import http.client
|
|
23
|
+
import json
|
|
24
|
+
import re
|
|
25
|
+
import time
|
|
26
|
+
import urllib.error
|
|
27
|
+
import urllib.request
|
|
28
|
+
from collections.abc import Callable, Mapping
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
from typing import Any
|
|
31
|
+
from urllib.parse import urlencode, urlsplit
|
|
32
|
+
|
|
33
|
+
from codeveto import __version__, jsonsafe
|
|
34
|
+
from codeveto.publish import PublishError
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"MAX_RESPONSE_BYTES",
|
|
38
|
+
"MAX_WAIT",
|
|
39
|
+
"Client",
|
|
40
|
+
"HttpError",
|
|
41
|
+
"Response",
|
|
42
|
+
"validate_base_url",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
MAX_RESPONSE_BYTES = 16 * 1024 * 1024
|
|
46
|
+
MAX_WAIT = 30.0
|
|
47
|
+
_RETRY_STATUSES = frozenset({500, 502, 503, 504})
|
|
48
|
+
_IDEMPOTENT = frozenset({"GET", "PUT", "PATCH"})
|
|
49
|
+
_LOOPBACK = frozenset({"127.0.0.1", "::1", "localhost"})
|
|
50
|
+
_HOST = re.compile(r"[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\]")
|
|
51
|
+
_PATH = re.compile(r"(?:/[A-Za-z0-9._~-]+)*/?")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class HttpError(PublishError):
|
|
55
|
+
"""An API request failed; ``status`` is the HTTP status, ``None`` for a network failure."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, message: str, status: int | None = None) -> None:
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.status = status
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate_base_url(raw: object, *, what: str = "API URL") -> str:
|
|
63
|
+
"""``raw`` without a trailing slash, or :class:`PublishError` when it is not a safe base URL."""
|
|
64
|
+
if not isinstance(raw, str) or not raw or re.search(r"[\s\\\x00-\x1f\x7f]", raw):
|
|
65
|
+
raise PublishError(f"invalid {what}")
|
|
66
|
+
url = urlsplit(raw)
|
|
67
|
+
host = url.hostname or ""
|
|
68
|
+
secure = url.scheme == "https" or (url.scheme == "http" and host in _LOOPBACK)
|
|
69
|
+
if (
|
|
70
|
+
not secure
|
|
71
|
+
or not host
|
|
72
|
+
or url.username is not None
|
|
73
|
+
or url.password is not None
|
|
74
|
+
or url.query
|
|
75
|
+
or url.fragment
|
|
76
|
+
or not _PATH.fullmatch(url.path)
|
|
77
|
+
or any(part in {".", ".."} for part in url.path.split("/"))
|
|
78
|
+
):
|
|
79
|
+
raise PublishError(f"invalid {what}")
|
|
80
|
+
try:
|
|
81
|
+
port = url.port
|
|
82
|
+
except ValueError as exc:
|
|
83
|
+
raise PublishError(f"invalid {what}") from exc
|
|
84
|
+
netloc_host = url.netloc.rsplit(":", 1)[0] if port is not None else url.netloc
|
|
85
|
+
if port == 0 or not _HOST.fullmatch(netloc_host):
|
|
86
|
+
raise PublishError(f"invalid {what}")
|
|
87
|
+
return raw.rstrip("/")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
91
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True, slots=True)
|
|
96
|
+
class Response:
|
|
97
|
+
"""A decoded API response."""
|
|
98
|
+
|
|
99
|
+
status: int
|
|
100
|
+
headers: Mapping[str, str]
|
|
101
|
+
body: bytes
|
|
102
|
+
|
|
103
|
+
def json(self) -> Any:
|
|
104
|
+
if not self.body.strip():
|
|
105
|
+
return None
|
|
106
|
+
try:
|
|
107
|
+
return jsonsafe.loads(self.body.decode("utf-8"), parse_constant=_no_constant)
|
|
108
|
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
|
109
|
+
raise HttpError("the API returned invalid JSON", self.status) from exc
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _no_constant(name: str) -> Any:
|
|
113
|
+
raise ValueError(f"JSON constant {name} is not allowed")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class Client:
|
|
117
|
+
"""Requests against one API base URL with one token (see the module docstring).
|
|
118
|
+
|
|
119
|
+
``auth`` is the ``Authorization`` scheme: ``Bearer`` for GitHub, ``token``
|
|
120
|
+
for Forgejo. ``sleep`` and ``clock`` are injectable for tests.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(
|
|
124
|
+
self,
|
|
125
|
+
base_url: str,
|
|
126
|
+
token: str,
|
|
127
|
+
*,
|
|
128
|
+
auth: str = "Bearer",
|
|
129
|
+
headers: Mapping[str, str] | None = None,
|
|
130
|
+
timeout: float = 20.0,
|
|
131
|
+
retries: int = 3,
|
|
132
|
+
sleep: Callable[[float], None] | None = None,
|
|
133
|
+
clock: Callable[[], float] | None = None,
|
|
134
|
+
) -> None:
|
|
135
|
+
self.base_url = validate_base_url(base_url)
|
|
136
|
+
if not token or any(ch in token for ch in "\r\n\x00"):
|
|
137
|
+
raise PublishError("no usable API token (set GITHUB_TOKEN)")
|
|
138
|
+
self._authorization = f"{auth} {token}"
|
|
139
|
+
self._headers = {
|
|
140
|
+
"Accept": "application/json",
|
|
141
|
+
"User-Agent": f"codeveto/{__version__}",
|
|
142
|
+
**(headers or {}),
|
|
143
|
+
}
|
|
144
|
+
self.timeout = timeout
|
|
145
|
+
self.retries = max(0, retries)
|
|
146
|
+
self._sleep = sleep or (lambda seconds: time.sleep(seconds))
|
|
147
|
+
self._clock = clock or (lambda: time.time())
|
|
148
|
+
host = urlsplit(self.base_url).hostname or ""
|
|
149
|
+
proxies: urllib.request.ProxyHandler = (
|
|
150
|
+
urllib.request.ProxyHandler({}) if host in _LOOPBACK else urllib.request.ProxyHandler()
|
|
151
|
+
)
|
|
152
|
+
self._opener = urllib.request.build_opener(proxies, _NoRedirect())
|
|
153
|
+
|
|
154
|
+
# -- one request --------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
def _wait(self, attempt: int, headers: Mapping[str, str]) -> float:
|
|
157
|
+
retry_after = headers.get("retry-after", "")
|
|
158
|
+
if retry_after.isdigit():
|
|
159
|
+
return min(float(retry_after), MAX_WAIT)
|
|
160
|
+
reset = headers.get("x-ratelimit-reset", "")
|
|
161
|
+
if headers.get("x-ratelimit-remaining") == "0" and reset.isdigit():
|
|
162
|
+
return min(max(0.0, float(reset) - self._clock()) + 1.0, MAX_WAIT)
|
|
163
|
+
return min(float(2**attempt), MAX_WAIT)
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _rate_limited(status: int, headers: Mapping[str, str]) -> bool:
|
|
167
|
+
if status == 429:
|
|
168
|
+
return True
|
|
169
|
+
return status == 403 and (
|
|
170
|
+
"retry-after" in headers or headers.get("x-ratelimit-remaining") == "0"
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def request(
|
|
174
|
+
self,
|
|
175
|
+
method: str,
|
|
176
|
+
path: str,
|
|
177
|
+
*,
|
|
178
|
+
body: Any = None,
|
|
179
|
+
query: Mapping[str, object] | None = None,
|
|
180
|
+
accept: str | None = None,
|
|
181
|
+
) -> Response:
|
|
182
|
+
"""Send one request (with retries); a non-2xx final status raises :class:`HttpError`."""
|
|
183
|
+
if not path.startswith("/"):
|
|
184
|
+
raise PublishError("API paths start with /")
|
|
185
|
+
url = self.base_url + path
|
|
186
|
+
if query:
|
|
187
|
+
url += "?" + urlencode({k: str(v) for k, v in query.items()})
|
|
188
|
+
data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
189
|
+
label = f"{method} {path}"
|
|
190
|
+
attempt = 0
|
|
191
|
+
while True:
|
|
192
|
+
request = urllib.request.Request(url, data=data, method=method) # noqa: S310
|
|
193
|
+
for key, value in self._headers.items():
|
|
194
|
+
request.add_header(key, value)
|
|
195
|
+
if accept:
|
|
196
|
+
request.add_header("Accept", accept)
|
|
197
|
+
if data is not None:
|
|
198
|
+
request.add_header("Content-Type", "application/json")
|
|
199
|
+
request.add_unredirected_header("Authorization", self._authorization)
|
|
200
|
+
status: int | None = None
|
|
201
|
+
headers: dict[str, str] = {}
|
|
202
|
+
try:
|
|
203
|
+
with self._opener.open(request, timeout=self.timeout) as response:
|
|
204
|
+
status = response.status
|
|
205
|
+
headers = {k.lower(): v for k, v in response.headers.items()}
|
|
206
|
+
raw = response.read(MAX_RESPONSE_BYTES + 1)
|
|
207
|
+
except urllib.error.HTTPError as exc:
|
|
208
|
+
status = exc.code
|
|
209
|
+
headers = {k.lower(): v for k, v in (exc.headers or {}).items()}
|
|
210
|
+
exc.close()
|
|
211
|
+
retry = self._rate_limited(status, headers) or (
|
|
212
|
+
status in _RETRY_STATUSES and method in _IDEMPOTENT
|
|
213
|
+
)
|
|
214
|
+
if retry and attempt < self.retries:
|
|
215
|
+
self._sleep(self._wait(attempt, headers))
|
|
216
|
+
attempt += 1
|
|
217
|
+
continue
|
|
218
|
+
raise HttpError(f"{label} returned HTTP {status}", status) from None
|
|
219
|
+
except (OSError, http.client.HTTPException): # URLError, timeouts, resets
|
|
220
|
+
if method in _IDEMPOTENT and attempt < self.retries:
|
|
221
|
+
self._sleep(self._wait(attempt, {}))
|
|
222
|
+
attempt += 1
|
|
223
|
+
continue
|
|
224
|
+
raise HttpError(f"{label} failed: no response from the API") from None
|
|
225
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
226
|
+
raise HttpError(f"{label}: response too large", status)
|
|
227
|
+
return Response(status, headers, raw)
|
|
228
|
+
|
|
229
|
+
def json(
|
|
230
|
+
self,
|
|
231
|
+
method: str,
|
|
232
|
+
path: str,
|
|
233
|
+
*,
|
|
234
|
+
body: Any = None,
|
|
235
|
+
query: Mapping[str, object] | None = None,
|
|
236
|
+
) -> Any:
|
|
237
|
+
"""The decoded JSON body of one request."""
|
|
238
|
+
return self.request(method, path, body=body, query=query).json()
|
|
239
|
+
|
|
240
|
+
def paginate(
|
|
241
|
+
self,
|
|
242
|
+
path: str,
|
|
243
|
+
*,
|
|
244
|
+
query: Mapping[str, object] | None = None,
|
|
245
|
+
per_page: int = 100,
|
|
246
|
+
max_pages: int = 30,
|
|
247
|
+
limit_param: str = "per_page",
|
|
248
|
+
) -> tuple[list[Any], bool]:
|
|
249
|
+
"""Every item of a list endpoint, page by page: ``(items, complete)``.
|
|
250
|
+
|
|
251
|
+
Stops at the first page shorter than ``per_page``; ``complete`` is
|
|
252
|
+
false when ``max_pages`` pages were read and more may exist.
|
|
253
|
+
"""
|
|
254
|
+
items: list[Any] = []
|
|
255
|
+
for page in range(1, max_pages + 1):
|
|
256
|
+
params = {**(query or {}), limit_param: per_page, "page": page}
|
|
257
|
+
data = self.json("GET", path, query=params)
|
|
258
|
+
if not isinstance(data, list):
|
|
259
|
+
raise HttpError(f"GET {path} did not return a list")
|
|
260
|
+
items.extend(data)
|
|
261
|
+
if len(data) < per_page:
|
|
262
|
+
return items, True
|
|
263
|
+
return items, False
|