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
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
from collections.abc import Iterator, Mapping
|
|
2
|
+
|
|
3
|
+
from agentbom.models import Agent, Hook, HookShell, Location, ScanError
|
|
4
|
+
from agentbom.parsers._shape import (
|
|
5
|
+
ShapeError,
|
|
6
|
+
as_list,
|
|
7
|
+
as_object,
|
|
8
|
+
as_optional_text,
|
|
9
|
+
as_text,
|
|
10
|
+
load_json,
|
|
11
|
+
)
|
|
12
|
+
from agentbom.parsers.jsonc import strip_jsonc
|
|
13
|
+
|
|
14
|
+
_COMMAND_ONLY: Mapping[str, HookShell] = {"command": "default"}
|
|
15
|
+
_COPILOT_SHELLS: Mapping[str, HookShell] = {
|
|
16
|
+
"command": "default",
|
|
17
|
+
"bash": "bash",
|
|
18
|
+
"powershell": "powershell",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parse_nested_hooks_json(
|
|
23
|
+
text: str, path: str, agents: tuple[Agent, ...]
|
|
24
|
+
) -> Iterator[Hook | ScanError]:
|
|
25
|
+
try:
|
|
26
|
+
document = document_object(text)
|
|
27
|
+
except ShapeError as error:
|
|
28
|
+
yield ScanError(path=path, message=str(error))
|
|
29
|
+
return
|
|
30
|
+
yield from nested_hooks(document, path, agents)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def nested_hooks(
|
|
34
|
+
document: dict[str, object], path: str, agents: tuple[Agent, ...]
|
|
35
|
+
) -> Iterator[Hook | ScanError]:
|
|
36
|
+
"""Claude Code and Codex: event -> matcher groups -> handlers."""
|
|
37
|
+
try:
|
|
38
|
+
events = _events(document)
|
|
39
|
+
except ShapeError as error:
|
|
40
|
+
yield ScanError(path=path, message=str(error))
|
|
41
|
+
return
|
|
42
|
+
for event, groups_value in events.items():
|
|
43
|
+
try:
|
|
44
|
+
groups = as_list(groups_value, f"hooks.{event}")
|
|
45
|
+
except ShapeError as error:
|
|
46
|
+
yield ScanError(path=path, message=str(error))
|
|
47
|
+
continue
|
|
48
|
+
for g, group_value in enumerate(groups):
|
|
49
|
+
where = f"hooks.{event}[{g}]"
|
|
50
|
+
try:
|
|
51
|
+
group = as_object(group_value, where)
|
|
52
|
+
matcher = as_optional_text(group.get("matcher"), f"{where}.matcher")
|
|
53
|
+
handlers = as_list(group.get("hooks"), f"{where}.hooks")
|
|
54
|
+
except ShapeError as error:
|
|
55
|
+
yield ScanError(path=path, message=str(error))
|
|
56
|
+
continue
|
|
57
|
+
for i, handler in enumerate(handlers):
|
|
58
|
+
name = f"{event}[{g}].hooks[{i}]"
|
|
59
|
+
try:
|
|
60
|
+
fields = as_object(handler, f"hooks.{name}")
|
|
61
|
+
hook = _hook(fields, name, event, matcher, path, agents, _COMMAND_ONLY)
|
|
62
|
+
except ShapeError as error:
|
|
63
|
+
yield ScanError(path=path, message=str(error))
|
|
64
|
+
continue
|
|
65
|
+
yield hook
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_cursor_hooks_json(
|
|
69
|
+
text: str, path: str, agents: tuple[Agent, ...]
|
|
70
|
+
) -> Iterator[Hook | ScanError]:
|
|
71
|
+
yield from _flat_hooks(text, path, agents, _COMMAND_ONLY)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def parse_copilot_hooks_json(
|
|
75
|
+
text: str, path: str, agents: tuple[Agent, ...]
|
|
76
|
+
) -> Iterator[Hook | ScanError]:
|
|
77
|
+
try:
|
|
78
|
+
stripped = strip_jsonc(text)
|
|
79
|
+
except ShapeError as error:
|
|
80
|
+
yield ScanError(path=path, message=str(error))
|
|
81
|
+
return
|
|
82
|
+
if not stripped.strip():
|
|
83
|
+
# A file that is entirely commented out is how repos disable their hooks.
|
|
84
|
+
return
|
|
85
|
+
yield from _flat_hooks(stripped, path, agents, _COPILOT_SHELLS)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _flat_hooks(
|
|
89
|
+
text: str, path: str, agents: tuple[Agent, ...], shells: Mapping[str, HookShell]
|
|
90
|
+
) -> Iterator[Hook | ScanError]:
|
|
91
|
+
"""Cursor and Copilot: event -> handlers, each handler carrying its own matcher."""
|
|
92
|
+
try:
|
|
93
|
+
events = _events(document_object(text))
|
|
94
|
+
except ShapeError as error:
|
|
95
|
+
yield ScanError(path=path, message=str(error))
|
|
96
|
+
return
|
|
97
|
+
for event, entries_value in events.items():
|
|
98
|
+
try:
|
|
99
|
+
entries = as_list(entries_value, f"hooks.{event}")
|
|
100
|
+
except ShapeError as error:
|
|
101
|
+
yield ScanError(path=path, message=str(error))
|
|
102
|
+
continue
|
|
103
|
+
for i, entry in enumerate(entries):
|
|
104
|
+
name = f"{event}[{i}]"
|
|
105
|
+
try:
|
|
106
|
+
fields = as_object(entry, f"hooks.{name}")
|
|
107
|
+
matcher = as_optional_text(fields.get("matcher"), f"hooks.{name}.matcher")
|
|
108
|
+
hook = _hook(fields, name, event, matcher, path, agents, shells)
|
|
109
|
+
except ShapeError as error:
|
|
110
|
+
yield ScanError(path=path, message=str(error))
|
|
111
|
+
continue
|
|
112
|
+
yield hook
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def document_object(text: str) -> dict[str, object]:
|
|
116
|
+
return as_object(load_json(text), "top level")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _events(document: dict[str, object]) -> dict[str, object]:
|
|
120
|
+
return as_object(document.get("hooks", {}), "hooks")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _hook(
|
|
124
|
+
fields: dict[str, object],
|
|
125
|
+
name: str,
|
|
126
|
+
event: str,
|
|
127
|
+
matcher: str | None,
|
|
128
|
+
path: str,
|
|
129
|
+
agents: tuple[Agent, ...],
|
|
130
|
+
shells: Mapping[str, HookShell],
|
|
131
|
+
) -> Hook:
|
|
132
|
+
where = f"hooks.{name}"
|
|
133
|
+
return Hook(
|
|
134
|
+
name=name,
|
|
135
|
+
source=Location(path=path),
|
|
136
|
+
agents=agents,
|
|
137
|
+
event=event,
|
|
138
|
+
matcher=matcher,
|
|
139
|
+
handler_type=as_text(fields.get("type", "command"), f"{where}.type"),
|
|
140
|
+
commands={
|
|
141
|
+
shell: as_text(fields[key], f"{where}.{key}")
|
|
142
|
+
for key, shell in shells.items()
|
|
143
|
+
if key in fields
|
|
144
|
+
},
|
|
145
|
+
url=as_optional_text(fields.get("url"), f"{where}.url"),
|
|
146
|
+
)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from agentbom.parsers._shape import ShapeError
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def strip_jsonc(text: str) -> str:
|
|
5
|
+
"""Remove comments and trailing commas, keeping line numbers intact."""
|
|
6
|
+
out: list[str] = []
|
|
7
|
+
last_token = -1
|
|
8
|
+
i, n = 0, len(text)
|
|
9
|
+
while i < n:
|
|
10
|
+
char = text[i]
|
|
11
|
+
if char == '"':
|
|
12
|
+
j = i + 1
|
|
13
|
+
while j < n and text[j] != '"':
|
|
14
|
+
j += 2 if text[j] == "\\" else 1
|
|
15
|
+
j = min(j + 1, n)
|
|
16
|
+
out.append(text[i:j])
|
|
17
|
+
last_token = len(out) - 1
|
|
18
|
+
i = j
|
|
19
|
+
elif text.startswith("//", i):
|
|
20
|
+
end = text.find("\n", i)
|
|
21
|
+
i = n if end == -1 else end
|
|
22
|
+
elif text.startswith("/*", i):
|
|
23
|
+
end = text.find("*/", i + 2)
|
|
24
|
+
if end == -1:
|
|
25
|
+
raise ShapeError("invalid JSON: unterminated block comment")
|
|
26
|
+
out.append("\n" * text.count("\n", i, end))
|
|
27
|
+
i = end + 2
|
|
28
|
+
else:
|
|
29
|
+
if char in "]}" and last_token >= 0 and out[last_token] == ",":
|
|
30
|
+
out[last_token] = " "
|
|
31
|
+
out.append(char)
|
|
32
|
+
if not char.isspace():
|
|
33
|
+
last_token = len(out) - 1
|
|
34
|
+
i += 1
|
|
35
|
+
return "".join(out)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Iterator
|
|
3
|
+
from pathlib import PurePosixPath
|
|
4
|
+
|
|
5
|
+
import yaml
|
|
6
|
+
from pydantic import JsonValue
|
|
7
|
+
|
|
8
|
+
from agentbom.models import Agent, Location, Rules, ScanError, Skill
|
|
9
|
+
from agentbom.parsers._shape import ShapeError, to_json_value
|
|
10
|
+
|
|
11
|
+
_DELIMITER = "---"
|
|
12
|
+
_FLAT_LINE = re.compile(r"([A-Za-z_][A-Za-z0-9_-]*)\s*:(.*)")
|
|
13
|
+
_FLAT_SCALARS: dict[str, JsonValue] = {"": None, "true": True, "false": False}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def parse_skill_md(text: str, path: str, agents: tuple[Agent, ...]) -> Iterator[Skill | ScanError]:
|
|
17
|
+
try:
|
|
18
|
+
frontmatter, body, body_line = _split_frontmatter(text)
|
|
19
|
+
except ShapeError as error:
|
|
20
|
+
yield ScanError(path=path, message=str(error))
|
|
21
|
+
return
|
|
22
|
+
declared_name = frontmatter.get("name")
|
|
23
|
+
description = frontmatter.get("description")
|
|
24
|
+
yield Skill(
|
|
25
|
+
name=declared_name
|
|
26
|
+
if isinstance(declared_name, str) and declared_name
|
|
27
|
+
else PurePosixPath(path).parent.name,
|
|
28
|
+
source=Location(path=path, line=1),
|
|
29
|
+
agents=agents,
|
|
30
|
+
description=description if isinstance(description, str) else None,
|
|
31
|
+
frontmatter=frontmatter,
|
|
32
|
+
body=body,
|
|
33
|
+
body_line=body_line,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_rules_md(text: str, path: str, agents: tuple[Agent, ...]) -> Iterator[Rules | ScanError]:
|
|
38
|
+
yield _rules(text, path, agents)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _rules(text: str, path: str, agents: tuple[Agent, ...]) -> Rules | ScanError:
|
|
42
|
+
try:
|
|
43
|
+
frontmatter, body, body_line = _split_frontmatter(text)
|
|
44
|
+
except ShapeError as error:
|
|
45
|
+
return ScanError(path=path, message=str(error))
|
|
46
|
+
return Rules(
|
|
47
|
+
name=path,
|
|
48
|
+
source=Location(path=path, line=1),
|
|
49
|
+
agents=agents,
|
|
50
|
+
frontmatter=frontmatter,
|
|
51
|
+
body=body,
|
|
52
|
+
body_line=body_line,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _split_frontmatter(text: str) -> tuple[dict[str, JsonValue], str, int]:
|
|
57
|
+
"""Return the frontmatter, the body, and the 1-based file line the body starts on."""
|
|
58
|
+
lines = text.split("\n")
|
|
59
|
+
if lines[0].rstrip(" \t") != _DELIMITER:
|
|
60
|
+
return {}, text, 1
|
|
61
|
+
closing = next((i for i in range(1, len(lines)) if lines[i].rstrip(" \t") == _DELIMITER), None)
|
|
62
|
+
if closing is None:
|
|
63
|
+
raise ShapeError("frontmatter has no closing --- line")
|
|
64
|
+
header, body, body_line = lines[1:closing], "\n".join(lines[closing + 1 :]), closing + 2
|
|
65
|
+
try:
|
|
66
|
+
return _yaml_mapping(header), body, body_line
|
|
67
|
+
except ShapeError:
|
|
68
|
+
# Real skills and rules ship frontmatter that YAML rejects but agents load, such as
|
|
69
|
+
# `globs: *.mdc` or an unquoted description with a second `: `, so read flat lines.
|
|
70
|
+
flat = _flat_mapping(header)
|
|
71
|
+
if flat is None:
|
|
72
|
+
raise
|
|
73
|
+
return flat, body, body_line
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _yaml_mapping(lines: list[str]) -> dict[str, JsonValue]:
|
|
77
|
+
try:
|
|
78
|
+
loaded = yaml.safe_load("".join(f"{line}\n" for line in lines))
|
|
79
|
+
except yaml.MarkedYAMLError as error:
|
|
80
|
+
mark = error.problem_mark
|
|
81
|
+
where = f" at line {mark.line + 2}" if mark is not None else ""
|
|
82
|
+
raise ShapeError(f"invalid YAML frontmatter: {error.problem}{where}") from error
|
|
83
|
+
except yaml.YAMLError as error:
|
|
84
|
+
raise ShapeError(f"invalid YAML frontmatter: {error}") from error
|
|
85
|
+
except RecursionError as error:
|
|
86
|
+
raise ShapeError("invalid YAML frontmatter: nesting too deep") from error
|
|
87
|
+
if loaded is None:
|
|
88
|
+
return {}
|
|
89
|
+
frontmatter = to_json_value(loaded, "frontmatter")
|
|
90
|
+
if not isinstance(frontmatter, dict):
|
|
91
|
+
raise ShapeError("frontmatter must be a mapping")
|
|
92
|
+
return frontmatter
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _flat_mapping(lines: list[str]) -> dict[str, JsonValue] | None:
|
|
96
|
+
mapping: dict[str, JsonValue] = {}
|
|
97
|
+
key: str | None = None
|
|
98
|
+
for line in lines:
|
|
99
|
+
if not line.strip():
|
|
100
|
+
continue
|
|
101
|
+
if line[0] in " \t" and key is not None:
|
|
102
|
+
previous = mapping[key]
|
|
103
|
+
text = line.strip()
|
|
104
|
+
mapping[key] = text if previous is None else f"{previous}\n{text}"
|
|
105
|
+
continue
|
|
106
|
+
match = _FLAT_LINE.fullmatch(line)
|
|
107
|
+
if match is None:
|
|
108
|
+
return None
|
|
109
|
+
key, raw = match.group(1), match.group(2).strip()
|
|
110
|
+
mapping[key] = _FLAT_SCALARS.get(raw, raw)
|
|
111
|
+
return mapping
|
agentbom/parsers/mcp.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
|
|
3
|
+
from agentbom.models import (
|
|
4
|
+
Agent,
|
|
5
|
+
Location,
|
|
6
|
+
McpServer,
|
|
7
|
+
RemoteLaunch,
|
|
8
|
+
RemoteTransport,
|
|
9
|
+
ScanError,
|
|
10
|
+
StdioLaunch,
|
|
11
|
+
)
|
|
12
|
+
from agentbom.parsers._shape import (
|
|
13
|
+
ShapeError,
|
|
14
|
+
as_object,
|
|
15
|
+
as_optional_text,
|
|
16
|
+
as_text,
|
|
17
|
+
as_text_list,
|
|
18
|
+
as_text_map,
|
|
19
|
+
load_json,
|
|
20
|
+
)
|
|
21
|
+
from agentbom.parsers.jsonc import strip_jsonc
|
|
22
|
+
|
|
23
|
+
_REMOTE_TRANSPORTS: dict[str | None, RemoteTransport] = {
|
|
24
|
+
None: "http",
|
|
25
|
+
"http": "http",
|
|
26
|
+
"streamable-http": "http",
|
|
27
|
+
"streamableHttp": "http",
|
|
28
|
+
"sse": "sse",
|
|
29
|
+
"ws": "ws",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse_mcp_json(
|
|
34
|
+
text: str, path: str, agents: tuple[Agent, ...]
|
|
35
|
+
) -> Iterator[McpServer | ScanError]:
|
|
36
|
+
yield from _parse_servers(text, path, agents, "mcpServers")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_vscode_mcp_json(
|
|
40
|
+
text: str, path: str, agents: tuple[Agent, ...]
|
|
41
|
+
) -> Iterator[McpServer | ScanError]:
|
|
42
|
+
try:
|
|
43
|
+
stripped = strip_jsonc(text)
|
|
44
|
+
except ShapeError as error:
|
|
45
|
+
yield ScanError(path=path, message=str(error))
|
|
46
|
+
return
|
|
47
|
+
yield from _parse_servers(stripped, path, agents, "servers")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _parse_servers(
|
|
51
|
+
text: str, path: str, agents: tuple[Agent, ...], key: str
|
|
52
|
+
) -> Iterator[McpServer | ScanError]:
|
|
53
|
+
try:
|
|
54
|
+
document = as_object(load_json(text), "top level")
|
|
55
|
+
servers = as_object(document.get(key, {}), key)
|
|
56
|
+
except ShapeError as error:
|
|
57
|
+
yield ScanError(path=path, message=str(error))
|
|
58
|
+
return
|
|
59
|
+
for name, entry in servers.items():
|
|
60
|
+
where = f"{key}.{name}"
|
|
61
|
+
try:
|
|
62
|
+
launch = _launch(entry, where)
|
|
63
|
+
except ShapeError as error:
|
|
64
|
+
yield ScanError(path=path, message=str(error))
|
|
65
|
+
continue
|
|
66
|
+
if launch is None:
|
|
67
|
+
continue
|
|
68
|
+
yield McpServer(name=name, source=Location(path=path), agents=agents, launch=launch)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _launch(entry: object, where: str) -> StdioLaunch | RemoteLaunch | None:
|
|
72
|
+
fields = as_object(entry, where)
|
|
73
|
+
if fields.get("type") == "sdk":
|
|
74
|
+
# Claude Code skips sdk entries in config files; only the SDK host can register them.
|
|
75
|
+
return None
|
|
76
|
+
if "command" in fields:
|
|
77
|
+
return StdioLaunch(
|
|
78
|
+
transport="stdio",
|
|
79
|
+
command=as_text(fields["command"], f"{where}.command"),
|
|
80
|
+
args=as_text_list(fields.get("args", []), f"{where}.args"),
|
|
81
|
+
env=as_text_map(fields.get("env", {}), f"{where}.env"),
|
|
82
|
+
)
|
|
83
|
+
if "url" not in fields:
|
|
84
|
+
raise ShapeError(f"{where} has neither a command nor a url")
|
|
85
|
+
declared = as_optional_text(fields.get("type"), f"{where}.type")
|
|
86
|
+
if declared == "stdio":
|
|
87
|
+
raise ShapeError(f"{where} is a stdio server with no command")
|
|
88
|
+
if declared not in _REMOTE_TRANSPORTS:
|
|
89
|
+
raise ShapeError(f"{where}.type {declared!r} is not a supported transport")
|
|
90
|
+
return RemoteLaunch(
|
|
91
|
+
transport=_REMOTE_TRANSPORTS[declared],
|
|
92
|
+
url=as_text(fields["url"], f"{where}.url"),
|
|
93
|
+
headers=as_text_map(fields.get("headers", {}), f"{where}.headers"),
|
|
94
|
+
)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
from pathlib import PurePosixPath
|
|
3
|
+
|
|
4
|
+
from agentbom.models import Agent, Location, ScanError, Script
|
|
5
|
+
from agentbom.registry import SCRIPT_LANGUAGES
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def parse_script(text: str, path: str, agents: tuple[Agent, ...]) -> Iterator[Script | ScanError]:
|
|
9
|
+
yield Script(
|
|
10
|
+
name=path,
|
|
11
|
+
source=Location(path=path, line=1),
|
|
12
|
+
agents=agents,
|
|
13
|
+
language=SCRIPT_LANGUAGES[PurePosixPath(path).suffix],
|
|
14
|
+
body=text,
|
|
15
|
+
)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
|
|
3
|
+
from agentbom.models import Agent, Hook, Location, ScanError, Settings
|
|
4
|
+
from agentbom.parsers._shape import (
|
|
5
|
+
ShapeError,
|
|
6
|
+
as_object,
|
|
7
|
+
as_optional_text,
|
|
8
|
+
as_text_list,
|
|
9
|
+
as_text_map,
|
|
10
|
+
)
|
|
11
|
+
from agentbom.parsers.hooks import document_object, nested_hooks
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse_claude_settings_json(
|
|
15
|
+
text: str, path: str, agents: tuple[Agent, ...]
|
|
16
|
+
) -> Iterator[Hook | Settings | ScanError]:
|
|
17
|
+
try:
|
|
18
|
+
document = document_object(text)
|
|
19
|
+
except ShapeError as error:
|
|
20
|
+
yield ScanError(path=path, message=str(error))
|
|
21
|
+
return
|
|
22
|
+
yield from nested_hooks(document, path, agents)
|
|
23
|
+
try:
|
|
24
|
+
yield _settings(document, path, agents)
|
|
25
|
+
except ShapeError as error:
|
|
26
|
+
yield ScanError(path=path, message=str(error))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _settings(document: dict[str, object], path: str, agents: tuple[Agent, ...]) -> Settings:
|
|
30
|
+
permissions = as_object(document.get("permissions", {}), "permissions")
|
|
31
|
+
enable_all = document.get("enableAllProjectMcpServers")
|
|
32
|
+
if enable_all is not None and not isinstance(enable_all, bool):
|
|
33
|
+
raise ShapeError("enableAllProjectMcpServers must be true or false")
|
|
34
|
+
return Settings(
|
|
35
|
+
name=path,
|
|
36
|
+
source=Location(path=path),
|
|
37
|
+
agents=agents,
|
|
38
|
+
allow=as_text_list(permissions.get("allow", []), "permissions.allow"),
|
|
39
|
+
deny=as_text_list(permissions.get("deny", []), "permissions.deny"),
|
|
40
|
+
ask=as_text_list(permissions.get("ask", []), "permissions.ask"),
|
|
41
|
+
default_mode=as_optional_text(permissions.get("defaultMode"), "permissions.defaultMode"),
|
|
42
|
+
additional_directories=as_text_list(
|
|
43
|
+
permissions.get("additionalDirectories", []), "permissions.additionalDirectories"
|
|
44
|
+
),
|
|
45
|
+
enable_all_project_mcp_servers=enable_all,
|
|
46
|
+
env=as_text_map(document.get("env", {}), "env"),
|
|
47
|
+
)
|
agentbom/policy.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""agentbom.policy.yml: the fail threshold, approved artifacts and expiring ignores."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from datetime import date
|
|
5
|
+
from typing import Annotated, Literal
|
|
6
|
+
|
|
7
|
+
import yaml
|
|
8
|
+
from pathspec import GitIgnoreSpec
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, StringConstraints, ValidationError
|
|
10
|
+
|
|
11
|
+
from agentbom.lockfile import LOCKFILE_NAME
|
|
12
|
+
from agentbom.models import Artifact, Finding, ScanResult, Severity, Suppression
|
|
13
|
+
|
|
14
|
+
POLICY_FILENAME = "agentbom.policy.yml"
|
|
15
|
+
POLICY_VERSION: Literal[1] = 1
|
|
16
|
+
_MAX_ERROR_LOCATION = 6
|
|
17
|
+
|
|
18
|
+
Text = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]
|
|
19
|
+
ContentHash = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")]
|
|
20
|
+
# Drift cannot be ignored: review the change and run `agentbom lock` instead.
|
|
21
|
+
IgnorableRuleId = Literal[
|
|
22
|
+
"ABOM-001",
|
|
23
|
+
"ABOM-002",
|
|
24
|
+
"ABOM-003",
|
|
25
|
+
"ABOM-004",
|
|
26
|
+
"ABOM-005",
|
|
27
|
+
"ABOM-007",
|
|
28
|
+
"ABOM-008",
|
|
29
|
+
"ABOM-009",
|
|
30
|
+
"ABOM-010",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PolicyError(ValueError):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _PolicyModel(BaseModel):
|
|
39
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AllowedServer(_PolicyModel):
|
|
43
|
+
path: Text
|
|
44
|
+
name: Text
|
|
45
|
+
sha256: ContentHash
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AllowedSkill(_PolicyModel):
|
|
49
|
+
path: Text
|
|
50
|
+
sha256: ContentHash
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Allow(_PolicyModel):
|
|
54
|
+
mcp_servers: tuple[AllowedServer, ...] = ()
|
|
55
|
+
skills: tuple[AllowedSkill, ...] = ()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Ignore(_PolicyModel):
|
|
59
|
+
rule: IgnorableRuleId
|
|
60
|
+
path: Text
|
|
61
|
+
reason: Text
|
|
62
|
+
expires: date
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Policy(_PolicyModel):
|
|
66
|
+
version: Literal[1]
|
|
67
|
+
fail_on: Severity = "high"
|
|
68
|
+
allow: Allow = Allow()
|
|
69
|
+
ignore: tuple[Ignore, ...] = ()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse_policy(text: str) -> Policy:
|
|
73
|
+
try:
|
|
74
|
+
document = yaml.safe_load(text)
|
|
75
|
+
except yaml.YAMLError as error:
|
|
76
|
+
raise PolicyError(f"invalid YAML: {error}") from error
|
|
77
|
+
except RecursionError as error:
|
|
78
|
+
raise PolicyError("invalid YAML: nesting too deep") from error
|
|
79
|
+
if not isinstance(document, dict):
|
|
80
|
+
raise PolicyError("the top level must be a mapping")
|
|
81
|
+
version = document.get("version")
|
|
82
|
+
if type(version) is not int or version != POLICY_VERSION:
|
|
83
|
+
raise PolicyError(f"unsupported version {version!r}; this agentbom reads version 1")
|
|
84
|
+
ignores = document.get("ignore")
|
|
85
|
+
for index, entry in enumerate(ignores if isinstance(ignores, list) else []):
|
|
86
|
+
if isinstance(entry, dict) and entry.get("rule") == "ABOM-006":
|
|
87
|
+
raise PolicyError(
|
|
88
|
+
f"ignore.{index}.rule: drift (ABOM-006) cannot be ignored; review the change "
|
|
89
|
+
f"and run `agentbom lock` to update {LOCKFILE_NAME}"
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
return Policy.model_validate(document)
|
|
93
|
+
except ValidationError as error:
|
|
94
|
+
first = error.errors()[0]
|
|
95
|
+
location = [str(part) for part in first["loc"]]
|
|
96
|
+
if len(location) > _MAX_ERROR_LOCATION:
|
|
97
|
+
location = [*location[:_MAX_ERROR_LOCATION], "..."]
|
|
98
|
+
where = ".".join(location) or "top level"
|
|
99
|
+
raise PolicyError(f"{where}: {first['msg']}") from error
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def apply_policy(policy: Policy, result: ScanResult, today: date) -> ScanResult:
|
|
103
|
+
"""Move approved and ignored findings to `suppressed`, and explain stale entries."""
|
|
104
|
+
approved, notes = _approved(policy.allow, result.artifacts)
|
|
105
|
+
active = [entry for entry in policy.ignore if today <= entry.expires]
|
|
106
|
+
notes += [
|
|
107
|
+
f'ignore for {entry.rule} on "{entry.path}" expired on {entry.expires}; '
|
|
108
|
+
"its findings are reported again"
|
|
109
|
+
for entry in policy.ignore
|
|
110
|
+
if today > entry.expires
|
|
111
|
+
]
|
|
112
|
+
patterns = [GitIgnoreSpec.from_lines([entry.path]) for entry in active]
|
|
113
|
+
used: set[int] = set()
|
|
114
|
+
kept: list[Finding] = []
|
|
115
|
+
suppressed: list[Suppression] = []
|
|
116
|
+
for finding in result.findings:
|
|
117
|
+
if finding.rule_id == "ABOM-006":
|
|
118
|
+
kept.append(finding)
|
|
119
|
+
elif finding.artifact_id in approved:
|
|
120
|
+
suppressed.append(
|
|
121
|
+
Suppression(finding=finding, by="allow", reason=approved[finding.artifact_id])
|
|
122
|
+
)
|
|
123
|
+
elif (index := _matching_ignore(active, patterns, finding)) is not None:
|
|
124
|
+
used.add(index)
|
|
125
|
+
suppressed.append(
|
|
126
|
+
Suppression(finding=finding, by="ignore", reason=active[index].reason)
|
|
127
|
+
)
|
|
128
|
+
else:
|
|
129
|
+
kept.append(finding)
|
|
130
|
+
notes += [
|
|
131
|
+
f'ignore for {entry.rule} on "{entry.path}" matches no finding; remove it'
|
|
132
|
+
for index, entry in enumerate(active)
|
|
133
|
+
if index not in used
|
|
134
|
+
]
|
|
135
|
+
return result.model_copy(
|
|
136
|
+
update={
|
|
137
|
+
"findings": tuple(kept),
|
|
138
|
+
"suppressed": tuple(suppressed),
|
|
139
|
+
"policy_notes": tuple(notes),
|
|
140
|
+
}
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _matching_ignore(
|
|
145
|
+
active: Sequence[Ignore], patterns: Sequence[GitIgnoreSpec], finding: Finding
|
|
146
|
+
) -> int | None:
|
|
147
|
+
return next(
|
|
148
|
+
(
|
|
149
|
+
index
|
|
150
|
+
for index, entry in enumerate(active)
|
|
151
|
+
if entry.rule == finding.rule_id and patterns[index].match_file(finding.location.path)
|
|
152
|
+
),
|
|
153
|
+
None,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _approved(allow: Allow, artifacts: Sequence[Artifact]) -> tuple[dict[str, str], list[str]]:
|
|
158
|
+
"""Artifact ids whose content matches an allow entry, with the reason; notes for the rest."""
|
|
159
|
+
by_key = {(a.kind, a.source.path, a.name): a for a in artifacts}
|
|
160
|
+
skills = {a.source.path: a for a in artifacts if a.kind == "skill"}
|
|
161
|
+
approved: dict[str, str] = {}
|
|
162
|
+
notes: list[str] = []
|
|
163
|
+
entries: list[tuple[str, Artifact | None, str]] = [
|
|
164
|
+
(f'MCP server "{e.name}" in {e.path}', by_key.get(("mcp_server", e.path, e.name)), e.sha256)
|
|
165
|
+
for e in allow.mcp_servers
|
|
166
|
+
]
|
|
167
|
+
entries += [(f'skill "{e.path}"', skills.get(e.path), e.sha256) for e in allow.skills]
|
|
168
|
+
for label, artifact, sha256 in entries:
|
|
169
|
+
if artifact is None:
|
|
170
|
+
notes.append(f"allowed {label} is not in the repository; remove it")
|
|
171
|
+
elif artifact.content_hash != sha256:
|
|
172
|
+
notes.append(
|
|
173
|
+
f"allowed {label} changed since it was approved; its findings are reported "
|
|
174
|
+
f"until the policy approves sha256 {artifact.content_hash}"
|
|
175
|
+
)
|
|
176
|
+
else:
|
|
177
|
+
approved[artifact.id] = f"approved in {POLICY_FILENAME} at sha256 {sha256[:12]}"
|
|
178
|
+
return approved, notes
|
agentbom/py.typed
ADDED
|
File without changes
|