stacktrace-cli 0.21.0__py3-none-any.whl → 0.23.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.
- stacktrace/__init__.py +1 -1
- stacktrace/agentspec/__init__.py +5 -0
- stacktrace/agentspec/author.py +409 -0
- stacktrace/agentspec/caller.py +100 -0
- stacktrace/agentspec/checks.py +621 -0
- stacktrace/agentspec/effects/__init__.py +290 -0
- stacktrace/agentspec/effects/context.py +46 -0
- stacktrace/agentspec/effects/model.py +70 -0
- stacktrace/agentspec/engine.py +566 -0
- stacktrace/agentspec/fleet.py +138 -0
- stacktrace/agentspec/grants.py +133 -0
- stacktrace/agentspec/intent.py +79 -0
- stacktrace/agentspec/judge.py +116 -0
- stacktrace/agentspec/ledger.py +385 -0
- stacktrace/agentspec/model.py +88 -0
- stacktrace/agentspec/packs/__init__.py +62 -0
- stacktrace/agentspec/packs/_args.py +50 -0
- stacktrace/agentspec/packs/clouds.py +420 -0
- stacktrace/agentspec/packs/iac.py +132 -0
- stacktrace/agentspec/packs/kubernetes.py +363 -0
- stacktrace/agentspec/packs/sql.py +126 -0
- stacktrace/agentspec/policies/deploys.yaml +109 -0
- stacktrace/agentspec/policies/infra.yaml +109 -0
- stacktrace/agentspec/redact.py +397 -0
- stacktrace/agentspec/rule.py +292 -0
- stacktrace/agentspec/serve.py +293 -0
- stacktrace/agentspec/trace.py +187 -0
- stacktrace/agentspec/triggers.py +275 -0
- stacktrace/cli.py +2 -0
- stacktrace/correlate/observed.py +6 -0
- stacktrace/daemon/config.py +19 -0
- stacktrace/daemon/gateway.py +18 -2
- stacktrace/daemon/inline_hook.py +26 -14
- stacktrace/daemon/policy_engine.py +470 -0
- stacktrace/daemon/policy_inputs.py +13 -11
- stacktrace/daemon/policy_result.py +4 -0
- stacktrace/daemon/policy_runtime.py +190 -17
- stacktrace/daemon/presentation.py +78 -8
- stacktrace/daemon/protocol.py +22 -5
- stacktrace/daemon/runtime.py +48 -0
- stacktrace/daemon/server.py +76 -4
- stacktrace/daemon/socket_path.py +36 -0
- stacktrace/daemon/store.py +9 -2
- stacktrace/daemon/usage.py +16 -3
- stacktrace/detector/deterministic.py +80 -6
- stacktrace/detector/inline.py +29 -5
- stacktrace/detector/personal_data.py +45 -10
- stacktrace/detector/rules.py +43 -25
- stacktrace/finding_contract.py +1 -0
- stacktrace/gateway/agentspec.py +177 -0
- stacktrace/gateway/analyzer.py +52 -5
- stacktrace/gateway/check.py +4 -0
- stacktrace/gateway/cli.py +8 -1
- stacktrace/gateway/service.py +12 -3
- stacktrace/hooks/claude.py +58 -4
- stacktrace/hooks/codex.py +105 -27
- stacktrace/hooks/cursor.py +81 -8
- stacktrace/hydrant_cli.py +537 -0
- stacktrace/monitor/render.py +1 -0
- stacktrace/monitor/site/app.js +1 -0
- stacktrace/remote/cli.py +2 -1
- stacktrace/remote/sync.py +17 -1
- stacktrace/sessions/access.py +17 -0
- stacktrace/sessions/outcome.py +35 -4
- stacktrace/telemetry/events.py +3 -0
- {stacktrace_cli-0.21.0.dist-info → stacktrace_cli-0.23.0.dist-info}/METADATA +4 -4
- {stacktrace_cli-0.21.0.dist-info → stacktrace_cli-0.23.0.dist-info}/RECORD +69 -39
- {stacktrace_cli-0.21.0.dist-info → stacktrace_cli-0.23.0.dist-info}/WHEEL +0 -0
- {stacktrace_cli-0.21.0.dist-info → stacktrace_cli-0.23.0.dist-info}/entry_points.txt +0 -0
stacktrace/__init__.py
CHANGED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""A person's words as Hydrant rules: write them, check them, read them back.
|
|
2
|
+
|
|
3
|
+
`translate` asks a model to turn what someone said ("don't let it push to
|
|
4
|
+
main without asking me") into AgentSpec rules, then loads the result with the
|
|
5
|
+
same validator the daemon uses, and asks again with the error when it doesn't
|
|
6
|
+
load. `readback` says what a rule will do in plain words, for the person who
|
|
7
|
+
said it. `merge` and `save` maintain the custom rules file the daemon reloads
|
|
8
|
+
on every change (`STACKTRACE_POLICY_RULES`).
|
|
9
|
+
|
|
10
|
+
The model is whatever is at hand on the machine: `claude -p` by default, or an
|
|
11
|
+
OpenAI-compatible endpoint when `STACKTRACE_HYDRANT_LLM_URL` names one.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import shutil
|
|
19
|
+
import subprocess
|
|
20
|
+
import tempfile
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
import httpx
|
|
25
|
+
import yaml
|
|
26
|
+
|
|
27
|
+
from stacktrace.agentspec.checks import CODE_CHECKS
|
|
28
|
+
from stacktrace.agentspec.fleet import call_rules
|
|
29
|
+
from stacktrace.agentspec.rule import ACTIONS, TRIGGERS, VIEWS, Policy, PolicyError, load_policy
|
|
30
|
+
|
|
31
|
+
ENV_URL = "STACKTRACE_HYDRANT_LLM_URL"
|
|
32
|
+
ENV_KEY = "STACKTRACE_HYDRANT_LLM_KEY"
|
|
33
|
+
ENV_MODEL = "STACKTRACE_HYDRANT_MODEL"
|
|
34
|
+
|
|
35
|
+
#: What each trigger means, for the model and for the readback.
|
|
36
|
+
TRIGGER_WORDS: Mapping[str, str] = {
|
|
37
|
+
"any_call": "makes any tool call",
|
|
38
|
+
"reads_secret": "reads a private key, token, password, .env file or cloud credentials file",
|
|
39
|
+
"writes_file": "creates, edits, moves or deletes a file",
|
|
40
|
+
"weakens_test": "skips, deletes or loosens a test, or makes CI ignore a failure",
|
|
41
|
+
"network_send": "sends data off the machine (upload, post, push)",
|
|
42
|
+
"publishes": "deploys a site, app or service, publishes a package, or uploads files publicly",
|
|
43
|
+
"deletes": "deletes files, directories, records or resources",
|
|
44
|
+
"installs_package": "installs a package or adds one to a dependency manifest",
|
|
45
|
+
"changes_agent_config": "edits the agent's settings, hooks, MCP config or instruction files",
|
|
46
|
+
"changes_ci_config": "edits CI configuration",
|
|
47
|
+
"vcs_push": "pushes to a git remote",
|
|
48
|
+
"sends_message": "sends a message to a person (email, chat, a comment)",
|
|
49
|
+
"changes_infra": "changes cloud or cluster infrastructure",
|
|
50
|
+
"ends_turn": "finishes its turn",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
VIEW_WORDS: Mapping[str, str] = {
|
|
54
|
+
"call": "the call itself",
|
|
55
|
+
"effects": "what the call does to known systems",
|
|
56
|
+
"files": "the files near the work, and what is in the ones the call names",
|
|
57
|
+
"project_config": "the project's config files",
|
|
58
|
+
"person_said": "what you said",
|
|
59
|
+
"person_latest": "your latest instruction",
|
|
60
|
+
"agent_said": "what the agent said",
|
|
61
|
+
"recent_steps": "the agent's recent steps",
|
|
62
|
+
"destinations": "where the call sends things",
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
ACTION_WORDS: Mapping[str, str] = {
|
|
66
|
+
"block": "blocks the call and tells the agent why",
|
|
67
|
+
"ask_person": "holds the call until you say yes",
|
|
68
|
+
"record": "lets it run and records it",
|
|
69
|
+
"allow": "lets it run",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
_EXAMPLES = """\
|
|
73
|
+
# "Don't let it fake a green CI run. Fix the cause, don't skip the test."
|
|
74
|
+
rules:
|
|
75
|
+
- id: ci-fix-not-skip
|
|
76
|
+
says: Don't let agents fake a green CI run. Fix the cause; never skip, delete or loosen the test.
|
|
77
|
+
trigger: weakens_test
|
|
78
|
+
checks:
|
|
79
|
+
weakens:
|
|
80
|
+
decision: "`call` skips, deletes or loosens a test or assertion, or makes CI ignore a failure."
|
|
81
|
+
over: [call, recent_steps]
|
|
82
|
+
criteria:
|
|
83
|
+
"true": It adds a skip or xfail, deletes or comments out a test, loosens an expected value, or changes CI so a failing test no longer fails the run.
|
|
84
|
+
"false": It fixes the code under test, adds or strengthens a test, only runs or reads tests, or doesn't touch tests or CI.
|
|
85
|
+
fires: weakens
|
|
86
|
+
enforce:
|
|
87
|
+
action: block
|
|
88
|
+
steer: This skips or loosens a test to get CI green. Find why the test fails and fix the code. If the test itself is wrong, stop and tell the person.
|
|
89
|
+
|
|
90
|
+
# "Public production deploys need a login in front of them, or my explicit yes."
|
|
91
|
+
rules:
|
|
92
|
+
- id: public-production-needs-login
|
|
93
|
+
says: Public production deploys need a login in front of them, or my explicit yes.
|
|
94
|
+
trigger: publishes
|
|
95
|
+
checks:
|
|
96
|
+
production:
|
|
97
|
+
decision: "`call` deploys to production: the live site or default production target."
|
|
98
|
+
over: [call, recent_steps]
|
|
99
|
+
criteria:
|
|
100
|
+
"true": It deploys to production or the live site. A --prod flag or a production branch counts.
|
|
101
|
+
"false": It deploys a preview, branch, draft or staging build, or deploys nothing.
|
|
102
|
+
public:
|
|
103
|
+
decision: What `call` publishes is reachable by anyone on the internet without a login.
|
|
104
|
+
over: [call, project_config, recent_steps]
|
|
105
|
+
asked:
|
|
106
|
+
decision: The person asked for this to go live in production for the public.
|
|
107
|
+
over: [person_said]
|
|
108
|
+
fires: production and public and not asked
|
|
109
|
+
enforce:
|
|
110
|
+
action: ask_person
|
|
111
|
+
steer: This is a public production deploy with no login in front of it. Put a login in front of it first, or ask the person to confirm it should be public.
|
|
112
|
+
|
|
113
|
+
# "Never send our keys anywhere."
|
|
114
|
+
rules:
|
|
115
|
+
- id: keys-stay-here
|
|
116
|
+
says: Never send our keys anywhere.
|
|
117
|
+
trigger: any_call
|
|
118
|
+
checks:
|
|
119
|
+
hit: {code: builtin, rule: stacktrace-credential-egress}
|
|
120
|
+
fires: hit
|
|
121
|
+
enforce:
|
|
122
|
+
action: block
|
|
123
|
+
steer: This would send a credential off the machine. Remove it from the call.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _instructions() -> str:
|
|
128
|
+
builtins = ", ".join(call_rules())
|
|
129
|
+
triggers = "\n".join(f" {t}: the agent {TRIGGER_WORDS[t]}" for t in TRIGGERS)
|
|
130
|
+
return f"""You turn what a person says they are worried about into Hydrant policy rules.
|
|
131
|
+
Hydrant checks every tool call a coding agent (Claude Code) makes before it runs.
|
|
132
|
+
|
|
133
|
+
Reply with one YAML document only, inside a ```yaml block, with a top-level `rules:` list.
|
|
134
|
+
No prose outside the block.
|
|
135
|
+
|
|
136
|
+
A rule:
|
|
137
|
+
id: short kebab-case name. Never starts with "stacktrace-".
|
|
138
|
+
says: the person's own words, lightly cleaned. Keep their meaning exactly.
|
|
139
|
+
trigger: the kind of action the rule is about. One of:
|
|
140
|
+
{triggers}
|
|
141
|
+
Pick the narrowest trigger that covers the worry. `any_call` makes the judge read
|
|
142
|
+
every call, so use it only with a `code:` check or when nothing narrower fits.
|
|
143
|
+
checks: named facts that decide the rule. Each is exactly one of:
|
|
144
|
+
decision: a yes/no question about the pending call, which a judge model answers
|
|
145
|
+
with a probability. Refer to the call as `call` in backticks. One fact per question.
|
|
146
|
+
over: what the judge may see, a list from: {", ".join(VIEWS)}.
|
|
147
|
+
Use [person_said] for "did the person ask for this".
|
|
148
|
+
criteria: {{"true": ..., "false": ...}} saying what counts as yes and no. Always
|
|
149
|
+
give it. In "false", name the harmless look-alikes the judge must let through:
|
|
150
|
+
previews, drafts, dry runs, plans, local or staging targets, reading or
|
|
151
|
+
listing, and tools whose default is a preview unless a flag says otherwise.
|
|
152
|
+
code: an exact check. Use only these:
|
|
153
|
+
builtin with rule: one of {builtins}
|
|
154
|
+
(use for literal credentials, personal data, credential files, deletes
|
|
155
|
+
outside the project, agent config tampering, persistence, unknown installs)
|
|
156
|
+
contains with source: secrets, target: published_files | payload | command
|
|
157
|
+
location with where: outside (paths outside the project folder)
|
|
158
|
+
last_result with is: failed | passed | none (the last test run)
|
|
159
|
+
tokens with measure: session | context, at_least: <tokens>
|
|
160
|
+
(session: every token the session used so far; context: the size of
|
|
161
|
+
its latest context. For token budgets: "after 2M tokens" is
|
|
162
|
+
{{code: tokens, measure: session, at_least: 2000000}})
|
|
163
|
+
fires: how checks combine, with and / or / not over check names. Default: all of them.
|
|
164
|
+
enforce:
|
|
165
|
+
action: one of {", ".join(ACTIONS)}. Use block for "never". Use ask_person when the
|
|
166
|
+
action is sometimes fine ("without asking me", "unless I say so").
|
|
167
|
+
steer: what the agent is told instead: what to do next, in one or two sentences.
|
|
168
|
+
|
|
169
|
+
How to write good rules:
|
|
170
|
+
- "Unless I asked" or "without my OK" becomes an `asked` decision over [person_said],
|
|
171
|
+
and `fires: <the fact> and not asked`.
|
|
172
|
+
- Split a compound worry into separate facts rather than one long question.
|
|
173
|
+
- Never name a specific tool, CLI, host or file unless the person did. Describe what
|
|
174
|
+
the call does.
|
|
175
|
+
- One rule per distinct worry. Usually one or two rules in total.
|
|
176
|
+
- An "asked" check's criteria: true only when the person's own words ask for this
|
|
177
|
+
specific action and target; a general task ("fix it", "ship it") is not enough
|
|
178
|
+
unless it names the target.
|
|
179
|
+
- The judge only knows what the rule tells it. When a fact about tools decides the
|
|
180
|
+
answer, write it into the criteria. Facts worth stating when they apply:
|
|
181
|
+
Vercel, Netlify and Cloudflare Pages CLIs deploy a preview unless given --prod (or
|
|
182
|
+
--production / a production branch); `terraform plan`, `kubectl diff`, `--dry-run`
|
|
183
|
+
and `helm template` change nothing; `git push` without a branch pushes the current
|
|
184
|
+
branch; a SELECT reads, an UPDATE/DELETE/ALTER/DROP changes data.
|
|
185
|
+
- Use only fields named here.
|
|
186
|
+
|
|
187
|
+
Examples:
|
|
188
|
+
{_EXAMPLES}"""
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _extract_yaml(text: str) -> str:
|
|
192
|
+
m = re.search(r"```(?:yaml|yml)?\s*\n(.*?)```", text, re.DOTALL)
|
|
193
|
+
return (m.group(1) if m else text).strip()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _map(value: object) -> dict[str, object]:
|
|
197
|
+
"""`value` as a string-keyed mapping, or empty."""
|
|
198
|
+
if not isinstance(value, dict):
|
|
199
|
+
return {}
|
|
200
|
+
return {str(k): v for k, v in value.items()} # pyright: ignore[reportUnknownVariableType]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _list(value: object) -> list[object]:
|
|
204
|
+
return list(value) if isinstance(value, list) else [] # pyright: ignore[reportUnknownArgumentType]
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _rules(doc: Mapping[str, object]) -> list[dict[str, object]]:
|
|
208
|
+
return [_map(r) for r in _list(doc.get("rules"))]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def parse(text: str) -> dict[str, object]:
|
|
212
|
+
"""A model's reply, or a file, as a policy document with a `rules` list."""
|
|
213
|
+
doc: dict[str, object]
|
|
214
|
+
try:
|
|
215
|
+
loaded: object = yaml.safe_load(_extract_yaml(text))
|
|
216
|
+
except yaml.YAMLError as error:
|
|
217
|
+
raise PolicyError(f"not YAML: {error}") from error
|
|
218
|
+
if isinstance(loaded, list):
|
|
219
|
+
loaded = {"rules": loaded}
|
|
220
|
+
doc = _map(loaded)
|
|
221
|
+
if "rules" not in doc and "id" in doc:
|
|
222
|
+
doc = {"rules": [dict(doc)]}
|
|
223
|
+
if not isinstance(doc.get("rules"), list):
|
|
224
|
+
raise PolicyError("a policy is a mapping with a rules list")
|
|
225
|
+
return doc
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def check(doc: Mapping[str, object]) -> Policy:
|
|
229
|
+
"""Load `doc` as the daemon would, plus the checks it only finds at run time."""
|
|
230
|
+
allowed = set(call_rules())
|
|
231
|
+
rules = _rules(doc)
|
|
232
|
+
for rule in rules:
|
|
233
|
+
rid = str(rule.get("id", ""))
|
|
234
|
+
if rid.startswith("stacktrace-"):
|
|
235
|
+
raise PolicyError(f"{rid}: ids starting with stacktrace- belong to Fleet")
|
|
236
|
+
for name, spec in _map(rule.get("checks")).items():
|
|
237
|
+
spec = _map(spec)
|
|
238
|
+
if spec.get("code") == "builtin" and spec.get("rule") not in allowed:
|
|
239
|
+
known = ", ".join(sorted(allowed))
|
|
240
|
+
raise PolicyError(
|
|
241
|
+
f"{rid}.{name}: builtin rule {spec.get('rule')!r} is not one of {known}"
|
|
242
|
+
)
|
|
243
|
+
if not rules:
|
|
244
|
+
return Policy(rules=())
|
|
245
|
+
return load_policy(doc, frozenset(CODE_CHECKS))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _ask_model(system: str, user: str) -> str:
|
|
249
|
+
url = os.environ.get(ENV_URL, "").strip()
|
|
250
|
+
model = os.environ.get(ENV_MODEL, "").strip()
|
|
251
|
+
if url:
|
|
252
|
+
key = os.environ.get(ENV_KEY, "")
|
|
253
|
+
response = httpx.post(
|
|
254
|
+
url.rstrip("/") + "/chat/completions",
|
|
255
|
+
headers={"Authorization": f"Bearer {key}"} if key else {},
|
|
256
|
+
json={
|
|
257
|
+
"model": model or "claude-sonnet-5-5",
|
|
258
|
+
"messages": [
|
|
259
|
+
{"role": "system", "content": system},
|
|
260
|
+
{"role": "user", "content": user},
|
|
261
|
+
],
|
|
262
|
+
"temperature": 0,
|
|
263
|
+
},
|
|
264
|
+
timeout=120,
|
|
265
|
+
)
|
|
266
|
+
response.raise_for_status()
|
|
267
|
+
return str(response.json()["choices"][0]["message"]["content"])
|
|
268
|
+
claude = shutil.which("claude")
|
|
269
|
+
if claude is None:
|
|
270
|
+
raise PolicyError(f"no model: install Claude Code (claude) or set {ENV_URL}")
|
|
271
|
+
# The person's own Claude Code and login. No tools, its own system prompt,
|
|
272
|
+
# run from an empty folder so no project's hooks or CLAUDE.md load, and
|
|
273
|
+
# without the variables a surrounding Claude Code session sets.
|
|
274
|
+
command = [claude, "-p", "--output-format", "text", "--system-prompt", system, "--tools", ""]
|
|
275
|
+
command += ["--no-session-persistence"]
|
|
276
|
+
if model:
|
|
277
|
+
command += ["--model", model]
|
|
278
|
+
env = {k: v for k, v in os.environ.items() if not _session_variable(k)}
|
|
279
|
+
with tempfile.TemporaryDirectory() as cwd:
|
|
280
|
+
done = subprocess.run(
|
|
281
|
+
command,
|
|
282
|
+
input=user,
|
|
283
|
+
capture_output=True,
|
|
284
|
+
text=True,
|
|
285
|
+
timeout=180,
|
|
286
|
+
check=False,
|
|
287
|
+
cwd=cwd,
|
|
288
|
+
env=env,
|
|
289
|
+
)
|
|
290
|
+
if done.returncode != 0:
|
|
291
|
+
said = (done.stderr.strip() or done.stdout.strip())[:300]
|
|
292
|
+
raise PolicyError(f"claude -p failed ({done.returncode}): {said}")
|
|
293
|
+
return done.stdout
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _session_variable(name: str) -> bool:
|
|
297
|
+
"""Set by a running Claude Code session; a child `claude -p` must not inherit it."""
|
|
298
|
+
return name in {"CLAUDECODE", "CLAUDE_PID", "CLAUDE_SESSION_INGRESS_TOKEN_FILE"} or (
|
|
299
|
+
name.startswith(("CLAUDE_CODE_", "CCR_"))
|
|
300
|
+
and not name.startswith(("CLAUDE_CODE_USE_", "CLAUDE_CODE_OAUTH"))
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def translate(
|
|
305
|
+
words: str, existing: Mapping[str, object] | None = None, tries: int = 3
|
|
306
|
+
) -> dict[str, object]:
|
|
307
|
+
"""Rules for `words` that load next to `existing`. Raises `PolicyError`."""
|
|
308
|
+
system = _instructions()
|
|
309
|
+
user = f"What the person said, verbatim:\n\n{words.strip()}\n"
|
|
310
|
+
ids = [r.get("id") for r in _rules(existing or {})]
|
|
311
|
+
if ids:
|
|
312
|
+
user += f"\nRules that already exist (don't repeat them; use new ids): {ids}\n"
|
|
313
|
+
error: str | None = None
|
|
314
|
+
for _ in range(tries):
|
|
315
|
+
prompt = (
|
|
316
|
+
user if error is None else f"{user}\nYour last answer did not load: {error}\nFix it."
|
|
317
|
+
)
|
|
318
|
+
reply = _ask_model(system, prompt)
|
|
319
|
+
try:
|
|
320
|
+
doc = parse(reply)
|
|
321
|
+
check(merge(existing or {}, doc))
|
|
322
|
+
except PolicyError as failed:
|
|
323
|
+
error = str(failed)
|
|
324
|
+
continue
|
|
325
|
+
return doc
|
|
326
|
+
raise PolicyError(f"the model's rules did not load after {tries} tries: {error}")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def merge(base: Mapping[str, object], add: Mapping[str, object]) -> dict[str, object]:
|
|
330
|
+
"""`base` with `add`'s rules appended; a rule with the same id is replaced."""
|
|
331
|
+
new = _rules(add)
|
|
332
|
+
ids = {r.get("id") for r in new}
|
|
333
|
+
old = [r for r in _rules(base) if r.get("id") not in ids]
|
|
334
|
+
out: dict[str, object] = {}
|
|
335
|
+
packs = list(dict.fromkeys([*_list(base.get("packs")), *_list(add.get("packs"))]))
|
|
336
|
+
if packs:
|
|
337
|
+
out["packs"] = packs
|
|
338
|
+
for key in ("sources", "settings"):
|
|
339
|
+
merged = {**_map(base.get(key)), **_map(add.get(key))}
|
|
340
|
+
if merged:
|
|
341
|
+
out[key] = merged
|
|
342
|
+
out["rules"] = old + new
|
|
343
|
+
return out
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def load_file(path: Path) -> dict[str, object]:
|
|
347
|
+
if not path.exists():
|
|
348
|
+
return {"rules": []}
|
|
349
|
+
return parse(path.read_text(encoding="utf-8"))
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def save(path: Path, doc: Mapping[str, object]) -> None:
|
|
353
|
+
"""Write the rules file in one step, so the daemon never reads half of it."""
|
|
354
|
+
check(doc)
|
|
355
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
356
|
+
text = yaml.safe_dump(dict(doc), sort_keys=False, allow_unicode=True, width=100)
|
|
357
|
+
with tempfile.NamedTemporaryFile("w", dir=path.parent, delete=False, encoding="utf-8") as f:
|
|
358
|
+
f.write(text)
|
|
359
|
+
tmp = Path(f.name)
|
|
360
|
+
os.replace(tmp, path)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def readback(doc: Mapping[str, object]) -> list[str]:
|
|
364
|
+
"""Each rule in plain words, as lines."""
|
|
365
|
+
lines: list[str] = []
|
|
366
|
+
for rule in _rules(doc):
|
|
367
|
+
enforce = _map(rule.get("enforce"))
|
|
368
|
+
checks = _map(rule.get("checks"))
|
|
369
|
+
trigger = str(rule.get("trigger", ""))
|
|
370
|
+
lines.append(f"Rule {rule.get('id')}: \u201c{str(rule.get('says', '')).strip()}\u201d")
|
|
371
|
+
lines.append(f" When the agent {TRIGGER_WORDS.get(trigger, trigger)},")
|
|
372
|
+
for name, raw in checks.items():
|
|
373
|
+
spec = _map(raw)
|
|
374
|
+
if "decision" in spec:
|
|
375
|
+
question = " ".join(str(spec["decision"]).split())
|
|
376
|
+
lines.append(f" {name}: the judge answers \u201c{question}\u201d")
|
|
377
|
+
seen = ", ".join(VIEW_WORDS.get(str(v), str(v)) for v in _list(spec.get("over")))
|
|
378
|
+
if seen:
|
|
379
|
+
lines.append(f" looking at {seen}")
|
|
380
|
+
else:
|
|
381
|
+
params = ", ".join(f"{k}={v}" for k, v in spec.items() if k != "code")
|
|
382
|
+
lines.append(f" {name}: exact check {spec.get('code')} ({params})")
|
|
383
|
+
if checks:
|
|
384
|
+
lines.append(f" It fires when: {rule.get('fires') or ' and '.join(checks)}")
|
|
385
|
+
action = str(enforce.get("action", ""))
|
|
386
|
+
lines.append(f" Then Hydrant {ACTION_WORDS.get(action, action)}.")
|
|
387
|
+
steer = " ".join(str(enforce.get("steer", "")).split())
|
|
388
|
+
if steer:
|
|
389
|
+
lines.append(f" The agent is told: \u201c{steer}\u201d")
|
|
390
|
+
lines.append("")
|
|
391
|
+
return lines
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def dump(doc: Mapping[str, object]) -> str:
|
|
395
|
+
return yaml.safe_dump(dict(doc), sort_keys=False, allow_unicode=True, width=100)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
__all__ = [
|
|
399
|
+
"ACTION_WORDS",
|
|
400
|
+
"TRIGGER_WORDS",
|
|
401
|
+
"check",
|
|
402
|
+
"dump",
|
|
403
|
+
"load_file",
|
|
404
|
+
"merge",
|
|
405
|
+
"parse",
|
|
406
|
+
"readback",
|
|
407
|
+
"save",
|
|
408
|
+
"translate",
|
|
409
|
+
]
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Whose access the engine reads files with (ADR-0218).
|
|
2
|
+
|
|
3
|
+
On the daemon's shared hook socket the caller is another user, and the daemon
|
|
4
|
+
can read more than they can: its own policy and log, and in the arena any file.
|
|
5
|
+
The engine reads the files a call names (manifests, SQL, `.env`, project
|
|
6
|
+
config), so a caller could name a file of the daemon's and have it read. While
|
|
7
|
+
a shared call is decided, the caller's uid is held here, and every engine read
|
|
8
|
+
asks `may_read` or `may_list` first. With no caller (the main socket, a laptop),
|
|
9
|
+
nothing changes.
|
|
10
|
+
|
|
11
|
+
The rule depends on nothing about the caller but its uid, because each other
|
|
12
|
+
field it trusted had a gap: groups rebuilt from NSS, group bits that are an ACL
|
|
13
|
+
mask, uid 0 without the capabilities that bypass DAC. Every component on the
|
|
14
|
+
resolved path must be either the caller's own with owner bits that allow it, or
|
|
15
|
+
open to anyone: no component on the path carries an access ACL and the other
|
|
16
|
+
bits allow it. A group-only read is refused, and so is anything an ACL decides.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import errno
|
|
22
|
+
import os
|
|
23
|
+
import stat
|
|
24
|
+
from collections.abc import Iterator
|
|
25
|
+
from contextlib import contextmanager
|
|
26
|
+
from contextvars import ContextVar
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Caller:
|
|
33
|
+
uid: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_CALLER: ContextVar[Caller | None] = ContextVar("stacktrace_agentspec_caller", default=None)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@contextmanager
|
|
40
|
+
def acting_for(caller: Caller) -> Iterator[None]:
|
|
41
|
+
token = _CALLER.set(caller)
|
|
42
|
+
try:
|
|
43
|
+
yield
|
|
44
|
+
finally:
|
|
45
|
+
_CALLER.reset(token)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
_ACL = "system.posix_acl_access"
|
|
49
|
+
#: The errors that mean "no access ACL here", as against "can't tell".
|
|
50
|
+
_NO_ACL = frozenset({errno.ENODATA, errno.ENOTSUP, errno.EOPNOTSUPP})
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _has_acl(path: Path) -> bool:
|
|
54
|
+
"""Whether `path` carries an extended access ACL. A read that fails for any
|
|
55
|
+
other reason, or a platform without xattrs, counts as one."""
|
|
56
|
+
getxattr = getattr(os, "getxattr", None)
|
|
57
|
+
if getxattr is None:
|
|
58
|
+
return True
|
|
59
|
+
try:
|
|
60
|
+
getxattr(path, _ACL, follow_symlinks=False)
|
|
61
|
+
except OSError as error:
|
|
62
|
+
return error.errno not in _NO_ACL
|
|
63
|
+
return True
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _bits(st: os.stat_result, shift: int, want: int) -> bool:
|
|
67
|
+
return (stat.S_IMODE(st.st_mode) >> shift) & want == want
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _may(path: Path, want: int) -> bool:
|
|
71
|
+
"""`want` is 4 (read) or 5 (read and search) on `path`, with search (1) on
|
|
72
|
+
every directory above it. Each component must be the caller's own with owner
|
|
73
|
+
bits that allow it, or open to anyone with no access ACL anywhere on the
|
|
74
|
+
path."""
|
|
75
|
+
caller = _CALLER.get()
|
|
76
|
+
if caller is None:
|
|
77
|
+
return True
|
|
78
|
+
try:
|
|
79
|
+
real = path.resolve(strict=True)
|
|
80
|
+
components = [*reversed(real.parents), real]
|
|
81
|
+
open_path = not any(_has_acl(c) for c in components)
|
|
82
|
+
for c in components:
|
|
83
|
+
need = want if c == real else 1
|
|
84
|
+
st = c.stat()
|
|
85
|
+
own = st.st_uid == caller.uid and _bits(st, 6, need)
|
|
86
|
+
if not (own or (open_path and _bits(st, 0, need))):
|
|
87
|
+
return False
|
|
88
|
+
return True
|
|
89
|
+
except (OSError, RuntimeError):
|
|
90
|
+
return False
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def may_read(path: Path) -> bool:
|
|
94
|
+
"""Whether the caller, if there is one, could read `path`."""
|
|
95
|
+
return _may(path, 4)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def may_list(directory: Path) -> bool:
|
|
99
|
+
"""Whether the caller, if there is one, could list `directory`."""
|
|
100
|
+
return _may(directory, 5)
|