phiward 0.2.0b1__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.
- phiward/__init__.py +8 -0
- phiward/__main__.py +5 -0
- phiward/_toml.py +211 -0
- phiward/adapters/__init__.py +105 -0
- phiward/adapters/claude.py +429 -0
- phiward/broker.py +831 -0
- phiward/carryover.py +1613 -0
- phiward/claude_settings.py +1307 -0
- phiward/cli.py +110 -0
- phiward/config.py +936 -0
- phiward/confine.py +476 -0
- phiward/copying.py +533 -0
- phiward/core.py +105 -0
- phiward/data/agents-section.md +43 -0
- phiward/doctor.py +1132 -0
- phiward/fasthook.py +70 -0
- phiward/fsinfo.py +241 -0
- phiward/gateway.py +159 -0
- phiward/githooks.py +248 -0
- phiward/guards/__init__.py +0 -0
- phiward/guards/protected_paths.py +1138 -0
- phiward/hidden.py +281 -0
- phiward/init.py +155 -0
- phiward/install.py +828 -0
- phiward/inventory.py +173 -0
- phiward/mcp.py +186 -0
- phiward/mcp_config.py +1736 -0
- phiward/names.py +5 -0
- phiward/packs/dates.toml +17 -0
- phiward/packs/genomics.toml +51 -0
- phiward/packs/msk.toml +32 -0
- phiward/pathid.py +403 -0
- phiward/pathmatch.py +98 -0
- phiward/paths.py +942 -0
- phiward/pin.py +214 -0
- phiward/procinfo.py +73 -0
- phiward/remote.py +448 -0
- phiward/run.py +788 -0
- phiward/safeio.py +84 -0
- phiward/sanitize.py +691 -0
- phiward/selfcheck.py +1506 -0
- phiward/service.py +321 -0
- phiward/session_note.py +86 -0
- phiward/setup_cmd.py +886 -0
- phiward/shell.py +504 -0
- phiward/wholetool.py +1463 -0
- phiward-0.2.0b1.dist-info/METADATA +147 -0
- phiward-0.2.0b1.dist-info/RECORD +53 -0
- phiward-0.2.0b1.dist-info/WHEEL +5 -0
- phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
- phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
- phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
- phiward-0.2.0b1.dist-info/top_level.txt +1 -0
phiward/wholetool.py
ADDED
|
@@ -0,0 +1,1463 @@
|
|
|
1
|
+
"""`phiward launch`: run the whole agent tool in the kernel profile.
|
|
2
|
+
|
|
3
|
+
The tool itself starts inside the profile, so everything it does (its file tools, MCP servers
|
|
4
|
+
and hooks), and every child it starts, is decided by the kernel, not by a path check. The text
|
|
5
|
+
users see is HELP below; this docstring is for developers.
|
|
6
|
+
|
|
7
|
+
Writes are denied by default. They are allowed only in the project, this session's own run
|
|
8
|
+
folder (`~/.phiward/tools/<tool>/runs/<id>`) and the spool. A write place that is a link, or has
|
|
9
|
+
a link on its path, is not used. Inside the project, files that run code later stay read-only:
|
|
10
|
+
git's control files, `.git`, `.claude` and `.vscode` themselves, Claude Code's and VS Code's
|
|
11
|
+
settings and `.mcp.json`. On Linux, missing settings files are made as read-only `{}`
|
|
12
|
+
placeholders, and the git control files are compared after the session.
|
|
13
|
+
|
|
14
|
+
Carry-over (see carryover): each session runs in its own config folder, built from a trusted
|
|
15
|
+
copy and thrown away at exit. Reads of protected data and credentials are denied, and credential
|
|
16
|
+
variables are removed. The launcher runs the tool through a helper that closes every descriptor
|
|
17
|
+
it holds, writes the tool's settings without following links, and runs "launch inside launch"
|
|
18
|
+
directly only when a canary that only this profile denies is denied with EPERM.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import errno
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import secrets
|
|
26
|
+
import shutil
|
|
27
|
+
import stat
|
|
28
|
+
import struct
|
|
29
|
+
import subprocess
|
|
30
|
+
import sys
|
|
31
|
+
import time
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from typing import Callable, Dict, List, Optional, Sequence, Set, Tuple
|
|
34
|
+
|
|
35
|
+
from phiward import carryover, config, confine, pathid, pathmatch, safeio
|
|
36
|
+
from phiward.hidden import (CREDENTIALS, IPC_PATHS, KRB5_CACHE_NAMES, # noqa: F401 (moved)
|
|
37
|
+
KRB5_CACHE_PATTERNS, _kerberos_caches, _ssh_identity_files,
|
|
38
|
+
_token_paths)
|
|
39
|
+
from phiward.hidden import credentials as _credentials # noqa: E402
|
|
40
|
+
|
|
41
|
+
USAGE = ("Run an agent tool, or one program, in phiward's kernel profile (Mode B), for example "
|
|
42
|
+
"`phiward launch --tool claude`.\n"
|
|
43
|
+
"usage: phiward launch [--tool NAME] [--memory] [--report FILE] [--entry ID] [--] "
|
|
44
|
+
"[PROGRAM [ARG]...]\n")
|
|
45
|
+
HELP = USAGE + """
|
|
46
|
+
Options:
|
|
47
|
+
--tool NAME the agent tool: claude, or generic (the default). With claude and no
|
|
48
|
+
PROGRAM, it starts `claude` from your PATH.
|
|
49
|
+
--memory turn Claude Code's auto memory on (it is off by default). Its changes go
|
|
50
|
+
to quarantine like other instructions.
|
|
51
|
+
--report FILE write a JSON report there when launch ends, for a script that runs it with
|
|
52
|
+
nobody watching (`-- claude -p ...`): exit, ran, needs_review (true when the
|
|
53
|
+
tool did not run, or the session changed instructions, files that run later,
|
|
54
|
+
settings or git control files), project_changed (counts by kind) and the lines
|
|
55
|
+
launch printed. Written on every exit, as a new file moved into place. FILE
|
|
56
|
+
must be outside every place the session can write (the project, the spool,
|
|
57
|
+
the temp folder, ~/.phiward); otherwise nothing runs.
|
|
58
|
+
--entry ID written by `phiward mcp wrap` into a wrapped MCP server's entry: the
|
|
59
|
+
server's profile (also keeps the project's .git folders, .claude and .vscode
|
|
60
|
+
read-only). Not for you to type.
|
|
61
|
+
-- ends the options. PROGRAM and its arguments follow. With --tool generic,
|
|
62
|
+
PROGRAM is required.
|
|
63
|
+
-h, --help show this help.
|
|
64
|
+
|
|
65
|
+
Run a whole agent tool, and everything it starts, in the kernel profile. The tool cannot
|
|
66
|
+
read protected data. It works with protected data only through the gateway (`phiward run`,
|
|
67
|
+
`phiward copy`), which masks what comes back.
|
|
68
|
+
|
|
69
|
+
Start it from the project folder, in your own terminal. It refuses to start in /, in your
|
|
70
|
+
home or a folder above it, in a dot folder of your home, in a folder that holds a phiward
|
|
71
|
+
folder, or in a folder inside or above protected data. It also refuses when the config has a
|
|
72
|
+
problem or when no protected paths are configured.
|
|
73
|
+
|
|
74
|
+
What the session can do:
|
|
75
|
+
- Write: only the project, its own session folder (in ~/.phiward/tools/<tool>/runs/) and the
|
|
76
|
+
spool. Files in the project that run code later stay read-only: git control files,
|
|
77
|
+
.claude and .vscode settings, and .mcp.json.
|
|
78
|
+
- Read: everything except the protected paths and credentials (~/.ssh, ~/.aws, tool logins,
|
|
79
|
+
Kerberos tickets, and similar). Credential variables such as SSH_AUTH_SOCK are removed.
|
|
80
|
+
- Other processes: no keystroke injection, no signals to processes outside, no scripting of
|
|
81
|
+
other apps. The network is open in this release.
|
|
82
|
+
|
|
83
|
+
When the session ends:
|
|
84
|
+
- The session's folder is thrown away. Each session starts from a trusted copy that no session
|
|
85
|
+
can read or write.
|
|
86
|
+
- Changes to the tool's instructions and settings go to quarantine. Read and keep them with
|
|
87
|
+
`phiward carryover show` and `phiward carryover accept ID`.
|
|
88
|
+
- Every file the session changed in the project is reported.
|
|
89
|
+
- No process is ended by phiward.
|
|
90
|
+
|
|
91
|
+
phiward checks its own installed files before it starts the tool. Set PHIWARD_DEV=1 to start
|
|
92
|
+
from a source checkout.
|
|
93
|
+
"""
|
|
94
|
+
MAX_DEPTH = 3
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class Adapter:
|
|
99
|
+
name: str
|
|
100
|
+
program: str = "" # the tool's command, found on the operator's PATH
|
|
101
|
+
config_env: str = "" # the variable that moves its config folder
|
|
102
|
+
# state folders under HOME the tool uses; not write places: the operator's plain tool
|
|
103
|
+
# reads them, so XDG_STATE_HOME and XDG_DATA_HOME point into the run folder instead
|
|
104
|
+
home_writes: List[str] = field(default_factory=list)
|
|
105
|
+
extra_env: Dict[str, str] = field(default_factory=dict)
|
|
106
|
+
|
|
107
|
+
def turn_own_sandbox_off(self, folder_fd: int) -> None:
|
|
108
|
+
"""The tool's settings in its own folder: its sandbox off on macOS (sandboxes do not
|
|
109
|
+
nest; this profile replaces it) and the fast hook as a first layer."""
|
|
110
|
+
if self.name != "claude":
|
|
111
|
+
return
|
|
112
|
+
data = _read_json_at(folder_fd, "settings.json")
|
|
113
|
+
before = json.dumps(data, sort_keys=True)
|
|
114
|
+
if sys.platform == "darwin":
|
|
115
|
+
sb = data.setdefault("sandbox", {})
|
|
116
|
+
if isinstance(sb, dict):
|
|
117
|
+
sb["enabled"] = False
|
|
118
|
+
import shlex
|
|
119
|
+
pkg = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
120
|
+
code = f"import sys; sys.path.insert(0, {pkg!r}); from phiward.cli import main; sys.exit(main())"
|
|
121
|
+
cmd = f"{shlex.quote(sys.executable)} -I -S -c {shlex.quote(code)} hook claude --launched"
|
|
122
|
+
hooks = data.setdefault("hooks", {})
|
|
123
|
+
if not isinstance(hooks, dict):
|
|
124
|
+
hooks = data["hooks"] = {}
|
|
125
|
+
pre = hooks.get("PreToolUse") if isinstance(hooks.get("PreToolUse"), list) else []
|
|
126
|
+
# our entry replaced each time (phiward may have moved; a decoy left by a session
|
|
127
|
+
# is dropped); other entries kept
|
|
128
|
+
pre = [g for g in pre if not (isinstance(g, dict) and any(
|
|
129
|
+
isinstance(h, dict) and "hook claude" in str(h.get("command", ""))
|
|
130
|
+
and any(n in str(h.get("command", "")) for n in config.PROGRAMS)
|
|
131
|
+
for h in g.get("hooks", []) if isinstance(g.get("hooks"), list)))]
|
|
132
|
+
pre.append({"matcher": "Read|Grep|Glob|Bash|Edit|Write|NotebookEdit|MultiEdit",
|
|
133
|
+
"hooks": [{"type": "command", "command": cmd, "timeout": 5}]})
|
|
134
|
+
hooks["PreToolUse"] = pre
|
|
135
|
+
if json.dumps(data, sort_keys=True) != before:
|
|
136
|
+
_write_at(folder_fd, "settings.json", json.dumps(data, indent=2) + "\n")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
ADAPTERS: Dict[str, Adapter] = {
|
|
140
|
+
"generic": Adapter("generic"),
|
|
141
|
+
"claude": Adapter("claude", "claude", "CLAUDE_CONFIG_DIR",
|
|
142
|
+
[".local/state/claude", "Library/Caches/claude-cli-nodejs"],
|
|
143
|
+
# no auto-update; no download of the official plugin catalog into each fresh
|
|
144
|
+
# folder (~14 MB and 830 files every session)
|
|
145
|
+
{"DISABLE_AUTOUPDATER": "1",
|
|
146
|
+
"CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL": "1"}),
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
# the tool's environment is an allow-list (a deny pattern always misses some secret);
|
|
150
|
+
# the operator adds more with [launch] pass_env in the user config
|
|
151
|
+
PASS_ENV = {"PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "TERM_PROGRAM",
|
|
152
|
+
"TERM_PROGRAM_VERSION", "COLORTERM", "LANG", "TZ", "EDITOR", "VISUAL", "PAGER", "LESS",
|
|
153
|
+
"COLUMNS", "LINES", "NO_COLOR", "FORCE_COLOR", "SHLVL", "PWD", "HTTP_PROXY",
|
|
154
|
+
"HTTPS_PROXY", "NO_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "no_proxy",
|
|
155
|
+
"all_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE",
|
|
156
|
+
"NODE_EXTRA_CA_CERTS", "JAVA_HOME", "GOPATH", "GOROOT", "CONDA_PREFIX",
|
|
157
|
+
"CONDA_DEFAULT_ENV", "VIRTUAL_ENV", "__CF_USER_TEXT_ENCODING",
|
|
158
|
+
# module systems on HPC (Lmod, Environment Modules) and build paths
|
|
159
|
+
"LD_LIBRARY_PATH", "MODULEPATH", "MODULESHOME", "LOADEDMODULES", "PKG_CONFIG_PATH",
|
|
160
|
+
"MANPATH", "CPATH", "LIBRARY_PATH", "_LMFILES_"}
|
|
161
|
+
PASS_PREFIXES = ("LC_", "ANTHROPIC_", "CLAUDE_", "PHIWARD_", "LMOD_", "__LMOD_")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _keep_env(k: str, extra: Sequence[str] = ()) -> bool:
|
|
165
|
+
if k == "PHIWARD_HOOK_ROOTS": # the v1 hook's list of protected roots
|
|
166
|
+
return False
|
|
167
|
+
return k in PASS_ENV or k.startswith(PASS_PREFIXES) or k in extra
|
|
168
|
+
# package caches, redirected into the session's own run folder and thrown away with it:
|
|
169
|
+
# a cache a session can write is code a later session runs
|
|
170
|
+
SESSION_CACHE_ENV = {"XDG_CACHE_HOME": "cache", "npm_config_cache": "cache/npm",
|
|
171
|
+
"BUN_INSTALL_CACHE_DIR": "cache/bun", "UV_CACHE_DIR": "cache/uv",
|
|
172
|
+
"PIP_CACHE_DIR": "cache/pip", "GOCACHE": "cache/go-build",
|
|
173
|
+
"GOMODCACHE": "cache/go-mod", "CARGO_HOME": "cache/cargo",
|
|
174
|
+
"GRADLE_USER_HOME": "cache/gradle", "YARN_CACHE_FOLDER": "cache/yarn",
|
|
175
|
+
"PRE_COMMIT_HOME": "cache/pre-commit", "POETRY_CACHE_DIR": "cache/poetry",
|
|
176
|
+
"XDG_STATE_HOME": "state", "XDG_DATA_HOME": "data"}
|
|
177
|
+
GIT_CONTROL = ("config", "commondir", "gitdir", "hooks", "info", "modules", "worktrees",
|
|
178
|
+
"config.worktree", "shallow", "objects/info/alternates")
|
|
179
|
+
# .claude/settings.local.json can hold hooks too, which run later outside launch: read-only
|
|
180
|
+
#; the tool keeps its permission answers in its own folder
|
|
181
|
+
# a wrapped MCP server's profile: the project's folders that Claude Code, an editor or git runs
|
|
182
|
+
# code from, read-only as a whole (with every `.git` folder and entry in the project)
|
|
183
|
+
SERVER_READ_ONLY = (".claude", ".vscode", ".idea", ".gitmodules", ".ripgreprc")
|
|
184
|
+
PROJECT_SETTINGS = (".mcp.json", ".claude/settings.json", ".claude/settings.local.json",
|
|
185
|
+
".vscode/settings.json", ".vscode/tasks.json", ".vscode/launch.json")
|
|
186
|
+
MACH_ALLOW = (
|
|
187
|
+
"com.apple.SecurityServer", "com.apple.securityd.xpc", "com.apple.trustd",
|
|
188
|
+
"com.apple.trustd.agent", "com.apple.ocspd", "com.apple.SystemConfiguration.configd",
|
|
189
|
+
"com.apple.SystemConfiguration.DNSConfiguration", "com.apple.dnssd.service",
|
|
190
|
+
"com.apple.system.opendirectoryd.libinfo", "com.apple.system.DirectoryService.libinfo_v1",
|
|
191
|
+
"com.apple.system.notification_center", "com.apple.system.logger", "com.apple.logd",
|
|
192
|
+
"com.apple.diagnosticd", "com.apple.cfprefsd.daemon", "com.apple.cfprefsd.agent",
|
|
193
|
+
"com.apple.bsd.dirhelper", "com.apple.FSEvents", "com.apple.CoreServices.coreservicesd",
|
|
194
|
+
"com.apple.lsd.mapdb", "com.apple.analyticsd", "com.apple.networkd",
|
|
195
|
+
"com.apple.nsurlsessiond", "com.apple.nesessionmanager.content-filter",
|
|
196
|
+
)
|
|
197
|
+
_TIOCSTI_MACOS = 0x80017472
|
|
198
|
+
CANARY = "launch-canary"
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class LaunchError(Exception):
|
|
202
|
+
pass
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# -- safe file work in agent-writable folders -----------------------------------
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _read_json_at(dfd: int, name: str) -> dict:
|
|
209
|
+
try:
|
|
210
|
+
fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=dfd)
|
|
211
|
+
except FileNotFoundError:
|
|
212
|
+
return {}
|
|
213
|
+
except OSError:
|
|
214
|
+
raise LaunchError(f"the tool's {name} is not a plain file (a link?)")
|
|
215
|
+
try:
|
|
216
|
+
st = os.fstat(fd)
|
|
217
|
+
if (st.st_mode & 0o170000) != 0o100000 or st.st_nlink != 1:
|
|
218
|
+
raise LaunchError(f"the tool's {name} is not a plain file with one link")
|
|
219
|
+
data = json.loads(os.read(fd, 1 << 20).decode("utf-8") or "{}")
|
|
220
|
+
except ValueError:
|
|
221
|
+
data = {}
|
|
222
|
+
finally:
|
|
223
|
+
os.close(fd)
|
|
224
|
+
return data if isinstance(data, dict) else {}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _write_at(dfd: int, name: str, text: str) -> None:
|
|
228
|
+
tmp = f".{name}.{secrets.token_hex(6)}.tmp"
|
|
229
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600,
|
|
230
|
+
dir_fd=dfd)
|
|
231
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
232
|
+
fh.write(text)
|
|
233
|
+
os.rename(tmp, name, src_dir_fd=dfd, dst_dir_fd=dfd)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _project_problem(project: str, env: Dict[str, str]) -> str:
|
|
237
|
+
"""The project folder is writable as a whole: it may not be `/`, the home folder or above
|
|
238
|
+
it, a dot-folder in it, or hold a phiward folder."""
|
|
239
|
+
home = os.path.realpath(pathid.home(env))
|
|
240
|
+
if project == "/":
|
|
241
|
+
return "it is /"
|
|
242
|
+
if not project.startswith("/"):
|
|
243
|
+
return "it is not an absolute folder"
|
|
244
|
+
if _inside(home, project):
|
|
245
|
+
return "it is the home folder or above it"
|
|
246
|
+
if _inside(project, home) and os.path.relpath(project, home).split("/")[0].startswith("."):
|
|
247
|
+
return "it is a dot-folder in the home folder"
|
|
248
|
+
for g in config.guard_files(env) + [os.path.join(home, ".phiward"),
|
|
249
|
+
os.path.join(home, config.LEGACY_STATE),
|
|
250
|
+
os.path.dirname(config.legacy_user_config_path(env))]:
|
|
251
|
+
if _inside(os.path.realpath(g), project):
|
|
252
|
+
return "it holds a phiward file or folder"
|
|
253
|
+
if sys.platform == "darwin" and _inside(project, os.path.join(home, "Library")):
|
|
254
|
+
return "it is in ~/Library (LaunchAgents and preferences run later)"
|
|
255
|
+
for e in (env.get("PATH") or "").split(":"):
|
|
256
|
+
if e and os.path.isabs(e) and _inside(os.path.realpath(e), project):
|
|
257
|
+
return "it holds a folder on PATH (programs there run later, outside launch)"
|
|
258
|
+
return ""
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _fixed_folders(folder: str) -> None:
|
|
262
|
+
"""The tool folder's own subfolders: made when missing; a link a session put there is
|
|
263
|
+
removed (unlink takes the link, not its target) and the folder made again."""
|
|
264
|
+
if os.path.islink(folder): # the operator's link, maybe: refused, never removed
|
|
265
|
+
raise LaunchError("the tool folder is a link; make it a real folder")
|
|
266
|
+
# the caches are made by carryover._layout, by descriptor (cache/ is a write place)
|
|
267
|
+
os.makedirs(folder, mode=0o700, exist_ok=True)
|
|
268
|
+
if not _no_link_on_path(folder) or not os.path.isdir(folder):
|
|
269
|
+
raise LaunchError("the tool folder is not a real folder")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _inside(p: str, folder: str) -> bool:
|
|
273
|
+
return pathid.inside(p, folder)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _no_link_on_path(p: str) -> bool:
|
|
277
|
+
return os.path.realpath(p) == os.path.normpath(p)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# -- places ------------------------------------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
def _real_home(env: Dict[str, str]) -> str:
|
|
283
|
+
"""The home folder with the links above it resolved: those are the system's (HPC homes are
|
|
284
|
+
often links); links below it are what a session could plant, and those are refused."""
|
|
285
|
+
return os.path.realpath(pathid.home(env))
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def tool_folder(adapter: Adapter, env: Dict[str, str]) -> str:
|
|
289
|
+
return os.path.join(_real_home(env), ".phiward", "tools", adapter.name)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _darwin_user_dir(name: str) -> str:
|
|
293
|
+
try:
|
|
294
|
+
r = subprocess.run(["/usr/bin/getconf", name], capture_output=True, text=True, timeout=5)
|
|
295
|
+
return os.path.realpath(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip() else ""
|
|
296
|
+
except (OSError, subprocess.SubprocessError):
|
|
297
|
+
return ""
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def write_places(project: str, env: Dict[str, str], run: str = "") -> List[str]:
|
|
301
|
+
"""The folders the tool may write; each one a real folder with no link on its path. In the
|
|
302
|
+
tool folder only this session's run folder: not the folder itself, not `trash/`, not
|
|
303
|
+
an earlier session's run folder."""
|
|
304
|
+
spool = config.spool_dir(env)
|
|
305
|
+
spool = os.path.join(os.path.realpath(os.path.dirname(spool)), os.path.basename(spool))
|
|
306
|
+
want = [project] + ([run] if run else []) + [spool]
|
|
307
|
+
# the adapter's HOME state folders are not write places (the operator's
|
|
308
|
+
# plain tool reads them); XDG_STATE_HOME and XDG_DATA_HOME point into the run folder
|
|
309
|
+
if sys.platform == "darwin": # D16: the per-user temp folder (clang and Apple tools use it,
|
|
310
|
+
t = _darwin_user_dir("DARWIN_USER_TEMP_DIR") # whatever TMPDIR says); xcrun's cache in
|
|
311
|
+
want += [t] if t else [] # it stays denied (seatbelt_tool_profile)
|
|
312
|
+
out: List[str] = []
|
|
313
|
+
for p in want:
|
|
314
|
+
p = os.path.normpath(p)
|
|
315
|
+
if os.path.lexists(p) and not _no_link_on_path(p):
|
|
316
|
+
sys.stderr.write("phiward launch: a write place is a link or has a link on its "
|
|
317
|
+
"path, so it is not used\n")
|
|
318
|
+
continue
|
|
319
|
+
if p not in out:
|
|
320
|
+
out.append(p)
|
|
321
|
+
return out
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# -- macOS -------------------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def _own_ttys() -> List[str]:
|
|
327
|
+
out = []
|
|
328
|
+
for fd in (0, 1, 2):
|
|
329
|
+
try:
|
|
330
|
+
if os.isatty(fd):
|
|
331
|
+
out.append(os.path.realpath(os.ttyname(fd)))
|
|
332
|
+
except OSError:
|
|
333
|
+
pass
|
|
334
|
+
return sorted(set(out))
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _rx(path: str) -> str:
|
|
338
|
+
out = ""
|
|
339
|
+
for ch in path:
|
|
340
|
+
out += "\\" + ch if ch in ".^$+(){}[]|\\*?" else ch
|
|
341
|
+
return out.replace('"', '\\"')
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def seatbelt_tool_profile(cfg: config.Config, places: Sequence[str], project: str,
|
|
345
|
+
env: Dict[str, str], folder: str, canary: str,
|
|
346
|
+
server: bool = False) -> str:
|
|
347
|
+
s = confine._sb_str
|
|
348
|
+
rules = confine._sb_paths(cfg.all_roots, cfg.patterns)
|
|
349
|
+
allow = [f"(subpath {s(p)})" for p in places] # exactly as given: no resolved spellings
|
|
350
|
+
allow += [f"(literal {s(d)})" for d in ("/dev/null", "/dev/zero", "/dev/dtracehelper",
|
|
351
|
+
"/dev/tty", "/dev/ptmx", "/dev/stdout",
|
|
352
|
+
"/dev/stderr")]
|
|
353
|
+
allow.append('(regex #"^/dev/fd/[0-9]+$")')
|
|
354
|
+
|
|
355
|
+
allow += [f"(literal {s(t)})" for t in _own_ttys()]
|
|
356
|
+
ctl = "|".join(c.replace(".", "\\.").replace("/", "\\/") for c in GIT_CONTROL)
|
|
357
|
+
ro: List[str] = []
|
|
358
|
+
for gd, entry in git_dirs_in(project):
|
|
359
|
+
ro.append(f'(regex #"^{_rx(gd)}/({ctl})(/.*)?$")')
|
|
360
|
+
ro.append(f"(literal {s(entry)})") # the .git entry itself: no rename or replacement
|
|
361
|
+
# .claude is made at start (build); a missing .vscode cannot be made, so neither can become a
|
|
362
|
+
# link to settings elsewhere
|
|
363
|
+
ro += [f"(literal {s(os.path.join(project, t))})" for t in (".claude", ".vscode")]
|
|
364
|
+
ro += [f"(literal {s(os.path.join(project, r))})" for r in PROJECT_SETTINGS]
|
|
365
|
+
if server:
|
|
366
|
+
# a wrapped MCP server (`--entry`) runs inside a Mode A session that is not confined:
|
|
367
|
+
# what Claude Code, an editor or git later runs from the project is read-only as a
|
|
368
|
+
# whole, made before the server starts or not (SERVER_READ_ONLY)
|
|
369
|
+
ro += [f"(subpath {s(os.path.join(project, t))})" for t in SERVER_READ_ONLY]
|
|
370
|
+
ro += [f"(subpath {s(gd)})" for gd, _entry in git_dirs_in(project)]
|
|
371
|
+
ro.append(f'(regex #"^{_rx(project)}/(.*/)?\\.git(/.*)?$")')
|
|
372
|
+
creds = [f"(subpath {s(c)})" for c in confine._spellings(_credentials(env, cfg))]
|
|
373
|
+
tdir = _darwin_user_dir("DARWIN_USER_TEMP_DIR")
|
|
374
|
+
for d in ["/private/tmp", "/private/var/tmp"] + ([tdir] if tdir else []):
|
|
375
|
+
creds.append(f'(regex #"^{_rx(d)}/{KRB5_CACHE_NAMES}")')
|
|
376
|
+
guards = [f"(subpath {s(g)})" for g in confine._spellings(config.guard_files(env))]
|
|
377
|
+
above = list(cfg.all_roots) + [confine._pattern_prefix(p) for p in cfg.patterns]
|
|
378
|
+
anc = [f"(literal {s(a)})" for a in confine._ancestors(above)]
|
|
379
|
+
p = "(version 1)(allow default)"
|
|
380
|
+
# the tool folder is not readable except this session's own run folder
|
|
381
|
+
# (sessions cannot read each other or the trusted copy's neighbours)
|
|
382
|
+
own = [q for q in places if q.startswith(os.path.join(folder, "runs") + os.sep)]
|
|
383
|
+
p += f"(deny file-read* (subpath {s(folder)}))"
|
|
384
|
+
p += "".join(f"(allow file-read* (subpath {s(q)}))" for q in own)
|
|
385
|
+
# the folders above the run folder may be looked at (not listed), or path resolution fails
|
|
386
|
+
# (Node's realpath, a shell's cd)
|
|
387
|
+
p += (f"(allow file-read-metadata (literal {s(folder)}) "
|
|
388
|
+
f"(literal {s(os.path.join(folder, 'runs'))}))")
|
|
389
|
+
if rules:
|
|
390
|
+
p += "(deny file* " + " ".join(rules) + ")"
|
|
391
|
+
p += f"(deny file* (literal {s(canary)}))"
|
|
392
|
+
p += "(deny file-read* file-write* " + " ".join(creds) + ")"
|
|
393
|
+
p += "(deny file-write* (require-not (require-any " + " ".join(allow) + ")))"
|
|
394
|
+
t = _darwin_user_dir("DARWIN_USER_TEMP_DIR")
|
|
395
|
+
if t: # xcrun's cache maps tool names to paths that /usr/bin shims use later: never written
|
|
396
|
+
ro.append(f'(regex #"^{_rx(t)}/xcrun_db")')
|
|
397
|
+
p += "(deny file-write* " + " ".join(ro + guards) + ")"
|
|
398
|
+
if anc:
|
|
399
|
+
p += "(deny file-write* " + " ".join(anc) + ")"
|
|
400
|
+
p += "(deny process-info* (require-not (target same-sandbox)))"
|
|
401
|
+
p += "(deny signal (require-not (target same-sandbox)))"
|
|
402
|
+
p += f"(deny file-ioctl (ioctl-command #x{_TIOCSTI_MACOS:x}))"
|
|
403
|
+
p += "(deny network-outbound (remote unix-socket))"
|
|
404
|
+
# unix sockets only under this session's own run folder, never another run's (its tmux
|
|
405
|
+
# server, for one)
|
|
406
|
+
p += "".join(f"(allow network-outbound (remote unix-socket (subpath {s(q)})))" for q in own)
|
|
407
|
+
# name lookups go through mDNSResponder's socket
|
|
408
|
+
p += '(allow network-outbound (remote unix-socket (subpath "/private/var/run/mDNSResponder")))'
|
|
409
|
+
p += "(deny lsopen)(deny appleevent-send)(deny user-preference-write)"
|
|
410
|
+
p += "(deny mach-lookup)(allow mach-lookup " + " ".join(
|
|
411
|
+
f"(global-name {s(m)})" for m in MACH_ALLOW) + ")"
|
|
412
|
+
# terminals: only the session's own can be read or written (another terminal's
|
|
413
|
+
# keystrokes could be read); new ptys need the pty relay
|
|
414
|
+
p += '(deny file-read* file-write* (regex #"^/dev/ttys[0-9]+$"))'
|
|
415
|
+
own = _own_ttys()
|
|
416
|
+
if own:
|
|
417
|
+
p += "(allow file-read* file-write* " + " ".join(f"(literal {s(t)})" for t in own) + ")"
|
|
418
|
+
return p
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _sandbox_check_self() -> bool:
|
|
422
|
+
"""macOS: whether this process is already in any sandbox."""
|
|
423
|
+
import ctypes
|
|
424
|
+
for lib in ("/usr/lib/libSystem.B.dylib", "/usr/lib/system/libsystem_sandbox.dylib"):
|
|
425
|
+
try:
|
|
426
|
+
fn = ctypes.CDLL(lib).sandbox_check
|
|
427
|
+
except (OSError, AttributeError):
|
|
428
|
+
continue
|
|
429
|
+
fn.restype = ctypes.c_int
|
|
430
|
+
fn.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int]
|
|
431
|
+
return bool(fn(os.getpid(), None, 0))
|
|
432
|
+
return True # cannot tell: refuse (fail closed)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
# -- Linux -------------------------------------------------------------------------------------
|
|
436
|
+
|
|
437
|
+
def tool_seccomp_program(machine: Optional[str] = None) -> bytes:
|
|
438
|
+
"""No keystroke injection (ioctl TIOCSTI, TIOCLINUX: compared on the low 32 bits) and no
|
|
439
|
+
kernel keyrings (keyctl, add_key, request_key: Kerberos KEYRING tickets); the x32 ABI is
|
|
440
|
+
refused on x86_64."""
|
|
441
|
+
machine = machine or confine._machine()
|
|
442
|
+
if machine not in confine._AUDIT_ARCH:
|
|
443
|
+
raise confine.ConfineError(f"no seccomp filter for the {machine} architecture")
|
|
444
|
+
col = 0 if machine == "x86_64" else 1
|
|
445
|
+
ioctl = 16 if machine == "x86_64" else 29
|
|
446
|
+
keys = [confine._DENY[k][col] for k in ("keyctl", "add_key", "request_key")]
|
|
447
|
+
allow, kill, eperm = 0x7FFF0000, 0x80000000, 0x00050001
|
|
448
|
+
ld, jeq, jge, ret = 0x20, 0x15, 0x35, 0x06
|
|
449
|
+
prog = [(ld, 0, 0, 4), (jeq, 1, 0, confine._AUDIT_ARCH[machine]), (ret, 0, 0, kill),
|
|
450
|
+
(ld, 0, 0, 0)]
|
|
451
|
+
if machine == "x86_64":
|
|
452
|
+
prog += [(jge, 0, 1, 0x40000000), (ret, 0, 0, eperm)]
|
|
453
|
+
for k in keys:
|
|
454
|
+
prog += [(jeq, 0, 1, k), (ret, 0, 0, eperm)]
|
|
455
|
+
prog += [(jeq, 0, 4, ioctl), (ld, 0, 0, 24), (jeq, 1, 0, 0x5412), (jeq, 0, 1, 0x541C),
|
|
456
|
+
(ret, 0, 0, eperm), (ret, 0, 0, allow)]
|
|
457
|
+
return b"".join(struct.pack("<HBBI", *i) for i in prog)
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
# system name-service sockets stay reachable (user and group lookups on clusters: sssd, nscd)
|
|
461
|
+
_NSS_SOCKETS = ("/var/lib/sss/pipes", "/var/run/nscd", "/run/nscd", "/run/systemd/userdb")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _outside_sockets(places: Sequence[str]) -> List[str]:
|
|
465
|
+
"""Path unix sockets bound outside the tool's places (from /proc/net/unix; the path is the
|
|
466
|
+
rest of the line after seven fields, so it may hold spaces)."""
|
|
467
|
+
out: List[str] = []
|
|
468
|
+
try:
|
|
469
|
+
with open("/proc/net/unix", encoding="utf-8", errors="replace") as fh:
|
|
470
|
+
next(fh, None)
|
|
471
|
+
for line in fh:
|
|
472
|
+
parts = line.rstrip("\n").split(None, 7)
|
|
473
|
+
if len(parts) == 8 and parts[7].startswith("/") and \
|
|
474
|
+
not any(_inside(parts[7], n) for n in _NSS_SOCKETS):
|
|
475
|
+
p = parts[7]
|
|
476
|
+
if not any(_inside(p, pl) for pl in places) and os.path.lexists(p) and \
|
|
477
|
+
p not in out:
|
|
478
|
+
out.append(p)
|
|
479
|
+
except OSError:
|
|
480
|
+
pass
|
|
481
|
+
return out
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def git_dirs_in(project: str, limit: int = 50000) -> List[Tuple[str, str]]:
|
|
485
|
+
"""Every git folder in the project at launch: (the folder that holds the control files, the
|
|
486
|
+
`.git` entry), for the top `.git`, nested repositories and the `.git` files of submodules and
|
|
487
|
+
worktrees (their gitdir when it is inside the project). Links are never followed; the walk
|
|
488
|
+
is bounded. Repositories made during the session are not covered (docs/threat-model.md:
|
|
489
|
+
files that run later)."""
|
|
490
|
+
out: List[Tuple[str, str]] = []
|
|
491
|
+
seen = 0
|
|
492
|
+
stack = [project]
|
|
493
|
+
skip = {"node_modules", ".venv", "venv", "__pycache__", ".tox", ".mypy_cache"}
|
|
494
|
+
while stack and seen < limit:
|
|
495
|
+
d = stack.pop()
|
|
496
|
+
try:
|
|
497
|
+
it = list(os.scandir(d))
|
|
498
|
+
except OSError:
|
|
499
|
+
continue
|
|
500
|
+
for e in it:
|
|
501
|
+
seen += 1
|
|
502
|
+
if e.name == ".git":
|
|
503
|
+
if e.is_dir(follow_symlinks=False):
|
|
504
|
+
out.append((e.path, e.path))
|
|
505
|
+
elif e.is_file(follow_symlinks=False):
|
|
506
|
+
gd = _gitdir_of(e.path)
|
|
507
|
+
real = gd and _no_link_on_path(gd) and _inside(gd, project) and os.path.isdir(gd)
|
|
508
|
+
# a gitdir with a link on its path is never used: it is agent-written;
|
|
509
|
+
# the .git file itself is still covered
|
|
510
|
+
out.append((gd if real else e.path, e.path))
|
|
511
|
+
continue
|
|
512
|
+
if e.is_dir(follow_symlinks=False) and e.name not in skip:
|
|
513
|
+
stack.append(e.path)
|
|
514
|
+
return out
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _gitdir_of(dot_git: str) -> str:
|
|
518
|
+
try:
|
|
519
|
+
fd = os.open(dot_git, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
520
|
+
try:
|
|
521
|
+
line = os.read(fd, 4096).decode("utf-8", "replace").strip().splitlines()[0]
|
|
522
|
+
finally:
|
|
523
|
+
os.close(fd)
|
|
524
|
+
except (OSError, IndexError):
|
|
525
|
+
return ""
|
|
526
|
+
if not line.startswith("gitdir:"):
|
|
527
|
+
return ""
|
|
528
|
+
return os.path.normpath(os.path.join(os.path.dirname(dot_git), line[7:].strip()))
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _placeholders(project: str) -> List[str]:
|
|
532
|
+
"""D15: settings files that do not exist yet are made as read-only `{}` placeholders, so
|
|
533
|
+
bubblewrap can cover them."""
|
|
534
|
+
made = []
|
|
535
|
+
rels = [".mcp.json", ".claude/settings.json", ".claude/settings.local.json"]
|
|
536
|
+
if os.path.isdir(os.path.join(project, ".vscode")):
|
|
537
|
+
rels += [".vscode/settings.json", ".vscode/tasks.json", ".vscode/launch.json"]
|
|
538
|
+
nofollow = os.O_NOFOLLOW | os.O_CLOEXEC
|
|
539
|
+
for rel in rels:
|
|
540
|
+
sub, name = os.path.split(rel)
|
|
541
|
+
# by descriptor, never through a link, and a file another launch made meanwhile is
|
|
542
|
+
# simply there already (two wrapped MCP servers start at once)
|
|
543
|
+
try:
|
|
544
|
+
top = os.open(project, os.O_RDONLY | os.O_DIRECTORY | nofollow)
|
|
545
|
+
except OSError:
|
|
546
|
+
continue
|
|
547
|
+
try:
|
|
548
|
+
dfd = top
|
|
549
|
+
if sub:
|
|
550
|
+
try:
|
|
551
|
+
os.mkdir(sub, 0o755, dir_fd=top)
|
|
552
|
+
except FileExistsError:
|
|
553
|
+
pass
|
|
554
|
+
try:
|
|
555
|
+
dfd = os.open(sub, os.O_RDONLY | os.O_DIRECTORY | nofollow, dir_fd=top)
|
|
556
|
+
except OSError:
|
|
557
|
+
continue # a link or not a folder: not covered here
|
|
558
|
+
try:
|
|
559
|
+
fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o644,
|
|
560
|
+
dir_fd=dfd)
|
|
561
|
+
except FileExistsError:
|
|
562
|
+
continue
|
|
563
|
+
except OSError:
|
|
564
|
+
continue
|
|
565
|
+
finally:
|
|
566
|
+
if dfd != top:
|
|
567
|
+
os.close(dfd)
|
|
568
|
+
with os.fdopen(fd, "w") as fh:
|
|
569
|
+
fh.write("{}\n")
|
|
570
|
+
made.append(rel)
|
|
571
|
+
finally:
|
|
572
|
+
os.close(top)
|
|
573
|
+
return made
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _open_no_follow(path: str) -> int:
|
|
577
|
+
"""An O_PATH descriptor of a file or folder reached part by part without following a link:
|
|
578
|
+
what is checked is what gets mounted."""
|
|
579
|
+
if os.path.isdir(path) and not os.path.islink(path):
|
|
580
|
+
return confine.open_place(path)
|
|
581
|
+
parent = confine.open_place(os.path.dirname(path))
|
|
582
|
+
try:
|
|
583
|
+
return os.open(os.path.basename(path), os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC, # type: ignore[attr-defined]
|
|
584
|
+
dir_fd=parent)
|
|
585
|
+
finally:
|
|
586
|
+
os.close(parent)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
# bwrap takes at most 9000 arguments; the snapshot view may use this many, the rest of the command
|
|
590
|
+
# line needs the others (counted in full before bwrap runs)
|
|
591
|
+
BWRAP_MAX_ARGS = 9000
|
|
592
|
+
VIEW_ARGS = 7500
|
|
593
|
+
_OP_ARGS = {"tmpfs": 4, "bind": 3, "symlink": 3, "mask": 3} # a tmpfs is also made read-only
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def hidden_view(literal: Sequence[str], patterns: Sequence[str], replaced: Sequence[str] = (),
|
|
597
|
+
limit: int = VIEW_ARGS, may_skip: Sequence[str] = (),
|
|
598
|
+
soft_patterns: Sequence[str] = (), named: Optional[Sequence[str]] = None
|
|
599
|
+
) -> Tuple[List[Tuple[str, ...]], List[str], List[str]]:
|
|
600
|
+
"""The Linux session's view of the file system, as mount operations; the folders made for
|
|
601
|
+
it; and the folders shown whole because they hold too many entries.
|
|
602
|
+
|
|
603
|
+
Every folder above a hidden path is "split": in the view it is an empty tmpfs, and each
|
|
604
|
+
entry it held at the start is bound back (a link is made again as a link), except the hidden
|
|
605
|
+
ones. A hidden path is never mounted over, so a protected path replaced, or a match made
|
|
606
|
+
after the start, is not in the view. For a pattern, every folder where a match could be
|
|
607
|
+
made is split, for the pattern as written and with its literal part resolved (a pattern
|
|
608
|
+
through a linked folder). Names are compared case-folded, so a
|
|
609
|
+
case-insensitive file system cannot show a hidden name in another case; on a
|
|
610
|
+
case-sensitive one this hides a little more, never less.
|
|
611
|
+
|
|
612
|
+
A split folder that can be entered but not listed (mode 711, common on HPC) cannot be
|
|
613
|
+
rebuilt: it is bound whole, and the hidden paths in it that exist are masked in place
|
|
614
|
+
("mask"). There, a match made later is not hidden. The same is done for split folders when
|
|
615
|
+
the view would not fit in `limit` bwrap arguments (a folder of thousands of entries above a
|
|
616
|
+
protected one), those that save the most arguments first. Shown whole, a folder lists its
|
|
617
|
+
masked entries by name, so this is never done for `/`, for a folder where a wildcard names a
|
|
618
|
+
hidden entry, or for the folder that holds a `named` hidden path (a protected root, whose
|
|
619
|
+
name may be a person's; default: every literal path not in `may_skip`): launch refuses
|
|
620
|
+
then. The cost elsewhere: what the host adds to a split folder after the start is not seen
|
|
621
|
+
until the next session, and a file the host replaces in it stays as it was.
|
|
622
|
+
|
|
623
|
+
Protection follows the path, as on macOS: a protected folder that the host moves into a
|
|
624
|
+
folder the session sees is readable there.
|
|
625
|
+
|
|
626
|
+
A pattern whose wildcard part falls on a folder that cannot be listed cannot be covered:
|
|
627
|
+
launch refuses (protect that folder as a root). A link at a wildcard level is not followed:
|
|
628
|
+
its target is not hidden by the pattern.
|
|
629
|
+
|
|
630
|
+
`may_skip`: credential files that need no hiding when they belong to another user and
|
|
631
|
+
cannot be read (a system keytab); never protected paths. `soft_patterns`: patterns that
|
|
632
|
+
are skipped where a folder cannot be listed, instead of refused (the Kerberos cache names).
|
|
633
|
+
|
|
634
|
+
Operations: ("tmpfs", dir), ("bind", path), ("symlink", target, path), ("mask", path).
|
|
635
|
+
Paths under `replaced` (the session's own /tmp, the hidden tool folder) are left to the
|
|
636
|
+
caller."""
|
|
637
|
+
import unicodedata
|
|
638
|
+
|
|
639
|
+
def fold(x: str) -> str: # case and Unicode form: ext4 casefold treats both as equal
|
|
640
|
+
return unicodedata.normalize("NFD", x).casefold()
|
|
641
|
+
skippable = {os.path.normpath(x) for x in may_skip}
|
|
642
|
+
split: Dict[str, str] = {} # folded -> as found
|
|
643
|
+
hidden: Dict[str, str] = {} # folded -> as written
|
|
644
|
+
wild: Set[str] = set() # folded folders where a wildcard names a hidden entry
|
|
645
|
+
|
|
646
|
+
def under_replaced(x: str) -> bool:
|
|
647
|
+
return any(x == r or _inside(x, r) for r in replaced)
|
|
648
|
+
|
|
649
|
+
def chain(d: str) -> None:
|
|
650
|
+
while True:
|
|
651
|
+
split.setdefault(fold(d), d)
|
|
652
|
+
if d == "/":
|
|
653
|
+
return
|
|
654
|
+
d = os.path.dirname(d)
|
|
655
|
+
|
|
656
|
+
def real_dir(d: str) -> bool:
|
|
657
|
+
return os.path.isdir(d) and not os.path.islink(d)
|
|
658
|
+
|
|
659
|
+
def unreadable_to_us(p: str) -> bool:
|
|
660
|
+
# another user's file we cannot read (a system keytab in /etc): hiding it would only
|
|
661
|
+
# split its folder, and a split folder shows host changes late
|
|
662
|
+
try: # a file only: a folder that cannot be listed may still be entered (mode 711)
|
|
663
|
+
st = os.lstat(p)
|
|
664
|
+
except OSError:
|
|
665
|
+
return False
|
|
666
|
+
return (st.st_uid != os.getuid() and not stat.S_ISDIR(st.st_mode) and
|
|
667
|
+
not os.access(p, os.R_OK))
|
|
668
|
+
|
|
669
|
+
keep_names = {os.path.normpath(x) for x in
|
|
670
|
+
(named if named is not None else [h for h in literal if h not in may_skip])}
|
|
671
|
+
named_dirs: Set[str] = set() # folded folders that hold a hidden path whose name must not show
|
|
672
|
+
for h in literal:
|
|
673
|
+
h = os.path.normpath(h)
|
|
674
|
+
for p in {os.path.join(os.path.realpath(os.path.dirname(h)), os.path.basename(h)),
|
|
675
|
+
os.path.realpath(h)}:
|
|
676
|
+
if p == "/" or under_replaced(p) or (h in skippable and unreadable_to_us(p)):
|
|
677
|
+
continue
|
|
678
|
+
d = os.path.dirname(p)
|
|
679
|
+
while d != "/" and not real_dir(d):
|
|
680
|
+
d = os.path.dirname(d)
|
|
681
|
+
chain(d)
|
|
682
|
+
hidden.setdefault(fold(p), p)
|
|
683
|
+
if h in keep_names:
|
|
684
|
+
named_dirs.add(fold(os.path.dirname(p)))
|
|
685
|
+
soft = set(confine._pattern_spellings(list(soft_patterns)))
|
|
686
|
+
for pat in confine._pattern_spellings(list(patterns) + list(soft_patterns)):
|
|
687
|
+
pp = pathmatch.parts(pat)
|
|
688
|
+
level = ["/"]
|
|
689
|
+
for k, part in enumerate(pp):
|
|
690
|
+
last, nxt = k == len(pp) - 1, []
|
|
691
|
+
for base in level:
|
|
692
|
+
if under_replaced(base):
|
|
693
|
+
continue
|
|
694
|
+
chain(base)
|
|
695
|
+
try:
|
|
696
|
+
names = [n for n in os.listdir(base) if pathmatch.match_part(part, n) or
|
|
697
|
+
fold(n) == fold(part)]
|
|
698
|
+
except OSError:
|
|
699
|
+
if pathmatch.WILD.search(part) and pat not in soft:
|
|
700
|
+
raise LaunchError("a folder where a protected pattern could match cannot "
|
|
701
|
+
"be listed, so the pattern cannot cover it; protect that "
|
|
702
|
+
"folder as a root instead")
|
|
703
|
+
names = [] # not listable: the literal name is still hidden below
|
|
704
|
+
if not pathmatch.WILD.search(part):
|
|
705
|
+
names.append(part)
|
|
706
|
+
for n in set(names):
|
|
707
|
+
c = os.path.join(base, n)
|
|
708
|
+
if not last and real_dir(c):
|
|
709
|
+
nxt.append(c)
|
|
710
|
+
else:
|
|
711
|
+
hidden.setdefault(fold(c), c) # a match, or a link where its folder would be
|
|
712
|
+
if pathmatch.WILD.search(part):
|
|
713
|
+
wild.add(fold(base)) # a hidden name a wildcard chose
|
|
714
|
+
level = nxt
|
|
715
|
+
whole: Set[str] = set() # folded split folders shown whole: too many entries to rebuild
|
|
716
|
+
ops = _view_ops(split, hidden, whole, under_replaced, fold)
|
|
717
|
+
total = sum(_OP_ARGS[o[0]] for o in ops)
|
|
718
|
+
if total > limit:
|
|
719
|
+
whole = _shrink(split, hidden, under_replaced, fold, wild | named_dirs, total, limit)
|
|
720
|
+
ops = _view_ops(split, hidden, whole, under_replaced, fold)
|
|
721
|
+
if sum(_OP_ARGS[o[0]] for o in ops) > limit:
|
|
722
|
+
crowded = any(f in named_dirs or f in wild for f in split)
|
|
723
|
+
raise LaunchError(f"the protected paths need more than {limit} mount arguments in the "
|
|
724
|
+
"session's view; protect fewer, larger folders" + (
|
|
725
|
+
" (a folder that holds a protected root or pattern matches "
|
|
726
|
+
"among many entries cannot be shown whole, since it would list "
|
|
727
|
+
"their names: protect that folder as a root instead)"
|
|
728
|
+
if crowded else ""))
|
|
729
|
+
return (ops, sorted(set(split.values()), key=lambda x: (x.count("/"), x)),
|
|
730
|
+
sorted(split[f] for f in whole))
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def _shrink(split: Dict[str, str], hidden: Dict[str, str], under_replaced: Callable[[str], bool],
|
|
734
|
+
fold: Callable[[str], str], never: Set[str], total: int, limit: int) -> Set[str]:
|
|
735
|
+
"""The split folders to show whole so the view fits in `limit` arguments: those that save
|
|
736
|
+
the most first. A folder's own mounts depend only on whether it and its parent are shown
|
|
737
|
+
whole (`_view_ops`), so each choice changes the savings of its parent and children only."""
|
|
738
|
+
import heapq
|
|
739
|
+
own: Dict[str, int] = {} # entries rebuilt: a bind or a link each
|
|
740
|
+
masks: Dict[str, int] = {} # hidden entries on disk: a mask each when shown whole
|
|
741
|
+
listable: Dict[str, bool] = {}
|
|
742
|
+
kids: Dict[str, List[str]] = {f: [] for f in split}
|
|
743
|
+
parent: Dict[str, Optional[str]] = {}
|
|
744
|
+
|
|
745
|
+
def gone(f: str) -> bool: # hidden, or below a hidden folder: never in the view
|
|
746
|
+
while True:
|
|
747
|
+
if f in hidden:
|
|
748
|
+
return True
|
|
749
|
+
up = os.path.dirname(f)
|
|
750
|
+
if up == f:
|
|
751
|
+
return False
|
|
752
|
+
f = up
|
|
753
|
+
for f, x in split.items():
|
|
754
|
+
if gone(f):
|
|
755
|
+
continue
|
|
756
|
+
p = fold(os.path.dirname(x)) if x != "/" else None
|
|
757
|
+
parent[f] = p if p in split else None
|
|
758
|
+
if parent[f] is not None:
|
|
759
|
+
kids[p].append(f)
|
|
760
|
+
own[f] = masks[f] = 0
|
|
761
|
+
try:
|
|
762
|
+
names = os.listdir(x)
|
|
763
|
+
listable[f] = True
|
|
764
|
+
except OSError:
|
|
765
|
+
listable[f] = False
|
|
766
|
+
continue
|
|
767
|
+
for n in names:
|
|
768
|
+
c = os.path.join(x, n)
|
|
769
|
+
fc = fold(c)
|
|
770
|
+
if fc in hidden:
|
|
771
|
+
masks[f] += 1
|
|
772
|
+
elif not (fc in split or under_replaced(c) or (x == "/" and n in ("proc", "dev"))):
|
|
773
|
+
own[f] += 1
|
|
774
|
+
whole: Set[str] = set()
|
|
775
|
+
|
|
776
|
+
def shown_whole(f: Optional[str]) -> bool:
|
|
777
|
+
return f is not None and (f in whole or not listable[f])
|
|
778
|
+
|
|
779
|
+
def gain(f: str) -> int:
|
|
780
|
+
rebuilt = _OP_ARGS["tmpfs"] + _OP_ARGS["bind"] * own[f]
|
|
781
|
+
as_whole = (0 if shown_whole(parent[f]) else _OP_ARGS["bind"]) + _OP_ARGS["mask"] * masks[f]
|
|
782
|
+
# a child shown whole needs no bind of its own inside a folder shown whole
|
|
783
|
+
return rebuilt - as_whole + _OP_ARGS["bind"] * sum(1 for k in kids[f] if shown_whole(k))
|
|
784
|
+
open_ = [f for f, x in split.items()
|
|
785
|
+
if x != "/" and f in listable and listable[f] and f not in never]
|
|
786
|
+
heap = [(-gain(f), f) for f in open_]
|
|
787
|
+
heapq.heapify(heap)
|
|
788
|
+
while total > limit and heap:
|
|
789
|
+
g, f = heapq.heappop(heap)
|
|
790
|
+
if f in whole:
|
|
791
|
+
continue
|
|
792
|
+
now = gain(f)
|
|
793
|
+
if now != -g: # changed since it was queued
|
|
794
|
+
heapq.heappush(heap, (-now, f))
|
|
795
|
+
continue
|
|
796
|
+
if now <= 0:
|
|
797
|
+
break
|
|
798
|
+
whole.add(f)
|
|
799
|
+
total -= now
|
|
800
|
+
for k in [parent[f]] + kids[f]:
|
|
801
|
+
if k is not None and k in listable and split[k] != "/" and listable[k] \
|
|
802
|
+
and k not in never and k not in whole:
|
|
803
|
+
heapq.heappush(heap, (-gain(k), k))
|
|
804
|
+
return whole
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def _view_ops(split: Dict[str, str], hidden: Dict[str, str], whole: Set[str],
|
|
808
|
+
under_replaced: Callable[[str], bool],
|
|
809
|
+
fold: Callable[[str], str]) -> List[Tuple[str, ...]]:
|
|
810
|
+
"""The mount operations of `hidden_view`, with the folders in `whole` shown whole."""
|
|
811
|
+
ops: List[Tuple[str, ...]] = []
|
|
812
|
+
|
|
813
|
+
def emit(d: str, inside_whole: bool = False) -> None:
|
|
814
|
+
try:
|
|
815
|
+
names = sorted(os.listdir(d))
|
|
816
|
+
listable = fold(d) not in whole
|
|
817
|
+
except OSError:
|
|
818
|
+
names, listable = [], False
|
|
819
|
+
if not listable and d != "/":
|
|
820
|
+
# bound whole (or already visible inside a folder bound whole): rebuild below it
|
|
821
|
+
# only what is known, and mask the hidden entries that exist
|
|
822
|
+
if not inside_whole:
|
|
823
|
+
ops.append(("bind", d))
|
|
824
|
+
for f, x in sorted(split.items()):
|
|
825
|
+
# a hidden folder that is also split (a pattern walks it) is masked below,
|
|
826
|
+
# not rebuilt: nothing of it shows
|
|
827
|
+
if x != d and os.path.dirname(f) == fold(d) and f not in hidden:
|
|
828
|
+
emit(os.path.join(d, os.path.basename(x)), True)
|
|
829
|
+
# every entry whose folded name is hidden, by the name it has on disk (a case or
|
|
830
|
+
# Unicode form other than the one written): as hidden as in a rebuilt folder
|
|
831
|
+
try:
|
|
832
|
+
on_disk = [os.path.join(d, n) for n in sorted(os.listdir(d))
|
|
833
|
+
if fold(os.path.join(d, n)) in hidden]
|
|
834
|
+
except OSError: # cannot be listed: the names as written
|
|
835
|
+
on_disk = [os.path.join(d, os.path.basename(x)) for f, x in sorted(hidden.items())
|
|
836
|
+
if os.path.dirname(f) == fold(d)
|
|
837
|
+
and os.path.lexists(os.path.join(d, os.path.basename(x)))]
|
|
838
|
+
ops.extend(("mask", c) for c in on_disk)
|
|
839
|
+
return
|
|
840
|
+
ops.append(("tmpfs", d)) if d != "/" else None
|
|
841
|
+
for n in names:
|
|
842
|
+
c = os.path.join(d, n)
|
|
843
|
+
fc = fold(c)
|
|
844
|
+
if fc in hidden or under_replaced(c) or (d == "/" and n in ("proc", "dev")):
|
|
845
|
+
continue
|
|
846
|
+
if fc in split:
|
|
847
|
+
emit(c)
|
|
848
|
+
elif os.path.islink(c):
|
|
849
|
+
ops.append(("symlink", os.readlink(c), c))
|
|
850
|
+
elif os.path.lexists(c):
|
|
851
|
+
ops.append(("bind", c))
|
|
852
|
+
|
|
853
|
+
emit("/")
|
|
854
|
+
return ops
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def bwrap_tool_args(cfg: config.Config, places: Sequence[str], project: str,
|
|
858
|
+
env: Dict[str, str], folder: str, run: str,
|
|
859
|
+
server: bool = False) -> Tuple[List[str], List[int]]:
|
|
860
|
+
# a root that does not exist is hidden like the others: its folder is split, so a root made
|
|
861
|
+
# later is not in the view either (inside a session, every root is missing: launch nests)
|
|
862
|
+
args: List[str] = []
|
|
863
|
+
fds: List[int] = []
|
|
864
|
+
hide = (confine._spellings(list(cfg.all_roots)) + _credentials(env, cfg) + list(IPC_PATHS) +
|
|
865
|
+
[os.path.join(_real_home(env), config.LEGACY_STATE)])
|
|
866
|
+
ops, split, whole = hidden_view(hide, list(cfg.patterns), replaced=["/tmp", folder],
|
|
867
|
+
may_skip=_credentials(env, cfg) + list(IPC_PATHS),
|
|
868
|
+
soft_patterns=KRB5_CACHE_PATTERNS,
|
|
869
|
+
named=confine._spellings(list(cfg.all_roots)))
|
|
870
|
+
if whole:
|
|
871
|
+
sys.stderr.write(f"phiward launch: {len(whole)} folder(s) above protected paths hold too "
|
|
872
|
+
"many entries to rebuild, so they are shown whole with their protected "
|
|
873
|
+
"entries masked; a protected entry made or replaced in them during the "
|
|
874
|
+
"session is not hidden\n")
|
|
875
|
+
gits = git_dirs_in(project)
|
|
876
|
+
guards = confine._spellings(config.guard_files(env))
|
|
877
|
+
# a descriptor for every bind: the view's, then the places, the tool's /tmp, the project's
|
|
878
|
+
# .claude and .vscode, the git control files, the settings files and the guard files
|
|
879
|
+
_raise_fd_limit(sum(1 for o in ops if o[0] == "bind") + len(places) + 3 +
|
|
880
|
+
len(gits) * (len(GIT_CONTROL) + 1) + len(PROJECT_SETTINGS) + len(guards) + 64)
|
|
881
|
+
|
|
882
|
+
def bind(path: str, ro: bool, dest: Optional[str] = None) -> None:
|
|
883
|
+
try:
|
|
884
|
+
fd = _open_no_follow(path)
|
|
885
|
+
except (OSError, confine.ConfineError) as exc:
|
|
886
|
+
if os.path.lexists(path) and _no_link_on_path(path):
|
|
887
|
+
# not a link on the way: a read-only bind left out would leave the file
|
|
888
|
+
# writable through the place above it
|
|
889
|
+
why = exc.strerror if isinstance(exc, OSError) and exc.strerror else str(exc)
|
|
890
|
+
raise LaunchError(f"{path} cannot be opened to mount it in the session's view "
|
|
891
|
+
f"({why}); nothing runs")
|
|
892
|
+
return # a link on the way: not mounted (and so not reachable through it)
|
|
893
|
+
os.set_inheritable(fd, True)
|
|
894
|
+
fds.append(fd)
|
|
895
|
+
args.extend(["--ro-bind" if ro else "--bind", f"/proc/self/fd/{fd}", dest or path])
|
|
896
|
+
|
|
897
|
+
# the snapshot view first: nothing hidden is in it, and every later mount lands on top
|
|
898
|
+
for op in ops:
|
|
899
|
+
if op[0] == "tmpfs":
|
|
900
|
+
args += ["--tmpfs", op[1]]
|
|
901
|
+
elif op[0] == "symlink":
|
|
902
|
+
args += ["--symlink", op[1], op[2]]
|
|
903
|
+
elif op[0] == "mask":
|
|
904
|
+
args += ["--tmpfs", op[1]] if os.path.isdir(op[1]) and not os.path.islink(op[1]) \
|
|
905
|
+
else ["--ro-bind", "/dev/null", op[1]]
|
|
906
|
+
else:
|
|
907
|
+
n = len(args)
|
|
908
|
+
bind(op[1], True)
|
|
909
|
+
if len(args) == n:
|
|
910
|
+
raise LaunchError("an entry of the session's view changed while it was made; "
|
|
911
|
+
"start again")
|
|
912
|
+
args += ["--dev", "/dev", "--proc", "/proc", "--unshare-pid", "--unshare-ipc",
|
|
913
|
+
"--die-with-parent"]
|
|
914
|
+
# outside sockets first (before /tmp is replaced), then the tool's own temp folder as /tmp,
|
|
915
|
+
# then the write places on top (a project under /tmp stays visible)
|
|
916
|
+
for sock in _outside_sockets(list(places)):
|
|
917
|
+
args += ["--ro-bind-try", "/dev/null", sock]
|
|
918
|
+
# the tool folder is hidden: a session sees only its own run folder, bound back below
|
|
919
|
+
# (sessions cannot read each other)
|
|
920
|
+
args += ["--tmpfs", folder]
|
|
921
|
+
bind(os.path.join(run, "tmp"), False, "/tmp")
|
|
922
|
+
for p in places:
|
|
923
|
+
if os.path.isdir(p) and _no_link_on_path(p):
|
|
924
|
+
bind(p, False)
|
|
925
|
+
# files that run code later, by descriptor: folders as mount points (no rename), control and
|
|
926
|
+
# settings files read-only
|
|
927
|
+
for top in (".claude", ".vscode"):
|
|
928
|
+
q = os.path.join(project, top)
|
|
929
|
+
if os.path.isdir(q) and _no_link_on_path(q):
|
|
930
|
+
bind(q, server) # a wrapped MCP server: read-only as a whole
|
|
931
|
+
for gd, entry in gits:
|
|
932
|
+
if _no_link_on_path(entry):
|
|
933
|
+
bind(entry, not os.path.isdir(entry) or server)
|
|
934
|
+
if gd != entry and not _no_link_on_path(gd):
|
|
935
|
+
continue
|
|
936
|
+
if server:
|
|
937
|
+
bind(gd, True) # the whole git folder: no index, config, commondir or hooks
|
|
938
|
+
continue
|
|
939
|
+
for c in GIT_CONTROL:
|
|
940
|
+
q = os.path.join(gd, c)
|
|
941
|
+
if os.path.lexists(q) and _no_link_on_path(q):
|
|
942
|
+
bind(q, True)
|
|
943
|
+
for rel in PROJECT_SETTINGS:
|
|
944
|
+
q = os.path.join(project, rel)
|
|
945
|
+
if os.path.lexists(q) and _no_link_on_path(q):
|
|
946
|
+
bind(q, True)
|
|
947
|
+
for g in guards:
|
|
948
|
+
if os.path.lexists(g) and _no_link_on_path(g):
|
|
949
|
+
bind(g, True)
|
|
950
|
+
# masks last, for a hidden path under a place bound above (the view cannot leave it out
|
|
951
|
+
# there): nothing mounted above can re-expose it
|
|
952
|
+
rebound = list(places) + [project] + [g for g in guards
|
|
953
|
+
if os.path.isdir(g)]
|
|
954
|
+
for r in confine._spellings(hide + confine._pattern_matches(cfg.patterns)):
|
|
955
|
+
if not any(_inside(r, q) for q in rebound):
|
|
956
|
+
continue
|
|
957
|
+
if os.path.isdir(r):
|
|
958
|
+
args += ["--tmpfs", r]
|
|
959
|
+
elif os.path.lexists(r):
|
|
960
|
+
args += ["--ro-bind", "/dev/null", r]
|
|
961
|
+
# the split folders are read-only, like the host they stand for (each one mount only)
|
|
962
|
+
made = {op[1] for op in ops if op[0] == "tmpfs"} | {"/"}
|
|
963
|
+
for d in reversed(split):
|
|
964
|
+
if d in made:
|
|
965
|
+
args += ["--remount-ro", d]
|
|
966
|
+
# with --seccomp, --chdir and `--`, and after it the helper, a descriptor number for each
|
|
967
|
+
# bind and the tool (`_bwrap_command` counts the whole line once it is known)
|
|
968
|
+
need = len(args) + 8 + len(fds) + 8
|
|
969
|
+
if need > BWRAP_MAX_ARGS:
|
|
970
|
+
for fd in fds:
|
|
971
|
+
os.close(fd)
|
|
972
|
+
raise LaunchError(_too_long(need))
|
|
973
|
+
return args, fds
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def _too_long(n: int) -> str:
|
|
977
|
+
return (f"the session needs {n} bwrap arguments and bwrap takes at most {BWRAP_MAX_ARGS}; "
|
|
978
|
+
"protect fewer, larger folders (each pattern match inside the project is masked on "
|
|
979
|
+
"its own)")
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def _bwrap_command(bwrap: str, seccomp_fd: int, args: Sequence[str], project: str,
|
|
983
|
+
helper: Sequence[str], held: Sequence[str], argv: Sequence[str]) -> List[str]:
|
|
984
|
+
"""The bwrap command line. bwrap counts every word of it, the ones after `--` too, and
|
|
985
|
+
stops above BWRAP_MAX_ARGS: phiward refuses first, and says why."""
|
|
986
|
+
cmd = [bwrap, "--seccomp", str(seccomp_fd)] + list(args) + ["--chdir", project, "--"] + \
|
|
987
|
+
list(helper) + [str(len(held))] + list(held) + list(argv)
|
|
988
|
+
if len(cmd) - 1 > BWRAP_MAX_ARGS:
|
|
989
|
+
raise LaunchError(_too_long(len(cmd) - 1))
|
|
990
|
+
return cmd
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def _raise_fd_limit(need: int) -> None:
|
|
994
|
+
import resource
|
|
995
|
+
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
|
|
996
|
+
if soft != resource.RLIM_INFINITY and soft < need:
|
|
997
|
+
if hard != resource.RLIM_INFINITY and hard < need:
|
|
998
|
+
raise LaunchError(f"the session's view needs {need} open files; the limit is {hard}")
|
|
999
|
+
resource.setrlimit(resource.RLIMIT_NOFILE, (need, hard))
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
# the helper the tool starts through: it closes the launcher's descriptors, applies the Landlock
|
|
1003
|
+
# scope for abstract unix sockets and signals where the kernel has it (ABI 6), and execs the tool
|
|
1004
|
+
HELPER = r"""
|
|
1005
|
+
import os, sys, ctypes, struct
|
|
1006
|
+
n = int(sys.argv[1]); close = sys.argv[2:2 + n]; cmd = sys.argv[2 + n:]
|
|
1007
|
+
for c in close:
|
|
1008
|
+
try:
|
|
1009
|
+
os.close(int(c))
|
|
1010
|
+
except OSError:
|
|
1011
|
+
pass
|
|
1012
|
+
if sys.platform.startswith("linux"):
|
|
1013
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
1014
|
+
libc.syscall.restype = ctypes.c_long
|
|
1015
|
+
abi = libc.syscall(444, None, ctypes.c_size_t(0), ctypes.c_uint32(1))
|
|
1016
|
+
if abi >= 6:
|
|
1017
|
+
attr = struct.pack("<QQQ", 0, 0, 3) # no file rights handled; scope: abstract unix, signals
|
|
1018
|
+
buf = ctypes.create_string_buffer(attr, len(attr))
|
|
1019
|
+
rs = libc.syscall(444, buf, ctypes.c_size_t(len(attr)), ctypes.c_uint32(0))
|
|
1020
|
+
ok = rs >= 0 and libc.prctl(38, 1, 0, 0, 0) == 0 and libc.syscall(446, ctypes.c_int(rs), ctypes.c_uint32(0)) == 0
|
|
1021
|
+
if rs >= 0:
|
|
1022
|
+
os.close(rs)
|
|
1023
|
+
if not ok:
|
|
1024
|
+
sys.stderr.write("phiward launch: WARNING: the Landlock scope could not be applied: abstract unix sockets outside stay reachable\n")
|
|
1025
|
+
else:
|
|
1026
|
+
sys.stderr.write("phiward launch: no Landlock scope on this kernel: abstract unix sockets outside stay reachable\n")
|
|
1027
|
+
try:
|
|
1028
|
+
os.execvp(cmd[0], cmd)
|
|
1029
|
+
except OSError as e:
|
|
1030
|
+
sys.stderr.write("phiward launch: the tool could not start (%s)\n" % e.strerror); os._exit(127)
|
|
1031
|
+
"""
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
def _git_snapshot(project: str, limit: int = 20000) -> Dict[str, str]:
|
|
1035
|
+
"""The git control files of every git folder in the project: content hashes, with links
|
|
1036
|
+
recorded and never followed, only below folders with no link on their path, at most
|
|
1037
|
+
`limit` entries."""
|
|
1038
|
+
out: Dict[str, str] = {}
|
|
1039
|
+
for gd, entry in git_dirs_in(project):
|
|
1040
|
+
for q in [entry] + [os.path.join(gd, c) for c in GIT_CONTROL]:
|
|
1041
|
+
if len(out) >= limit or not os.path.lexists(q):
|
|
1042
|
+
continue
|
|
1043
|
+
if not _no_link_on_path(os.path.dirname(q)):
|
|
1044
|
+
out[q] = "link on the path"
|
|
1045
|
+
continue
|
|
1046
|
+
if os.path.islink(q):
|
|
1047
|
+
out[q] = "link:" + os.readlink(q)
|
|
1048
|
+
continue
|
|
1049
|
+
if os.path.isdir(q) and q != entry:
|
|
1050
|
+
for dirpath, dirs, files in os.walk(q, followlinks=False):
|
|
1051
|
+
for n in dirs + files:
|
|
1052
|
+
if len(out) >= limit:
|
|
1053
|
+
break
|
|
1054
|
+
x = os.path.join(dirpath, n)
|
|
1055
|
+
out[x] = _digest(x)
|
|
1056
|
+
elif os.path.isfile(q):
|
|
1057
|
+
out[q] = _digest(q)
|
|
1058
|
+
return out
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
def _digest(path: str) -> str:
|
|
1062
|
+
try:
|
|
1063
|
+
st = os.lstat(path)
|
|
1064
|
+
if stat.S_ISLNK(st.st_mode):
|
|
1065
|
+
return "link:" + os.readlink(path)
|
|
1066
|
+
if not stat.S_ISREG(st.st_mode):
|
|
1067
|
+
return "dir" if stat.S_ISDIR(st.st_mode) else "special"
|
|
1068
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
1069
|
+
try:
|
|
1070
|
+
return hashlib.sha256(os.read(fd, 1 << 20)).hexdigest()
|
|
1071
|
+
finally:
|
|
1072
|
+
os.close(fd)
|
|
1073
|
+
except OSError:
|
|
1074
|
+
return "?"
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
# -- the launcher ------------------------------------------------------------------------------
|
|
1078
|
+
|
|
1079
|
+
def _canary_path(env: Dict[str, str]) -> str:
|
|
1080
|
+
home = pathid.home(env)
|
|
1081
|
+
return os.path.join(home, ".phiward", CANARY)
|
|
1082
|
+
|
|
1083
|
+
|
|
1084
|
+
def _make_canary(canary: str) -> None:
|
|
1085
|
+
"""Make the canary unless it is there. Another launch may make it at the same moment (two
|
|
1086
|
+
wrapped MCP servers start at once): that is fine, its content does not matter;
|
|
1087
|
+
already_confined checks what is there."""
|
|
1088
|
+
try:
|
|
1089
|
+
fd = os.open(canary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
|
|
1090
|
+
except FileExistsError:
|
|
1091
|
+
return
|
|
1092
|
+
with os.fdopen(fd, "w") as fh:
|
|
1093
|
+
fh.write("the agent profile denies this file; launch checks it\n")
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
def already_confined(env: Dict[str, str]) -> bool:
|
|
1097
|
+
"""True only when the canary that only this profile denies is denied with EPERM (ordinary
|
|
1098
|
+
permissions give EACCES and do not count)."""
|
|
1099
|
+
if sys.platform != "darwin":
|
|
1100
|
+
return False # Linux nests: always wrap again
|
|
1101
|
+
# both must hold: this process is in a sandbox at all, and the canary that only phiward's
|
|
1102
|
+
# profile denies is denied. A canary replaced by a link into a folder macOS guards (privacy
|
|
1103
|
+
# folders give EPERM too), or another sandbox that denies ~/.phiward, must not let launch
|
|
1104
|
+
# skip its own profile
|
|
1105
|
+
if not _sandbox_check_self():
|
|
1106
|
+
return False
|
|
1107
|
+
canary = _canary_path(env)
|
|
1108
|
+
try:
|
|
1109
|
+
st = os.lstat(canary)
|
|
1110
|
+
if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode) or st.st_uid != os.getuid():
|
|
1111
|
+
return False
|
|
1112
|
+
except OSError as exc:
|
|
1113
|
+
if exc.errno != errno.EPERM:
|
|
1114
|
+
return False
|
|
1115
|
+
try:
|
|
1116
|
+
fd = os.open(canary, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
|
|
1117
|
+
os.close(fd)
|
|
1118
|
+
return False
|
|
1119
|
+
except OSError as exc:
|
|
1120
|
+
if exc.errno != errno.EPERM:
|
|
1121
|
+
return False
|
|
1122
|
+
# and the spool, a write place of phiward's own profile, is readable: another sandbox that
|
|
1123
|
+
# denies all of ~/.phiward does not pass for phiward's
|
|
1124
|
+
try:
|
|
1125
|
+
fd = os.open(config.spool_dir(env), os.O_RDONLY | os.O_DIRECTORY)
|
|
1126
|
+
os.close(fd)
|
|
1127
|
+
except OSError:
|
|
1128
|
+
return False
|
|
1129
|
+
return True
|
|
1130
|
+
|
|
1131
|
+
|
|
1132
|
+
def _make_dot_claude(project: str) -> None:
|
|
1133
|
+
"""`.claude` is made before the tool starts (after every check), so the session cannot make
|
|
1134
|
+
it a link."""
|
|
1135
|
+
p = os.path.join(project, ".claude")
|
|
1136
|
+
try:
|
|
1137
|
+
os.mkdir(p, 0o755)
|
|
1138
|
+
except FileExistsError:
|
|
1139
|
+
pass # there already, or another launch in this project made it just now
|
|
1140
|
+
st = os.lstat(p)
|
|
1141
|
+
if not stat.S_ISDIR(st.st_mode):
|
|
1142
|
+
raise OSError(errno.ENOTDIR, "the project's .claude is not a folder (a link?)", p)
|
|
1143
|
+
|
|
1144
|
+
|
|
1145
|
+
def build(argv: Sequence[str], cwd: str, env: Dict[str, str], adapter: Adapter,
|
|
1146
|
+
memory: bool = False, store: Optional[carryover.Store] = None,
|
|
1147
|
+
server: bool = False) -> Tuple[List[str], Dict[str, str], List[int], str]:
|
|
1148
|
+
cfg = config.load(cwd, env=env)
|
|
1149
|
+
if cfg.problem:
|
|
1150
|
+
raise LaunchError("the phiward config cannot be used (run phiward doctor)")
|
|
1151
|
+
if not cfg.has_protected_paths:
|
|
1152
|
+
raise LaunchError("no protected paths are configured: there is nothing to confine")
|
|
1153
|
+
from phiward import paths
|
|
1154
|
+
project = os.path.realpath(cwd)
|
|
1155
|
+
# only the configured roots count for "above": a derived git folder inside the project
|
|
1156
|
+
# must not stop work there
|
|
1157
|
+
if paths.ProtectedSet(cfg.all_roots, cfg.patterns).relation(project) == paths.INSIDE or \
|
|
1158
|
+
paths.ProtectedSet(cfg.roots, cfg.patterns).relation(project) == paths.ABOVE:
|
|
1159
|
+
raise LaunchError("this folder is inside or above a protected path; start the tool in a "
|
|
1160
|
+
"project folder")
|
|
1161
|
+
why = _project_problem(project, env)
|
|
1162
|
+
if why:
|
|
1163
|
+
raise LaunchError(f"this folder cannot be the project ({why}); start the tool in a "
|
|
1164
|
+
"project folder")
|
|
1165
|
+
# a settings path that is already a link would carry the session's writes to a file a later
|
|
1166
|
+
# plain run reads: refused
|
|
1167
|
+
for rel in (".claude", ".vscode") + PROJECT_SETTINGS:
|
|
1168
|
+
if os.path.islink(os.path.join(project, rel)):
|
|
1169
|
+
raise LaunchError(f"{rel} in the project is a link; replace it with a real file or "
|
|
1170
|
+
"folder")
|
|
1171
|
+
folder = tool_folder(adapter, env)
|
|
1172
|
+
_fixed_folders(folder)
|
|
1173
|
+
# this session's own folder: its config folder, built from the trusted copy, and its
|
|
1174
|
+
# temp folder; discarded after it, so nothing a session leaves there is read again
|
|
1175
|
+
run = os.path.join(folder, carryover.RUNS, time.strftime("%Y%m%d-%H%M%S-") + secrets.token_hex(4))
|
|
1176
|
+
store = store if store is not None else carryover.Store(adapter.name, _real_home(env))
|
|
1177
|
+
try:
|
|
1178
|
+
for line in store.start(folder, run, memory, adapter.turn_own_sandbox_off):
|
|
1179
|
+
sys.stderr.write(line + "\n")
|
|
1180
|
+
except (carryover.CarryoverError, OSError, RecursionError) as exc:
|
|
1181
|
+
raise LaunchError(f"carry-over: {exc}")
|
|
1182
|
+
if adapter.name == "claude" and not any(env.get(k) for k in (
|
|
1183
|
+
"CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN")):
|
|
1184
|
+
sys.stderr.write("phiward launch: each session starts with a fresh config folder, so "
|
|
1185
|
+
"Claude Code asks you to log in every time; to log in once, run `claude "
|
|
1186
|
+
"setup-token` and set CLAUDE_CODE_OAUTH_TOKEN (the agent can read it)\n")
|
|
1187
|
+
tmp = os.path.join(run, "tmp")
|
|
1188
|
+
os.makedirs(tmp, mode=0o700, exist_ok=True)
|
|
1189
|
+
canary = _canary_path(env)
|
|
1190
|
+
if sys.platform == "darwin":
|
|
1191
|
+
_make_canary(canary)
|
|
1192
|
+
child_env = {k: v for k, v in env.items() if _keep_env(k, cfg.launch_pass_env)}
|
|
1193
|
+
child_env["TMPDIR"] = tmp
|
|
1194
|
+
for k, rel in SESSION_CACHE_ENV.items():
|
|
1195
|
+
child_env[k] = os.path.join(run, rel)
|
|
1196
|
+
os.makedirs(child_env[k], mode=0o700, exist_ok=True)
|
|
1197
|
+
if sys.platform == "darwin":
|
|
1198
|
+
# xcrun's cache maps tool names to paths that /usr/bin shims use later: not used and not
|
|
1199
|
+
# writable; clang's module cache goes into the tool's folder
|
|
1200
|
+
child_env["xcrun_nocache"] = "1"
|
|
1201
|
+
child_env["CLANG_MODULE_CACHE_PATH"] = os.path.join(run, "cache", "clang")
|
|
1202
|
+
child_env["TMUX_TMPDIR"] = tmp # tmux's sockets in the session's folder
|
|
1203
|
+
child_env.update(adapter.extra_env)
|
|
1204
|
+
if adapter.name == "claude": # auto memory off unless asked
|
|
1205
|
+
if memory:
|
|
1206
|
+
child_env.pop("CLAUDE_CODE_DISABLE_AUTO_MEMORY", None)
|
|
1207
|
+
else:
|
|
1208
|
+
child_env["CLAUDE_CODE_DISABLE_AUTO_MEMORY"] = "1"
|
|
1209
|
+
if adapter.config_env:
|
|
1210
|
+
child_env[adapter.config_env] = os.path.join(run, "config")
|
|
1211
|
+
if adapter.name == "claude":
|
|
1212
|
+
child_env["CLAUDE_CODE_TMPDIR"] = tmp
|
|
1213
|
+
child_env["PHIWARD_HOOK_ROOTS"] = json.dumps(sorted(set(cfg.all_roots)))
|
|
1214
|
+
child_env["PHIWARD_LAUNCH_DEPTH"] = str(int(env.get("PHIWARD_LAUNCH_DEPTH", "0") or 0) + 1)
|
|
1215
|
+
os.makedirs(config.spool_dir(env), mode=0o700, exist_ok=True)
|
|
1216
|
+
places = write_places(project, env, run)
|
|
1217
|
+
# phiward's own files as installed, unchanged, owned by the operator or root
|
|
1218
|
+
from phiward import selfcheck
|
|
1219
|
+
installed, problems = selfcheck.check_isolated()
|
|
1220
|
+
if not installed and env.get("PHIWARD_DEV") != "1":
|
|
1221
|
+
raise LaunchError("phiward has no install record to check itself against (a source "
|
|
1222
|
+
"checkout or an editable install); install it with uv tool or pipx, "
|
|
1223
|
+
"or set PHIWARD_DEV=1 to start anyway")
|
|
1224
|
+
if problems:
|
|
1225
|
+
raise LaunchError(selfcheck.refusal(problems) + "; " +
|
|
1226
|
+
selfcheck.fix_text(problems, selfcheck._running_package()))
|
|
1227
|
+
backend = confine.backend()
|
|
1228
|
+
helper = [sys.executable, "-I", "-S", "-c", HELPER]
|
|
1229
|
+
if backend == "seatbelt":
|
|
1230
|
+
if _sandbox_check_self():
|
|
1231
|
+
raise LaunchError("this process is inside another sandbox; macOS cannot apply a second "
|
|
1232
|
+
"one (start the tool from a plain terminal)")
|
|
1233
|
+
_make_dot_claude(project)
|
|
1234
|
+
prof = seatbelt_tool_profile(cfg, places, project, env, folder, canary, server)
|
|
1235
|
+
return [confine.SANDBOX_EXEC, "-p", prof] + helper + ["0"] + list(argv), child_env, [], \
|
|
1236
|
+
project
|
|
1237
|
+
if backend == "bwrap":
|
|
1238
|
+
if not os.path.isfile(config.user_config_path(env)):
|
|
1239
|
+
raise LaunchError("no user config exists, and on Linux the tool could create one; "
|
|
1240
|
+
"run phiward setup first")
|
|
1241
|
+
_make_dot_claude(project)
|
|
1242
|
+
made = _placeholders(project)
|
|
1243
|
+
if made:
|
|
1244
|
+
sys.stderr.write("phiward launch: made read-only placeholders in the project: "
|
|
1245
|
+
f"{', '.join(made)}\n")
|
|
1246
|
+
args, fds = bwrap_tool_args(cfg, places, project, env, folder, run, server)
|
|
1247
|
+
r, w = os.pipe()
|
|
1248
|
+
os.write(w, tool_seccomp_program())
|
|
1249
|
+
os.close(w)
|
|
1250
|
+
os.set_inheritable(r, True)
|
|
1251
|
+
held = [str(fd) for fd in fds]
|
|
1252
|
+
bwrap = shutil.which("bwrap", path="/usr/bin:/bin") or "bwrap"
|
|
1253
|
+
try:
|
|
1254
|
+
cmd = _bwrap_command(bwrap, r, args, project, helper, held, argv)
|
|
1255
|
+
except LaunchError:
|
|
1256
|
+
for fd in fds + [r]:
|
|
1257
|
+
os.close(fd)
|
|
1258
|
+
raise
|
|
1259
|
+
return cmd, child_env, fds + [r], project
|
|
1260
|
+
raise LaunchError("no confinement backend on this system")
|
|
1261
|
+
|
|
1262
|
+
|
|
1263
|
+
class _Run:
|
|
1264
|
+
"""What one `launch` did, for `--report`."""
|
|
1265
|
+
|
|
1266
|
+
def __init__(self) -> None:
|
|
1267
|
+
self.ran = False
|
|
1268
|
+
self.notes: List[str] = [] # every line launch printed at the end, in order
|
|
1269
|
+
self.carryover: List[str] = [] # the session's instructions and folders (quarantine)
|
|
1270
|
+
self.groups: Dict[int, List[Tuple[str, str]]] = {} # changed project files by kind
|
|
1271
|
+
self.git: List[str] = [] # changed git control files (Linux)
|
|
1272
|
+
self.truncated = False # the project scan was cut short
|
|
1273
|
+
|
|
1274
|
+
def say(self, line: str) -> None:
|
|
1275
|
+
sys.stderr.write(line + "\n")
|
|
1276
|
+
self.notes.append(line)
|
|
1277
|
+
|
|
1278
|
+
def data(self, code: Optional[int]) -> Dict[str, object]:
|
|
1279
|
+
kinds = {k: len(self.groups.get(i, [])) for i, k in enumerate(carryover.KINDS)}
|
|
1280
|
+
return {"exit": code, "ran": self.ran,
|
|
1281
|
+
"needs_review": (not self.ran or bool(self.carryover) or bool(self.git)
|
|
1282
|
+
or self.truncated or any(kinds[k] for k in carryover.KINDS[:3])),
|
|
1283
|
+
"carryover": self.carryover, "project_changed": kinds,
|
|
1284
|
+
"git_control_changed": self.git, "notes": self.notes}
|
|
1285
|
+
|
|
1286
|
+
|
|
1287
|
+
def main(argv: List[str]) -> int:
|
|
1288
|
+
tool = "generic"
|
|
1289
|
+
rest = list(argv)
|
|
1290
|
+
if rest[:1] in (["-h"], ["--help"]):
|
|
1291
|
+
sys.stdout.write(HELP)
|
|
1292
|
+
return 0
|
|
1293
|
+
memory = False
|
|
1294
|
+
report = ""
|
|
1295
|
+
server = False
|
|
1296
|
+
while rest[:1] in (["--tool"], ["--memory"], ["--report"], ["--entry"]):
|
|
1297
|
+
if rest[0] == "--entry" and len(rest) >= 2:
|
|
1298
|
+
# the id `phiward mcp wrap` gives an entry: part of this launcher's record, and a
|
|
1299
|
+
# wrapped MCP server's profile (SERVER_READ_ONLY)
|
|
1300
|
+
rest, server = rest[2:], True
|
|
1301
|
+
elif rest[0] == "--memory":
|
|
1302
|
+
memory, rest = True, rest[1:]
|
|
1303
|
+
elif rest[0] == "--report" and len(rest) >= 2:
|
|
1304
|
+
report, rest = rest[1], rest[2:]
|
|
1305
|
+
elif len(rest) >= 2:
|
|
1306
|
+
tool, rest = rest[1], rest[2:]
|
|
1307
|
+
else:
|
|
1308
|
+
break
|
|
1309
|
+
env = dict(os.environ)
|
|
1310
|
+
if report:
|
|
1311
|
+
report, why = _report_place(report, env)
|
|
1312
|
+
if why:
|
|
1313
|
+
sys.stderr.write(f"phiward launch: --report: {why}; nothing runs\n")
|
|
1314
|
+
return 2
|
|
1315
|
+
run = _Run()
|
|
1316
|
+
# this launcher's record, while it runs: the hook trusts an MCP server wrapped in
|
|
1317
|
+
# `phiward launch --` only when a live launcher of its command is a child of Claude Code
|
|
1318
|
+
from phiward import mcp_config
|
|
1319
|
+
record = mcp_config.record_launch(list(argv))
|
|
1320
|
+
try:
|
|
1321
|
+
code = _launch(tool, memory, rest, env, run, report, server)
|
|
1322
|
+
finally:
|
|
1323
|
+
mcp_config.end_launch(record)
|
|
1324
|
+
if report and not _write_report(report, run.data(code)):
|
|
1325
|
+
return code or 2
|
|
1326
|
+
return code
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
def _launch(tool: str, memory: bool, rest: List[str], env: Dict[str, str], run: _Run,
|
|
1330
|
+
report: str, server: bool = False) -> int:
|
|
1331
|
+
if tool not in ADAPTERS:
|
|
1332
|
+
run.say(f"phiward launch: no adapter for '{tool}' (known: {', '.join(sorted(ADAPTERS))})")
|
|
1333
|
+
return 2
|
|
1334
|
+
adapter = ADAPTERS[tool]
|
|
1335
|
+
if rest[:1] == ["--"]:
|
|
1336
|
+
rest = rest[1:]
|
|
1337
|
+
if not rest:
|
|
1338
|
+
if not adapter.program:
|
|
1339
|
+
run.say(USAGE.rstrip())
|
|
1340
|
+
return 2
|
|
1341
|
+
prog = shutil.which(adapter.program)
|
|
1342
|
+
if not prog:
|
|
1343
|
+
run.say(f"phiward launch: {adapter.program} is not on PATH")
|
|
1344
|
+
return 127
|
|
1345
|
+
rest = [prog]
|
|
1346
|
+
if int(env.get("PHIWARD_LAUNCH_DEPTH", "0") or 0) >= MAX_DEPTH:
|
|
1347
|
+
run.say("phiward launch: launched too many times inside itself; nothing runs")
|
|
1348
|
+
return 126
|
|
1349
|
+
if already_confined(env):
|
|
1350
|
+
if report: # the tool replaces this process: the report says so, without an exit
|
|
1351
|
+
run.notes.append("launch inside launch: the outer session's profile holds; "
|
|
1352
|
+
"this launch reports nothing more")
|
|
1353
|
+
if not _write_report(report, run.data(None)):
|
|
1354
|
+
# an earlier run's report must not stand for this one
|
|
1355
|
+
run.say("phiward launch: the --report file cannot be written; nothing runs")
|
|
1356
|
+
return 2
|
|
1357
|
+
os.execvp(rest[0], rest) # launch inside launch: this profile already holds
|
|
1358
|
+
# until the end, the report says the run needs review (a crash, a signal); a report that
|
|
1359
|
+
# cannot be written stops the run, so an earlier report never stands for this one. It is
|
|
1360
|
+
# written before the session's view is built: on Linux the view holds the report file by
|
|
1361
|
+
# descriptor, which must stay the file that is there until the tool exits
|
|
1362
|
+
if report and not _write_report(report, run.data(None)):
|
|
1363
|
+
run.say("phiward launch: the report cannot be written; nothing runs")
|
|
1364
|
+
return 2
|
|
1365
|
+
store = carryover.Store(adapter.name, _real_home(env))
|
|
1366
|
+
folder = tool_folder(adapter, env)
|
|
1367
|
+
try:
|
|
1368
|
+
cmd, child_env, fds, project = build(rest, os.getcwd(), env, adapter, memory, store,
|
|
1369
|
+
server)
|
|
1370
|
+
except (LaunchError, confine.ConfineError, OSError, RecursionError) as exc:
|
|
1371
|
+
run.say(f"phiward launch: {exc}; nothing runs")
|
|
1372
|
+
if store.run: # only a session this launcher built: closed, it never ran
|
|
1373
|
+
try:
|
|
1374
|
+
store.end(folder)
|
|
1375
|
+
except (carryover.CarryoverError, OSError):
|
|
1376
|
+
pass
|
|
1377
|
+
return 126
|
|
1378
|
+
# wait for the tool; then carry-over: the session's instruction changes to
|
|
1379
|
+
# quarantine and its folder discarded, the project's changes reported, and on Linux git
|
|
1380
|
+
# control files outside the project compared too
|
|
1381
|
+
import signal
|
|
1382
|
+
git_before = _git_snapshot(project) if sys.platform.startswith("linux") else {}
|
|
1383
|
+
proj_before = carryover.project_state(project)
|
|
1384
|
+
proc = subprocess.Popen(cmd, env=child_env, pass_fds=fds)
|
|
1385
|
+
run.ran = True
|
|
1386
|
+
for fd in fds:
|
|
1387
|
+
os.close(fd)
|
|
1388
|
+
old = signal.signal(signal.SIGINT, signal.SIG_IGN) # Ctrl-C goes to the tool, not to us
|
|
1389
|
+
try:
|
|
1390
|
+
code = proc.wait()
|
|
1391
|
+
finally:
|
|
1392
|
+
signal.signal(signal.SIGINT, old)
|
|
1393
|
+
# no process is ever ended: on Linux the PID namespace ends them with the tool; on
|
|
1394
|
+
# macOS a process left behind can still write the project and the temp folders, but
|
|
1395
|
+
# not a run folder a later session reads
|
|
1396
|
+
try:
|
|
1397
|
+
run.carryover = store.end(folder)
|
|
1398
|
+
except Exception as exc: # the session stays open: the next start tries again
|
|
1399
|
+
run.carryover = [f"phiward launch: carry-over did not finish ({exc}); the next "
|
|
1400
|
+
"launch tries again before the tool starts"]
|
|
1401
|
+
proj_after = carryover.project_state(project)
|
|
1402
|
+
changes = carryover.project_changes(proj_before, proj_after, project)
|
|
1403
|
+
run.groups, run.truncated = changes
|
|
1404
|
+
for line in run.carryover + carryover.project_report(changes):
|
|
1405
|
+
run.say(line)
|
|
1406
|
+
git_after = _git_snapshot(project) if sys.platform.startswith("linux") else {}
|
|
1407
|
+
run.git = sorted(k for k in set(git_before) | set(git_after)
|
|
1408
|
+
if git_before.get(k) != git_after.get(k))
|
|
1409
|
+
for line in _git_lines(run.git):
|
|
1410
|
+
run.say(line)
|
|
1411
|
+
return code
|
|
1412
|
+
|
|
1413
|
+
|
|
1414
|
+
def _report_place(path: str, env: Dict[str, str]) -> Tuple[str, str]:
|
|
1415
|
+
"""(the report's full path in its real folder, why it is refused or ""), decided before the
|
|
1416
|
+
tool runs. Never a place the session can write (the project, its run folders, the spool,
|
|
1417
|
+
the per-user temp folder, ~/.phiward), where it could change the report or plant something
|
|
1418
|
+
at its place; never a file that controls the guards (phiward's config and code, Claude
|
|
1419
|
+
Code's settings, the hidden list), which the report would replace; never a folder.
|
|
1420
|
+
Compared in every spelling the file system treats as equal (case on macOS)."""
|
|
1421
|
+
from phiward import claude_settings, hidden
|
|
1422
|
+
folder = os.path.realpath(os.path.dirname(os.path.abspath(path)) or ".")
|
|
1423
|
+
full = os.path.join(folder, os.path.basename(path))
|
|
1424
|
+
if not os.path.basename(path) or not os.path.isdir(folder):
|
|
1425
|
+
return full, "its folder does not exist"
|
|
1426
|
+
if os.path.isdir(full):
|
|
1427
|
+
return full, "it is a folder; give a file name"
|
|
1428
|
+
home = _real_home(env)
|
|
1429
|
+
project = os.path.realpath(os.getcwd())
|
|
1430
|
+
places = write_places(project, env) + [os.path.join(home, ".phiward")]
|
|
1431
|
+
if any(config._deny_inside(full, os.path.realpath(p)) for p in places):
|
|
1432
|
+
return full, ("it is in a place the session can write (the project, the spool, the "
|
|
1433
|
+
"temp folder or ~/.phiward); give a path outside them")
|
|
1434
|
+
cfg = config.load(project, env=env)
|
|
1435
|
+
guards = config.guard_files(env) + hidden.paths(None, cfg, session=True) + [
|
|
1436
|
+
claude_settings.user_dir(home, env)] + list(claude_settings.MANAGED)
|
|
1437
|
+
if any(config._deny_inside(full, os.path.realpath(g)) for g in guards):
|
|
1438
|
+
return full, ("it is a file that controls the guards (phiward's config or code, Claude "
|
|
1439
|
+
"Code's settings) or a hidden credential; give another path")
|
|
1440
|
+
return full, ""
|
|
1441
|
+
|
|
1442
|
+
|
|
1443
|
+
def _write_report(path: str, data: Dict[str, object]) -> bool:
|
|
1444
|
+
"""Write the report as a new file next to `path` and move it into place: nothing that is
|
|
1445
|
+
at the place (a link, a FIFO, a hard link to another file) is opened or written."""
|
|
1446
|
+
try:
|
|
1447
|
+
safeio.write_new(path, json.dumps(data, indent=2) + "\n")
|
|
1448
|
+
return True
|
|
1449
|
+
except OSError as exc:
|
|
1450
|
+
sys.stderr.write(f"phiward launch: the report was not written ({type(exc).__name__})\n")
|
|
1451
|
+
return False
|
|
1452
|
+
|
|
1453
|
+
|
|
1454
|
+
def _git_lines(changed: List[str]) -> List[str]:
|
|
1455
|
+
"""The warning about git control files the session changed (Linux)."""
|
|
1456
|
+
if not changed:
|
|
1457
|
+
return []
|
|
1458
|
+
out = [f"phiward launch: WARNING: the session changed {len(changed)} git control file(s); "
|
|
1459
|
+
"check them before you run git outside launch:"]
|
|
1460
|
+
out += [" " + c.encode("unicode_escape").decode("ascii") for c in changed[:50]]
|
|
1461
|
+
if len(changed) > 50:
|
|
1462
|
+
out.append(f" ... and {len(changed) - 50} more")
|
|
1463
|
+
return out
|