@mokuyoaxis/agent-guard 0.2.2
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.
- package/CONTRIBUTING.md +101 -0
- package/LICENSE +21 -0
- package/README.md +558 -0
- package/README.zh-CN.md +488 -0
- package/adapters/INTEGRATION.md +94 -0
- package/adapters/claude/README.md +141 -0
- package/adapters/claude/compatibility.json +17 -0
- package/adapters/claude/harness/README.md +59 -0
- package/adapters/claude/harness/mock_anthropic_api.mjs +47 -0
- package/adapters/claude/harness/run_scenario.sh +79 -0
- package/adapters/claude/harness/run_scenario_no_python3.sh +49 -0
- package/adapters/claude/hook_bridge.sh +33 -0
- package/adapters/claude/pre_tool_use.py +264 -0
- package/adapters/claude/settings.example.json +16 -0
- package/adapters/codex/harness/README.md +53 -0
- package/adapters/codex/harness/acceptance.py +226 -0
- package/adapters/dsh/README.md +62 -0
- package/adapters/dsh/cordis.patch.yml +30 -0
- package/adapters/dsh/lib/index.js +500 -0
- package/adapters/kimi-code/README.md +169 -0
- package/adapters/kimi-code/compatibility.json +17 -0
- package/adapters/kimi-code/config.example.toml +26 -0
- package/adapters/kimi-code/hook_bridge.sh +32 -0
- package/adapters/kimi-code/pre_tool_use.py +72 -0
- package/core/__init__.py +47 -0
- package/core/audit.py +86 -0
- package/core/classifier.py +1175 -0
- package/core/dialects.py +898 -0
- package/core/policy.py +817 -0
- package/core/recovery.py +700 -0
- package/core/redaction.py +1096 -0
- package/core/safe_view.py +212 -0
- package/docs/architecture.md +223 -0
- package/docs/compatibility.md +142 -0
- package/docs/development-note-unguarded-deletion.md +187 -0
- package/docs/friction.md +266 -0
- package/docs/harness-capabilities.md +72 -0
- package/docs/host-drift.md +142 -0
- package/docs/publishing-from-ephemeral-environments.md +104 -0
- package/docs/release-notes-0.2.0-rc1.md +46 -0
- package/docs/release-notes-0.2.0.md +72 -0
- package/docs/release-notes-0.2.1.md +78 -0
- package/docs/release-notes-0.2.2.md +120 -0
- package/docs/secret-guard-analysis.md +416 -0
- package/docs/secret-guard-architecture.md +93 -0
- package/docs/secret-guard-design.md +649 -0
- package/docs/test-report-claude-code-harness.md +462 -0
- package/docs/test-report-codex-gpt-5.6-sol.md +335 -0
- package/docs/test-report-codex-gpt-6-astra-high.md +129 -0
- package/docs/test-report-dsh-0.1.5-rc.1.md +84 -0
- package/docs/test-report-dsh-v0.1.1.md +126 -0
- package/docs/test-report-kimi-code-block.md +198 -0
- package/docs/test-report-zcode-glm-flash.md +241 -0
- package/docs/threat-model.md +44 -0
- package/doctor.py +756 -0
- package/live_sentinel.py +339 -0
- package/package.json +69 -0
- package/skills/delete-guard/SKILL.md +109 -0
- package/skills/delete-guard/agents/openai.yaml +4 -0
- package/skills/delete-guard/references/policy.md +161 -0
- package/skills/delete-guard/scripts/_bootstrap.py +8 -0
- package/skills/delete-guard/scripts/check.py +370 -0
- package/skills/delete-guard/scripts/gc.py +103 -0
- package/skills/delete-guard/scripts/restore.py +98 -0
- package/skills/delete-guard/scripts/safe_delete.py +256 -0
- package/skills/delete-guard/scripts/status.py +130 -0
- package/skills/exfil-guard/SKILL.md +143 -0
- package/skills/exfil-guard/agents/openai.yaml +4 -0
- package/skills/exfil-guard/references/channels.md +58 -0
- package/skills/exfil-guard/references/rules.md +194 -0
- package/skills/exfil-guard/scripts/_bootstrap.py +8 -0
- package/skills/exfil-guard/scripts/check_span.py +250 -0
- package/skills/exfil-guard/scripts/sanitize.py +155 -0
- package/skills/exfil-guard/scripts/view.py +44 -0
- package/skills/recovery-audit/SKILL.md +283 -0
- package/skills/recovery-audit/agents/openai.yaml +4 -0
- package/skills/recovery-audit/references/evidence-records.md +85 -0
package/core/policy.py
ADDED
|
@@ -0,0 +1,817 @@
|
|
|
1
|
+
"""Decision Protocol: turn classified facts into decisions.
|
|
2
|
+
|
|
3
|
+
The stable cross-harness interface is NOT allow/block. It is:
|
|
4
|
+
|
|
5
|
+
Effect -> Classifier -> Policy -> Decision
|
|
6
|
+
+ ReasonCode
|
|
7
|
+
+ Explanation
|
|
8
|
+
+ RecoveryPlan (payload)
|
|
9
|
+
|
|
10
|
+
Decision classes (docs/architecture.md):
|
|
11
|
+
|
|
12
|
+
ALLOW safe to run as-is (noop / provably regenerable / trash GC)
|
|
13
|
+
RELOCATE compensate by quarantine, then run
|
|
14
|
+
SNAPSHOT compensate by git snapshot, then run
|
|
15
|
+
SANITIZE rewrite the PAYLOAD (not the command) before it is emitted:
|
|
16
|
+
the degraded compensation of an irreversible channel. It
|
|
17
|
+
restores nothing; it only records what was removed
|
|
18
|
+
(core/redaction.py, exfil-guard). Ranks below ASK: it is
|
|
19
|
+
automatic (SAFE tier), while ASK forfeits automation
|
|
20
|
+
ASK guard cannot safely automate, but user intent may be legit:
|
|
21
|
+
single-execution authorization (ASK_ONCE, never a rule
|
|
22
|
+
exemption); adapters map to their native ask, or degrade to
|
|
23
|
+
BLOCK with the explanation
|
|
24
|
+
BLOCK refuse (policy violations and true effect-uncertainty)
|
|
25
|
+
|
|
26
|
+
Interaction tiers: SAFE (auto) / AMBIGUOUS (occasional ASK) / FORBIDDEN
|
|
27
|
+
(BLOCK). Hard boundaries NEVER ask - a user who truly wants them acts
|
|
28
|
+
outside the agent, or changes configuration/mode explicitly.
|
|
29
|
+
|
|
30
|
+
Authorization model:
|
|
31
|
+
|
|
32
|
+
workspace: policy, artifact patterns, quarantine, audit
|
|
33
|
+
session/agent: NORMAL / RESTRICTED capability (one agent's veto must
|
|
34
|
+
not degrade concurrent agents - the guard must not become a DoS source)
|
|
35
|
+
|
|
36
|
+
NORMAL --(user veto / high-risk event)--> RESTRICTED
|
|
37
|
+
RESTRICTED --(human explicit action ONLY)--> NORMAL
|
|
38
|
+
|
|
39
|
+
The portable on-disk state is advisory by construction; harness adapters
|
|
40
|
+
SHOULD hold the authoritative mode in host memory. force_mode() exists for
|
|
41
|
+
host-side callers (slash commands, settings) and skips the TTY guard on
|
|
42
|
+
purpose - agents never get it as a model tool.
|
|
43
|
+
|
|
44
|
+
Guiding rule: uncertainty increases restriction. ASK is reserved for
|
|
45
|
+
well-understood operations whose safe *automation* is unavailable - never
|
|
46
|
+
for operations whose *effect* is unknown.
|
|
47
|
+
"""
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
import fnmatch
|
|
51
|
+
import json
|
|
52
|
+
import os
|
|
53
|
+
import re
|
|
54
|
+
import subprocess
|
|
55
|
+
import sys
|
|
56
|
+
import time
|
|
57
|
+
from dataclasses import dataclass, field
|
|
58
|
+
from typing import Any, Dict, List, Optional
|
|
59
|
+
|
|
60
|
+
from . import STATE_NAME, TRASH_DIRNAME
|
|
61
|
+
from . import redaction
|
|
62
|
+
from .redaction import get_channel
|
|
63
|
+
from .classifier import (
|
|
64
|
+
KIND_FS_DELETE,
|
|
65
|
+
KIND_GIT_CLEAN,
|
|
66
|
+
KIND_GIT_DISCARD,
|
|
67
|
+
KIND_GIT_PUSH_FORCE,
|
|
68
|
+
KIND_GIT_RESET_HARD,
|
|
69
|
+
KIND_UNKNOWN,
|
|
70
|
+
PathSpec,
|
|
71
|
+
OpSpec,
|
|
72
|
+
_physical,
|
|
73
|
+
_physical_keep_final,
|
|
74
|
+
classify_paths,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# --------------------------------------------------------- decision classes
|
|
78
|
+
|
|
79
|
+
DECISION_ALLOW = "ALLOW"
|
|
80
|
+
DECISION_RELOCATE = "RELOCATE"
|
|
81
|
+
DECISION_SNAPSHOT = "SNAPSHOT"
|
|
82
|
+
DECISION_SANITIZE = "SANITIZE"
|
|
83
|
+
DECISION_ASK = "ASK"
|
|
84
|
+
DECISION_BLOCK = "BLOCK"
|
|
85
|
+
|
|
86
|
+
# ------------------------------------------------------------- reason codes
|
|
87
|
+
|
|
88
|
+
CODE_ALLOW_NOOP = "ALLOW_NOOP"
|
|
89
|
+
CODE_ALLOW_REGENERABLE = "ALLOW_REGENERABLE"
|
|
90
|
+
CODE_ALLOW_TRASH_GC = "ALLOW_TRASH_GC"
|
|
91
|
+
CODE_RELOCATE_PATHS = "RELOCATE_PATHS"
|
|
92
|
+
CODE_RELOCATE_TREE = "RELOCATE_TREE"
|
|
93
|
+
CODE_RELOCATE_NARROW = "RELOCATE_NARROW"
|
|
94
|
+
CODE_RELOCATE_VIA_CLEAN_ENUMERATE = "RELOCATE_VIA_CLEAN_ENUMERATE"
|
|
95
|
+
CODE_SNAPSHOT_GIT_STASH = "SNAPSHOT_GIT_STASH"
|
|
96
|
+
CODE_ASK_COMPOUND_CWD_DELETE = "COMPOUND_CWD_DELETE" # F1
|
|
97
|
+
CODE_ASK_COMPOUND_CREATE_DELETE = "COMPOUND_CREATE_DELETE" # F2
|
|
98
|
+
CODE_BLOCK_UNDETERMINABLE_EFFECT = "BLOCK_UNDETERMINABLE_EFFECT"
|
|
99
|
+
CODE_BLOCK_OUT_OF_WORKSPACE = "BLOCK_OUT_OF_WORKSPACE"
|
|
100
|
+
CODE_BLOCK_PROTECTED_PATH = "BLOCK_PROTECTED_PATH"
|
|
101
|
+
CODE_BLOCK_PROTECTED_ANCESTOR = "BLOCK_PROTECTED_ANCESTOR"
|
|
102
|
+
CODE_BLOCK_WILDCARD = "BLOCK_WILDCARD"
|
|
103
|
+
CODE_BLOCK_RESTRICTED_MODE = "BLOCK_RESTRICTED_MODE"
|
|
104
|
+
CODE_BLOCK_FORCE_PUSH = "BLOCK_FORCE_PUSH"
|
|
105
|
+
CODE_BLOCK_DIALECT_UNKNOWN = "BLOCK_DIALECT_UNKNOWN" # config
|
|
106
|
+
CODE_BLOCK_DIALECT_INVALID = "BLOCK_DIALECT_INVALID" # config
|
|
107
|
+
CODE_BLOCK_RELOCATE_FAILED_STORAGE = "RELOCATE_FAILED_STORAGE"
|
|
108
|
+
# exfil-guard (span decisions). Rule ids (`secret/*`, `path/*`) are payload,
|
|
109
|
+
# never verdict codes; these codes name the *disposition*, not the pattern.
|
|
110
|
+
CODE_SANITIZE_SECRET_REDACT = "SANITIZE_SECRET_REDACT"
|
|
111
|
+
CODE_SANITIZE_PATH_REWRITE = "SANITIZE_PATH_REWRITE"
|
|
112
|
+
CODE_BLOCK_SECRET_EMISSION = "BLOCK_SECRET_EMISSION"
|
|
113
|
+
CODE_BLOCK_PATH_EMISSION = "BLOCK_PATH_EMISSION"
|
|
114
|
+
CODE_BLOCK_SECRET_SOURCE_DUMP = "BLOCK_SECRET_SOURCE_DUMP"
|
|
115
|
+
CODE_BLOCK_OUTPUT_UNSCANNABLE = "BLOCK_OUTPUT_UNSCANNABLE"
|
|
116
|
+
CODE_ASK_SECRET_EMISSION = "ASK_SECRET_EMISSION"
|
|
117
|
+
CODE_ASK_PATH_EMISSION = "ASK_PATH_EMISSION"
|
|
118
|
+
CODE_ALLOW_SECRET_PLACEHOLDER = "ALLOW_SECRET_PLACEHOLDER"
|
|
119
|
+
CODE_ALLOW_PATH_IN_WORKSPACE = "ALLOW_PATH_IN_WORKSPACE"
|
|
120
|
+
CODE_BLOCK_COMPENSATION_FAILED = "COMPENSATION_FAILED"
|
|
121
|
+
|
|
122
|
+
# Human-facing one-liners: why the guard cannot just do it (or did do it).
|
|
123
|
+
EXPLANATIONS: Dict[str, str] = {
|
|
124
|
+
CODE_ALLOW_NOOP: "Nothing to delete; command may run unchanged.",
|
|
125
|
+
CODE_ALLOW_REGENERABLE: "All targets are git-ignored and match known "
|
|
126
|
+
"artifact patterns; deleted directly.",
|
|
127
|
+
CODE_ALLOW_TRASH_GC: "Targets live inside the quarantine; housekeeping "
|
|
128
|
+
"is permitted.",
|
|
129
|
+
CODE_RELOCATE_PATHS: "Named targets were relocated to quarantine before "
|
|
130
|
+
"execution; restorable via txid.",
|
|
131
|
+
CODE_RELOCATE_TREE: "Rooted directory relocated to quarantine whole; "
|
|
132
|
+
"restorable via txid.",
|
|
133
|
+
CODE_RELOCATE_NARROW: "Restricted mode: named files relocated to "
|
|
134
|
+
"quarantine.",
|
|
135
|
+
CODE_RELOCATE_VIA_CLEAN_ENUMERATE: "git clean was dry-run enumerated and "
|
|
136
|
+
"every match relocated before the "
|
|
137
|
+
"real command ran.",
|
|
138
|
+
CODE_SNAPSHOT_GIT_STASH: "Tracked modifications snapshotted as a stash "
|
|
139
|
+
"before the command; apply it to recover.",
|
|
140
|
+
CODE_ASK_COMPOUND_CWD_DELETE: "This line combines a working-directory "
|
|
141
|
+
"change with deletion, so the guard "
|
|
142
|
+
"cannot safely relocate the target before "
|
|
143
|
+
"execution. Allow once to run it as-is, "
|
|
144
|
+
"or split the deletion into its own "
|
|
145
|
+
"command.",
|
|
146
|
+
CODE_ASK_COMPOUND_CREATE_DELETE: "This line creates files and then "
|
|
147
|
+
"destroys them, so pre-execution "
|
|
148
|
+
"compensation cannot see the targets. "
|
|
149
|
+
"Allow once to run it as-is, or split "
|
|
150
|
+
"the deletion into its own command.",
|
|
151
|
+
CODE_BLOCK_UNDETERMINABLE_EFFECT: "The effect of this command cannot be "
|
|
152
|
+
"determined statically; allowing it "
|
|
153
|
+
"would forfeit the guard's core "
|
|
154
|
+
"guarantee. Restate with explicit "
|
|
155
|
+
"paths.",
|
|
156
|
+
CODE_BLOCK_OUT_OF_WORKSPACE: "Target lies outside the workspace "
|
|
157
|
+
"boundary. Hard boundary - not askable.",
|
|
158
|
+
CODE_BLOCK_PROTECTED_ANCESTOR: "Target is a filesystem root that must "
|
|
159
|
+
"never be deleted (/, /home, $HOME, "
|
|
160
|
+
"/usr, /etc, ...), regardless of the "
|
|
161
|
+
"workspace setting. Hard boundary - not "
|
|
162
|
+
"askable.",
|
|
163
|
+
CODE_BLOCK_PROTECTED_PATH: "Target is the workspace root or git "
|
|
164
|
+
"metadata. Hard boundary - not askable.",
|
|
165
|
+
CODE_BLOCK_WILDCARD: "Glob target sets are opaque; use safe_delete, "
|
|
166
|
+
"which expands globs explicitly.",
|
|
167
|
+
CODE_BLOCK_RESTRICTED_MODE: "This session is in RESTRICTED mode; the "
|
|
168
|
+
"operation exceeds its remaining "
|
|
169
|
+
"capability.",
|
|
170
|
+
CODE_BLOCK_FORCE_PUSH: "Remote history destruction is never automated "
|
|
171
|
+
"by the guard. Hard boundary - not askable.",
|
|
172
|
+
CODE_BLOCK_DIALECT_UNKNOWN: "The requested command dialect is not "
|
|
173
|
+
"recognised, so the command line was never "
|
|
174
|
+
"classified. This is a configuration "
|
|
175
|
+
"problem, not one-off authorization: fix the "
|
|
176
|
+
"dialect selector (posix | cmd | powershell) "
|
|
177
|
+
"and retry.",
|
|
178
|
+
CODE_BLOCK_DIALECT_INVALID: "The requested command dialect is malformed "
|
|
179
|
+
"(expected a single dialect name such as "
|
|
180
|
+
"posix, cmd or powershell), so the command "
|
|
181
|
+
"line was never classified. Fix the selector "
|
|
182
|
+
"and retry.",
|
|
183
|
+
CODE_BLOCK_RELOCATE_FAILED_STORAGE: "Quarantine could not accept the "
|
|
184
|
+
"relocation (storage). Refusing to "
|
|
185
|
+
"fall back to permanent deletion.",
|
|
186
|
+
CODE_BLOCK_COMPENSATION_FAILED: "Compensation failed before execution; "
|
|
187
|
+
"refusing to proceed unrecoverable.",
|
|
188
|
+
CODE_SANITIZE_SECRET_REDACT: "A credential would leave the machine on this "
|
|
189
|
+
"payload; it is replaced in place before "
|
|
190
|
+
"emission. Apply the redaction plan to the "
|
|
191
|
+
"payload you hold - the guard never rewrites "
|
|
192
|
+
"it for you.",
|
|
193
|
+
CODE_SANITIZE_PATH_REWRITE: "A host-identifying path would leave the "
|
|
194
|
+
"machine on this payload; it is rewritten to a "
|
|
195
|
+
"stable placeholder before emission. Apply the "
|
|
196
|
+
"redaction plan to the payload you hold.",
|
|
197
|
+
CODE_BLOCK_SECRET_EMISSION: "A credential would enter an immutable or "
|
|
198
|
+
"remote history on this channel, where it "
|
|
199
|
+
"cannot be taken back. Remove it and retry "
|
|
200
|
+
"(amend the message / rewrite before pushing).",
|
|
201
|
+
CODE_BLOCK_PATH_EMISSION: "A host-identifying path would enter an "
|
|
202
|
+
"immutable or remote history on this channel. "
|
|
203
|
+
"Remove it and retry.",
|
|
204
|
+
CODE_BLOCK_SECRET_SOURCE_DUMP: "This payload reads a secret source (a "
|
|
205
|
+
"credential file, or the whole "
|
|
206
|
+
"environment) whose content cannot be "
|
|
207
|
+
"scanned or rewritten here. Fail closed: "
|
|
208
|
+
"such a dump is not a clean emission.",
|
|
209
|
+
CODE_BLOCK_OUTPUT_UNSCANNABLE: "The payload was never scanned (scanner "
|
|
210
|
+
"unavailable or the text exceeds the "
|
|
211
|
+
"supported size). An unscanned egress is "
|
|
212
|
+
"not a clean egress.",
|
|
213
|
+
CODE_ASK_SECRET_EMISSION: "A credential would leave the machine on a "
|
|
214
|
+
"channel the guard cannot rewrite and cannot "
|
|
215
|
+
"take back (it cannot un-print). Allow once to "
|
|
216
|
+
"proceed as-is, or remove the value first.",
|
|
217
|
+
CODE_ASK_PATH_EMISSION: "A host-identifying path would leave the machine "
|
|
218
|
+
"on a channel the guard cannot rewrite. Low "
|
|
219
|
+
"severity; allow once to proceed as-is.",
|
|
220
|
+
CODE_ALLOW_SECRET_PLACEHOLDER: "Every match is a documented placeholder "
|
|
221
|
+
"or an already-redacted marker; nothing to "
|
|
222
|
+
"remove.",
|
|
223
|
+
CODE_ALLOW_PATH_IN_WORKSPACE: "Every path lies inside the workspace, so "
|
|
224
|
+
"it identifies no host.",
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
# ------------------------------------------------------------------- verdict
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@dataclass
|
|
231
|
+
class Verdict:
|
|
232
|
+
decision: str # DECISION_* constant
|
|
233
|
+
code: str # stable machine-readable reason code
|
|
234
|
+
reasons: List[str] = field(default_factory=list) # technical detail
|
|
235
|
+
explanation: str = "" # human-facing one-liner
|
|
236
|
+
payload: Dict[str, Any] = field(default_factory=dict)
|
|
237
|
+
|
|
238
|
+
def __post_init__(self):
|
|
239
|
+
if not self.explanation:
|
|
240
|
+
self.explanation = EXPLANATIONS.get(
|
|
241
|
+
self.code, "Guard decision: " + self.code)
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def blocked(self) -> bool:
|
|
245
|
+
return self.decision == DECISION_BLOCK
|
|
246
|
+
|
|
247
|
+
@property
|
|
248
|
+
def asks(self) -> bool:
|
|
249
|
+
return self.decision == DECISION_ASK
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def sanitizes(self) -> bool:
|
|
253
|
+
return self.decision == DECISION_SANITIZE
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def worst(verdicts: List[Verdict]) -> Verdict:
|
|
257
|
+
"""Aggregate: BLOCK > ASK > RELOCATE/SNAPSHOT > SANITIZE > ALLOW.
|
|
258
|
+
|
|
259
|
+
SANITIZE ranks *below* ASK deliberately (design 1.3): it is automatic
|
|
260
|
+
(SAFE tier, like RELOCATE/SNAPSHOT) while ASK forfeits automation. A
|
|
261
|
+
payload carrying both a sanitizable secret and an uninspectable,
|
|
262
|
+
un-rewritable shape must ASK - you cannot silently proceed when part of
|
|
263
|
+
the emission cannot be inspected.
|
|
264
|
+
"""
|
|
265
|
+
rank = {DECISION_ALLOW: 0, DECISION_SANITIZE: 1, DECISION_RELOCATE: 2,
|
|
266
|
+
DECISION_SNAPSHOT: 2, DECISION_ASK: 3, DECISION_BLOCK: 4}
|
|
267
|
+
if not verdicts:
|
|
268
|
+
return Verdict(DECISION_ALLOW, CODE_ALLOW_NOOP,
|
|
269
|
+
explanation=EXPLANATIONS[CODE_ALLOW_NOOP])
|
|
270
|
+
return max(verdicts, key=lambda v: rank[v.decision])
|
|
271
|
+
|
|
272
|
+
# --------------------------------------------------------------------- modes
|
|
273
|
+
|
|
274
|
+
MODE_NORMAL = "NORMAL"
|
|
275
|
+
MODE_RESTRICTED = "RESTRICTED"
|
|
276
|
+
|
|
277
|
+
_SESSION_SANITIZE_RE = re.compile(r"[^A-Za-z0-9._-]")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class AuthorizationRequired(RuntimeError):
|
|
281
|
+
"""Raised when a mode change requires a human and none is present."""
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _session_key(session: Optional[str]) -> str:
|
|
285
|
+
sid = session or os.environ.get("AGENT_GUARD_SESSION") or ""
|
|
286
|
+
sid = _SESSION_SANITIZE_RE.sub("_", sid)[:80]
|
|
287
|
+
return sid
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def state_path(trash_root: str, session: Optional[str] = None) -> str:
|
|
291
|
+
"""Session-scoped authorization state; legacy file when sessionless."""
|
|
292
|
+
sid = _session_key(session)
|
|
293
|
+
if sid:
|
|
294
|
+
return os.path.join(trash_root, "sessions", sid + ".json")
|
|
295
|
+
return os.path.join(trash_root, STATE_NAME)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def load_mode(trash_root: str, session: Optional[str] = None) -> Dict[str, Any]:
|
|
299
|
+
"""Read one session's capability; corrupt/missing falls back to NORMAL.
|
|
300
|
+
|
|
301
|
+
Sessions start NORMAL by design: authorization is a per-agent
|
|
302
|
+
capability, not workspace pollution (friction: one degraded agent must
|
|
303
|
+
not DoS concurrent agents).
|
|
304
|
+
"""
|
|
305
|
+
path = state_path(trash_root, session)
|
|
306
|
+
try:
|
|
307
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
308
|
+
data = json.load(fh)
|
|
309
|
+
mode = data.get("mode")
|
|
310
|
+
if mode in (MODE_NORMAL, MODE_RESTRICTED):
|
|
311
|
+
return {"mode": mode, "since": data.get("since"),
|
|
312
|
+
"set_by": data.get("set_by"), "degraded": False}
|
|
313
|
+
except (OSError, json.JSONDecodeError, AttributeError):
|
|
314
|
+
pass
|
|
315
|
+
return {"mode": MODE_NORMAL, "since": None, "set_by": None,
|
|
316
|
+
"degraded": False}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _save_mode(trash_root: str, mode: str, actor: str,
|
|
320
|
+
session: Optional[str]) -> Dict[str, Any]:
|
|
321
|
+
path = state_path(trash_root, session)
|
|
322
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
323
|
+
state = {"mode": mode,
|
|
324
|
+
"since": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
325
|
+
"set_by": actor}
|
|
326
|
+
tmp = path + ".tmp"
|
|
327
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
328
|
+
json.dump(state, fh, ensure_ascii=False, indent=2)
|
|
329
|
+
os.replace(tmp, path)
|
|
330
|
+
return state
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def request_mode(trash_root: str, new_mode: str, actor: str = "unknown",
|
|
334
|
+
session: Optional[str] = None) -> Dict[str, Any]:
|
|
335
|
+
"""Change one session's capability, enforcing the one-way downgrade.
|
|
336
|
+
|
|
337
|
+
Downgrade is always safe. Promotion demands an interactive human
|
|
338
|
+
terminal - agents running non-interactively can never satisfy it.
|
|
339
|
+
Host-side callers with real authority use force_mode() instead.
|
|
340
|
+
"""
|
|
341
|
+
current = load_mode(trash_root, session)
|
|
342
|
+
if new_mode == current["mode"]:
|
|
343
|
+
return current
|
|
344
|
+
if new_mode == MODE_RESTRICTED:
|
|
345
|
+
return _save_mode(trash_root, MODE_RESTRICTED, actor, session)
|
|
346
|
+
if new_mode == MODE_NORMAL:
|
|
347
|
+
if not sys.stdin.isatty():
|
|
348
|
+
raise AuthorizationRequired(
|
|
349
|
+
"RESTRICTED -> NORMAL requires an interactive human "
|
|
350
|
+
"terminal or a host-side command; the agent cannot "
|
|
351
|
+
"promote itself.")
|
|
352
|
+
return _save_mode(trash_root, MODE_NORMAL, actor, session)
|
|
353
|
+
raise ValueError(f"unknown mode: {new_mode}")
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def force_mode(trash_root: str, new_mode: str, actor: str,
|
|
357
|
+
session: Optional[str] = None) -> Dict[str, Any]:
|
|
358
|
+
"""Host-side authority entry point (slash commands, settings UI).
|
|
359
|
+
|
|
360
|
+
Deliberately skips the TTY guard: the caller is the host, not the
|
|
361
|
+
agent. Never expose this as a model tool.
|
|
362
|
+
"""
|
|
363
|
+
current = load_mode(trash_root, session)
|
|
364
|
+
if new_mode == current["mode"]:
|
|
365
|
+
return current
|
|
366
|
+
return _save_mode(trash_root, new_mode, actor, session)
|
|
367
|
+
|
|
368
|
+
# -------------------------------------------------------------------- config
|
|
369
|
+
|
|
370
|
+
DEFAULT_ARTIFACT_PATTERNS = [
|
|
371
|
+
"node_modules", "dist", "build", "out", "target", "__pycache__",
|
|
372
|
+
".cache", "coverage", ".next", ".nuxt", ".venv", "venv",
|
|
373
|
+
".pytest_cache", ".mypy_cache", ".tox", ".turbo", ".parcel-cache",
|
|
374
|
+
"*.pyc", "*.pyo", "*.egg-info",
|
|
375
|
+
]
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
@dataclass
|
|
379
|
+
class GuardConfig:
|
|
380
|
+
artifact_patterns: List[str] = field(
|
|
381
|
+
default_factory=lambda: list(DEFAULT_ARTIFACT_PATTERNS))
|
|
382
|
+
allow_regenerable: bool = True
|
|
383
|
+
|
|
384
|
+
@classmethod
|
|
385
|
+
def from_env(cls) -> "GuardConfig":
|
|
386
|
+
cfg = cls()
|
|
387
|
+
extra = os.environ.get("AGENT_GUARD_ARTIFACTS")
|
|
388
|
+
if extra:
|
|
389
|
+
cfg.artifact_patterns.extend(
|
|
390
|
+
p for p in extra.split(os.pathsep) if p)
|
|
391
|
+
if os.environ.get("AGENT_GUARD_ALLOW_REGENERABLE", "").strip() in (
|
|
392
|
+
"0", "false", "no"):
|
|
393
|
+
cfg.allow_regenerable = False
|
|
394
|
+
return cfg
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
@dataclass
|
|
398
|
+
class PolicyContext:
|
|
399
|
+
workspace: str
|
|
400
|
+
trash_root: str
|
|
401
|
+
base_dir: str
|
|
402
|
+
mode: str = MODE_NORMAL
|
|
403
|
+
config: GuardConfig = field(default_factory=GuardConfig.from_env)
|
|
404
|
+
|
|
405
|
+
# ------------------------------------------------------------- regenerability
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _matches_artifact(rel: str, patterns: List[str]) -> bool:
|
|
409
|
+
parts = rel.split(os.sep)
|
|
410
|
+
for pat in patterns:
|
|
411
|
+
if any(fnmatch.fnmatch(part, pat) for part in parts):
|
|
412
|
+
return True
|
|
413
|
+
if fnmatch.fnmatch(rel, pat):
|
|
414
|
+
return True
|
|
415
|
+
return False
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def is_git_ignored(workspace: str, path: str) -> bool:
|
|
419
|
+
"""True when git ignores path. Outside a work tree -> NOT ignored
|
|
420
|
+
(uncertainty increases restriction)."""
|
|
421
|
+
try:
|
|
422
|
+
proc = subprocess.run(
|
|
423
|
+
["git", "-C", workspace, "check-ignore", "-q", "--", path],
|
|
424
|
+
capture_output=True, timeout=10)
|
|
425
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
426
|
+
return False
|
|
427
|
+
return proc.returncode == 0
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def regenerable(specs: List[PathSpec], ctx: PolicyContext) -> bool:
|
|
431
|
+
"""True when every target is git-ignored AND matches an artifact pattern.
|
|
432
|
+
|
|
433
|
+
The workspace-relative path used for artifact matching is computed from
|
|
434
|
+
PHYSICAL spellings on BOTH sides (F9c). ``ctx.workspace`` comes from
|
|
435
|
+
``discover_workspace()`` and is realpath-resolved, while
|
|
436
|
+
``PathSpec.resolved`` deliberately keeps the caller's LEXICAL spelling
|
|
437
|
+
(MR !7) - mixing the two yields a ``..``-laden relpath whenever the
|
|
438
|
+
workspace sits under a symlinked ancestor (macOS: /var -> /private/var,
|
|
439
|
+
/tmp -> /private/tmp), so the segmented artifact match silently failed
|
|
440
|
+
and the fast RELOCATE path degraded into a full compensation.
|
|
441
|
+
|
|
442
|
+
The FINAL component stays verbatim (``_physical_keep_final``): artifact
|
|
443
|
+
matching is about where the ENTRY lives, so a target that is itself a
|
|
444
|
+
symlink is classified by the link's own location, never by its target
|
|
445
|
+
(the same choice relocation makes for the quarantine layout).
|
|
446
|
+
|
|
447
|
+
The effect direction is conservative either way - a false negative only
|
|
448
|
+
buys a relocation - and this is a pure spelling fix: patterns, defaults
|
|
449
|
+
and the decision table are untouched. ``spec.resolved`` is still handed
|
|
450
|
+
to git unchanged.
|
|
451
|
+
"""
|
|
452
|
+
if not ctx.config.allow_regenerable:
|
|
453
|
+
return False
|
|
454
|
+
for spec in specs:
|
|
455
|
+
if not spec.resolved or not spec.exists:
|
|
456
|
+
return False
|
|
457
|
+
rel = os.path.relpath(_physical_keep_final(spec.resolved),
|
|
458
|
+
_physical(ctx.workspace))
|
|
459
|
+
if not _matches_artifact(rel, ctx.config.artifact_patterns):
|
|
460
|
+
return False
|
|
461
|
+
if not is_git_ignored(ctx.workspace, spec.resolved):
|
|
462
|
+
return False
|
|
463
|
+
return True
|
|
464
|
+
|
|
465
|
+
# ------------------------------------------------------------------ decisions
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _block_undeterminable_effect(spec: OpSpec) -> Verdict:
|
|
469
|
+
return Verdict(
|
|
470
|
+
decision=DECISION_BLOCK,
|
|
471
|
+
code=CODE_BLOCK_UNDETERMINABLE_EFFECT,
|
|
472
|
+
reasons=["effect cannot be determined statically"] + spec.notes,
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def decide_path_batch(specs: List[PathSpec], ctx: PolicyContext,
|
|
477
|
+
recursive: bool) -> Verdict:
|
|
478
|
+
"""One batch of concrete deletion targets through the rule table."""
|
|
479
|
+
reasons: List[str] = []
|
|
480
|
+
|
|
481
|
+
errored = [s for s in specs if s.error or s.indeterminable]
|
|
482
|
+
if errored:
|
|
483
|
+
reasons.extend(s.error or "indeterminable target" for s in errored)
|
|
484
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_UNDETERMINABLE_EFFECT,
|
|
485
|
+
reasons)
|
|
486
|
+
|
|
487
|
+
protected_ancestor = [s for s in specs
|
|
488
|
+
if s.protected == "ancestor-root"]
|
|
489
|
+
if protected_ancestor:
|
|
490
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_PROTECTED_ANCESTOR,
|
|
491
|
+
[f"protected filesystem root: {s.raw}"
|
|
492
|
+
for s in protected_ancestor[:5]])
|
|
493
|
+
|
|
494
|
+
if specs and all(s.inside_trash for s in specs):
|
|
495
|
+
return Verdict(DECISION_ALLOW, CODE_ALLOW_TRASH_GC)
|
|
496
|
+
|
|
497
|
+
protected_outside = [s for s in specs
|
|
498
|
+
if s.protected == "outside-workspace"]
|
|
499
|
+
if protected_outside:
|
|
500
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_OUT_OF_WORKSPACE,
|
|
501
|
+
[f"outside workspace boundary: {s.raw}"
|
|
502
|
+
for s in protected_outside[:5]])
|
|
503
|
+
|
|
504
|
+
protected_other = [s for s in specs
|
|
505
|
+
if s.protected in ("workspace-root", "git-metadata")]
|
|
506
|
+
if protected_other:
|
|
507
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_PROTECTED_PATH,
|
|
508
|
+
[f"protected: {s.protected} ({s.raw})"
|
|
509
|
+
for s in protected_other[:5]])
|
|
510
|
+
|
|
511
|
+
wild = [s for s in specs if s.wildcard]
|
|
512
|
+
if wild:
|
|
513
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_WILDCARD,
|
|
514
|
+
["glob targets are opaque; enumerate explicitly "
|
|
515
|
+
"(safe_delete expands globs itself)"])
|
|
516
|
+
|
|
517
|
+
missing = [s for s in specs if not s.exists]
|
|
518
|
+
if len(missing) == len(specs):
|
|
519
|
+
return Verdict(DECISION_ALLOW, CODE_ALLOW_NOOP)
|
|
520
|
+
|
|
521
|
+
if ctx.mode == MODE_RESTRICTED:
|
|
522
|
+
if all((s.is_file or s.is_symlink) for s in specs):
|
|
523
|
+
return Verdict(DECISION_RELOCATE, CODE_RELOCATE_NARROW,
|
|
524
|
+
["restricted mode: named files only, quarantined"])
|
|
525
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_RESTRICTED_MODE,
|
|
526
|
+
["restricted mode permits only explicit single-file "
|
|
527
|
+
"deletes inside the workspace"])
|
|
528
|
+
|
|
529
|
+
if recursive and regenerable(specs, ctx):
|
|
530
|
+
return Verdict(DECISION_ALLOW, CODE_ALLOW_REGENERABLE,
|
|
531
|
+
["all targets are git-ignored and match known "
|
|
532
|
+
"artifact patterns"])
|
|
533
|
+
if recursive:
|
|
534
|
+
dirs = [s.raw for s in specs if s.is_dir]
|
|
535
|
+
if dirs:
|
|
536
|
+
return Verdict(DECISION_RELOCATE, CODE_RELOCATE_TREE,
|
|
537
|
+
["rooted recursive delete relocated whole"])
|
|
538
|
+
return Verdict(DECISION_RELOCATE, CODE_RELOCATE_PATHS,
|
|
539
|
+
["named targets relocated"])
|
|
540
|
+
return Verdict(DECISION_RELOCATE, CODE_RELOCATE_PATHS,
|
|
541
|
+
["named targets relocated"])
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _ask_compound(spec: OpSpec, code: str) -> Verdict:
|
|
545
|
+
return Verdict(
|
|
546
|
+
decision=DECISION_ASK,
|
|
547
|
+
code=code,
|
|
548
|
+
reasons=list(spec.notes),
|
|
549
|
+
payload={"op": spec.op, "kind": spec.kind},
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def decide_dialect_failure(resolution, source: str = "cli") -> Verdict:
|
|
554
|
+
"""A BLOCK verdict for an unusable dialect selector.
|
|
555
|
+
|
|
556
|
+
Called *before* classification, because an unusable selector means the
|
|
557
|
+
command line was never classified at all. The guard must not silently
|
|
558
|
+
lex a PowerShell line with the POSIX lexer (or vice versa): that is the
|
|
559
|
+
exact failure the dialect layer exists to prevent, and it would let a
|
|
560
|
+
destructive line through as an ordinary - or, worse, mis-parsed -
|
|
561
|
+
delete.
|
|
562
|
+
|
|
563
|
+
BLOCK rather than ASK: a bad dialect selector is a configuration defect
|
|
564
|
+
that recurs on every command, not a one-time authorization a human can
|
|
565
|
+
meaningfully grant per execution. The explanation names the selector so
|
|
566
|
+
the fix is mechanical.
|
|
567
|
+
"""
|
|
568
|
+
if resolution is not None and resolution.ok:
|
|
569
|
+
raise ValueError("decide_dialect_failure called with a usable dialect")
|
|
570
|
+
reason = getattr(resolution, "reason", None) or \
|
|
571
|
+
f"{source}: unusable dialect selector"
|
|
572
|
+
# The resolver owns the unknown-vs-invalid classification; policy only
|
|
573
|
+
# mirrors it onto a reason code (single source of truth).
|
|
574
|
+
kind = getattr(resolution, "kind", None)
|
|
575
|
+
code = (CODE_BLOCK_DIALECT_INVALID if kind == "invalid"
|
|
576
|
+
else CODE_BLOCK_DIALECT_UNKNOWN)
|
|
577
|
+
return Verdict(decision=DECISION_BLOCK, code=code,
|
|
578
|
+
reasons=[reason, "command line was not classified"])
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def decide_op(spec: OpSpec, ctx: PolicyContext) -> Optional[Verdict]:
|
|
582
|
+
"""Map one classified operation to its decision. None => not destructive."""
|
|
583
|
+
if spec.kind == KIND_UNKNOWN:
|
|
584
|
+
return _block_undeterminable_effect(spec)
|
|
585
|
+
|
|
586
|
+
# Authorization gate first. In RESTRICTED mode nothing may escalate to
|
|
587
|
+
# ASK: the capability was already narrowed by a human veto.
|
|
588
|
+
if ctx.mode == MODE_RESTRICTED and (
|
|
589
|
+
spec.kind != KIND_FS_DELETE or spec.shape):
|
|
590
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_RESTRICTED_MODE,
|
|
591
|
+
[f"restricted mode disables {spec.kind} operations"])
|
|
592
|
+
|
|
593
|
+
# Hard refusals must win over any F1/F2 request for authorization. In
|
|
594
|
+
# particular, `cd x && git push --force` is still a force push; letting
|
|
595
|
+
# the shape return ASK first silently grants it on auto-approving hosts.
|
|
596
|
+
if spec.kind == KIND_GIT_PUSH_FORCE:
|
|
597
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_FORCE_PUSH,
|
|
598
|
+
list(spec.notes) or ["remote history destruction"])
|
|
599
|
+
if spec.undeterminable:
|
|
600
|
+
return _block_undeterminable_effect(spec)
|
|
601
|
+
if spec.wildcard and spec.kind in (KIND_GIT_CLEAN, KIND_GIT_DISCARD):
|
|
602
|
+
return Verdict(DECISION_BLOCK, CODE_BLOCK_WILDCARD,
|
|
603
|
+
["Git target globs are opaque"])
|
|
604
|
+
|
|
605
|
+
# Shape facts ask; they never masquerade as effect-uncertainty. But a
|
|
606
|
+
# shape rule describes *compensation* difficulty, never effect scope:
|
|
607
|
+
# when the target set also trips a hard boundary, that boundary wins.
|
|
608
|
+
# Without this, `cd /tmp && rm -rf /home` degrades a hard refusal into
|
|
609
|
+
# an ASK - and any auto-approving host grants an ASK silently, which is
|
|
610
|
+
# the incident finding described in docs/development-note-unguarded-deletion.md.
|
|
611
|
+
if spec.shape in ("F1", "F2"):
|
|
612
|
+
ask_code = (CODE_ASK_COMPOUND_CWD_DELETE if spec.shape == "F1"
|
|
613
|
+
else CODE_ASK_COMPOUND_CREATE_DELETE)
|
|
614
|
+
if spec.kind == KIND_FS_DELETE and spec.targets:
|
|
615
|
+
path_specs = classify_paths(
|
|
616
|
+
spec.targets, ctx.base_dir, ctx.workspace, ctx.trash_root)
|
|
617
|
+
boundary = decide_path_batch(
|
|
618
|
+
path_specs, ctx, recursive=spec.recursive)
|
|
619
|
+
hard = [boundary] if boundary.blocked else []
|
|
620
|
+
if hard:
|
|
621
|
+
return worst(hard)
|
|
622
|
+
return _ask_compound(spec, ask_code)
|
|
623
|
+
|
|
624
|
+
if spec.kind == KIND_FS_DELETE:
|
|
625
|
+
if spec.dry_run:
|
|
626
|
+
# A dry run mutates nothing: PowerShell's `-WhatIf` (and only a
|
|
627
|
+
# literal `$true`, never a variable - that stays undeterminable)
|
|
628
|
+
# reaches this branch. Nothing to relocate, nothing to refuse.
|
|
629
|
+
return Verdict(DECISION_ALLOW, CODE_ALLOW_NOOP,
|
|
630
|
+
list(spec.notes) or ["dry run: no effect"])
|
|
631
|
+
if not spec.targets:
|
|
632
|
+
return Verdict(DECISION_ALLOW, CODE_ALLOW_NOOP)
|
|
633
|
+
path_specs = classify_paths(
|
|
634
|
+
spec.targets, ctx.base_dir, ctx.workspace, ctx.trash_root)
|
|
635
|
+
return decide_path_batch(path_specs, ctx, recursive=spec.recursive)
|
|
636
|
+
|
|
637
|
+
if spec.kind == KIND_GIT_CLEAN:
|
|
638
|
+
if spec.dry_run:
|
|
639
|
+
return Verdict(DECISION_ALLOW, CODE_ALLOW_NOOP,
|
|
640
|
+
["git clean dry run"])
|
|
641
|
+
return Verdict(
|
|
642
|
+
DECISION_RELOCATE, CODE_RELOCATE_VIA_CLEAN_ENUMERATE,
|
|
643
|
+
["enumerate via git clean -n, relocate matches, then let the "
|
|
644
|
+
"command run"],
|
|
645
|
+
payload={"paths": spec.targets},
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
if spec.kind == KIND_GIT_RESET_HARD:
|
|
649
|
+
return Verdict(
|
|
650
|
+
DECISION_SNAPSHOT, CODE_SNAPSHOT_GIT_STASH,
|
|
651
|
+
["snapshot tracked modifications via git stash create/store "
|
|
652
|
+
"before reset --hard"],
|
|
653
|
+
)
|
|
654
|
+
|
|
655
|
+
if spec.kind == KIND_GIT_DISCARD:
|
|
656
|
+
return Verdict(
|
|
657
|
+
DECISION_SNAPSHOT, CODE_SNAPSHOT_GIT_STASH,
|
|
658
|
+
["snapshot tracked modifications before discarding "
|
|
659
|
+
"working-tree changes"],
|
|
660
|
+
)
|
|
661
|
+
|
|
662
|
+
return None
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def decide_ops(specs: List[OpSpec], ctx: PolicyContext) -> List[Verdict]:
|
|
666
|
+
"""All decisions for a command line; empty list means nothing destructive."""
|
|
667
|
+
verdicts = []
|
|
668
|
+
for spec in specs:
|
|
669
|
+
verdict = decide_op(spec, ctx)
|
|
670
|
+
if verdict is not None:
|
|
671
|
+
verdict.payload.setdefault("op", spec.op)
|
|
672
|
+
verdict.payload.setdefault("kind", spec.kind)
|
|
673
|
+
verdicts.append(verdict)
|
|
674
|
+
return verdicts
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
# --------------------------------------------------------------------------
|
|
678
|
+
# exfil-guard: text-span decisions (design 1.3)
|
|
679
|
+
# --------------------------------------------------------------------------
|
|
680
|
+
#
|
|
681
|
+
# Same Decision Protocol, different input type. `decide_spans` is a pure
|
|
682
|
+
# function of (spans, channel, workspace, mode) - it holds no payload bytes
|
|
683
|
+
# and returns verdicts whose payload carries only offsets, rule ids and
|
|
684
|
+
# placeholders (never the matched content). First-match-wins, like the
|
|
685
|
+
# delete-guard rule table.
|
|
686
|
+
#
|
|
687
|
+
# The asymmetric tolerance from the analysis (0.1) is encoded here: secret
|
|
688
|
+
# rules are strict (a false ALLOW is a permanent leak), path rules are quiet
|
|
689
|
+
# (a false SANITIZE corrupts output and erodes trust).
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _span_verdict(decision: str, code: str, span, reasons=None,
|
|
693
|
+
**payload) -> Verdict:
|
|
694
|
+
verdict = Verdict(decision=decision, code=code, reasons=list(reasons or []))
|
|
695
|
+
verdict.payload.update({
|
|
696
|
+
"rule_id": span.rule_id,
|
|
697
|
+
"family": span.family,
|
|
698
|
+
"confidence": span.confidence,
|
|
699
|
+
"channel": span.channel,
|
|
700
|
+
"span": [span.start, span.end],
|
|
701
|
+
"length": span.length,
|
|
702
|
+
})
|
|
703
|
+
verdict.payload.update(payload)
|
|
704
|
+
return verdict
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def _span_is_unrewritable(channel) -> bool:
|
|
708
|
+
"""True when the guard cannot hand back a rewritten payload."""
|
|
709
|
+
return not channel.rewritable
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _blocked_channel(channel) -> bool:
|
|
713
|
+
"""Immutable + persistent: refuse rather than emit what cannot be undone."""
|
|
714
|
+
return channel.default_decision == DECISION_BLOCK
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def decide_span(span, ctx, channel=None) -> Verdict:
|
|
718
|
+
"""Map one SpanSpec to a Verdict (facts -> decision, first match wins)."""
|
|
719
|
+
if channel is None and getattr(span, "channel", ""):
|
|
720
|
+
# The caller may pass the channel on the span instead of as a
|
|
721
|
+
# Channel object; resolve it once, so an *unknown* name still
|
|
722
|
+
# reaches the fail-closed branch below rather than being ignored.
|
|
723
|
+
channel = get_channel(span.channel)
|
|
724
|
+
reasons = list(getattr(span, "notes", []) or [])
|
|
725
|
+
reasons.append("rule " + span.rule_id)
|
|
726
|
+
|
|
727
|
+
is_secret = span.family == redaction.FAMILY_SECRET
|
|
728
|
+
deterministic = span.confidence == redaction.CONFIDENCE_DETERMINISTIC
|
|
729
|
+
|
|
730
|
+
# --- 1. a secret source we cannot scan: fail closed -------------------
|
|
731
|
+
if getattr(span, "source_dump", False):
|
|
732
|
+
return _span_verdict(DECISION_BLOCK, CODE_BLOCK_SECRET_SOURCE_DUMP,
|
|
733
|
+
span, reasons)
|
|
734
|
+
|
|
735
|
+
# --- 2. placeholder / provably benign --------------------------------
|
|
736
|
+
if getattr(span, "placeholder", False):
|
|
737
|
+
code = (CODE_ALLOW_SECRET_PLACEHOLDER if is_secret
|
|
738
|
+
else CODE_ALLOW_PATH_IN_WORKSPACE)
|
|
739
|
+
return _span_verdict(DECISION_ALLOW, code, span, reasons)
|
|
740
|
+
|
|
741
|
+
# --- 3. paths inside the workspace are not host identifiers ----------
|
|
742
|
+
if not is_secret and span.rule_id == redaction.RULE_WORKSPACE_PATH and \
|
|
743
|
+
not getattr(span, "at_workspace_root", False):
|
|
744
|
+
return _span_verdict(DECISION_ALLOW, CODE_ALLOW_PATH_IN_WORKSPACE,
|
|
745
|
+
span, reasons)
|
|
746
|
+
|
|
747
|
+
# --- 4. RESTRICTED tightens, never loosens ---------------------------
|
|
748
|
+
restricted = ctx is not None and getattr(ctx, "mode", None) == \
|
|
749
|
+
MODE_RESTRICTED
|
|
750
|
+
|
|
751
|
+
# --- 5. channel shape decides SANITIZE vs ASK vs BLOCK ---------------
|
|
752
|
+
if channel is None:
|
|
753
|
+
# Invalid configuration: the guard cannot say what would carry the
|
|
754
|
+
# bytes, so it cannot say it is safe. Fail closed.
|
|
755
|
+
return _span_verdict(DECISION_BLOCK, CODE_BLOCK_OUTPUT_UNSCANNABLE,
|
|
756
|
+
span, reasons + ["unknown egress channel"])
|
|
757
|
+
|
|
758
|
+
if _blocked_channel(channel):
|
|
759
|
+
# Immutable history: the emission cannot be taken back, so refuse
|
|
760
|
+
# rather than rewrite (design 4.4, first bullet). This outranks
|
|
761
|
+
# `rewritable`, which is why a commit message BLOCKs even though
|
|
762
|
+
# rewriting the argv would be technically possible.
|
|
763
|
+
code = (CODE_BLOCK_SECRET_EMISSION if is_secret
|
|
764
|
+
else CODE_BLOCK_PATH_EMISSION)
|
|
765
|
+
return _span_verdict(DECISION_BLOCK, code, span, reasons)
|
|
766
|
+
|
|
767
|
+
if _span_is_unrewritable(channel):
|
|
768
|
+
code = (CODE_ASK_SECRET_EMISSION if is_secret
|
|
769
|
+
else CODE_ASK_PATH_EMISSION)
|
|
770
|
+
return _span_verdict(DECISION_ASK, code, span, reasons)
|
|
771
|
+
|
|
772
|
+
# --- 6. rewritable: secrets are redacted, paths rewritten ------------
|
|
773
|
+
if is_secret:
|
|
774
|
+
# Deterministic (T1) matches auto-SANITIZE. A contextual match is
|
|
775
|
+
# still SANITIZE behind the context gate (design 5.3), but only
|
|
776
|
+
# where the rule is enabled; otherwise a human decides.
|
|
777
|
+
if deterministic or getattr(span, "context_gate", False):
|
|
778
|
+
return _span_verdict(DECISION_SANITIZE,
|
|
779
|
+
CODE_SANITIZE_SECRET_REDACT, span, reasons)
|
|
780
|
+
return _span_verdict(DECISION_ASK, CODE_ASK_SECRET_EMISSION,
|
|
781
|
+
span, reasons)
|
|
782
|
+
|
|
783
|
+
if span.rule_id == redaction.RULE_SYSTEM_PATH:
|
|
784
|
+
# System prefixes are not host-identifying (design 3.1).
|
|
785
|
+
return _span_verdict(DECISION_ALLOW, CODE_ALLOW_PATH_IN_WORKSPACE,
|
|
786
|
+
span, reasons)
|
|
787
|
+
|
|
788
|
+
if deterministic or getattr(span, "at_workspace_root", False):
|
|
789
|
+
return _span_verdict(DECISION_SANITIZE, CODE_SANITIZE_PATH_REWRITE,
|
|
790
|
+
span, reasons)
|
|
791
|
+
|
|
792
|
+
# A generic absolute path with no prefix correlation is contextual: the
|
|
793
|
+
# default is quiet (design 3.4), so a human decides whether it matters.
|
|
794
|
+
if restricted:
|
|
795
|
+
return _span_verdict(DECISION_SANITIZE, CODE_SANITIZE_PATH_REWRITE,
|
|
796
|
+
span, reasons + ["restricted mode: strict"])
|
|
797
|
+
return _span_verdict(DECISION_ASK, CODE_ASK_PATH_EMISSION, span, reasons)
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def decide_spans(spans, ctx=None, channel=None, workspace=None,
|
|
801
|
+
mode=None) -> List[Verdict]:
|
|
802
|
+
"""All decisions for a payload; empty list means nothing matched.
|
|
803
|
+
|
|
804
|
+
`ctx` is a PolicyContext when the caller has one (reuse of the existing
|
|
805
|
+
mode state), otherwise `mode` alone is accepted so `check_span.py` stays
|
|
806
|
+
usable without a workspace or quarantine.
|
|
807
|
+
"""
|
|
808
|
+
if ctx is None:
|
|
809
|
+
ctx = PolicyContext(workspace=workspace or "",
|
|
810
|
+
trash_root="", base_dir=workspace or "",
|
|
811
|
+
mode=mode or MODE_NORMAL)
|
|
812
|
+
verdicts = []
|
|
813
|
+
for span in spans:
|
|
814
|
+
if channel is not None:
|
|
815
|
+
span.channel = channel.name
|
|
816
|
+
verdicts.append(decide_span(span, ctx, channel))
|
|
817
|
+
return verdicts
|