braid-coding-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""纯判定:把规则集合与一次请求折成 allow / ask / deny。
|
|
2
|
+
|
|
3
|
+
这一层不读文件、不等待批准、不改会话状态。:class:`~braid_coding_agent.permissions.engine.PermissionEngine`
|
|
4
|
+
负责批准与记忆,判定错在哪里可以直接用本模块的测试定位。
|
|
5
|
+
|
|
6
|
+
## 两个层次
|
|
7
|
+
|
|
8
|
+
**维度内按具体度**:工具、命令、路径、域名各是一组。同一组里取具体度最高的一条,
|
|
9
|
+
具体度相同再按 deny > ask > allow。
|
|
10
|
+
|
|
11
|
+
**维度之间按严重程度**:一组明确说 deny,另一组说 allow,结果是 deny。具体度只
|
|
12
|
+
解决同一组内部的冲突,不能让一条更具体的 allow 把另一组的 deny 盖掉。这条规则
|
|
13
|
+
堵住两类绕过:``tools: bash = deny`` 被某条命令 allow 放行,以及复合命令里一段
|
|
14
|
+
allow、另一段 deny 被 allow 的具体度压住。
|
|
15
|
+
|
|
16
|
+
``default`` 兜底只在没有任何显式维度命中时生效。模式只改这一条兜底的动作:
|
|
17
|
+
``full`` 把兜底 ``ask`` 变成 ``allow``,``accept-edits`` 只对写工具这样做。显式
|
|
18
|
+
规则的 ask / deny 不受模式影响。
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from fnmatch import fnmatchcase
|
|
26
|
+
|
|
27
|
+
from braid_coding_agent.permissions.matching import (
|
|
28
|
+
allow_variants,
|
|
29
|
+
match_domain,
|
|
30
|
+
match_path,
|
|
31
|
+
match_tool,
|
|
32
|
+
segment_variants,
|
|
33
|
+
)
|
|
34
|
+
from braid_coding_agent.permissions.model import (
|
|
35
|
+
BUILTIN_BASH_RULES,
|
|
36
|
+
BUILTIN_PATH_RULES,
|
|
37
|
+
PermissionAction,
|
|
38
|
+
PermissionContext,
|
|
39
|
+
PermissionDecision,
|
|
40
|
+
PermissionRequest,
|
|
41
|
+
PermissionSettings,
|
|
42
|
+
RuleRef,
|
|
43
|
+
RuleScope,
|
|
44
|
+
RuleSet,
|
|
45
|
+
ScopedRule,
|
|
46
|
+
)
|
|
47
|
+
from braid_coding_agent.permissions.policy import mode_block_reason, mode_default
|
|
48
|
+
|
|
49
|
+
_ACTION_STRENGTH: Mapping[PermissionAction, int] = {"deny": 2, "ask": 1, "allow": 0}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(slots=True, frozen=True)
|
|
53
|
+
class RuleHit:
|
|
54
|
+
"""一条命中记录。``rule`` 为空表示模式、外部目录或动态命令的兜底标记。"""
|
|
55
|
+
|
|
56
|
+
action: PermissionAction
|
|
57
|
+
specificity: int
|
|
58
|
+
label: str
|
|
59
|
+
rule: ScopedRule | None = None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def compile_ruleset(settings: PermissionSettings) -> RuleSet:
|
|
63
|
+
"""把配置折成规则集合。``settings.rules`` 非空时以它为准,否则从四张表现编译。"""
|
|
64
|
+
builtin: list[ScopedRule] = [
|
|
65
|
+
ScopedRule("bash", pattern, action, "builtin", "builtin")
|
|
66
|
+
for pattern, action in BUILTIN_BASH_RULES.items()
|
|
67
|
+
]
|
|
68
|
+
builtin.extend(
|
|
69
|
+
ScopedRule("paths", pattern, action, "builtin", "builtin")
|
|
70
|
+
for pattern, action in BUILTIN_PATH_RULES.items()
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
configured = settings.rules or tuple(_rules_from_tables(settings))
|
|
74
|
+
return RuleSet(tuple((*builtin, *configured)))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def evaluate_rules(settings: PermissionSettings, request: PermissionRequest) -> PermissionDecision:
|
|
78
|
+
"""兼容入口:从一份设置编译规则并判定。"""
|
|
79
|
+
context = PermissionContext(
|
|
80
|
+
request=request,
|
|
81
|
+
mode=settings.mode,
|
|
82
|
+
workspace=request.cwd,
|
|
83
|
+
default=settings.default,
|
|
84
|
+
project_trusted=settings.project_trusted,
|
|
85
|
+
)
|
|
86
|
+
return evaluate(compile_ruleset(settings), context)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def evaluate(ruleset: RuleSet, context: PermissionContext) -> PermissionDecision:
|
|
90
|
+
"""按模式硬限制、维度内具体度、维度间严重程度给出结论。"""
|
|
91
|
+
request = context.request
|
|
92
|
+
mode = context.mode
|
|
93
|
+
|
|
94
|
+
if mode in ("read-only", "plan"):
|
|
95
|
+
blocked = mode_block_reason(mode, request)
|
|
96
|
+
if blocked is not None:
|
|
97
|
+
label = f"mode:{mode}"
|
|
98
|
+
return PermissionDecision(
|
|
99
|
+
action="deny",
|
|
100
|
+
reason=(
|
|
101
|
+
f"权限拒绝:{blocked}(规则 {label})。"
|
|
102
|
+
"请改用只读工具,或请用户调整权限模式与规则。"
|
|
103
|
+
),
|
|
104
|
+
rule=label,
|
|
105
|
+
tool_name=request.tool_name,
|
|
106
|
+
tool_call_id=request.tool_call_id,
|
|
107
|
+
fingerprint=request.fingerprint,
|
|
108
|
+
origin=None,
|
|
109
|
+
matched=(),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
winners, matched_hits = collect_hits(ruleset, request, default=context.default)
|
|
113
|
+
winner = max(
|
|
114
|
+
winners,
|
|
115
|
+
key=lambda hit: (_ACTION_STRENGTH[hit.action], hit.specificity),
|
|
116
|
+
)
|
|
117
|
+
action = winner.action
|
|
118
|
+
label = winner.label
|
|
119
|
+
if winner.rule is None and winner.label in ("bash:*", "default:*"):
|
|
120
|
+
relaxed = mode_default(mode, request.tool_name, action)
|
|
121
|
+
if relaxed != action:
|
|
122
|
+
action = relaxed
|
|
123
|
+
label = f"mode:{mode}/{winner.label}"
|
|
124
|
+
matched = _matched_rules(matched_hits)
|
|
125
|
+
origin: RuleScope | None = winner.rule.scope if winner.rule is not None else None
|
|
126
|
+
|
|
127
|
+
if action == "deny":
|
|
128
|
+
reason = f"权限拒绝:命中 {label}(deny)。请改用只读工具,或请用户调整权限模式与规则。"
|
|
129
|
+
elif action == "allow":
|
|
130
|
+
reason = f"权限允许:命中 {label}(allow)"
|
|
131
|
+
else:
|
|
132
|
+
reason = f"命中 {label}(ask)"
|
|
133
|
+
return PermissionDecision(
|
|
134
|
+
action=action,
|
|
135
|
+
reason=reason,
|
|
136
|
+
rule=label,
|
|
137
|
+
tool_name=request.tool_name,
|
|
138
|
+
tool_call_id=request.tool_call_id,
|
|
139
|
+
fingerprint=request.fingerprint,
|
|
140
|
+
origin=origin,
|
|
141
|
+
matched=matched,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def collect_hits(
|
|
146
|
+
ruleset: RuleSet,
|
|
147
|
+
request: PermissionRequest,
|
|
148
|
+
*,
|
|
149
|
+
default: PermissionAction,
|
|
150
|
+
) -> tuple[list[RuleHit], list[RuleHit]]:
|
|
151
|
+
"""收集每个维度的胜出项与全部命中规则。
|
|
152
|
+
|
|
153
|
+
返回 ``(维度胜出项, 全部命中规则)``。前者用于给出最终结论,后者用于展示与审计。
|
|
154
|
+
"""
|
|
155
|
+
matched: list[RuleHit] = []
|
|
156
|
+
seen: set[tuple[str, str, str, str]] = set()
|
|
157
|
+
|
|
158
|
+
def add(rule: ScopedRule) -> RuleHit:
|
|
159
|
+
key = (rule.table, rule.pattern, rule.effect, rule.scope)
|
|
160
|
+
hit = RuleHit(
|
|
161
|
+
action=rule.effect,
|
|
162
|
+
specificity=_specificity(rule.pattern),
|
|
163
|
+
label=f"{rule.table}:{rule.pattern}",
|
|
164
|
+
rule=rule,
|
|
165
|
+
)
|
|
166
|
+
if key not in seen:
|
|
167
|
+
seen.add(key)
|
|
168
|
+
matched.append(hit)
|
|
169
|
+
return hit
|
|
170
|
+
|
|
171
|
+
dimensions: list[RuleHit] = []
|
|
172
|
+
|
|
173
|
+
tool_hits = [
|
|
174
|
+
add(rule)
|
|
175
|
+
for rule in ruleset.by_table("tools")
|
|
176
|
+
if match_tool(request.tool_name, rule.pattern)
|
|
177
|
+
]
|
|
178
|
+
if tool_hits:
|
|
179
|
+
dimensions.append(_specificity_winner(tool_hits))
|
|
180
|
+
|
|
181
|
+
if request.command is not None:
|
|
182
|
+
bash_hits = _bash_hits(ruleset, request, default, add)
|
|
183
|
+
if bash_hits:
|
|
184
|
+
dimensions.append(_bash_winner(bash_hits))
|
|
185
|
+
|
|
186
|
+
path_hits: list[RuleHit] = []
|
|
187
|
+
for path in _path_variants(request):
|
|
188
|
+
for rule in ruleset.by_table("paths"):
|
|
189
|
+
if match_path(rule.pattern, path, request.cwd):
|
|
190
|
+
path_hits.append(add(rule))
|
|
191
|
+
if path_hits:
|
|
192
|
+
dimensions.append(_specificity_winner(path_hits))
|
|
193
|
+
|
|
194
|
+
if request.host is not None:
|
|
195
|
+
domain_hits = [
|
|
196
|
+
add(rule)
|
|
197
|
+
for rule in ruleset.by_table("domains")
|
|
198
|
+
if match_domain(rule.pattern, request.host)
|
|
199
|
+
]
|
|
200
|
+
if domain_hits:
|
|
201
|
+
dimensions.append(_specificity_winner(domain_hits))
|
|
202
|
+
|
|
203
|
+
if request.external:
|
|
204
|
+
dimensions.append(
|
|
205
|
+
RuleHit(
|
|
206
|
+
action="ask",
|
|
207
|
+
specificity=0,
|
|
208
|
+
label="external_directory:工作目录之外的路径",
|
|
209
|
+
)
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
if dimensions:
|
|
213
|
+
return dimensions, matched
|
|
214
|
+
return [RuleHit(action=default, specificity=-1, label="default:*")], matched
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _bash_hits(
|
|
218
|
+
ruleset: RuleSet,
|
|
219
|
+
request: PermissionRequest,
|
|
220
|
+
default: PermissionAction,
|
|
221
|
+
add: Callable[[ScopedRule], RuleHit],
|
|
222
|
+
) -> list[RuleHit]:
|
|
223
|
+
"""每个命令段先取段内胜出项,再交给调用方按严重程度合并。"""
|
|
224
|
+
bash_default: PermissionAction = "deny" if default == "deny" else "ask"
|
|
225
|
+
winners: list[RuleHit] = []
|
|
226
|
+
for segment in request.segments:
|
|
227
|
+
segment_hits: list[RuleHit] = []
|
|
228
|
+
for rule in ruleset.by_table("bash"):
|
|
229
|
+
variants = (
|
|
230
|
+
allow_variants(segment) if rule.effect == "allow" else segment_variants(segment)
|
|
231
|
+
)
|
|
232
|
+
if any(_bash_match(variant, rule.pattern) for variant in variants):
|
|
233
|
+
segment_hits.append(add(rule))
|
|
234
|
+
segment_hits.append(RuleHit(action=bash_default, specificity=0, label="bash:*"))
|
|
235
|
+
winners.append(_specificity_winner(segment_hits))
|
|
236
|
+
if request.dynamic:
|
|
237
|
+
winners.append(
|
|
238
|
+
RuleHit(
|
|
239
|
+
action="ask",
|
|
240
|
+
specificity=0,
|
|
241
|
+
label="dynamic_command:命令包含动态求值",
|
|
242
|
+
)
|
|
243
|
+
)
|
|
244
|
+
return winners
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _specificity_winner(hits: list[RuleHit]) -> RuleHit:
|
|
248
|
+
"""维度内:具体度最高,具体度相同取最严。"""
|
|
249
|
+
best = max(hit.specificity for hit in hits)
|
|
250
|
+
return max(
|
|
251
|
+
(hit for hit in hits if hit.specificity == best),
|
|
252
|
+
key=lambda hit: _ACTION_STRENGTH[hit.action],
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _bash_winner(hits: list[RuleHit]) -> RuleHit:
|
|
257
|
+
"""命令维度内:段与段之间按严重程度合并,严重程度相同取具体度高的。
|
|
258
|
+
|
|
259
|
+
一段 deny 必须让整条命令 deny,哪怕另一段命中了一条更具体的 allow。
|
|
260
|
+
"""
|
|
261
|
+
return max(
|
|
262
|
+
hits,
|
|
263
|
+
key=lambda hit: (_ACTION_STRENGTH[hit.action], hit.specificity),
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _rules_from_tables(settings: PermissionSettings) -> Iterator[ScopedRule]:
|
|
268
|
+
for pattern, action in settings.tools.items():
|
|
269
|
+
yield ScopedRule("tools", pattern, action, "global", "settings")
|
|
270
|
+
for pattern, action in settings.bash.items():
|
|
271
|
+
yield ScopedRule("bash", pattern, action, "global", "settings")
|
|
272
|
+
for pattern, action in settings.paths.items():
|
|
273
|
+
yield ScopedRule("paths", pattern, action, "global", "settings")
|
|
274
|
+
for pattern, action in settings.domains.items():
|
|
275
|
+
yield ScopedRule("domains", pattern, action, "global", "settings")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _specificity(pattern: str) -> int:
|
|
279
|
+
return sum(1 for char in pattern if char not in "*?")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _bash_match(segment: str, pattern: str) -> bool:
|
|
283
|
+
return fnmatchcase(segment, pattern)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _path_variants(request: PermissionRequest) -> tuple[str, ...]:
|
|
287
|
+
values: list[str] = []
|
|
288
|
+
for path in (*request.paths, *request.real_paths):
|
|
289
|
+
if path not in values:
|
|
290
|
+
values.append(path)
|
|
291
|
+
return tuple(values)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _matched_rules(hits: list[RuleHit]) -> tuple[RuleRef, ...]:
|
|
295
|
+
ordered = sorted(hits, key=lambda hit: hit.specificity, reverse=True)
|
|
296
|
+
rules: list[RuleRef] = []
|
|
297
|
+
seen: set[tuple[str, str, str, str]] = set()
|
|
298
|
+
for hit in ordered:
|
|
299
|
+
if hit.rule is None:
|
|
300
|
+
continue
|
|
301
|
+
key = (hit.rule.table, hit.rule.pattern, hit.rule.effect, hit.rule.scope)
|
|
302
|
+
if key in seen:
|
|
303
|
+
continue
|
|
304
|
+
seen.add(key)
|
|
305
|
+
rules.append(hit.rule)
|
|
306
|
+
return tuple(rules)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
__all__ = ["RuleHit", "collect_hits", "compile_ruleset", "evaluate", "evaluate_rules"]
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""纯匹配函数:工具名、路径、主机与 shell 命令段。
|
|
2
|
+
|
|
3
|
+
## 为什么命令要分段
|
|
4
|
+
|
|
5
|
+
``fnmatchcase("git status && rm -rf ~", "git status*")`` 的结果是真:``*`` 跨过了
|
|
6
|
+
``&&`` 与后面的命令。把整条命令当一个字符串匹配,等于让一条 allow 规则放行它后面
|
|
7
|
+
追加的任何东西。这里按 shell 运算符切段,每一段单独判定;任一段 deny 则整条 deny,
|
|
8
|
+
任一段 ask 或动态求值则整条 ask,全部 allow 才 allow。
|
|
9
|
+
|
|
10
|
+
## 这套分析能做什么、不能做什么
|
|
11
|
+
|
|
12
|
+
它能挡住常见的复合命令、绝对路径程序名与包装器(``timeout``、``env``、``nice``)。
|
|
13
|
+
它挡不住刻意构造的混淆:变量拼接、编码后的命令、脚本文件内部的行为。权限规则是
|
|
14
|
+
提示层的边界,真正的执行边界是沙箱。这句话要写进用户文档。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import posixpath
|
|
21
|
+
import re
|
|
22
|
+
import shlex
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from fnmatch import fnmatchcase
|
|
25
|
+
|
|
26
|
+
from braid_coding_agent.sandbox.policy import host_matches
|
|
27
|
+
from braid_coding_agent.tools.path_utils import relative_posix, to_posix
|
|
28
|
+
|
|
29
|
+
#: 环境变量赋值的前缀,例如 ``FOO=bar cmd``。
|
|
30
|
+
_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
|
|
31
|
+
#: 会把后面的参数当成命令执行的包装器。
|
|
32
|
+
_WRAPPERS = frozenset({"env", "timeout", "nice", "nohup", "command", "builtin", "time"})
|
|
33
|
+
#: 自带命令求值能力的程序,命中即按动态命令处理。
|
|
34
|
+
_DYNAMIC_PROGRAMS = frozenset(
|
|
35
|
+
{"eval", "exec", "source", ".", "xargs", "watch", "setsid", "ionice", "flock"}
|
|
36
|
+
)
|
|
37
|
+
#: 带 ``-c`` 参数执行脚本的 shell。
|
|
38
|
+
_SHELLS = frozenset({"bash", "sh", "zsh", "dash", "ksh", "fish"})
|
|
39
|
+
#: 命令文本里出现这些片段就说明存在动态求值。
|
|
40
|
+
_DYNAMIC_MARKERS = ("$(", "`", "${", "$'", "<(", ">(", "<<")
|
|
41
|
+
#: ``find`` 的这些动作会执行命令或删除文件,不能只看程序名。
|
|
42
|
+
_FIND_ACTIONS = frozenset({"-exec", "-execdir", "-delete", "-ok", "-okdir"})
|
|
43
|
+
#: 分段的运算符。``<``、``>`` 属于重定向,留在段内。
|
|
44
|
+
_SEPARATORS = frozenset({";", "&&", "||", "|", "&", "(", ")", ";;", "|&"})
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(slots=True, frozen=True)
|
|
48
|
+
class ShellCommand:
|
|
49
|
+
"""一条命令的分段结果。``error`` 非空表示无法安全分段。"""
|
|
50
|
+
|
|
51
|
+
segments: tuple[str, ...]
|
|
52
|
+
dynamic: bool
|
|
53
|
+
error: str | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def match_tool(name: str, pattern: str) -> bool:
|
|
57
|
+
"""工具名按 ``fnmatch`` 匹配,大小写敏感。"""
|
|
58
|
+
return fnmatchcase(name, pattern)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def match_domain(pattern: str, host: str) -> bool:
|
|
62
|
+
"""主机规则:``*.example.com`` 匹配子域,``example.com`` 只匹配本身。"""
|
|
63
|
+
return host_matches(pattern, host)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def match_path(pattern: str, path: str, root: str) -> bool:
|
|
67
|
+
"""路径规则同时匹配相对写法与绝对写法;``**/`` 前缀允许零层目录。"""
|
|
68
|
+
expanded = to_posix(os.path.expanduser(pattern))
|
|
69
|
+
variants = [expanded]
|
|
70
|
+
if expanded.startswith("**/"):
|
|
71
|
+
variants.append(expanded[3:])
|
|
72
|
+
candidates = (relative_posix(path, root), path)
|
|
73
|
+
return any(fnmatchcase(candidate, variant) for variant in variants for candidate in candidates)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def real_path_variants(path: str) -> tuple[str, ...]:
|
|
77
|
+
"""词法路径与真实路径。符号链接指向别处时,两份都要参与规则匹配。"""
|
|
78
|
+
real = to_posix(os.path.realpath(path))
|
|
79
|
+
if real == path:
|
|
80
|
+
return (path,)
|
|
81
|
+
return (path, real)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def is_external(path: str, root: str) -> bool:
|
|
85
|
+
"""路径是否在 ``root`` 之外。调用方负责传入已经归一化的路径。"""
|
|
86
|
+
return path != root and not path.startswith(root + "/")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def split_shell_command(command: str) -> ShellCommand:
|
|
90
|
+
"""按 shell 运算符切分命令。无法分段时返回空段与 ``dynamic=True``。
|
|
91
|
+
|
|
92
|
+
换行在分词前替换成分号:引号内的换行也会被切开。这会多产生几段,判定更保守,
|
|
93
|
+
不会少检查一段。
|
|
94
|
+
"""
|
|
95
|
+
normalized = command.replace("\r\n", "\n").replace("\n", " ; ")
|
|
96
|
+
lexer = shlex.shlex(normalized, posix=True, punctuation_chars=";&|()<>")
|
|
97
|
+
lexer.whitespace_split = True
|
|
98
|
+
try:
|
|
99
|
+
tokens = list(lexer)
|
|
100
|
+
except ValueError as exc:
|
|
101
|
+
return ShellCommand(segments=(), dynamic=True, error=str(exc))
|
|
102
|
+
|
|
103
|
+
segments: list[str] = []
|
|
104
|
+
current: list[str] = []
|
|
105
|
+
for token in tokens:
|
|
106
|
+
if token in _SEPARATORS or (token and set(token) <= set(";&|()")):
|
|
107
|
+
_flush(current, segments)
|
|
108
|
+
current = []
|
|
109
|
+
continue
|
|
110
|
+
current.append(token)
|
|
111
|
+
_flush(current, segments)
|
|
112
|
+
|
|
113
|
+
dynamic = _has_dynamic_marker(command) or any(_segment_is_dynamic(seg) for seg in segments)
|
|
114
|
+
return ShellCommand(segments=tuple(segments), dynamic=dynamic)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def effective_segment(segment: str) -> str:
|
|
118
|
+
"""去掉前置环境变量赋值与包装器后的命令段。无法分词时原样返回。"""
|
|
119
|
+
tokens = _tokens(segment)
|
|
120
|
+
if not tokens:
|
|
121
|
+
return segment.strip()
|
|
122
|
+
start = _skip_prefix(tokens)
|
|
123
|
+
if start >= len(tokens):
|
|
124
|
+
return ""
|
|
125
|
+
return " ".join(tokens[start:])
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def segment_variants(segment: str) -> tuple[str, ...]:
|
|
129
|
+
"""用于 deny 匹配的变体:有效段 + 绝对路径程序的 basename 版本。"""
|
|
130
|
+
effective = effective_segment(segment)
|
|
131
|
+
if not effective:
|
|
132
|
+
return ()
|
|
133
|
+
tokens = effective.split()
|
|
134
|
+
program = tokens[0]
|
|
135
|
+
variants = [effective]
|
|
136
|
+
if "/" in program:
|
|
137
|
+
basename = posixpath.basename(program)
|
|
138
|
+
if basename and basename != program:
|
|
139
|
+
variants.append(" ".join((basename, *tokens[1:])))
|
|
140
|
+
return tuple(variants)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def allow_variants(segment: str) -> tuple[str, ...]:
|
|
144
|
+
"""用于 allow 匹配的变体:只取有效段,绝对路径不做 basename 回退。"""
|
|
145
|
+
effective = effective_segment(segment)
|
|
146
|
+
return () if not effective else (effective,)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def command_fingerprint(command: str, segments: tuple[str, ...], dynamic: bool) -> str:
|
|
150
|
+
"""会话批准的分组键。
|
|
151
|
+
|
|
152
|
+
单段命令取前两个词,与既有行为一致。复合命令或动态命令取完整命令:否则批准
|
|
153
|
+
一次 ``git status`` 会连带放行 ``git status && echo hi``。
|
|
154
|
+
"""
|
|
155
|
+
if dynamic or len(segments) > 1:
|
|
156
|
+
return f"bash:{' '.join(command.split())}"
|
|
157
|
+
tokens = command.split()
|
|
158
|
+
return f"bash:{' '.join(tokens[:2])}"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _flush(current: list[str], segments: list[str]) -> None:
|
|
162
|
+
if not current:
|
|
163
|
+
return
|
|
164
|
+
segment = " ".join(current).strip()
|
|
165
|
+
if segment:
|
|
166
|
+
segments.append(segment)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _tokens(segment: str) -> list[str]:
|
|
170
|
+
try:
|
|
171
|
+
return shlex.split(segment, posix=True)
|
|
172
|
+
except ValueError:
|
|
173
|
+
return []
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _skip_prefix(tokens: list[str]) -> int:
|
|
177
|
+
"""跳过赋值与包装器,返回第一个真正的程序 token 的下标。"""
|
|
178
|
+
index = 0
|
|
179
|
+
while index < len(tokens):
|
|
180
|
+
token = tokens[index]
|
|
181
|
+
if _ASSIGNMENT.match(token):
|
|
182
|
+
index += 1
|
|
183
|
+
continue
|
|
184
|
+
if token not in _WRAPPERS:
|
|
185
|
+
break
|
|
186
|
+
index += 1
|
|
187
|
+
if token == "env":
|
|
188
|
+
while index < len(tokens) and (
|
|
189
|
+
tokens[index].startswith("-") or _ASSIGNMENT.match(tokens[index])
|
|
190
|
+
):
|
|
191
|
+
index += 1
|
|
192
|
+
elif token in ("timeout", "nice", "time"):
|
|
193
|
+
while index < len(tokens) and tokens[index].startswith("-"):
|
|
194
|
+
index += 1
|
|
195
|
+
if token == "timeout" and index < len(tokens):
|
|
196
|
+
index += 1
|
|
197
|
+
return index
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _has_dynamic_marker(command: str) -> bool:
|
|
201
|
+
return any(marker in command for marker in _DYNAMIC_MARKERS)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _segment_is_dynamic(segment: str) -> bool:
|
|
205
|
+
tokens = _tokens(segment)
|
|
206
|
+
if not tokens:
|
|
207
|
+
return False
|
|
208
|
+
start = _skip_prefix(tokens)
|
|
209
|
+
if start >= len(tokens):
|
|
210
|
+
return False
|
|
211
|
+
program = posixpath.basename(tokens[start])
|
|
212
|
+
if program in _DYNAMIC_PROGRAMS:
|
|
213
|
+
return True
|
|
214
|
+
if program in _SHELLS and any(token == "-c" for token in tokens[start + 1 :]):
|
|
215
|
+
return True
|
|
216
|
+
if program == "env" and any(token == "-S" for token in tokens[start + 1 :]):
|
|
217
|
+
return True
|
|
218
|
+
return bool(program == "find" and any(token in _FIND_ACTIONS for token in tokens[start + 1 :]))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
__all__ = [
|
|
222
|
+
"ShellCommand",
|
|
223
|
+
"allow_variants",
|
|
224
|
+
"command_fingerprint",
|
|
225
|
+
"effective_segment",
|
|
226
|
+
"is_external",
|
|
227
|
+
"match_domain",
|
|
228
|
+
"match_path",
|
|
229
|
+
"match_tool",
|
|
230
|
+
"real_path_variants",
|
|
231
|
+
"segment_variants",
|
|
232
|
+
"split_shell_command",
|
|
233
|
+
]
|