secondkey 0.2.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.
@@ -0,0 +1,85 @@
1
+ # SecondKey policy
2
+ #
3
+ # Every agent action gets a dotted category such as sql.drop, git.force_push
4
+ # or secrets.read (run `secondkey check "<command>"` to see one). Rules are
5
+ # checked top to bottom and the first match wins. Globs are allowed.
6
+ #
7
+ # action: allow run immediately
8
+ # ask hold until a human approves (`secondkey approve <id>`)
9
+ # deny never run
10
+ # snapshot: take a restore point right before the command runs
11
+ # (default true for ask, false for allow)
12
+ #
13
+ # A command made of several parts (a && b; c | d) gets the strictest decision
14
+ # of all its parts.
15
+ version: 1
16
+
17
+ rules:
18
+ # Never: these leak data or can't be undone.
19
+ - match: ["secrets.*", "shell.pipe_to_shell", "fs.delete_critical", "sql.drop_database", "system.destructive"]
20
+ action: deny
21
+ reason: "Blocked by policy: this can leak secrets or cause damage that can't be undone."
22
+
23
+ # Destructive and undoable: snapshot, then wait for the second key.
24
+ - match: ["sql.drop", "sql.truncate", "sql.delete", "sql.update", "sql.alter", "sql.drop_other", "sql.other"]
25
+ action: ask
26
+ # Migration tools that drop or roll back schema (alembic downgrade, prisma migrate reset, rails db:drop ...).
27
+ # With a Postgres DATABASE_URL in the environment, the whole database is snapshotted.
28
+ - match: ["db.reset", "db.migrate_down"]
29
+ action: ask
30
+ - match: ["fs.delete_recursive", "git.force_push", "git.delete_remote_branch", "git.reset_hard",
31
+ "git.clean", "git.branch_delete", "git.discard", "git.rewrite"]
32
+ action: ask
33
+ - match: ["tf.destroy", "tf.apply", "tf.state_write", "k8s.delete", "k8s.scale_to_zero"]
34
+ action: ask
35
+ - match: ["docker.delete", "cloud.delete"]
36
+ action: ask
37
+ # MCP tools whose names look destructive.
38
+ - match: ["mcp.*.*delete*", "mcp.*.*drop*", "mcp.*.*destroy*", "mcp.*.*remove*", "mcp.*.*truncate*",
39
+ "mcp.*.*purge*", "mcp.*.*wipe*", "mcp.*.*reset*", "mcp.*.*force*"]
40
+ action: ask
41
+
42
+ # Small and common: let it run, but keep a restore point.
43
+ - match: ["fs.delete"]
44
+ action: allow
45
+ snapshot: true
46
+
47
+ # Commands SecondKey can't read fully: ask rather than guess.
48
+ - match: ["shell.unparsed", "sql.interactive"]
49
+ action: ask
50
+ snapshot: false
51
+
52
+ # Anything not matched above.
53
+ default: allow
54
+
55
+ approval:
56
+ # Where the second key is turned:
57
+ # secondkey hold the command; approve with `secondkey approve <id>` (works when
58
+ # you're away, records who approved). Default.
59
+ # agent take the snapshot, then let the agent's own permission prompt
60
+ # (e.g. Claude Code's) ask you on the spot.
61
+ via: secondkey
62
+ # How long the hook waits for an approval before telling the agent the
63
+ # command is held. 0 = return immediately; the agent retries after you
64
+ # run `secondkey approve <id>`.
65
+ wait_seconds: 0
66
+ # How long an approval stays valid for the exact same command.
67
+ ttl_minutes: 15
68
+ # If a snapshot fails right before an approved command runs, block it.
69
+ require_snapshot: true
70
+
71
+ notify:
72
+ # Slack incoming webhook, e.g. ${SECONDKEY_SLACK_WEBHOOK}. Leave empty to disable.
73
+ slack_webhook: "${SECONDKEY_SLACK_WEBHOOK}"
74
+
75
+ snapshots:
76
+ # Delete restore points older than this (the newest one is always kept).
77
+ retention_days: 14
78
+ # Keep total snapshot storage under this; the oldest go first.
79
+ max_total_mb: 5120
80
+ # Skip file snapshots bigger than this (they'll be reported as not protected).
81
+ max_file_snapshot_mb: 500
82
+ # Postgres: dumps larger than this are refused (use strategy: neon for big databases).
83
+ postgres_max_dump_mb: 2048
84
+ # Postgres snapshot method: dump (pg_dump) or neon (instant branch via neonctl).
85
+ postgres_strategy: dump
secondkey/gate.py ADDED
@@ -0,0 +1,192 @@
1
+ """The decision flow shared by every integration.
2
+
3
+ classify → policy → deny
4
+ → allow (snapshot first if the rule says so)
5
+ → ask → already approved for this exact call? snapshot, then run
6
+ → otherwise create a held request, notify, optionally wait
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import time
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from . import audit, notify
19
+ from .classify import Action, classify_tool
20
+ from .policy import Decision, Policy, load_policy
21
+ from .snapshots import plan as plan_snapshots
22
+ from .snapshots import take_all
23
+ from .store import Request, Snapshot, Store
24
+ from .util import redact
25
+
26
+ VOLATILE_INPUT_KEYS = {"description", "timeout", "run_in_background", "dangerouslyDisableSandbox"}
27
+ QUIET_CATEGORIES = ("fs.read", "tool.", "shell.other", "git.read", "sql.read", "sql.write", "k8s.read", "tf.read",
28
+ "cloud.read", "secondkey.read")
29
+
30
+
31
+ @dataclass
32
+ class GateResult:
33
+ outcome: str # allow | deny | held | ask (native prompt)
34
+ message: str # text for the agent
35
+ decision: Decision
36
+ request: Request | None = None
37
+ snapshots: list[Snapshot] = field(default_factory=list)
38
+
39
+
40
+ def command_text(tool: str, tool_input: dict[str, Any]) -> str:
41
+ if tool == "SQL":
42
+ return f"[{tool_input.get('database', '')}] {tool_input.get('command', '')}"
43
+ if "command" in tool_input:
44
+ return str(tool_input["command"])
45
+ return f"{tool} " + json.dumps({k: v for k, v in tool_input.items() if k not in VOLATILE_INPUT_KEYS}, sort_keys=True)
46
+
47
+
48
+ def fingerprint(cwd: str, tool: str, tool_input: dict[str, Any]) -> str:
49
+ stable = {k: v for k, v in tool_input.items() if k not in VOLATILE_INPUT_KEYS}
50
+ if "command" in stable:
51
+ stable["command"] = str(stable["command"]).strip()
52
+ raw = json.dumps([os.path.realpath(cwd), tool, stable], sort_keys=True)
53
+ return hashlib.sha256(raw.encode()).hexdigest()
54
+
55
+
56
+ def _categories(decision: Decision) -> list[str]:
57
+ return [v.action.category for v in decision.verdicts]
58
+
59
+
60
+ def _quiet(decision: Decision) -> bool:
61
+ return all(c.startswith(QUIET_CATEGORIES) for c in _categories(decision))
62
+
63
+
64
+ def _undo_hint(snaps: list[Snapshot]) -> str:
65
+ if not snaps:
66
+ return ""
67
+ ids = " ".join(s.id for s in snaps)
68
+ return f" Restore point{'s' if len(snaps) > 1 else ''} saved: {ids} (undo with `secondkey undo {snaps[0].id}`)."
69
+
70
+
71
+ def evaluate(*, source: str, tool: str, tool_input: dict[str, Any], cwd: str, env: dict[str, str] | None = None,
72
+ policy: Policy | None = None, store: Store | None = None, wait: float | None = None,
73
+ native_ask: bool | None = None) -> GateResult:
74
+ policy = policy or load_policy(cwd)
75
+ store = store or Store()
76
+ actions = classify_tool(tool, tool_input, cwd, env)
77
+ decision = policy.evaluate(actions)
78
+ cmd = redact(command_text(tool, tool_input))
79
+ base = {"source": source, "tool": tool, "cwd": cwd, "command": cmd[:2000], "categories": _categories(decision)}
80
+
81
+ if decision.decision == "deny":
82
+ audit.record("deny", **base, reason=decision.reason)
83
+ return GateResult("deny", f"SecondKey blocked this: {decision.reason} "
84
+ "Do not retry it or look for another way to do the same thing; tell the user what you were trying to do.",
85
+ decision)
86
+
87
+ if decision.decision == "allow":
88
+ snaps: list[Snapshot] = []
89
+ if decision.snapshot_actions:
90
+ snaps, _skipped, failures = take_all(decision.snapshot_actions, None, policy, store)
91
+ for f in failures:
92
+ audit.record("snapshot_failed", **base, error=f)
93
+ if snaps or not _quiet(decision):
94
+ audit.record("allow", **base, snapshots=[s.id for s in snaps])
95
+ return GateResult("allow", _undo_hint(snaps).strip(), decision, snapshots=snaps)
96
+
97
+ # ask
98
+ if native_ask is None:
99
+ native_ask = str(policy.approval.get("via", "secondkey")) == "agent"
100
+ if native_ask:
101
+ return _native_ask(decision, policy, store, base)
102
+
103
+ fp = fingerprint(cwd, tool, tool_input)
104
+ grant = store.claim_grant(fp)
105
+ if grant:
106
+ return _run_approved(grant, decision, policy, store, base)
107
+
108
+ denied = store.recent_denial(fp, policy.ttl_seconds)
109
+ if denied:
110
+ return _denied_message(denied, decision)
111
+
112
+ protect = decision.snapshot_actions
113
+ req, created = store.create_request(source=source, cwd=cwd, tool=tool, command=cmd, fingerprint=fp,
114
+ actions=[a.to_dict() for a in protect], reason=decision.reason, impact=[])
115
+ if created:
116
+ impact, problems = plan_snapshots(protect, policy) if protect else ([], [])
117
+ store.db.execute("UPDATE requests SET impact=? WHERE id=?", (json.dumps(impact + [f"not protected: {p}" for p in problems]), req.id))
118
+ req = store.get_request(req.id) # type: ignore[assignment]
119
+ audit.record("hold", **base, request=req.id, reason=decision.reason, impact=req.impact)
120
+ hook = policy.slack_webhook()
121
+ if hook:
122
+ notify.slack(hook, notify.approval_text(req, impact, problems))
123
+
124
+ wait = policy.wait_seconds if wait is None else wait
125
+ deadline = time.time() + max(0.0, wait)
126
+ while wait > 0 and time.time() < deadline:
127
+ cur = store.get_request(req.id)
128
+ if cur and cur.status == "approved":
129
+ grant = store.claim_grant(fp)
130
+ if grant:
131
+ return _run_approved(grant, decision, policy, store, base)
132
+ if cur and cur.status == "denied":
133
+ return _denied_message(cur, decision)
134
+ time.sleep(1)
135
+
136
+ cur = store.get_request(req.id) or req
137
+ if cur.status == "denied":
138
+ return _denied_message(cur, decision)
139
+ return GateResult("held", _held_message(cur), decision, request=cur)
140
+
141
+
142
+ def _held_message(req: Request) -> str:
143
+ lines = [f"SecondKey held this command for human approval (request {req.id}).",
144
+ f"Why: {req.reason}."]
145
+ if req.impact:
146
+ lines.append("Impact: " + "; ".join(req.impact[:6]) + ".")
147
+ if not any(i.startswith("not protected") for i in req.impact) and req.actions:
148
+ lines.append("A restore point will be taken right before it runs, so it can be undone.")
149
+ lines.append(f"Do not try to work around this or run an equivalent command. Ask the user to review it and run "
150
+ f"`secondkey approve {req.id}` (or `secondkey deny {req.id}`), then retry exactly the same command.")
151
+ return " ".join(lines)
152
+
153
+
154
+ def _denied_message(req: Request, decision: Decision) -> GateResult:
155
+ by = f" by {req.decided_by}" if req.decided_by else ""
156
+ return GateResult("deny", f"SecondKey: a human denied this command{by} (request {req.id}). Do not retry it; "
157
+ "ask the user how they want to proceed.", decision, request=req)
158
+
159
+
160
+ def _run_approved(grant: Request, decision: Decision, policy: Policy, store: Store, base: dict[str, Any]) -> GateResult:
161
+ actions = [Action.from_dict(a) for a in grant.actions]
162
+ snaps: list[Snapshot] = []
163
+ if actions and not grant.skip_snapshot:
164
+ snaps, skipped, failures = take_all(actions, grant.id, policy, store)
165
+ if failures and policy.require_snapshot:
166
+ for s in snaps:
167
+ store.db.execute("UPDATE snapshots SET status='unused' WHERE id=?", (s.id,))
168
+ reason = "snapshot failed: " + "; ".join(failures)
169
+ store.db.execute("UPDATE requests SET status='pending', reason=?, updated=? WHERE id=?",
170
+ (reason, time.time(), grant.id))
171
+ audit.record("snapshot_failed", **base, request=grant.id, error=reason)
172
+ return GateResult("deny", f"SecondKey: approved, but the restore point could not be taken ({'; '.join(failures)}), "
173
+ f"so nothing was run. Tell the user. They can fix the problem and retry, or run "
174
+ f"`secondkey approve {grant.id} --no-snapshot` to run it without a restore point.",
175
+ decision, request=grant)
176
+ store.finish(grant.id, "executed", [s.id for s in snaps])
177
+ audit.record("run_approved", **base, request=grant.id, approved_by=grant.decided_by,
178
+ snapshots=[s.id for s in snaps], without_snapshot=grant.skip_snapshot)
179
+ msg = f"SecondKey: approved by {grant.decided_by or 'a human'} (request {grant.id}).{_undo_hint(snaps)}"
180
+ return GateResult("allow", msg, decision, request=grant, snapshots=snaps)
181
+
182
+
183
+ def _native_ask(decision: Decision, policy: Policy, store: Store, base: dict[str, Any]) -> GateResult:
184
+ """Snapshot now, then let the agent's own permission prompt ask the human."""
185
+ snaps, _skipped, failures = take_all(decision.snapshot_actions, None, policy, store)
186
+ audit.record("ask_agent_prompt", **base, reason=decision.reason, snapshots=[s.id for s in snaps], snapshot_failures=failures)
187
+ parts = [f"SecondKey: {decision.reason}."]
188
+ if snaps:
189
+ parts.append(f"Restore point taken ({', '.join(s.id for s in snaps)}); if you approve and regret it, run `secondkey undo {snaps[0].id}`.")
190
+ if failures:
191
+ parts.append("WARNING: no restore point: " + "; ".join(failures) + ".")
192
+ return GateResult("ask", " ".join(parts), decision, snapshots=snaps)
File without changes
@@ -0,0 +1,67 @@
1
+ """Claude Code PreToolUse hook.
2
+
3
+ Reads the hook JSON on stdin and answers with a permission decision:
4
+
5
+ * allow -> no output, so Claude Code's normal permission flow still applies
6
+ (SecondKey never widens what Claude Code would allow on its own)
7
+ * deny / held -> permissionDecision "deny" with the reason shown to Claude
8
+ * ask (approval.via: agent) -> permissionDecision "ask" so Claude Code prompts
9
+
10
+ If SecondKey itself fails, it answers "ask" instead of crashing: a crashing
11
+ hook is treated as a non-blocking error and the tool would simply run.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import sys
19
+ import traceback
20
+ from typing import IO
21
+
22
+ from .. import gate
23
+ from ..policy import PolicyError
24
+
25
+
26
+ def _emit(out: IO[str], decision: str | None, reason: str = "", context: str = "") -> None:
27
+ spec: dict = {"hookEventName": "PreToolUse"}
28
+ if decision:
29
+ spec["permissionDecision"] = decision
30
+ spec["permissionDecisionReason"] = reason
31
+ if context:
32
+ spec["additionalContext"] = context
33
+ out.write(json.dumps({"hookSpecificOutput": spec}))
34
+ out.flush()
35
+
36
+
37
+ def main(stdin: IO[str] | None = None, stdout: IO[str] | None = None, stderr: IO[str] | None = None) -> int:
38
+ stdin, stdout, stderr = stdin or sys.stdin, stdout or sys.stdout, stderr or sys.stderr
39
+ try:
40
+ data = json.load(stdin)
41
+ except (json.JSONDecodeError, ValueError) as e:
42
+ _emit(stdout, "ask", f"SecondKey couldn't read the hook input ({e}); please review this action yourself.")
43
+ return 0
44
+ if data.get("hook_event_name", "PreToolUse") != "PreToolUse":
45
+ return 0
46
+ tool = str(data.get("tool_name") or "")
47
+ tool_input = data.get("tool_input") or {}
48
+ cwd = str(data.get("cwd") or os.getcwd())
49
+ try:
50
+ result = gate.evaluate(source="claude-code", tool=tool, tool_input=tool_input, cwd=cwd)
51
+ except PolicyError as e:
52
+ _emit(stdout, "ask", f"SecondKey policy error: {e}. Please review this action yourself.")
53
+ return 0
54
+ except Exception as e: # noqa: BLE001 - must never crash open
55
+ print("secondkey hook error:\n" + traceback.format_exc(), file=stderr)
56
+ _emit(stdout, "ask", f"SecondKey hit an internal error ({e.__class__.__name__}: {e}). Please review this action yourself.")
57
+ return 0
58
+
59
+ if result.outcome == "allow":
60
+ if result.message:
61
+ _emit(stdout, None, context=result.message)
62
+ return 0
63
+ if result.outcome == "ask":
64
+ _emit(stdout, "ask", result.message)
65
+ return 0
66
+ _emit(stdout, "deny", result.message)
67
+ return 0
@@ -0,0 +1,77 @@
1
+ """Cursor hooks: beforeShellExecution, beforeReadFile and beforeMCPExecution.
2
+
3
+ Cursor's contract differs from Claude Code's: the command is at the top level
4
+ of the input, and every response must carry a "permission" field
5
+ ("allow" | "deny" | "ask") plus optional user_message / agent_message.
6
+
7
+ Held commands are answered with "deny" (never "ask"): several Cursor versions
8
+ have run commands anyway when a hook answered "ask".
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import sys
16
+ import traceback
17
+ from typing import IO, Any
18
+
19
+ from .. import gate
20
+ from ..policy import PolicyError
21
+
22
+
23
+ def _emit(out: IO[str], permission: str, agent: str = "", user: str = "") -> None:
24
+ body: dict[str, Any] = {"permission": permission}
25
+ if agent:
26
+ body["agent_message"] = agent
27
+ if user:
28
+ body["user_message"] = user
29
+ out.write(json.dumps(body))
30
+ out.flush()
31
+
32
+
33
+ def _call(data: dict[str, Any]) -> tuple[str, dict[str, Any], str]:
34
+ event = data.get("hook_event_name", "beforeShellExecution")
35
+ roots = data.get("workspace_roots") or []
36
+ cwd = str(data.get("cwd") or (roots[0] if roots else os.getcwd()))
37
+ if event == "beforeReadFile":
38
+ return "Read", {"file_path": data.get("file_path") or data.get("path") or ""}, cwd
39
+ if event == "beforeMCPExecution":
40
+ server = data.get("server") or data.get("server_name") or "cursor"
41
+ tool = data.get("tool_name") or "unknown"
42
+ tool_input = data.get("tool_input")
43
+ if isinstance(tool_input, str):
44
+ try:
45
+ tool_input = json.loads(tool_input)
46
+ except json.JSONDecodeError:
47
+ tool_input = {"raw": tool_input}
48
+ return f"mcp__{server}__{tool}", tool_input or {}, cwd
49
+ return "Bash", {"command": str(data.get("command") or "")}, cwd
50
+
51
+
52
+ def main(stdin: IO[str] | None = None, stdout: IO[str] | None = None, stderr: IO[str] | None = None) -> int:
53
+ stdin, stdout, stderr = stdin or sys.stdin, stdout or sys.stdout, stderr or sys.stderr
54
+ try:
55
+ data = json.load(stdin)
56
+ except (json.JSONDecodeError, ValueError) as e:
57
+ _emit(stdout, "deny", f"SecondKey couldn't read the hook input ({e}).", "SecondKey hook input was unreadable; blocked to be safe.")
58
+ return 0
59
+ tool, tool_input, cwd = _call(data)
60
+ try:
61
+ result = gate.evaluate(source="cursor", tool=tool, tool_input=tool_input, cwd=cwd, native_ask=False)
62
+ except PolicyError as e:
63
+ _emit(stdout, "deny", f"SecondKey policy error: {e}. Ask the user to fix .secondkey/policy.yaml.", f"SecondKey policy error: {e}")
64
+ return 0
65
+ except Exception as e: # noqa: BLE001 - must never fail open
66
+ print("secondkey cursor hook error:\n" + traceback.format_exc(), file=stderr)
67
+ _emit(stdout, "deny", f"SecondKey hit an internal error ({e}); this action was blocked to be safe.",
68
+ f"SecondKey internal error: {e}. Run `secondkey doctor`.")
69
+ return 0
70
+ if result.outcome == "allow":
71
+ _emit(stdout, "allow", result.message)
72
+ return 0
73
+ user = result.message
74
+ if result.request is not None and result.outcome == "held":
75
+ user = f"SecondKey is holding a command for you: `secondkey approve {result.request.id}` (or deny)."
76
+ _emit(stdout, "deny", result.message, user)
77
+ return 0
secondkey/notify.py ADDED
@@ -0,0 +1,36 @@
1
+ """Approval notifications. Failures are logged, never fatal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ import urllib.request
8
+
9
+ from .store import Request
10
+
11
+
12
+ def approval_text(req: Request, impact: list[str], problems: list[str]) -> str:
13
+ lines = [f"*SecondKey: approval needed* (`{req.id}`)",
14
+ f"{req.source} wants to run in `{req.cwd}`:",
15
+ f"```{req.command[:1500]}```"]
16
+ if req.reason:
17
+ lines.append(f"Why it's held: {req.reason}")
18
+ if impact:
19
+ lines.append("Impact: " + "; ".join(impact[:8]))
20
+ if problems:
21
+ lines.append("Not protected by a snapshot: " + "; ".join(problems[:4]))
22
+ else:
23
+ lines.append("A snapshot is taken right before it runs, so it can be undone.")
24
+ lines.append(f"Approve: `secondkey approve {req.id}` Deny: `secondkey deny {req.id}`")
25
+ return "\n".join(lines)
26
+
27
+
28
+ def slack(webhook: str, text: str, timeout: float = 5.0) -> bool:
29
+ body = json.dumps({"text": text, "mrkdwn": True}).encode()
30
+ req = urllib.request.Request(webhook, data=body, headers={"Content-Type": "application/json"})
31
+ try:
32
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
33
+ return 200 <= resp.status < 300
34
+ except Exception as e: # network errors must never break the gate
35
+ print(f"secondkey: Slack notification failed: {e}", file=sys.stderr)
36
+ return False
secondkey/policy.py ADDED
@@ -0,0 +1,165 @@
1
+ """Policy loading and evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import os
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from importlib import resources
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import yaml
14
+
15
+ from .classify import Action
16
+ from .util import home
17
+
18
+ STRICTNESS = {"allow": 0, "ask": 1, "deny": 2}
19
+ GUARD_REASON = ("An agent can't approve its own requests, run undo, or change SecondKey's policy, hooks or state. "
20
+ "Only a human can turn the second key")
21
+
22
+
23
+ class PolicyError(ValueError):
24
+ pass
25
+
26
+
27
+ @dataclass
28
+ class Rule:
29
+ match: list[str]
30
+ action: str
31
+ snapshot: bool
32
+ reason: str | None = None
33
+
34
+ def matches(self, category: str) -> bool:
35
+ return any(fnmatch.fnmatchcase(category, pat) for pat in self.match)
36
+
37
+
38
+ @dataclass
39
+ class Verdict:
40
+ action: Action
41
+ decision: str
42
+ snapshot: bool
43
+ rule: str
44
+ reason: str | None = None
45
+
46
+
47
+ @dataclass
48
+ class Decision:
49
+ decision: str # allow | ask | deny
50
+ verdicts: list[Verdict]
51
+ reason: str = ""
52
+
53
+ @property
54
+ def snapshot_actions(self) -> list[Action]:
55
+ return [v.action for v in self.verdicts if v.snapshot and v.decision != "deny"]
56
+
57
+
58
+ @dataclass
59
+ class Policy:
60
+ rules: list[Rule]
61
+ default: str = "allow"
62
+ approval: dict[str, Any] = field(default_factory=dict)
63
+ notify: dict[str, Any] = field(default_factory=dict)
64
+ snapshots: dict[str, Any] = field(default_factory=dict)
65
+ source: str = "built-in"
66
+
67
+ @property
68
+ def wait_seconds(self) -> float:
69
+ return float(self.approval.get("wait_seconds", 0) or 0)
70
+
71
+ @property
72
+ def ttl_seconds(self) -> float:
73
+ return float(self.approval.get("ttl_minutes", 15)) * 60
74
+
75
+ @property
76
+ def require_snapshot(self) -> bool:
77
+ return bool(self.approval.get("require_snapshot", True))
78
+
79
+ @property
80
+ def retention_days(self) -> float:
81
+ return float(self.snapshots.get("retention_days", 14))
82
+
83
+ @property
84
+ def max_total_bytes(self) -> int:
85
+ return int(float(self.snapshots.get("max_total_mb", 5120)) * 1024 * 1024)
86
+
87
+ @property
88
+ def max_file_snapshot_bytes(self) -> int:
89
+ return int(float(self.snapshots.get("max_file_snapshot_mb", 500)) * 1024 * 1024)
90
+
91
+ def slack_webhook(self) -> str | None:
92
+ raw = str(self.notify.get("slack_webhook") or "")
93
+ val = _interpolate(raw).strip()
94
+ return val or None
95
+
96
+ def verdict(self, action: Action) -> Verdict:
97
+ if action.category.startswith("secondkey.") and action.category != "secondkey.read":
98
+ # Built-in guard, not configurable: the agent must never hold the second key.
99
+ return Verdict(action, "deny", False, "built-in guard", GUARD_REASON)
100
+ for i, rule in enumerate(self.rules):
101
+ if rule.matches(action.category):
102
+ return Verdict(action, rule.action, rule.snapshot, f"rules[{i}] {', '.join(rule.match)[:60]}", rule.reason)
103
+ return Verdict(action, self.default, False, "default")
104
+
105
+ def evaluate(self, actions: list[Action]) -> Decision:
106
+ verdicts = [self.verdict(a) for a in actions]
107
+ if not verdicts:
108
+ return Decision("allow", [], "nothing to check")
109
+ worst = max(verdicts, key=lambda v: STRICTNESS[v.decision])
110
+ reason = worst.reason or (f"{worst.action.category} → {worst.decision}")
111
+ return Decision(worst.decision, verdicts, reason)
112
+
113
+
114
+ def _interpolate(value: str) -> str:
115
+ return re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}", lambda m: os.environ.get(m.group(1), ""), value)
116
+
117
+
118
+ def parse_policy(data: dict[str, Any], source: str) -> Policy:
119
+ if not isinstance(data, dict):
120
+ raise PolicyError(f"{source}: policy must be a mapping")
121
+ default = str(data.get("default", "allow"))
122
+ if default not in STRICTNESS:
123
+ raise PolicyError(f"{source}: default must be allow, ask or deny")
124
+ rules = []
125
+ for i, r in enumerate(data.get("rules") or []):
126
+ if not isinstance(r, dict) or "match" not in r or "action" not in r:
127
+ raise PolicyError(f"{source}: rules[{i}] needs 'match' and 'action'")
128
+ match = r["match"] if isinstance(r["match"], list) else [r["match"]]
129
+ action = str(r["action"])
130
+ if action not in STRICTNESS:
131
+ raise PolicyError(f"{source}: rules[{i}].action must be allow, ask or deny (got {action!r})")
132
+ snapshot = bool(r.get("snapshot", action == "ask"))
133
+ rules.append(Rule([str(m) for m in match], action, snapshot, r.get("reason")))
134
+ return Policy(rules, default, dict(data.get("approval") or {}), dict(data.get("notify") or {}),
135
+ dict(data.get("snapshots") or {}), source)
136
+
137
+
138
+ def default_policy_text() -> str:
139
+ return resources.files("secondkey").joinpath("default_policy.yaml").read_text(encoding="utf-8")
140
+
141
+
142
+ def find_policy_file(cwd: str) -> Path | None:
143
+ env = os.environ.get("SECONDKEY_POLICY")
144
+ if env:
145
+ return Path(env)
146
+ d = Path(cwd).resolve()
147
+ for p in [d, *d.parents]:
148
+ cand = p / ".secondkey" / "policy.yaml"
149
+ if cand.is_file():
150
+ return cand
151
+ if (p / ".git").exists():
152
+ break
153
+ user = home() / "policy.yaml"
154
+ return user if user.is_file() else None
155
+
156
+
157
+ def load_policy(cwd: str, path: str | None = None) -> Policy:
158
+ file = Path(path) if path else find_policy_file(cwd)
159
+ if file is None:
160
+ return parse_policy(yaml.safe_load(default_policy_text()), "built-in default")
161
+ try:
162
+ data = yaml.safe_load(file.read_text(encoding="utf-8"))
163
+ except (OSError, yaml.YAMLError) as e:
164
+ raise PolicyError(f"{file}: {e}") from e
165
+ return parse_policy(data, str(file))