contextlock 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.
- agentbom/__init__.py +0 -0
- agentbom/__main__.py +3 -0
- agentbom/cli.py +221 -0
- agentbom/discover.py +337 -0
- agentbom/gitindex.py +119 -0
- agentbom/lockfile.py +261 -0
- agentbom/models.py +180 -0
- agentbom/parsers/__init__.py +53 -0
- agentbom/parsers/_shape.py +96 -0
- agentbom/parsers/hooks.py +146 -0
- agentbom/parsers/jsonc.py +35 -0
- agentbom/parsers/markdown.py +111 -0
- agentbom/parsers/mcp.py +94 -0
- agentbom/parsers/script.py +15 -0
- agentbom/parsers/settings.py +47 -0
- agentbom/policy.py +178 -0
- agentbom/py.typed +0 -0
- agentbom/registry.py +120 -0
- agentbom/report.py +237 -0
- agentbom/rules/__init__.py +51 -0
- agentbom/rules/_prose.py +109 -0
- agentbom/rules/_surfaces.py +92 -0
- agentbom/rules/abom_001_hidden_unicode.py +232 -0
- agentbom/rules/abom_002_remote_exec.py +148 -0
- agentbom/rules/abom_003_credential_paths.py +200 -0
- agentbom/rules/abom_004_outbound_transfer.py +219 -0
- agentbom/rules/abom_005_unpinned.py +399 -0
- agentbom/rules/abom_006_drift.py +52 -0
- agentbom/rules/abom_007_permissions.py +192 -0
- agentbom/rules/abom_008_auto_run_hooks.py +160 -0
- agentbom/rules/abom_009_instruction_override.py +166 -0
- agentbom/rules/abom_010_secrets.py +203 -0
- agentbom/sarif.py +142 -0
- agentbom/scan.py +35 -0
- contextlock-0.1.0.dist-info/METADATA +238 -0
- contextlock-0.1.0.dist-info/RECORD +39 -0
- contextlock-0.1.0.dist-info/WHEEL +4 -0
- contextlock-0.1.0.dist-info/entry_points.txt +3 -0
- contextlock-0.1.0.dist-info/licenses/LICENSE +201 -0
agentbom/lockfile.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""agentbom.lock: the reviewed definition of every artifact, and the drift from it."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
6
|
+
from typing import Annotated, Any, Literal, Self
|
|
7
|
+
|
|
8
|
+
from pydantic import (
|
|
9
|
+
BaseModel,
|
|
10
|
+
ConfigDict,
|
|
11
|
+
JsonValue,
|
|
12
|
+
StringConstraints,
|
|
13
|
+
ValidationError,
|
|
14
|
+
model_validator,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
from agentbom.models import Artifact, ArtifactKind, Change, Drift, FieldChange, Location
|
|
18
|
+
|
|
19
|
+
LOCKFILE_NAME = "agentbom.lock"
|
|
20
|
+
LOCK_VERSION: Literal[1] = 1
|
|
21
|
+
DIGEST_PREFIX = "sha256:"
|
|
22
|
+
|
|
23
|
+
FieldPath = tuple[str, ...]
|
|
24
|
+
Digest = Annotated[str, StringConstraints(pattern=r"^sha256:[0-9a-f]{64}$")]
|
|
25
|
+
|
|
26
|
+
# The lockfile is committed and reviewed. Secret maps keep only their keys, because even a
|
|
27
|
+
# digest confirms a guessed value; the file digest still catches a changed value. Bodies
|
|
28
|
+
# are too long to read in a pull request, so they keep a digest.
|
|
29
|
+
_KEYS_ONLY: dict[ArtifactKind, tuple[FieldPath, ...]] = {
|
|
30
|
+
"mcp_server": (("launch", "env"), ("launch", "headers")),
|
|
31
|
+
"settings": (("env",),),
|
|
32
|
+
}
|
|
33
|
+
_DIGESTED: dict[ArtifactKind, tuple[FieldPath, ...]] = {
|
|
34
|
+
"skill": (("body",),),
|
|
35
|
+
"rules": (("body",),),
|
|
36
|
+
"script": (("body",),),
|
|
37
|
+
}
|
|
38
|
+
_MAX_ERROR_LOCATION = 6
|
|
39
|
+
# The id holds kind, path and name; agents and body_line are not content; a skill's
|
|
40
|
+
# description is a copy of its frontmatter description.
|
|
41
|
+
_NOT_DEFINITION = frozenset({"kind", "name", "source", "agents", "body_line", "description"})
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class LockError(ValueError):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _LockModel(BaseModel):
|
|
49
|
+
model_config = ConfigDict(frozen=True, extra="forbid", strict=True)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class LockEntry(_LockModel):
|
|
53
|
+
kind: ArtifactKind
|
|
54
|
+
path: str
|
|
55
|
+
name: str
|
|
56
|
+
definition: dict[str, JsonValue]
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def id(self) -> str:
|
|
60
|
+
return f"{self.kind}:{self.path}:{self.name}"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Lockfile(_LockModel):
|
|
64
|
+
"""Each artifact's definition for a readable diff, and each source file's digest.
|
|
65
|
+
|
|
66
|
+
The file digests make the lock complete: a change the artifact model does not
|
|
67
|
+
capture, such as a YAML comment or a config key no parser reads, still drifts.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
version: Literal[1]
|
|
71
|
+
artifacts: dict[str, LockEntry]
|
|
72
|
+
files: dict[str, Digest]
|
|
73
|
+
|
|
74
|
+
@model_validator(mode="after")
|
|
75
|
+
def _keys_are_ids(self) -> Self:
|
|
76
|
+
for key, entry in self.artifacts.items():
|
|
77
|
+
if key != entry.id:
|
|
78
|
+
raise ValueError(f"key {key!r} does not match its entry {entry.id!r}")
|
|
79
|
+
return self
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def lock_entry(artifact: Artifact) -> LockEntry:
|
|
83
|
+
definition = artifact.model_dump(mode="json", exclude=set(_NOT_DEFINITION))
|
|
84
|
+
for field_path in _KEYS_ONLY.get(artifact.kind, ()):
|
|
85
|
+
_replace_in_place(definition, field_path, lambda value: sorted(value))
|
|
86
|
+
for field_path in _DIGESTED.get(artifact.kind, ()):
|
|
87
|
+
_replace_in_place(definition, field_path, digest_text)
|
|
88
|
+
return LockEntry(
|
|
89
|
+
kind=artifact.kind, path=artifact.source.path, name=artifact.name, definition=definition
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def build_lock(artifacts: Sequence[Artifact], file_digests: Mapping[str, str]) -> Lockfile:
|
|
94
|
+
entries: dict[str, LockEntry] = {}
|
|
95
|
+
for artifact in artifacts:
|
|
96
|
+
entry = lock_entry(artifact)
|
|
97
|
+
if entry.id in entries:
|
|
98
|
+
raise ValueError(f"two artifacts share the id {entry.id!r}")
|
|
99
|
+
entries[entry.id] = entry
|
|
100
|
+
return Lockfile(version=LOCK_VERSION, artifacts=entries, files=dict(file_digests))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def render_lock(lock: Lockfile) -> str:
|
|
104
|
+
# ensure_ascii, so a hidden character in a definition shows as an escape in review.
|
|
105
|
+
document = lock.model_dump(mode="json")
|
|
106
|
+
return json.dumps(document, indent=2, sort_keys=True, ensure_ascii=True) + "\n"
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def parse_lock(text: str) -> Lockfile:
|
|
110
|
+
try:
|
|
111
|
+
document = json.loads(text, parse_constant=_reject_constant)
|
|
112
|
+
except (ValueError, RecursionError) as error:
|
|
113
|
+
raise LockError(f"invalid JSON: {error}") from error
|
|
114
|
+
if not isinstance(document, dict):
|
|
115
|
+
raise LockError("the top level must be an object")
|
|
116
|
+
version = document.get("version")
|
|
117
|
+
if type(version) is not int or version != LOCK_VERSION:
|
|
118
|
+
raise LockError(f"unsupported version {version!r}; this agentbom reads version 1")
|
|
119
|
+
try:
|
|
120
|
+
return Lockfile.model_validate(document)
|
|
121
|
+
except ValidationError as error:
|
|
122
|
+
first = error.errors()[0]
|
|
123
|
+
location = [str(part) for part in first["loc"]]
|
|
124
|
+
if len(location) > _MAX_ERROR_LOCATION:
|
|
125
|
+
location = [*location[:_MAX_ERROR_LOCATION], "..."]
|
|
126
|
+
where = ".".join(location) or "top level"
|
|
127
|
+
raise LockError(f"{where}: {first['msg']}") from error
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def diff_lock(
|
|
131
|
+
lock: Lockfile, artifacts: Sequence[Artifact], file_digests: Mapping[str, str]
|
|
132
|
+
) -> tuple[Drift, ...]:
|
|
133
|
+
current = {artifact.id for artifact in artifacts}
|
|
134
|
+
drift = [
|
|
135
|
+
_drift("removed", entry, Location(path=entry.path), before=entry, after=None)
|
|
136
|
+
for key, entry in lock.artifacts.items()
|
|
137
|
+
if key not in current
|
|
138
|
+
]
|
|
139
|
+
for artifact in artifacts:
|
|
140
|
+
before, after = lock.artifacts.get(artifact.id), lock_entry(artifact)
|
|
141
|
+
if before != after:
|
|
142
|
+
change: Change = "added" if before is None else "changed"
|
|
143
|
+
drift.append(_drift(change, after, artifact.source, before=before, after=after))
|
|
144
|
+
# Every changed file is listed too, because its artifacts may not show all of the change.
|
|
145
|
+
drift.extend(
|
|
146
|
+
_file_drift(path, lock.files.get(path), file_digests.get(path))
|
|
147
|
+
for path in lock.files.keys() | file_digests.keys()
|
|
148
|
+
if lock.files.get(path) != file_digests.get(path)
|
|
149
|
+
)
|
|
150
|
+
return tuple(sorted(drift, key=lambda item: item.artifact_id))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _file_drift(path: str, before: str | None, after: str | None) -> Drift:
|
|
154
|
+
change: Change = "added" if before is None else "removed" if after is None else "changed"
|
|
155
|
+
text = FieldChange(field="text", change=change, before=before, after=after, hidden=True)
|
|
156
|
+
return Drift(
|
|
157
|
+
artifact_id=f"file:{path}",
|
|
158
|
+
change=change,
|
|
159
|
+
kind="file",
|
|
160
|
+
name=path,
|
|
161
|
+
location=Location(path=path),
|
|
162
|
+
fields=(text,),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _drift(
|
|
167
|
+
change: Change,
|
|
168
|
+
entry: LockEntry,
|
|
169
|
+
location: Location,
|
|
170
|
+
*,
|
|
171
|
+
before: LockEntry | None,
|
|
172
|
+
after: LockEntry | None,
|
|
173
|
+
) -> Drift:
|
|
174
|
+
return Drift(
|
|
175
|
+
artifact_id=entry.id,
|
|
176
|
+
change=change,
|
|
177
|
+
kind=entry.kind,
|
|
178
|
+
name=entry.name,
|
|
179
|
+
location=location,
|
|
180
|
+
fields=_field_changes(entry.kind, before, after),
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _field_changes(
|
|
185
|
+
kind: ArtifactKind, before: LockEntry | None, after: LockEntry | None
|
|
186
|
+
) -> tuple[FieldChange, ...]:
|
|
187
|
+
old = {} if before is None else _leaves(before.definition)
|
|
188
|
+
new = {} if after is None else _leaves(after.definition)
|
|
189
|
+
whole = before is None or after is None
|
|
190
|
+
changes: list[FieldChange] = []
|
|
191
|
+
for path in sorted(old.keys() | new.keys()):
|
|
192
|
+
field = ".".join(path)
|
|
193
|
+
hidden = any(path[: len(prefix)] == prefix for prefix in _DIGESTED.get(kind, ()))
|
|
194
|
+
if path in old and path in new:
|
|
195
|
+
if old[path] != new[path]:
|
|
196
|
+
changes.append(
|
|
197
|
+
FieldChange(
|
|
198
|
+
field=field,
|
|
199
|
+
change="changed",
|
|
200
|
+
before=old[path],
|
|
201
|
+
after=new[path],
|
|
202
|
+
hidden=hidden,
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
elif path in old:
|
|
206
|
+
if not _says_nothing(path, old[path], new, whole=whole):
|
|
207
|
+
changes.append(
|
|
208
|
+
FieldChange(field=field, change="removed", before=old[path], hidden=hidden)
|
|
209
|
+
)
|
|
210
|
+
elif not _says_nothing(path, new[path], old, whole=whole):
|
|
211
|
+
changes.append(FieldChange(field=field, change="added", after=new[path], hidden=hidden))
|
|
212
|
+
return tuple(changes)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _says_nothing(
|
|
216
|
+
path: FieldPath, value: JsonValue, other: Mapping[FieldPath, JsonValue], *, whole: bool
|
|
217
|
+
) -> bool:
|
|
218
|
+
# An empty value says nothing about an artifact that came or went, and an empty object
|
|
219
|
+
# says nothing when keys inside it already show the change.
|
|
220
|
+
if whole:
|
|
221
|
+
return value in ({}, [])
|
|
222
|
+
return value == {} and any(key[: len(path)] == path for key in other)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _leaves(
|
|
226
|
+
document: Mapping[str, JsonValue], prefix: FieldPath = ()
|
|
227
|
+
) -> dict[FieldPath, JsonValue]:
|
|
228
|
+
# Lists stay whole, and an empty object is a leaf, so equal leaves mean equal definitions.
|
|
229
|
+
leaves: dict[FieldPath, JsonValue] = {}
|
|
230
|
+
for key, value in document.items():
|
|
231
|
+
path = (*prefix, key)
|
|
232
|
+
if isinstance(value, dict) and value:
|
|
233
|
+
leaves.update(_leaves(value, path))
|
|
234
|
+
else:
|
|
235
|
+
leaves[path] = value
|
|
236
|
+
return leaves
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _replace_in_place(
|
|
240
|
+
document: dict[str, Any], path: FieldPath, replace: Callable[[Any], JsonValue]
|
|
241
|
+
) -> None:
|
|
242
|
+
*parents, leaf = path
|
|
243
|
+
for key in parents:
|
|
244
|
+
child = document.get(key)
|
|
245
|
+
if not isinstance(child, dict):
|
|
246
|
+
return
|
|
247
|
+
document = child
|
|
248
|
+
if leaf in document:
|
|
249
|
+
document[leaf] = replace(document[leaf])
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _reject_constant(name: str) -> None:
|
|
253
|
+
raise ValueError(f"{name} is not valid JSON")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def digest_text(text: str) -> str:
|
|
257
|
+
return DIGEST_PREFIX + hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def digest_link(target: str) -> str:
|
|
261
|
+
return digest_text(f"symlink -> {target}")
|
agentbom/models.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import json
|
|
3
|
+
from typing import Annotated, Literal
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field, JsonValue
|
|
6
|
+
|
|
7
|
+
ArtifactKind = Literal["mcp_server", "hook", "skill", "rules", "script", "settings"]
|
|
8
|
+
DriftKind = ArtifactKind | Literal["file"]
|
|
9
|
+
Agent = Literal["claude_code", "cursor", "vscode", "copilot", "codex", "agents_md"]
|
|
10
|
+
HookShell = Literal["default", "bash", "powershell"]
|
|
11
|
+
RemoteTransport = Literal["http", "sse", "ws"]
|
|
12
|
+
Severity = Literal["low", "medium", "high"]
|
|
13
|
+
Confidence = Literal["low", "medium", "high"]
|
|
14
|
+
RuleId = Literal[
|
|
15
|
+
"ABOM-001",
|
|
16
|
+
"ABOM-002",
|
|
17
|
+
"ABOM-003",
|
|
18
|
+
"ABOM-004",
|
|
19
|
+
"ABOM-005",
|
|
20
|
+
"ABOM-006",
|
|
21
|
+
"ABOM-007",
|
|
22
|
+
"ABOM-008",
|
|
23
|
+
"ABOM-009",
|
|
24
|
+
"ABOM-010",
|
|
25
|
+
]
|
|
26
|
+
SEVERITY_RANK: dict[Severity, int] = {"low": 0, "medium": 1, "high": 2}
|
|
27
|
+
ScriptLanguage = Literal[
|
|
28
|
+
"shell", "powershell", "python", "javascript", "typescript", "ruby", "perl", "batch"
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _Frozen(BaseModel):
|
|
33
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Location(_Frozen):
|
|
37
|
+
path: str
|
|
38
|
+
line: int | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class StdioLaunch(_Frozen):
|
|
42
|
+
transport: Literal["stdio"]
|
|
43
|
+
command: str
|
|
44
|
+
args: tuple[str, ...] = ()
|
|
45
|
+
env: dict[str, str] = Field(default_factory=dict)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class RemoteLaunch(_Frozen):
|
|
49
|
+
transport: RemoteTransport
|
|
50
|
+
url: str
|
|
51
|
+
headers: dict[str, str] = Field(default_factory=dict)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _ArtifactBase(_Frozen):
|
|
55
|
+
kind: ArtifactKind
|
|
56
|
+
name: str
|
|
57
|
+
source: Location
|
|
58
|
+
agents: tuple[Agent, ...]
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def id(self) -> str:
|
|
62
|
+
return f"{self.kind}:{self.source.path}:{self.name}"
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def content_hash(self) -> str:
|
|
66
|
+
content = self.model_dump(mode="json", exclude={"source", "agents", "body_line"})
|
|
67
|
+
canonical = json.dumps(content, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
68
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class McpServer(_ArtifactBase):
|
|
72
|
+
kind: Literal["mcp_server"] = "mcp_server"
|
|
73
|
+
launch: Annotated[StdioLaunch | RemoteLaunch, Field(discriminator="transport")]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Hook(_ArtifactBase):
|
|
77
|
+
kind: Literal["hook"] = "hook"
|
|
78
|
+
event: str
|
|
79
|
+
matcher: str | None
|
|
80
|
+
handler_type: str
|
|
81
|
+
commands: dict[HookShell, str]
|
|
82
|
+
url: str | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Skill(_ArtifactBase):
|
|
86
|
+
kind: Literal["skill"] = "skill"
|
|
87
|
+
description: str | None
|
|
88
|
+
frontmatter: dict[str, JsonValue]
|
|
89
|
+
body: str
|
|
90
|
+
body_line: int
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Rules(_ArtifactBase):
|
|
94
|
+
kind: Literal["rules"] = "rules"
|
|
95
|
+
frontmatter: dict[str, JsonValue]
|
|
96
|
+
body: str
|
|
97
|
+
body_line: int
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Script(_ArtifactBase):
|
|
101
|
+
kind: Literal["script"] = "script"
|
|
102
|
+
language: ScriptLanguage
|
|
103
|
+
body: str
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Settings(_ArtifactBase):
|
|
107
|
+
kind: Literal["settings"] = "settings"
|
|
108
|
+
allow: tuple[str, ...] = ()
|
|
109
|
+
deny: tuple[str, ...] = ()
|
|
110
|
+
ask: tuple[str, ...] = ()
|
|
111
|
+
default_mode: str | None = None
|
|
112
|
+
additional_directories: tuple[str, ...] = ()
|
|
113
|
+
enable_all_project_mcp_servers: bool | None = None
|
|
114
|
+
env: dict[str, str] = Field(default_factory=dict)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
Artifact = Annotated[
|
|
118
|
+
McpServer | Hook | Skill | Rules | Script | Settings, Field(discriminator="kind")
|
|
119
|
+
]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class ScanError(_Frozen):
|
|
123
|
+
path: str
|
|
124
|
+
message: str
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Finding(_Frozen):
|
|
128
|
+
rule_id: RuleId
|
|
129
|
+
severity: Severity
|
|
130
|
+
confidence: Confidence
|
|
131
|
+
message: str
|
|
132
|
+
location: Location
|
|
133
|
+
artifact_id: str
|
|
134
|
+
fix: str | None = None
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
Change = Literal["added", "removed", "changed"]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class FieldChange(_Frozen):
|
|
141
|
+
"""One leaf of an artifact definition that differs from the lockfile.
|
|
142
|
+
|
|
143
|
+
`before` is meaningful unless the field was added, `after` unless it was removed.
|
|
144
|
+
A hidden field holds a digest, because the lockfile never stores its value.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
field: str
|
|
148
|
+
change: Change
|
|
149
|
+
before: JsonValue = None
|
|
150
|
+
after: JsonValue = None
|
|
151
|
+
hidden: bool
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class Drift(_Frozen):
|
|
155
|
+
"""An artifact, or a whole source file, that differs from the lockfile."""
|
|
156
|
+
|
|
157
|
+
artifact_id: str
|
|
158
|
+
change: Change
|
|
159
|
+
kind: DriftKind
|
|
160
|
+
name: str
|
|
161
|
+
location: Location
|
|
162
|
+
fields: tuple[FieldChange, ...]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class Suppression(_Frozen):
|
|
166
|
+
"""A finding that agentbom.policy.yml approves or ignores, with its reason."""
|
|
167
|
+
|
|
168
|
+
finding: Finding
|
|
169
|
+
by: Literal["allow", "ignore"]
|
|
170
|
+
reason: str
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class ScanResult(_Frozen):
|
|
174
|
+
artifacts: tuple[Artifact, ...]
|
|
175
|
+
errors: tuple[ScanError, ...]
|
|
176
|
+
findings: tuple[Finding, ...]
|
|
177
|
+
drift: tuple[Drift, ...] = ()
|
|
178
|
+
suppressed: tuple[Suppression, ...] = ()
|
|
179
|
+
policy_notes: tuple[str, ...] = ()
|
|
180
|
+
file_digests: dict[str, str] = Field(default_factory=dict)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from collections.abc import Callable, Iterator
|
|
2
|
+
from typing import assert_never
|
|
3
|
+
|
|
4
|
+
from agentbom.models import Agent, Artifact, ScanError
|
|
5
|
+
from agentbom.parsers.hooks import (
|
|
6
|
+
parse_copilot_hooks_json,
|
|
7
|
+
parse_cursor_hooks_json,
|
|
8
|
+
parse_nested_hooks_json,
|
|
9
|
+
)
|
|
10
|
+
from agentbom.parsers.markdown import parse_rules_md, parse_skill_md
|
|
11
|
+
from agentbom.parsers.mcp import parse_mcp_json, parse_vscode_mcp_json
|
|
12
|
+
from agentbom.parsers.script import parse_script
|
|
13
|
+
from agentbom.parsers.settings import parse_claude_settings_json
|
|
14
|
+
from agentbom.registry import Format
|
|
15
|
+
|
|
16
|
+
ParseFn = Callable[[str, str, tuple[Agent, ...]], Iterator[Artifact | ScanError]]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parser_for(format: Format) -> ParseFn:
|
|
20
|
+
match format:
|
|
21
|
+
case "mcp_json":
|
|
22
|
+
return parse_mcp_json
|
|
23
|
+
case "vscode_mcp_json":
|
|
24
|
+
return parse_vscode_mcp_json
|
|
25
|
+
case "claude_settings_json":
|
|
26
|
+
return parse_claude_settings_json
|
|
27
|
+
case "nested_hooks_json":
|
|
28
|
+
return parse_nested_hooks_json
|
|
29
|
+
case "cursor_hooks_json":
|
|
30
|
+
return parse_cursor_hooks_json
|
|
31
|
+
case "copilot_hooks_json":
|
|
32
|
+
return parse_copilot_hooks_json
|
|
33
|
+
case "skill_md":
|
|
34
|
+
return parse_skill_md
|
|
35
|
+
case "rules_md":
|
|
36
|
+
return parse_rules_md
|
|
37
|
+
case "script":
|
|
38
|
+
return parse_script
|
|
39
|
+
case _:
|
|
40
|
+
assert_never(format)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse(
|
|
44
|
+
text: str, path: str, format: Format, agents: tuple[Agent, ...]
|
|
45
|
+
) -> tuple[list[Artifact], list[ScanError]]:
|
|
46
|
+
artifacts: list[Artifact] = []
|
|
47
|
+
errors: list[ScanError] = []
|
|
48
|
+
for item in parser_for(format)(text, path, agents):
|
|
49
|
+
if isinstance(item, ScanError):
|
|
50
|
+
errors.append(item)
|
|
51
|
+
else:
|
|
52
|
+
artifacts.append(item)
|
|
53
|
+
return artifacts, errors
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import math
|
|
3
|
+
import re
|
|
4
|
+
from datetime import date
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import JsonValue
|
|
8
|
+
|
|
9
|
+
_SURROGATE = re.compile("[\ud800-\udfff]")
|
|
10
|
+
_MAX_DEPTH = 64
|
|
11
|
+
_MAX_NODES = 100_000
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ShapeError(Exception):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_json(text: str) -> Any:
|
|
19
|
+
try:
|
|
20
|
+
return json.loads(text)
|
|
21
|
+
except json.JSONDecodeError as error:
|
|
22
|
+
raise ShapeError(
|
|
23
|
+
f"invalid JSON: {error.msg} (line {error.lineno}, column {error.colno})"
|
|
24
|
+
) from error
|
|
25
|
+
except RecursionError as error:
|
|
26
|
+
raise ShapeError("invalid JSON: nesting too deep") from error
|
|
27
|
+
except ValueError as error:
|
|
28
|
+
raise ShapeError(f"invalid JSON: {error}") from error
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def as_text(value: object, where: str) -> str:
|
|
32
|
+
if not isinstance(value, str):
|
|
33
|
+
raise ShapeError(f"{where} must be a string")
|
|
34
|
+
if _SURROGATE.search(value):
|
|
35
|
+
raise ShapeError(f"{where} contains an unpaired surrogate escape")
|
|
36
|
+
return value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def as_optional_text(value: object, where: str) -> str | None:
|
|
40
|
+
return None if value is None else as_text(value, where)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def as_object(value: object, where: str) -> dict[str, object]:
|
|
44
|
+
if not isinstance(value, dict):
|
|
45
|
+
raise ShapeError(f"{where} must be an object")
|
|
46
|
+
for key in value:
|
|
47
|
+
as_text(key, f"{where} key")
|
|
48
|
+
return value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def as_list(value: object, where: str) -> list[object]:
|
|
52
|
+
if not isinstance(value, list):
|
|
53
|
+
raise ShapeError(f"{where} must be a list")
|
|
54
|
+
return value
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def as_text_list(value: object, where: str) -> tuple[str, ...]:
|
|
58
|
+
return tuple(as_text(item, f"{where}[{i}]") for i, item in enumerate(as_list(value, where)))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def as_text_map(value: object, where: str) -> dict[str, str]:
|
|
62
|
+
return {key: as_text(item, f"{where}.{key}") for key, item in as_object(value, where).items()}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def to_json_value(value: object, where: str) -> JsonValue:
|
|
66
|
+
nodes = 0
|
|
67
|
+
|
|
68
|
+
def convert(item: object, at: str, depth: int) -> JsonValue:
|
|
69
|
+
nonlocal nodes
|
|
70
|
+
nodes += 1
|
|
71
|
+
if nodes > _MAX_NODES:
|
|
72
|
+
raise ShapeError(f"{where} expands to more than {_MAX_NODES} values")
|
|
73
|
+
if depth > _MAX_DEPTH:
|
|
74
|
+
raise ShapeError(f"{where} nests deeper than {_MAX_DEPTH} levels")
|
|
75
|
+
if item is None or isinstance(item, bool | int):
|
|
76
|
+
return item
|
|
77
|
+
if isinstance(item, float):
|
|
78
|
+
if not math.isfinite(item):
|
|
79
|
+
raise ShapeError(f"{at} is not a finite number")
|
|
80
|
+
return item
|
|
81
|
+
if isinstance(item, str):
|
|
82
|
+
return as_text(item, at)
|
|
83
|
+
if isinstance(item, date):
|
|
84
|
+
return item.isoformat()
|
|
85
|
+
if isinstance(item, list):
|
|
86
|
+
return [convert(child, f"{at}[{i}]", depth + 1) for i, child in enumerate(item)]
|
|
87
|
+
if isinstance(item, dict):
|
|
88
|
+
result: dict[str, JsonValue] = {}
|
|
89
|
+
for key, child in item.items():
|
|
90
|
+
if not isinstance(key, str):
|
|
91
|
+
raise ShapeError(f"{at} has a non-string key {key!r}")
|
|
92
|
+
result[as_text(key, f"{at} key")] = convert(child, f"{at}.{key}", depth + 1)
|
|
93
|
+
return result
|
|
94
|
+
raise ShapeError(f"{at} is a {type(item).__name__}, which has no JSON form")
|
|
95
|
+
|
|
96
|
+
return convert(value, where, 0)
|