commit-check 2.24.2__py3-none-any.whl → 2.26.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.
- commit_check/__init__.py +23 -2
- commit_check/agent_config.py +558 -0
- commit_check/agent_configs.toml +111 -0
- commit_check/ai_policy.py +67 -18
- commit_check/ai_signatures.py +10 -0
- commit_check/ai_signatures_data.py +2 -0
- commit_check/ci.py +61 -5
- commit_check/config_merger.py +38 -3
- commit_check/engine.py +550 -40
- commit_check/main.py +89 -20
- commit_check/rule_builder.py +134 -19
- commit_check/rules_catalog.py +70 -4
- commit_check/util.py +33 -2
- {commit_check-2.24.2.dist-info → commit_check-2.26.0.dist-info}/METADATA +25 -10
- commit_check-2.26.0.dist-info/RECORD +25 -0
- commit_check-2.24.2.dist-info/RECORD +0 -23
- {commit_check-2.24.2.dist-info → commit_check-2.26.0.dist-info}/WHEEL +0 -0
- {commit_check-2.24.2.dist-info → commit_check-2.26.0.dist-info}/entry_points.txt +0 -0
- {commit_check-2.24.2.dist-info → commit_check-2.26.0.dist-info}/licenses/LICENSE +0 -0
- {commit_check-2.24.2.dist-info → commit_check-2.26.0.dist-info}/top_level.txt +0 -0
commit_check/__init__.py
CHANGED
|
@@ -164,8 +164,10 @@ DEFAULT_BOOLEAN_RULES = {
|
|
|
164
164
|
#: The policies ``ai_attribution`` accepts. ``ignore`` checks nothing;
|
|
165
165
|
#: ``forbid`` rejects every known AI signature; ``disclose`` accepts AI
|
|
166
166
|
#: assistance that is disclosed with an accepted trailer and rejects the tool
|
|
167
|
-
#: as a co-author or a sign-off
|
|
168
|
-
|
|
167
|
+
#: as a co-author or a sign-off; ``require`` is ``disclose`` with a
|
|
168
|
+
#: disclosure on every commit, ``Assisted-by: none`` when no tool helped, so
|
|
169
|
+
#: a missing trailer is not read as "no AI".
|
|
170
|
+
AI_ATTRIBUTION_POLICIES = ("ignore", "forbid", "disclose", "require")
|
|
169
171
|
DEFAULT_AI_ATTRIBUTION = "ignore"
|
|
170
172
|
# The trailers that disclose AI assistance under "disclose": Assisted-by is
|
|
171
173
|
# the Linux kernel's, Fedora's and FluxCD's; Generated-by is the Apache
|
|
@@ -173,6 +175,25 @@ DEFAULT_AI_ATTRIBUTION = "ignore"
|
|
|
173
175
|
DEFAULT_AI_DISCLOSURE_TRAILERS = ["Assisted-by", "Generated-by"]
|
|
174
176
|
# A regex the disclosure's value must match; empty accepts any non-empty value.
|
|
175
177
|
DEFAULT_AI_DISCLOSURE_PATTERN = ""
|
|
178
|
+
#: The value of a disclosure trailer that says no AI tool helped.
|
|
179
|
+
AI_DISCLOSURE_NONE = "none"
|
|
180
|
+
|
|
181
|
+
# Pull request rules
|
|
182
|
+
#: What counts as naming an issue in a pull request description when
|
|
183
|
+
#: ``[pull_request] issue_reference_pattern`` is not set (CC502): ``#123``,
|
|
184
|
+
#: ``GH-123``, ``owner/repo#123`` (or a GitLab ``group/sub/project#123``),
|
|
185
|
+
#: and a link to an issue on GitHub, GitLab or Bitbucket Cloud, or to a Jira
|
|
186
|
+
#: ticket. A bare Jira key is left out: ``[A-Z]+-\d+`` also matches
|
|
187
|
+
#: ``UTF-8``, ``SHA-256`` and ``ISO-8601``.
|
|
188
|
+
DEFAULT_ISSUE_REFERENCE_PATTERN = (
|
|
189
|
+
r"(?<![\w/&#])#\d+\b"
|
|
190
|
+
r"|\b[Gg][Hh]-\d+\b"
|
|
191
|
+
r"|(?<![\w/.-])[\w.-]+(?:/[\w.-]+)+#\d+\b"
|
|
192
|
+
# The path of a link: its start is not needed to tell, and matching from
|
|
193
|
+
# "https://" would rescan the rest of a long line from every scheme.
|
|
194
|
+
r"|/(?:issues|work_items)/\d+\b"
|
|
195
|
+
r"|/browse/[A-Z][A-Z0-9_]*-\d+\b"
|
|
196
|
+
)
|
|
176
197
|
|
|
177
198
|
|
|
178
199
|
if TYPE_CHECKING:
|
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
"""Find risky settings in the agent config files a commit changes.
|
|
2
|
+
|
|
3
|
+
What to look for is data: ``agent_configs.toml`` beside this module lists,
|
|
4
|
+
per agent, the files it reads and the settings in them that the agent config
|
|
5
|
+
rules (CC601 to CC604) report. This module reads that list and matches file
|
|
6
|
+
contents against it; the validator in :mod:`commit_check.engine` feeds it
|
|
7
|
+
the files of the commits under test.
|
|
8
|
+
|
|
9
|
+
A setting is reported where it is committed, whoever wrote it: a project
|
|
10
|
+
file applies to everyone who opens the repository, and the agents' own
|
|
11
|
+
safeguards (a trust prompt, a first-run question) are a click away from
|
|
12
|
+
letting it through.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import re
|
|
19
|
+
import tomllib
|
|
20
|
+
from collections.abc import Iterable, Iterator, Sequence
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from fnmatch import fnmatchcase
|
|
23
|
+
from functools import cache
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
#: The catalog of agents and their settings.
|
|
28
|
+
CATALOG_PATH = Path(__file__).with_name("agent_configs.toml")
|
|
29
|
+
|
|
30
|
+
#: The rule each catalog entry may name, kebab-case as the catalog writes
|
|
31
|
+
#: it, mapped to the check it reports under.
|
|
32
|
+
RULES = {
|
|
33
|
+
"agent-mcp-auto-approve": "agent_mcp_auto_approve",
|
|
34
|
+
"agent-api-endpoint": "agent_api_endpoint",
|
|
35
|
+
"agent-full-access": "agent_full_access",
|
|
36
|
+
"agent-unrestricted-trigger": "agent_unrestricted_trigger",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
#: The ``[agent]`` list that lets a finding of each check through,
|
|
40
|
+
#: for the checks that have one. A server is let through by its name, an
|
|
41
|
+
#: endpoint by its URL.
|
|
42
|
+
ALLOWLISTS = {
|
|
43
|
+
"agent_mcp_auto_approve": "allow_mcp_servers",
|
|
44
|
+
"agent_api_endpoint": "allow_api_endpoints",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
#: The formats a catalog file may be in, by file name ending.
|
|
48
|
+
_FORMATS = {".json": "json", ".toml": "toml", ".yml": "yaml", ".yaml": "yaml"}
|
|
49
|
+
|
|
50
|
+
#: Config files are small; anything bigger is not one and is not read.
|
|
51
|
+
MAX_FILE_SIZE = 1024 * 1024
|
|
52
|
+
|
|
53
|
+
_AGENT_KEYS = frozenset({"name", "files", "uses", "docs", "settings"})
|
|
54
|
+
_SETTING_KEYS = frozenset({"rule", "key", "value", "docs"})
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class _Any:
|
|
58
|
+
"""The ``value`` of a setting whose every value is risky."""
|
|
59
|
+
|
|
60
|
+
def __repr__(self) -> str:
|
|
61
|
+
return "ANY"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
ANY: Any = _Any()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class AgentSetting:
|
|
69
|
+
"""One risky setting of one agent, from the catalog.
|
|
70
|
+
|
|
71
|
+
:param agent: The agent's name.
|
|
72
|
+
:param check: The check that reports it, e.g. ``agent_full_access``.
|
|
73
|
+
:param files: Globs of the files it is read from.
|
|
74
|
+
:param key: The setting's path, split on ``.``; ``*`` is any one key.
|
|
75
|
+
:param value: The risky value, or :data:`ANY`.
|
|
76
|
+
:param uses: For a YAML file, the action a step's ``uses:`` names;
|
|
77
|
+
only that step's settings count.
|
|
78
|
+
:param docs: Where the agent documents the setting.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
agent: str
|
|
82
|
+
check: str
|
|
83
|
+
files: tuple[str, ...]
|
|
84
|
+
key: tuple[str, ...]
|
|
85
|
+
value: Any
|
|
86
|
+
uses: str | None
|
|
87
|
+
docs: str
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def key_text(self) -> str:
|
|
91
|
+
return ".".join(self.key)
|
|
92
|
+
|
|
93
|
+
def reads(self, path: str) -> bool:
|
|
94
|
+
"""Whether *path* is one of the files this setting is read from.
|
|
95
|
+
|
|
96
|
+
A ``*`` stays within one directory, as it does in a shell:
|
|
97
|
+
``.github/workflows/*.yml`` is not ``.github/workflows/old/ci.yml``,
|
|
98
|
+
which GitHub does not run.
|
|
99
|
+
"""
|
|
100
|
+
depth = path.count("/")
|
|
101
|
+
return any(
|
|
102
|
+
depth == pattern.count("/") and fnmatchcase(path, pattern)
|
|
103
|
+
for pattern in self.files
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True)
|
|
108
|
+
class Finding:
|
|
109
|
+
"""A risky setting found in a file.
|
|
110
|
+
|
|
111
|
+
:param subject: What an allowlist names to let it through: the server's
|
|
112
|
+
name or the endpoint's URL. ``None`` when nothing can, such as a
|
|
113
|
+
setting that approves every server at once.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
check: str
|
|
117
|
+
path: str
|
|
118
|
+
setting: str
|
|
119
|
+
subject: str | None
|
|
120
|
+
agent: str
|
|
121
|
+
|
|
122
|
+
def __str__(self) -> str:
|
|
123
|
+
return f"{self.setting} in {self.path}"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _https_url(value: Any) -> bool:
|
|
127
|
+
return isinstance(value, str) and value.startswith("https://")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class CatalogError(ValueError):
|
|
131
|
+
"""An entry of ``agent_configs.toml`` that cannot be used."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def parse_catalog(data: dict[str, Any]) -> tuple[AgentSetting, ...]:
|
|
135
|
+
"""The settings a parsed catalog lists, or :class:`CatalogError` naming
|
|
136
|
+
the first entry that is not usable.
|
|
137
|
+
|
|
138
|
+
The catalog is checked whole on load, so a mistake in a new entry fails
|
|
139
|
+
the test suite rather than silently matching nothing.
|
|
140
|
+
"""
|
|
141
|
+
agents = data.get("agent")
|
|
142
|
+
if set(data) != {"agent"} or not isinstance(agents, list) or not agents:
|
|
143
|
+
raise CatalogError("the catalog must hold [[agent]] tables and nothing else")
|
|
144
|
+
settings: list[AgentSetting] = []
|
|
145
|
+
for agent in agents:
|
|
146
|
+
name = agent.get("name") if isinstance(agent, dict) else None
|
|
147
|
+
if not isinstance(name, str) or not name.strip():
|
|
148
|
+
raise CatalogError(f"an [[agent]] table has no name: {agent!r}")
|
|
149
|
+
where = f"agent {name!r}"
|
|
150
|
+
unknown = set(agent) - _AGENT_KEYS
|
|
151
|
+
if unknown:
|
|
152
|
+
raise CatalogError(f"{where}: unknown keys {sorted(unknown)}")
|
|
153
|
+
files = agent.get("files")
|
|
154
|
+
if not isinstance(files, list) or not files:
|
|
155
|
+
raise CatalogError(f"{where}: files must be a list of paths")
|
|
156
|
+
for pattern in files:
|
|
157
|
+
if not isinstance(pattern, str) or _format(pattern) is None:
|
|
158
|
+
raise CatalogError(
|
|
159
|
+
f"{where}: {pattern!r} is not a .json, .toml, .yml or .yaml path"
|
|
160
|
+
)
|
|
161
|
+
uses = agent.get("uses")
|
|
162
|
+
if uses is not None and (not isinstance(uses, str) or not uses.strip()):
|
|
163
|
+
raise CatalogError(f"{where}: uses must name the action")
|
|
164
|
+
docs = agent.get("docs")
|
|
165
|
+
if not _https_url(docs):
|
|
166
|
+
raise CatalogError(f"{where}: docs must be an https:// link")
|
|
167
|
+
entries = agent.get("settings")
|
|
168
|
+
if not isinstance(entries, list) or not entries:
|
|
169
|
+
raise CatalogError(f"{where}: settings must list at least one setting")
|
|
170
|
+
for entry in entries:
|
|
171
|
+
if not isinstance(entry, dict):
|
|
172
|
+
raise CatalogError(f"{where}: a setting must be a table, got {entry!r}")
|
|
173
|
+
unknown = set(entry) - _SETTING_KEYS
|
|
174
|
+
if unknown:
|
|
175
|
+
raise CatalogError(f"{where}: unknown setting keys {sorted(unknown)}")
|
|
176
|
+
rule = entry.get("rule")
|
|
177
|
+
if rule not in RULES:
|
|
178
|
+
raise CatalogError(
|
|
179
|
+
f"{where}: rule {rule!r} is not one of {', '.join(RULES)}"
|
|
180
|
+
)
|
|
181
|
+
key = entry.get("key")
|
|
182
|
+
parts = tuple(key.split(".")) if isinstance(key, str) else ()
|
|
183
|
+
if not parts or not all(parts) or parts.count("*") > 1:
|
|
184
|
+
raise CatalogError(
|
|
185
|
+
f"{where}: key {key!r} must be keys joined with '.', "
|
|
186
|
+
"with at most one '*'"
|
|
187
|
+
)
|
|
188
|
+
value = entry.get("value", ANY)
|
|
189
|
+
if value is not ANY and not isinstance(value, (bool, int, str)):
|
|
190
|
+
raise CatalogError(f"{where}: value of {key!r} must be one value")
|
|
191
|
+
setting_docs = entry.get("docs", docs)
|
|
192
|
+
if not _https_url(setting_docs):
|
|
193
|
+
raise CatalogError(f"{where}: docs of {key!r} must be an https:// link")
|
|
194
|
+
settings.append(
|
|
195
|
+
AgentSetting(
|
|
196
|
+
agent=name,
|
|
197
|
+
check=RULES[rule],
|
|
198
|
+
files=tuple(files),
|
|
199
|
+
key=parts,
|
|
200
|
+
value=value,
|
|
201
|
+
uses=uses,
|
|
202
|
+
docs=setting_docs,
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
return tuple(settings)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@cache
|
|
209
|
+
def load_settings() -> tuple[AgentSetting, ...]:
|
|
210
|
+
"""Every setting in the catalog, read from disk once per process."""
|
|
211
|
+
with CATALOG_PATH.open("rb") as f:
|
|
212
|
+
return parse_catalog(tomllib.load(f))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _format(path: str) -> str | None:
|
|
216
|
+
for ending, fmt in _FORMATS.items():
|
|
217
|
+
if path.endswith(ending):
|
|
218
|
+
return fmt
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# A string or a comment: comments are dropped and strings kept as they are,
|
|
223
|
+
# so "//" inside a URL survives. One left open runs to the end of the text,
|
|
224
|
+
# so each character is read once: retrying a "/*" that never closes from
|
|
225
|
+
# every later "/*" would take time that grows with the square of the size.
|
|
226
|
+
# Left as text, not compiled at import: most runs read no JSON file that
|
|
227
|
+
# needs them.
|
|
228
|
+
_JSON_STRING = r'"(?:\\.|[^"\\])*(?:"|\\?\Z)'
|
|
229
|
+
_JSONC_TOKEN = rf"{_JSON_STRING}|//[^\n]*|/\*.*?(?:\*/|\Z)"
|
|
230
|
+
_TRAILING_COMMA = rf"{_JSON_STRING}|,(\s*[}}\]])"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _loads_jsonc(text: str) -> Any:
|
|
234
|
+
"""JSON that may hold comments and trailing commas, as VS Code's does."""
|
|
235
|
+
try:
|
|
236
|
+
return json.loads(text)
|
|
237
|
+
except ValueError:
|
|
238
|
+
pass
|
|
239
|
+
stripped = re.sub(
|
|
240
|
+
_JSONC_TOKEN,
|
|
241
|
+
lambda m: m.group(0) if m.group(0).startswith('"') else " ",
|
|
242
|
+
text,
|
|
243
|
+
flags=re.DOTALL,
|
|
244
|
+
)
|
|
245
|
+
stripped = re.sub(
|
|
246
|
+
_TRAILING_COMMA,
|
|
247
|
+
lambda m: m.group(1) if m.group(1) is not None else m.group(0),
|
|
248
|
+
stripped,
|
|
249
|
+
)
|
|
250
|
+
return json.loads(stripped)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _parse(fmt: str, text: str) -> Any:
|
|
254
|
+
"""The file's data, or ``None`` when it does not parse.
|
|
255
|
+
|
|
256
|
+
A file its own agent could not read either holds no setting that
|
|
257
|
+
takes effect, so it is not reported.
|
|
258
|
+
"""
|
|
259
|
+
try:
|
|
260
|
+
if fmt == "json":
|
|
261
|
+
return _loads_jsonc(text)
|
|
262
|
+
return tomllib.loads(text)
|
|
263
|
+
except (ValueError, RecursionError):
|
|
264
|
+
# Nested deeper than Python's parsers go: no agent reads it either.
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _lookup(
|
|
269
|
+
node: Any, keys: tuple[str, ...], name: str | None = None
|
|
270
|
+
) -> Iterator[tuple[str | None, tuple[str, ...], Any]]:
|
|
271
|
+
"""``(name, path, value)`` for each value at *keys* in *node*.
|
|
272
|
+
|
|
273
|
+
*name* is the key ``*`` stood for, *path* the keys as found. A key that
|
|
274
|
+
holds dots itself, as VS Code's ``chat.tools.autoApprove`` does, is
|
|
275
|
+
tried whole as well as split: every run of keys that is present is
|
|
276
|
+
followed, so a decoy ``"env.X"`` key cannot hide the ``env`` block
|
|
277
|
+
beside it.
|
|
278
|
+
"""
|
|
279
|
+
if not keys:
|
|
280
|
+
yield name, (), node
|
|
281
|
+
return
|
|
282
|
+
if not isinstance(node, dict):
|
|
283
|
+
return
|
|
284
|
+
if keys[0] == "*":
|
|
285
|
+
for key, value in node.items():
|
|
286
|
+
for found_name, path, found in _lookup(value, keys[1:], key):
|
|
287
|
+
yield found_name, (key, *path), found
|
|
288
|
+
return
|
|
289
|
+
stop = keys.index("*") if "*" in keys else len(keys)
|
|
290
|
+
for end in range(stop, 0, -1):
|
|
291
|
+
joined = ".".join(keys[:end])
|
|
292
|
+
if joined in node:
|
|
293
|
+
for found_name, path, found in _lookup(node[joined], keys[end:], name):
|
|
294
|
+
yield found_name, (joined, *path), found
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _same(found: Any, value: Any) -> bool:
|
|
298
|
+
# ``True == 1`` in Python; a setting's type is part of what it means.
|
|
299
|
+
return type(found) is type(value) and found == value
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _show(value: Any) -> str:
|
|
303
|
+
return json.dumps(value, ensure_ascii=False)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _structured_findings(
|
|
307
|
+
path: str, data: Any, settings: Iterable[AgentSetting]
|
|
308
|
+
) -> Iterator[Finding]:
|
|
309
|
+
for setting in settings:
|
|
310
|
+
for name, keys, found in _lookup(data, setting.key):
|
|
311
|
+
shown_key = ".".join(keys)
|
|
312
|
+
items = found if isinstance(found, list) else [found]
|
|
313
|
+
verb = "has" if isinstance(found, list) else "="
|
|
314
|
+
if setting.value is ANY:
|
|
315
|
+
for item in items:
|
|
316
|
+
if not item:
|
|
317
|
+
continue
|
|
318
|
+
subject = name
|
|
319
|
+
if subject is None and isinstance(item, str):
|
|
320
|
+
subject = item
|
|
321
|
+
yield Finding(
|
|
322
|
+
setting.check,
|
|
323
|
+
path,
|
|
324
|
+
f"{shown_key} {verb} {_show(item)}",
|
|
325
|
+
subject,
|
|
326
|
+
setting.agent,
|
|
327
|
+
)
|
|
328
|
+
elif any(_same(item, setting.value) for item in items):
|
|
329
|
+
yield Finding(
|
|
330
|
+
setting.check,
|
|
331
|
+
path,
|
|
332
|
+
f"{shown_key} {verb} {_show(setting.value)}",
|
|
333
|
+
name,
|
|
334
|
+
setting.agent,
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
# YAML's double-quoted escapes, besides \x, \u and \U.
|
|
339
|
+
_YAML_ESCAPES = {
|
|
340
|
+
"0": "\0", "a": "\a", "b": "\b", "t": "\t", "\t": "\t", "n": "\n",
|
|
341
|
+
"v": "\v", "f": "\f", "r": "\r", "e": "\x1b", " ": " ", '"': '"',
|
|
342
|
+
"/": "/", "\\": "\\", "N": "\x85", "_": "\xa0", "L": "\u2028",
|
|
343
|
+
"P": "\u2029",
|
|
344
|
+
} # fmt: skip
|
|
345
|
+
_YAML_ESCAPE = r"\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|.)"
|
|
346
|
+
_YAML_QUOTED = {'"': r'"((?:\\.|[^"\\])*)"', "'": r"'((?:''|[^'])*)'"}
|
|
347
|
+
# A node's tag and anchor, such as "!!str " and "&name ", before its key or value.
|
|
348
|
+
_YAML_PROPERTIES = r"(?:[!&]\S*(?:\s+|$))*"
|
|
349
|
+
# A "key: rest" line of a block mapping, as a list item or not. Only keys
|
|
350
|
+
# spelled with word characters, dots and dashes are read unquoted: no key
|
|
351
|
+
# this module looks for is spelled otherwise. Each run of spaces can be
|
|
352
|
+
# matched one way only, so a long line that is not an entry fails at once.
|
|
353
|
+
_YAML_ENTRY = re.compile(
|
|
354
|
+
rf"""^\s*(?:(?P<dash>-)\s+)?{_YAML_PROPERTIES}"""
|
|
355
|
+
r"""(?P<key>"(?:\\.|[^"\\])*"|'(?:''|[^'])*'|[\w.-]+)\s*:(?P<rest>.*)$"""
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _yaml_unescape(match: re.Match[str]) -> str:
|
|
360
|
+
code = match.group(1)
|
|
361
|
+
if code[0] in "xuU" and len(code) > 1:
|
|
362
|
+
point = int(code[1:], 16)
|
|
363
|
+
return chr(point) if point <= 0x10FFFF else match.group(0)
|
|
364
|
+
return _YAML_ESCAPES.get(code, match.group(0))
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _yaml_scalar(raw: str) -> str | None:
|
|
368
|
+
"""The value on a ``key: value`` line, unquoted, or ``None`` for one
|
|
369
|
+
that starts a block, a mapping or a list on the lines below.
|
|
370
|
+
|
|
371
|
+
A quoted value is read as YAML reads it, so ``"\\u002a"`` is ``*``, and
|
|
372
|
+
a tag or anchor before it, as in ``!!str "*"``, is passed over.
|
|
373
|
+
"""
|
|
374
|
+
raw = re.sub(rf"^{_YAML_PROPERTIES}", "", raw.strip(), count=1)
|
|
375
|
+
if raw[:1] in _YAML_QUOTED:
|
|
376
|
+
quoted = re.match(_YAML_QUOTED[raw[0]], raw)
|
|
377
|
+
if quoted is None:
|
|
378
|
+
return None
|
|
379
|
+
if raw[0] == "'":
|
|
380
|
+
return quoted.group(1).replace("''", "'")
|
|
381
|
+
return re.sub(_YAML_ESCAPE, _yaml_unescape, quoted.group(1))
|
|
382
|
+
raw = re.split(r"\s#", raw, maxsplit=1)[0].strip()
|
|
383
|
+
if not raw or raw[0] in "|>&*{[":
|
|
384
|
+
return None
|
|
385
|
+
return raw
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _yaml_entry(line: str) -> tuple[str, str, bool] | None:
|
|
389
|
+
"""The key of a ``key: value`` line, the text after its colon, and
|
|
390
|
+
whether the line starts a list item; ``None`` for any other line.
|
|
391
|
+
|
|
392
|
+
The key is read as YAML reads it, so ``"wi\\u0074h"`` is ``with``.
|
|
393
|
+
"""
|
|
394
|
+
match = _YAML_ENTRY.match(line)
|
|
395
|
+
if match is None:
|
|
396
|
+
return None
|
|
397
|
+
key = match.group("key")
|
|
398
|
+
if key[0] in _YAML_QUOTED:
|
|
399
|
+
key = _yaml_scalar(key) or ""
|
|
400
|
+
return key, match.group("rest"), match.group("dash") is not None
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _indent(line: str) -> int:
|
|
404
|
+
return len(line) - len(line.lstrip(" "))
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _steps_using(lines: list[str], uses: str) -> list[list[str]]:
|
|
408
|
+
"""The lines of each YAML step whose ``uses:`` names *uses*.
|
|
409
|
+
|
|
410
|
+
A step runs from its ``-`` to the next line indented no deeper than
|
|
411
|
+
that ``-``, so a setting of another step, another job's action or a
|
|
412
|
+
comment that names the action is not taken for this one's. Steps do
|
|
413
|
+
not overlap, so each line is walked over once, however many ``uses:``
|
|
414
|
+
lines the file holds.
|
|
415
|
+
"""
|
|
416
|
+
steps = []
|
|
417
|
+
covered = 0 # the lines before this one are in a step already found
|
|
418
|
+
for number, line in enumerate(lines):
|
|
419
|
+
if number < covered:
|
|
420
|
+
continue
|
|
421
|
+
entry = _yaml_entry(line)
|
|
422
|
+
if entry is None or entry[0] != "uses":
|
|
423
|
+
continue
|
|
424
|
+
action = _yaml_scalar(entry[1]) or ""
|
|
425
|
+
if action != uses and not action.startswith(f"{uses}@"):
|
|
426
|
+
continue
|
|
427
|
+
start = number
|
|
428
|
+
if entry[2]:
|
|
429
|
+
dash = _indent(line)
|
|
430
|
+
else:
|
|
431
|
+
# "uses:" under the step's "- name:" line: the step starts at the
|
|
432
|
+
# nearest line above that begins with a "-" further left.
|
|
433
|
+
dash = _indent(line) - 2
|
|
434
|
+
while start > covered:
|
|
435
|
+
start -= 1
|
|
436
|
+
above = lines[start]
|
|
437
|
+
if above.strip().startswith("-") and _indent(above) <= dash:
|
|
438
|
+
dash = _indent(above)
|
|
439
|
+
break
|
|
440
|
+
end = number + 1
|
|
441
|
+
while end < len(lines):
|
|
442
|
+
stripped = lines[end].strip()
|
|
443
|
+
if (
|
|
444
|
+
stripped
|
|
445
|
+
and not stripped.startswith("#")
|
|
446
|
+
and _indent(lines[end]) <= dash
|
|
447
|
+
):
|
|
448
|
+
break
|
|
449
|
+
end += 1
|
|
450
|
+
steps.append(lines[start:end])
|
|
451
|
+
covered = end
|
|
452
|
+
return steps
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _inputs(step: list[str]) -> list[str]:
|
|
456
|
+
"""The lines of a step's ``with:`` inputs, one input each.
|
|
457
|
+
|
|
458
|
+
Lines nested deeper, such as those of a multi-line ``prompt``, are left
|
|
459
|
+
out: text in a prompt is not a setting.
|
|
460
|
+
"""
|
|
461
|
+
inputs: list[str] = []
|
|
462
|
+
for number, line in enumerate(step):
|
|
463
|
+
entry = _yaml_entry(line)
|
|
464
|
+
if entry is None or entry[0] != "with":
|
|
465
|
+
continue
|
|
466
|
+
# Nothing after "with:" but a tag, an anchor or a comment, as in
|
|
467
|
+
# "with: !!map": the inputs are on the lines below.
|
|
468
|
+
if not re.fullmatch(rf"\s*{_YAML_PROPERTIES}(?:#.*)?", entry[1]):
|
|
469
|
+
continue
|
|
470
|
+
column = len(line) - len(line.lstrip(" -"))
|
|
471
|
+
depth = None
|
|
472
|
+
for below_number in range(number + 1, len(step)):
|
|
473
|
+
below = step[below_number]
|
|
474
|
+
stripped = below.strip()
|
|
475
|
+
if not stripped or stripped.startswith("#"):
|
|
476
|
+
continue
|
|
477
|
+
indent = _indent(below)
|
|
478
|
+
if indent <= column:
|
|
479
|
+
break
|
|
480
|
+
if depth is None:
|
|
481
|
+
depth = indent
|
|
482
|
+
if indent == depth:
|
|
483
|
+
inputs.append(below)
|
|
484
|
+
return inputs
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _yaml_findings(
|
|
488
|
+
path: str, text: str, settings: Iterable[AgentSetting]
|
|
489
|
+
) -> Iterator[Finding]:
|
|
490
|
+
lines = text.splitlines()
|
|
491
|
+
for setting in settings:
|
|
492
|
+
scopes = (
|
|
493
|
+
[lines]
|
|
494
|
+
if setting.uses is None
|
|
495
|
+
else [_inputs(step) for step in _steps_using(lines, setting.uses)]
|
|
496
|
+
)
|
|
497
|
+
key = setting.key[-1]
|
|
498
|
+
for line in (line for scope in scopes for line in scope):
|
|
499
|
+
entry = _yaml_entry(line)
|
|
500
|
+
if entry is None or entry[0] != key:
|
|
501
|
+
continue
|
|
502
|
+
value = _yaml_scalar(entry[1])
|
|
503
|
+
if value is None:
|
|
504
|
+
continue
|
|
505
|
+
if setting.value is ANY:
|
|
506
|
+
yield Finding(
|
|
507
|
+
setting.check, path, f"{key} = {_show(value)}", value, setting.agent
|
|
508
|
+
)
|
|
509
|
+
continue
|
|
510
|
+
expected = setting.value
|
|
511
|
+
if isinstance(expected, bool):
|
|
512
|
+
hit = value.lower() == str(expected).lower()
|
|
513
|
+
else:
|
|
514
|
+
hit = value == str(expected)
|
|
515
|
+
if hit:
|
|
516
|
+
yield Finding(
|
|
517
|
+
setting.check, path, f"{key} = {_show(value)}", None, setting.agent
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def find_settings(
|
|
522
|
+
path: str, text: str, settings: Sequence[AgentSetting] | None = None
|
|
523
|
+
) -> list[Finding]:
|
|
524
|
+
"""The risky settings in *text*, the contents of the file at *path*.
|
|
525
|
+
|
|
526
|
+
:param settings: The catalog entries to look for; the whole catalog
|
|
527
|
+
when not given. Only those whose files include *path* are used.
|
|
528
|
+
"""
|
|
529
|
+
if settings is None:
|
|
530
|
+
settings = load_settings()
|
|
531
|
+
relevant = [s for s in settings if s.reads(path)]
|
|
532
|
+
if not relevant:
|
|
533
|
+
return []
|
|
534
|
+
# The catalog admits only files whose format is known.
|
|
535
|
+
fmt = _format(path) or "json"
|
|
536
|
+
if fmt == "yaml":
|
|
537
|
+
found = _yaml_findings(path, text, relevant)
|
|
538
|
+
else:
|
|
539
|
+
data = _parse(fmt, text)
|
|
540
|
+
if data is None:
|
|
541
|
+
return []
|
|
542
|
+
found = _structured_findings(path, data, relevant)
|
|
543
|
+
return list(dict.fromkeys(found))
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def is_allowed(finding: Finding, allowed: Iterable[str]) -> bool:
|
|
547
|
+
"""Whether an ``[agent]`` allowlist lets *finding* through.
|
|
548
|
+
|
|
549
|
+
An endpoint matches with or without a trailing slash; anything else
|
|
550
|
+
must match exactly. A URL is never matched by its start, which
|
|
551
|
+
``https://gateway.example.com.attacker.net`` would pass.
|
|
552
|
+
"""
|
|
553
|
+
if finding.subject is None:
|
|
554
|
+
return False
|
|
555
|
+
if finding.check == "agent_api_endpoint":
|
|
556
|
+
subject = finding.subject.rstrip("/")
|
|
557
|
+
return any(subject == item.rstrip("/") for item in allowed)
|
|
558
|
+
return finding.subject in allowed
|