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/fasthook.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""The hook under `phiward launch`: a fast, helpful first layer.
|
|
2
|
+
|
|
3
|
+
Under `launch` the kernel decides about every file the tool touches, so the hook only has to
|
|
4
|
+
turn an attempt at a protected path into a helpful refusal (use the gateway) before the tool
|
|
5
|
+
wastes a turn on a kernel error. It loads only `json`, `os` and the gateway's command parser
|
|
6
|
+
(to allow a whole `phiward run|copy` call): the protected paths come from
|
|
7
|
+
`PHIWARD_HOOK_ROOTS`, which `launch` sets in the tool's environment. Allow is
|
|
8
|
+
silence; deny is exit 2 with one short line. A payload it cannot read is allowed: the kernel is
|
|
9
|
+
the boundary here, and this layer must never stop work by mistake.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
REASON = ("phiward: that path is protected; read it with `phiward run -- CMD` "
|
|
17
|
+
"(see AGENTS.md)")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
PATH_FIELDS = ("file_path", "path", "notebook_path", "pattern")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _protected(s: str, keys, cwd: str, fold: bool) -> bool:
|
|
24
|
+
cand = s.casefold() if fold else s
|
|
25
|
+
if any(k in cand for k in keys):
|
|
26
|
+
return True
|
|
27
|
+
if s.startswith(("/", "~", ".")) and len(s) < 4096 and "\n" not in s:
|
|
28
|
+
p = os.path.realpath(os.path.join(cwd, os.path.expanduser(s)))
|
|
29
|
+
p = p.casefold() if fold else p
|
|
30
|
+
return any(p == k or p.startswith(k + "/") for k in keys)
|
|
31
|
+
return False
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main() -> int:
|
|
35
|
+
try:
|
|
36
|
+
roots = [r for r in json.loads(os.environ.get("PHIWARD_HOOK_ROOTS", "[]"))
|
|
37
|
+
if isinstance(r, str) and r.startswith("/")]
|
|
38
|
+
payload = json.load(sys.stdin)
|
|
39
|
+
except (ValueError, OSError):
|
|
40
|
+
return 0
|
|
41
|
+
fold = sys.platform == "darwin"
|
|
42
|
+
keys = [(r.rstrip("/").casefold() if fold else r.rstrip("/")) for r in roots]
|
|
43
|
+
tool = payload.get("tool_name") or payload.get("toolName") or ""
|
|
44
|
+
inp = payload.get("tool_input") or payload.get("toolArgs") or {}
|
|
45
|
+
cwd = payload.get("cwd") or os.getcwd()
|
|
46
|
+
if not isinstance(inp, dict):
|
|
47
|
+
return 0
|
|
48
|
+
if tool in ("Bash", "bash"):
|
|
49
|
+
cmd = inp.get("command", "")
|
|
50
|
+
if not isinstance(cmd, str):
|
|
51
|
+
return 0
|
|
52
|
+
if "phiward" in cmd:
|
|
53
|
+
# a whole gateway call names protected paths by design
|
|
54
|
+
from phiward import gateway
|
|
55
|
+
if gateway.parse_call(cmd) is not None:
|
|
56
|
+
return 0
|
|
57
|
+
texts = [cmd]
|
|
58
|
+
else:
|
|
59
|
+
# only where a file tool goes, not what it writes: a script may name the data folder
|
|
60
|
+
#
|
|
61
|
+
texts = [inp[f] for f in PATH_FIELDS if isinstance(inp.get(f), str)]
|
|
62
|
+
for s in texts:
|
|
63
|
+
if _protected(s, keys, cwd, fold):
|
|
64
|
+
sys.stderr.write(REASON + "\n")
|
|
65
|
+
return 2
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if __name__ == "__main__":
|
|
70
|
+
sys.exit(main())
|
phiward/fsinfo.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""File-system behaviours that matter for protected folders, found without naming a vendor.
|
|
2
|
+
|
|
3
|
+
- `snapshot_dirs(root, names)`: snapshot folders next to the root or above it (`.snapshot`,
|
|
4
|
+
`.snapshots`, `.zfs`, `~snapshot`, and names from `[protected_paths] snapshot_names`). Each one
|
|
5
|
+
holds old copies of protected files under another path, so it becomes a derived root.
|
|
6
|
+
- `alias_paths(root, mountinfo)`: on Linux, other mount points that show the same part of the
|
|
7
|
+
same file system (bind mounts, a second mount of one export), from `/proc/self/mountinfo`.
|
|
8
|
+
- `mount_of(path, mountinfo)`: the mount that holds a path, with its file-system type.
|
|
9
|
+
- `hardlinked_count(roots, limit)`: protected files that have other hard links. Path rules
|
|
10
|
+
cannot cover those other names; `doctor` warns.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import stat
|
|
15
|
+
from typing import Dict, List, Optional, Sequence
|
|
16
|
+
|
|
17
|
+
SNAPSHOT_NAMES = (".snapshot", ".snapshots", ".zfs", "~snapshot", ".snap")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def snapshot_dirs(root: str, names: Sequence[str] = ()) -> List[str]:
|
|
21
|
+
out: List[str] = []
|
|
22
|
+
want = list(SNAPSHOT_NAMES) + [n for n in names if n not in SNAPSHOT_NAMES]
|
|
23
|
+
here = os.path.dirname(os.path.realpath(root)) # the real place
|
|
24
|
+
while True:
|
|
25
|
+
for n in want:
|
|
26
|
+
cand = os.path.join(here, n)
|
|
27
|
+
try:
|
|
28
|
+
st = os.lstat(cand)
|
|
29
|
+
except OSError:
|
|
30
|
+
continue
|
|
31
|
+
if stat.S_ISDIR(st.st_mode) and cand not in out:
|
|
32
|
+
out.append(cand)
|
|
33
|
+
parent = os.path.dirname(here)
|
|
34
|
+
if parent == here:
|
|
35
|
+
return out
|
|
36
|
+
here = parent
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _unescape(field: str) -> str:
|
|
40
|
+
# mountinfo escapes space, tab, newline and backslash as octal
|
|
41
|
+
out, i = "", 0
|
|
42
|
+
while i < len(field):
|
|
43
|
+
if field[i] == "\\" and i + 3 < len(field) and field[i + 1:i + 4].isdigit():
|
|
44
|
+
out += chr(int(field[i + 1:i + 4], 8))
|
|
45
|
+
i += 4
|
|
46
|
+
else:
|
|
47
|
+
out += field[i]
|
|
48
|
+
i += 1
|
|
49
|
+
return out
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def read_mountinfo() -> str:
|
|
53
|
+
try:
|
|
54
|
+
with open("/proc/self/mountinfo", encoding="utf-8", errors="replace") as fh:
|
|
55
|
+
return fh.read()
|
|
56
|
+
except OSError:
|
|
57
|
+
return ""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _mounts(mountinfo: str) -> List[Dict[str, str]]:
|
|
61
|
+
out = []
|
|
62
|
+
for line in mountinfo.splitlines():
|
|
63
|
+
if " - " not in line:
|
|
64
|
+
continue
|
|
65
|
+
left, right = line.split(" - ", 1)
|
|
66
|
+
lf, rf = left.split(), right.split()
|
|
67
|
+
if len(lf) < 5 or len(rf) < 2:
|
|
68
|
+
continue
|
|
69
|
+
out.append({"dev": lf[2], "root": _unescape(lf[3]), "point": _unescape(lf[4]),
|
|
70
|
+
"fstype": rf[0], "source": _unescape(rf[1]),
|
|
71
|
+
"superopts_raw": rf[2] if len(rf) > 2 else ""})
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _inside(p: str, folder: str) -> bool:
|
|
76
|
+
from phiward import pathid
|
|
77
|
+
return pathid.inside(p, folder)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def mount_of(path: str, mountinfo: Optional[str] = None) -> Optional[Dict[str, str]]:
|
|
81
|
+
mi = read_mountinfo() if mountinfo is None else mountinfo
|
|
82
|
+
best = None
|
|
83
|
+
for m in _mounts(mi):
|
|
84
|
+
if _inside(path, m["point"]) and (best is None or len(m["point"]) >= len(best["point"])):
|
|
85
|
+
best = m
|
|
86
|
+
return best
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# sources that name no particular data: two tmpfs mounts are not the same file system
|
|
90
|
+
_GENERIC_SOURCES = {"none", "tmpfs", "overlay", "proc", "sysfs", "devtmpfs", "cgroup", "cgroup2",
|
|
91
|
+
"devpts", "mqueue", "shm", "fuse", "autofs", "nsfs", "bpf", "tracefs",
|
|
92
|
+
"securityfs", "debugfs", "configfs", "pstore", "efivarfs", "ramfs",
|
|
93
|
+
"hugetlbfs", "binfmt_misc", "rpc_pipefs", "portal", "fusectl"}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _same_data(a: Dict[str, str], b: Dict[str, str]) -> bool:
|
|
97
|
+
"""Whether two mounts show the same file system: the same device numbers, or (network and
|
|
98
|
+
block file systems only) the same source and type."""
|
|
99
|
+
if a["dev"] == b["dev"]: # one superblock: the same data, whatever the type
|
|
100
|
+
return True
|
|
101
|
+
generic = (a["source"] in _GENERIC_SOURCES or a["fstype"] in _GENERIC_SOURCES or
|
|
102
|
+
a["fstype"].startswith("fuse."))
|
|
103
|
+
return a["source"] == b["source"] and a["fstype"] == b["fstype"] and not generic
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _split_unescaped(text: str, seps: str) -> List[str]:
|
|
107
|
+
"""Split on separators that are not escaped (mountinfo writes `,` and `:` in a path as
|
|
108
|
+
`\\054`, a backslash as `\\134`; a raw split before unescaping cuts the path)."""
|
|
109
|
+
# the kernel writes `,` in a path as \054 and a user's backslash as \134, so a separator
|
|
110
|
+
# right after \134 is part of the path
|
|
111
|
+
out, cur, i = [], "", 0
|
|
112
|
+
while i < len(text):
|
|
113
|
+
if text[i] in seps and not cur.endswith("\\134"):
|
|
114
|
+
out.append(cur)
|
|
115
|
+
cur = ""
|
|
116
|
+
else:
|
|
117
|
+
cur += text[i]
|
|
118
|
+
i += 1
|
|
119
|
+
out.append(cur)
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _overlay_lowers(m: Dict[str, str]) -> Optional[List[str]]:
|
|
124
|
+
"""The lower and upper folders of an overlay mount, unescaped; None when one cannot be
|
|
125
|
+
read as an absolute path (then it is unknown)."""
|
|
126
|
+
out: List[str] = []
|
|
127
|
+
for kv in _split_unescaped(m.get("superopts_raw", ""), ","):
|
|
128
|
+
key, _, val = kv.partition("=")
|
|
129
|
+
if key in ("lowerdir", "upperdir", "lowerdir+", "datadir+"):
|
|
130
|
+
for part in _split_unescaped(val, ":"):
|
|
131
|
+
part = _unescape(part)
|
|
132
|
+
if not part:
|
|
133
|
+
continue
|
|
134
|
+
if not part.startswith("/"):
|
|
135
|
+
return None
|
|
136
|
+
out.append(os.path.normpath(part))
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def unknown_overlays(mountinfo: Optional[str] = None) -> List[str]:
|
|
141
|
+
"""Mount points of overlays whose lower or upper folders cannot be read; phiward
|
|
142
|
+
cannot tell whether they show a protected folder, so the config refuses (fail closed)."""
|
|
143
|
+
mi = read_mountinfo() if mountinfo is None else mountinfo
|
|
144
|
+
return [m["point"] for m in _mounts(mi) if m["fstype"] == "overlay" and
|
|
145
|
+
_overlay_lowers(m) is None]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _relation_by_identity(root: str, other: str) -> Optional[str]:
|
|
149
|
+
"""'lower-inside' when `other` is the root or inside it, 'root-inside' when the root is
|
|
150
|
+
inside `other`, by (dev, ino) of the walked chains, not by spelling (an overlay
|
|
151
|
+
lower may be a link to the root, or a bind mount of it)."""
|
|
152
|
+
from phiward import pathid
|
|
153
|
+
try:
|
|
154
|
+
r = pathid.walk_full(root)
|
|
155
|
+
o = pathid.walk_full(other)
|
|
156
|
+
except OSError:
|
|
157
|
+
return "lower-inside" # cannot tell: treat as showing the root (fail closed)
|
|
158
|
+
if not (r.ids and o.ids):
|
|
159
|
+
return None
|
|
160
|
+
if r.ids[-1] in o.ids:
|
|
161
|
+
return "lower-inside"
|
|
162
|
+
if o.ids[-1] in r.ids:
|
|
163
|
+
return "root-inside"
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _alias_against(in_fs: str, m: Dict[str, str], mounts: List[Dict[str, str]],
|
|
168
|
+
skip: str) -> List[str]:
|
|
169
|
+
out: List[str] = []
|
|
170
|
+
for n in mounts:
|
|
171
|
+
if n["point"] == skip:
|
|
172
|
+
continue
|
|
173
|
+
alias = None
|
|
174
|
+
if _same_data(n, m):
|
|
175
|
+
if _inside(in_fs, n["root"]): # the mount shows the whole path
|
|
176
|
+
alias = os.path.join(n["point"], os.path.relpath(in_fs, n["root"]))
|
|
177
|
+
elif _inside(n["root"], in_fs): # the mount shows a folder inside it
|
|
178
|
+
alias = n["point"]
|
|
179
|
+
if alias:
|
|
180
|
+
out.append(os.path.normpath(alias))
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def alias_paths(root: str, mountinfo: Optional[str] = None) -> List[str]:
|
|
185
|
+
"""Other mount points that show the root or any part of it (both
|
|
186
|
+
directions), including through a separate mount inside the root, and
|
|
187
|
+
overlay mounts that use it, or a folder inside it, as a lower or upper folder."""
|
|
188
|
+
mi = read_mountinfo() if mountinfo is None else mountinfo
|
|
189
|
+
root = os.path.realpath(root) if mountinfo is None else os.path.normpath(root)
|
|
190
|
+
mounts = _mounts(mi)
|
|
191
|
+
m = mount_of(root, mi)
|
|
192
|
+
if m is None:
|
|
193
|
+
return []
|
|
194
|
+
out: List[str] = []
|
|
195
|
+
rel = os.path.relpath(root, m["point"])
|
|
196
|
+
out += _alias_against(os.path.normpath(os.path.join(m["root"], rel)), m, mounts, m["point"])
|
|
197
|
+
# separate mounts inside the root: whatever shows their data elsewhere shows the root's
|
|
198
|
+
for inner in mounts:
|
|
199
|
+
if inner["point"] != m["point"] and inner["point"] != root and _inside(inner["point"], root):
|
|
200
|
+
out += _alias_against(inner["root"], inner, mounts, inner["point"])
|
|
201
|
+
elif inner["point"] == root and inner is not m:
|
|
202
|
+
out += _alias_against(inner["root"], inner, mounts, inner["point"])
|
|
203
|
+
for n in mounts:
|
|
204
|
+
if n["fstype"] != "overlay":
|
|
205
|
+
continue
|
|
206
|
+
for lower in _overlay_lowers(n) or []:
|
|
207
|
+
rel = _relation_by_identity(root, lower) if mountinfo is None else \
|
|
208
|
+
("lower-inside" if _inside(lower, root) else
|
|
209
|
+
"root-inside" if _inside(root, lower) else None)
|
|
210
|
+
if rel == "root-inside":
|
|
211
|
+
real_lower = os.path.realpath(lower) if mountinfo is None else lower
|
|
212
|
+
real_root = os.path.realpath(root) if mountinfo is None else root
|
|
213
|
+
sub = os.path.relpath(real_root, real_lower) if _inside(real_root, real_lower) \
|
|
214
|
+
else ""
|
|
215
|
+
out.append(os.path.normpath(os.path.join(n["point"], sub)) if sub else n["point"])
|
|
216
|
+
elif rel == "lower-inside":
|
|
217
|
+
out.append(n["point"])
|
|
218
|
+
seen: List[str] = []
|
|
219
|
+
for a in out:
|
|
220
|
+
if a != root and a not in seen:
|
|
221
|
+
seen.append(a)
|
|
222
|
+
return seen
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def hardlinked_count(roots: Sequence[str], limit: int) -> int:
|
|
226
|
+
n = seen = 0
|
|
227
|
+
for r in roots:
|
|
228
|
+
if not os.path.isdir(r):
|
|
229
|
+
continue
|
|
230
|
+
for dirpath, _dirs, files in os.walk(r, followlinks=False):
|
|
231
|
+
for f in files:
|
|
232
|
+
seen += 1
|
|
233
|
+
if seen > limit:
|
|
234
|
+
return n
|
|
235
|
+
try:
|
|
236
|
+
st = os.lstat(os.path.join(dirpath, f))
|
|
237
|
+
except OSError:
|
|
238
|
+
continue
|
|
239
|
+
if stat.S_ISREG(st.st_mode) and st.st_nlink > 1:
|
|
240
|
+
n += 1
|
|
241
|
+
return n
|
phiward/gateway.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Recognize a gateway call: `phiward run ...` or `phiward copy ...` as the whole command.
|
|
2
|
+
|
|
3
|
+
The hook allows such a command although it names protected paths: it is a client that hands
|
|
4
|
+
argv to the broker (broker.py), it runs in the agent's sandbox like any command, and the broker
|
|
5
|
+
checks grants against the user config. The form is strict all the same: one simple command with the bare
|
|
6
|
+
head `phiward`, no operators (only trailing newlines), no redirections, no command or
|
|
7
|
+
process substitution, no variable other than $HOME. Globs, braces and `~` are allowed: the shell
|
|
8
|
+
expands them into the client's arguments. Any other spelling (a path, `python -m`) is an
|
|
9
|
+
ordinary command, and the guard checks it as one.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import List, Optional
|
|
15
|
+
|
|
16
|
+
from phiward import shell
|
|
17
|
+
from phiward.names import MODULES, PROGRAMS
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Call:
|
|
22
|
+
name: str # "run" or "copy"
|
|
23
|
+
args: List[str] # the words after the subcommand, as written (quotes removed)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _only_home(w: shell.Word) -> bool:
|
|
27
|
+
return all(k != "var" or n == "HOME" for k, n, _ in w.segs) and \
|
|
28
|
+
not any(k in ("special", "sub", "varx") for k, _, _ in w.segs)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parse_call(command: str) -> Optional[Call]:
|
|
32
|
+
words = whole_command(command)
|
|
33
|
+
if not words or words[0] not in ("run", "copy"):
|
|
34
|
+
return None
|
|
35
|
+
return Call(words[0], words[1:])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def whole_command(command: str) -> Optional[List[str]]:
|
|
39
|
+
"""The words after `phiward` of a phiward command written as the whole command (the bare
|
|
40
|
+
name, then words fixed as written: no substitution, no variable but `~` and `$HOME`, one
|
|
41
|
+
simple command), or None."""
|
|
42
|
+
try:
|
|
43
|
+
parsed = shell.parse(command)
|
|
44
|
+
except (shell.ShellSyntaxError, ValueError, RecursionError):
|
|
45
|
+
return None
|
|
46
|
+
items = list(parsed.items)
|
|
47
|
+
while items and isinstance(items[-1], shell.Op) and items[-1].text == "\n":
|
|
48
|
+
items.pop() # only trailing newlines; one between words would start a second command
|
|
49
|
+
if not items or not all(isinstance(it, shell.Word) for it in items):
|
|
50
|
+
return None
|
|
51
|
+
if parsed.subs or parsed.heredocs:
|
|
52
|
+
return None
|
|
53
|
+
words: List[shell.Word] = items # type: ignore[assignment]
|
|
54
|
+
if any(w.has_sub or not _only_home(w) for w in words):
|
|
55
|
+
return None
|
|
56
|
+
texts = [w.text() for w in words]
|
|
57
|
+
if texts[0] != "phiward" or words[0].raw != "phiward":
|
|
58
|
+
return None
|
|
59
|
+
return texts[1:]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# programs that run the words after them as a command: before a gateway call, a prefix to remove
|
|
63
|
+
_PREFIXES = frozenset({"sudo", "doas", "time", "nohup", "exec", "command", "builtin", "nice",
|
|
64
|
+
"ionice", "env", "stdbuf", "timeout", "caffeinate", "chrt", "taskset",
|
|
65
|
+
"xargs", "!"})
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def not_whole(command: str) -> Optional[str]:
|
|
69
|
+
"""For a command that holds a gateway call (`phiward run|copy`) but is not that call written
|
|
70
|
+
whole (`whole_command`): what to change, in a few words; None when it holds none or is
|
|
71
|
+
whole. The extra part is quoted as written, so the agent knows what to remove."""
|
|
72
|
+
if whole_command(command) is not None:
|
|
73
|
+
return None
|
|
74
|
+
try:
|
|
75
|
+
parsed = shell.parse(command)
|
|
76
|
+
except (shell.ShellSyntaxError, ValueError, RecursionError):
|
|
77
|
+
return None
|
|
78
|
+
items = list(parsed.items)
|
|
79
|
+
start = next((i for i in range(len(items) - 1)
|
|
80
|
+
if isinstance(items[i], shell.Word) and isinstance(items[i + 1], shell.Word)
|
|
81
|
+
and items[i].raw == "phiward" and items[i + 1].text() in ("run", "copy")), None)
|
|
82
|
+
if start is None:
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
def cut(text: str) -> str:
|
|
86
|
+
text = " ".join(text.split())
|
|
87
|
+
return text if len(text) <= 60 else text[:57] + "..."
|
|
88
|
+
|
|
89
|
+
# where each item is in the text, in order
|
|
90
|
+
pos, at = 0, []
|
|
91
|
+
for it in items:
|
|
92
|
+
raw = it.raw if isinstance(it, shell.Word) else it.text
|
|
93
|
+
i = command.find(raw, pos)
|
|
94
|
+
at.append(i if i >= 0 else pos)
|
|
95
|
+
pos = (i + len(raw)) if i >= 0 else pos
|
|
96
|
+
before = command[:at[start]].strip()
|
|
97
|
+
# the words since the last operator before `phiward`: when one of them is not a variable
|
|
98
|
+
# assignment, `phiward` is that command's argument (`echo phiward run ...`), not a command
|
|
99
|
+
lead = []
|
|
100
|
+
for it in reversed(items[:start]):
|
|
101
|
+
if isinstance(it, shell.Op):
|
|
102
|
+
break
|
|
103
|
+
lead.insert(0, it)
|
|
104
|
+
cmd_word = next((w for w in lead if isinstance(w, shell.Word) and
|
|
105
|
+
not re.match(r"[A-Za-z_][A-Za-z0-9_]*=", w.raw)), None)
|
|
106
|
+
if cmd_word is not None and cmd_word.raw.rsplit("/", 1)[-1] in _PREFIXES:
|
|
107
|
+
# a program that runs the rest as its command: the gateway call itself, with a prefix
|
|
108
|
+
return (f"A gateway call must be the whole command: remove `{cut(before)}` (it runs "
|
|
109
|
+
"outside the gateway, with no prefix).")
|
|
110
|
+
if cmd_word is not None:
|
|
111
|
+
return (f"Here `phiward` is an argument of `{cut(cmd_word.raw)}`, not the command: a "
|
|
112
|
+
"gateway call must be the whole command, starting with `phiward`.")
|
|
113
|
+
# the first operator after it, a line break too unless only space follows it
|
|
114
|
+
op = next((j for j in range(start, len(items)) if isinstance(items[j], shell.Op)
|
|
115
|
+
and (items[j].text != "\n" or command[at[j]:].strip())), None)
|
|
116
|
+
after = command[at[op]:].strip() if op is not None else ""
|
|
117
|
+
if op is not None and items[op].text == "\n":
|
|
118
|
+
return (f"A gateway call must be the whole command, one gateway call per command: run "
|
|
119
|
+
f"`{cut(after)}` as its own call.")
|
|
120
|
+
parts = [f"`{cut(x)}`" for x in (before, after) if x]
|
|
121
|
+
if parts:
|
|
122
|
+
return ("A gateway call must be the whole command: remove " + " and ".join(parts) +
|
|
123
|
+
" (run each step as its own call; the script `phiward run` runs may pipe or "
|
|
124
|
+
"redirect inside it).")
|
|
125
|
+
if parsed.subs or parsed.heredocs or any(isinstance(w, shell.Word) and
|
|
126
|
+
(w.has_sub or not _only_home(w)) for w in items):
|
|
127
|
+
return ("A gateway call is written with fixed words: no `$(...)`, backquotes, heredocs "
|
|
128
|
+
"or variables but `~` and `$HOME`.")
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# carryover: accepting a quarantined change makes it trusted
|
|
133
|
+
# broker: once a config exists, the broker is the operator's (a service file the
|
|
134
|
+
# agent wrote could run it, outside every sandbox, with a config of the agent's choosing)
|
|
135
|
+
OPERATOR_ONLY = ("setup", "pin", "carryover", "broker")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def is_operator_command(command: str) -> bool:
|
|
139
|
+
"""Whether some simple command in `command` runs an operator-only subcommand
|
|
140
|
+
(`phiward setup`), in any spelling of the program the guard can see."""
|
|
141
|
+
try:
|
|
142
|
+
parsed = shell.parse(command)
|
|
143
|
+
except (shell.ShellSyntaxError, ValueError, RecursionError):
|
|
144
|
+
return any(op in command for op in OPERATOR_ONLY) and \
|
|
145
|
+
any(n in command for n in PROGRAMS + MODULES)
|
|
146
|
+
words = [it.text() for it in parsed.items if isinstance(it, shell.Word)]
|
|
147
|
+
for i, w in enumerate(words):
|
|
148
|
+
base = w.rsplit("/", 1)[-1]
|
|
149
|
+
if base in PROGRAMS + MODULES and i + 1 < len(words) and \
|
|
150
|
+
words[i + 1] in OPERATOR_ONLY:
|
|
151
|
+
return True
|
|
152
|
+
# any other spelling that names the program and an operator-only word together
|
|
153
|
+
# (`sh -c 'phiward broker'`, `$p broker`, `xargs phiward`): refused unless it is a plain
|
|
154
|
+
# gateway call
|
|
155
|
+
if parse_call(command) is None and \
|
|
156
|
+
re.search(r"\b(?:phiward|agent[-_]guards)\b", command) and \
|
|
157
|
+
re.search(r"\b(?:" + "|".join(OPERATOR_ONLY) + r")\b", command):
|
|
158
|
+
return True
|
|
159
|
+
return False
|