Skip to content

Commit 37db4f7

Browse files
committed
fix(sandbox): a linked tool's install root is granted by one rule; the uv special case goes
- A PATH entry that links to `<root>/bin/<name>` grants `<root>` read-only, so an interpreter's `lib` beside its `bin` is inside the jail whatever installed it; a link not under a `bin` grants its directory as before; a root that is home, an ancestor of it or an agent6 private dir keeps the `bin` grant and the row says so. - The uv interpreters grant, its constant and its description go; uv's pythons are covered through their shims. Security review note: the grant widens from a linked tool's `bin` to its install root, read-only, for tools the operator linked onto PATH; the home and private-dir refusals now also apply to resolved paths.
1 parent 5b47919 commit 37db4f7

5 files changed

Lines changed: 284 additions & 64 deletions

File tree

‎docs/security.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,8 @@ Config, flag, and env var are operator-only; the model reaches neither argv nor
169169
agent6 warns about such a grant at run start and in `agent6 check sandbox`.
170170
Under `full`, agent6 hides only its own config dir and state base, plus the paths in `sandbox.hide_paths`
171171
- the paths kept read-only inside the workspace (`.git` under `protect_git`, a machine bundle) are bound after every grant: a grant that contains the workspace does not make them writable
172-
- a tool dir is mounted only when its identity clears a default-deny.
172+
- a symlink into `<root>/bin` grants `<root>` read-only only if no jail PATH directory lies at or under `<root>`; other targets grant their directory.
173+
A refused root keeps the `bin` grant.
173174
Refused: a dir at, inside, or containing an agent6 private dir, and `$HOME` or an ancestor of it
174175
- a fork's execution or a `run --worktree` run (cwd is its linked worktree) also grants the repository's `.git`: a read-only bind under `full`, a Landlock read+exec rule under `partial`, in both cases whatever `protect_git` says.
175176
The main checkout's `.git` is read-only only under `full` with `protect_git`, so a worktree's is the more confined of the two.

‎src/agent6/sandbox/tool_paths.py‎

Lines changed: 35 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from __future__ import annotations
1111

1212
import dataclasses
13-
import os
1413
import pathlib
1514
import shutil
1615

@@ -46,9 +45,14 @@ def _never_mounted(p: pathlib.Path) -> bool:
4645
True for $HOME and its ancestors, and for a dir inside or above one of agent6's
4746
private dirs (`agent6.paths.private_dirs`).
4847
"""
49-
if pathlib.Path.home().is_relative_to(p):
48+
home = pathlib.Path.home()
49+
if home.is_relative_to(p) or home.resolve().is_relative_to(p):
5050
return True
51-
return any(p.is_relative_to(d) or d.is_relative_to(p) for d in paths.private_dirs())
51+
return any(
52+
p.is_relative_to(d) or d.is_relative_to(p)
53+
for private in paths.private_dirs()
54+
for d in (private, private.resolve())
55+
)
5256

5357

5458
@dataclasses.dataclass(frozen=True, slots=True)
@@ -58,35 +62,32 @@ class ToolMount:
5862
Attributes:
5963
path: The dir, at its real location.
6064
on_path: The directory is on the jail's PATH.
61-
links: Symlink sources whose targets live in this directory.
62-
runtimes: Established runtime dependencies supplied by this directory.
65+
links: Symlink sources whose targets live under this directory.
66+
root_refusal: The refused install root, with the PATH reason when applicable.
6367
"""
6468

6569
path: pathlib.Path
6670
on_path: bool = False
6771
links: tuple[pathlib.Path, ...] = ()
68-
runtimes: tuple[str, ...] = ()
69-
70-
71-
_UV_PYTHONS = "uv-managed interpreters"
72+
root_refusal: str = ""
7273

7374

7475
def operator_tool_mounts() -> tuple[ToolMount, ...]:
7576
"""Return the dirs the jail mounts read+exec, each with its reason, sorted by path.
7677
77-
Recomputed per call, so a tool just installed is picked up. A bin dir under a
78-
mounted system root only joins PATH; a dir outside one, and the real dir a
79-
symlink resolves to, also needs the mount.
78+
Recomputed per call, so a tool just installed is picked up. A symlink into
79+
`<root>/bin` grants the root only if it holds no jail PATH directory and passes
80+
the mount safety checks. Other links grant the target's directory.
8081
8182
Returns:
8283
The mounts, with every discovery source retained for each directory.
8384
"""
85+
bin_dirs = tuple(d for d in _tool_bin_dirs() if d.is_dir())
86+
path_dirs = tuple(pathlib.Path(p) for p in _JAIL_BASE_PATH_DIRS) + bin_dirs
8487
on_path: set[pathlib.Path] = set()
8588
links: dict[pathlib.Path, list[pathlib.Path]] = {}
86-
whys: dict[pathlib.Path, list[str]] = {}
87-
for d in _tool_bin_dirs():
88-
if not d.is_dir():
89-
continue
89+
root_refusals: dict[pathlib.Path, str] = {}
90+
for d in bin_dirs:
9091
if not _under_system_root(d) and not _never_mounted(d):
9192
on_path.add(d)
9293
try:
@@ -100,19 +101,22 @@ def operator_tool_mounts() -> tuple[ToolMount, ...]:
100101
real = entry.resolve()
101102
except OSError:
102103
continue
103-
if real.is_file() and not _under_system_root(real) and not _never_mounted(real.parent):
104-
links.setdefault(real.parent, []).append(entry)
105-
# uv-managed CPython lives under XDG data; without this mount an in-jail `uv run` sees the
106-
# venv's interpreter missing and recreates the operator's .venv. A mount, never a PATH entry.
107-
data_home = pathlib.Path(
108-
os.environ.get("XDG_DATA_HOME") or pathlib.Path.home() / ".local/share"
109-
)
110-
uv_pythons = data_home / "uv" / "python"
111-
if uv_pythons.is_dir():
112-
whys.setdefault(uv_pythons, []).append(_UV_PYTHONS)
104+
parent = real.parent
105+
if not real.is_file() or _never_mounted(parent):
106+
continue
107+
if parent.name == "bin":
108+
root = parent.parent
109+
if _never_mounted(root):
110+
root_refusals[parent] = str(root)
111+
elif any(p.is_relative_to(root) for p in path_dirs):
112+
root_refusals[parent] = f"{root} holds a PATH directory"
113+
else:
114+
parent = root
115+
if not _under_system_root(parent) or parent in root_refusals:
116+
links.setdefault(parent, []).append(entry)
113117
return tuple(
114-
ToolMount(path, path in on_path, tuple(links.get(path, ())), tuple(whys.get(path, ())))
115-
for path in sorted(on_path | links.keys() | whys.keys())
118+
ToolMount(path, path in on_path, tuple(links.get(path, ())), root_refusals.get(path, ""))
119+
for path in sorted(on_path | links.keys())
116120
)
117121

118122

@@ -123,7 +127,9 @@ def operator_tool_paths() -> tuple[str, tuple[pathlib.Path, ...]]:
123127
The PATH string and the sorted mount dirs.
124128
"""
125129
path_dirs = [*_JAIL_BASE_PATH_DIRS, *(str(d) for d in _tool_bin_dirs() if d.is_dir())]
126-
return ":".join(path_dirs), tuple(m.path for m in operator_tool_mounts())
130+
return ":".join(path_dirs), tuple(
131+
m.path for m in operator_tool_mounts() if not _under_system_root(m.path)
132+
)
127133

128134

129135
def _tool_bin_dirs() -> tuple[pathlib.Path, ...]:

‎src/agent6/ui/cli/_sandbox_paths.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,11 +101,12 @@ def _tool_rows() -> list[Row]:
101101
rows: list[Row] = []
102102
for mount in tool_paths.operator_tool_mounts():
103103
notes = ["on the jail's PATH"] if mount.on_path else []
104-
notes.extend(mount.runtimes)
105104
if mount.links:
106105
first, *others = mount.links
107106
more = f", {len(others)} more" if others else ""
108-
notes.append(f"{first} links into this directory{more}")
107+
notes.append(f"{first} links into {mount.path}{more}")
108+
if mount.root_refusal:
109+
notes.append(f"install root not widened: {mount.root_refusal}")
109110
rows.append(Row("ro", mount.path, "; ".join(notes), "tool"))
110111
return rows
111112

‎tests/unit/test_cli_check_sandbox.py‎

Lines changed: 158 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
_MOUNTS = (
3434
tool_paths.ToolMount(pathlib.Path("/opt/tools/bin"), on_path=True),
3535
tool_paths.ToolMount(
36-
pathlib.Path("/opt/tools/lib/x/bin"), links=(pathlib.Path("/opt/tools/bin/x"),)
36+
pathlib.Path("/opt/tools/lib/x"), links=(pathlib.Path("/opt/tools/bin/x"),)
3737
),
3838
)
3939

@@ -229,7 +229,7 @@ def test_check_sandbox_degraded_names_why(
229229
assert f"'full' is unavailable because {why}" in out
230230
# Under partial nothing is mounted: the tool dirs are Landlock read grants, one row each.
231231
assert " ro tool /opt/tools/bin (on the jail's PATH)" in out
232-
assert " ro tool /opt/tools/lib/x/bin (/opt/tools/bin/x links into this directory)" in out
232+
assert " ro tool /opt/tools/lib/x (/opt/tools/bin/x links into /opt/tools/lib/x)" in out
233233
assert " -- / (denied except the paths below)" in out
234234

235235

@@ -243,9 +243,7 @@ def test_every_operator_tool_mount_is_a_row(
243243
_check_sandbox.check_sandbox_section(Config())
244244
rows = _commands_block(capsys.readouterr().out)
245245
assert " ro tool /opt/tools/bin (on the jail's PATH)" in rows
246-
assert (
247-
" ro tool /opt/tools/lib/x/bin (/opt/tools/bin/x links into this directory)" in rows
248-
)
246+
assert " ro tool /opt/tools/lib/x (/opt/tools/bin/x links into /opt/tools/lib/x)" in rows
249247

250248

251249
def test_rows_sort_by_path_with_a_root_and_a_home_row(
@@ -599,7 +597,7 @@ def test_report_colours_and_plain_modes_carry_the_same_words(
599597
assert capsys.readouterr().out == plain
600598

601599

602-
def test_tool_discovery_retains_links_beside_path_and_runtime_reasons(
600+
def test_tool_discovery_retains_links_beside_path_reason(
603601
tmp_path: pathlib.Path,
604602
monkeypatch: pytest.MonkeyPatch,
605603
capsys: pytest.CaptureFixture[str],
@@ -626,10 +624,161 @@ def run(policy: kinds.JailPolicy) -> kinds.CommandResult:
626624
rows = _commands_block(capsys.readouterr().out)
627625
bin_row = next(line for line in rows if f" {bins} " in line)
628626
assert "on the jail's PATH" in bin_row
629-
assert f"{bins}/a links into this directory, 1 more" in bin_row
627+
assert f"{bins}/a links into {bins}, 1 more" in bin_row
630628
runtime_row = next(line for line in rows if f" {runtime} " in line)
631-
assert "uv-managed interpreters" in runtime_row
632-
assert f"{bins}/python links into this directory" in runtime_row
629+
assert "uv-managed interpreters" not in runtime_row
630+
assert f"{bins}/python links into {runtime}" in runtime_row
631+
632+
633+
def test_regular_path_tools_have_no_install_root_row(
634+
tmp_path: pathlib.Path,
635+
monkeypatch: pytest.MonkeyPatch,
636+
capsys: pytest.CaptureFixture[str],
637+
) -> None:
638+
"""A regular PATH tool has no link annotation or row exposing sibling credentials."""
639+
root = tmp_path / "x"
640+
bins = root / "bin"
641+
bins.mkdir(parents=True)
642+
(bins / "tool").touch()
643+
(root / "credentials.toml").touch()
644+
monkeypatch.setattr(tool_paths, "_tool_bin_dirs", lambda: (bins,))
645+
646+
rows = _sandbox_paths._tool_rows()
647+
648+
assert rows == [_sandbox_paths.Row("ro", bins, "on the jail's PATH", "tool")]
649+
_check_render.rows(rows)
650+
assert capsys.readouterr().out.strip() == f"ro tool {bins} (on the jail's PATH)"
651+
652+
653+
@pytest.mark.parametrize("path_subdir", [".", "bin", "other/bin"])
654+
def test_linked_tool_keeps_bin_when_the_install_root_holds_path(
655+
tmp_path: pathlib.Path,
656+
monkeypatch: pytest.MonkeyPatch,
657+
capsys: pytest.CaptureFixture[str],
658+
path_subdir: str,
659+
) -> None:
660+
"""A PATH directory at or under the install root prevents widening and names the reason."""
661+
bins = tmp_path / "pathdir"
662+
bins.mkdir()
663+
root = tmp_path / "y"
664+
target = root / "bin" / "py"
665+
target.parent.mkdir(parents=True)
666+
target.touch()
667+
link = bins / "py"
668+
link.symlink_to(target)
669+
path_dir = root / path_subdir
670+
path_dir.mkdir(parents=True, exist_ok=True)
671+
monkeypatch.setattr(tool_paths, "_tool_bin_dirs", lambda: (bins, path_dir))
672+
673+
rows = _sandbox_paths._tool_rows()
674+
675+
assert {r.path for r in rows} == {bins, path_dir, target.parent}
676+
bin_row = next(r for r in rows if r.path == target.parent)
677+
note = "on the jail's PATH; " if path_subdir == "bin" else ""
678+
note += (
679+
f"{link} links into {target.parent}; "
680+
f"install root not widened: {root} holds a PATH directory"
681+
)
682+
assert bin_row == _sandbox_paths.Row("ro", target.parent, note, "tool")
683+
_check_render.rows([bin_row])
684+
assert capsys.readouterr().out.strip() == f"ro tool {target.parent} ({note})"
685+
686+
687+
@pytest.mark.parametrize("target_dir", ["bin", "libexec"])
688+
def test_linked_tools_grant_the_install_root_only_for_bin_targets(
689+
tmp_path: pathlib.Path,
690+
monkeypatch: pytest.MonkeyPatch,
691+
capsys: pytest.CaptureFixture[str],
692+
target_dir: str,
693+
) -> None:
694+
"""Linked bin tools grant their install root; other targets grant only their directory."""
695+
home = tmp_path / "home"
696+
bins = home / ".local" / "bin"
697+
bins.mkdir(parents=True)
698+
root = tmp_path / "package"
699+
target = root / target_dir / "py"
700+
target.parent.mkdir(parents=True)
701+
target.touch()
702+
for name in ("py", "python3"):
703+
(bins / name).symlink_to(target)
704+
monkeypatch.setenv("HOME", str(home))
705+
monkeypatch.setattr(tool_paths, "_tool_bin_dirs", lambda: (bins,))
706+
grant = root if target_dir == "bin" else root / "libexec"
707+
708+
_, mounts = tool_paths.operator_tool_paths()
709+
assert mounts == tuple(sorted((bins, grant)))
710+
rows = [r for r in _sandbox_paths._tool_rows() if r.path == grant]
711+
assert rows == [
712+
_sandbox_paths.Row("ro", grant, f"{bins}/py links into {grant}, 1 more", "tool")
713+
]
714+
_check_render.rows(rows)
715+
assert capsys.readouterr().out.strip() == (
716+
f"ro tool {grant} ({bins}/py links into {grant}, 1 more)"
717+
)
718+
719+
720+
@pytest.mark.parametrize(
721+
"root_kind", ["ancestor", "filesystem", "home", "home-link", "private", "private-link"]
722+
)
723+
def test_linked_tool_keeps_bin_when_the_install_root_is_unsafe(
724+
tmp_path: pathlib.Path,
725+
monkeypatch: pytest.MonkeyPatch,
726+
root_kind: str,
727+
) -> None:
728+
"""A blocked install root keeps the bin grant and names the refusal in its annotation."""
729+
home = tmp_path / "home"
730+
bins = home / ".local" / "bin"
731+
bins.mkdir(parents=True)
732+
root = {
733+
"ancestor": tmp_path,
734+
"filesystem": pathlib.Path("/"),
735+
"home": home,
736+
"home-link": home,
737+
"private": tmp_path / "private-holder",
738+
"private-link": tmp_path / "private-holder",
739+
}[root_kind]
740+
target = root / "bin" / "sh"
741+
if root_kind != "filesystem":
742+
target.parent.mkdir(parents=True)
743+
target.touch()
744+
if root_kind.startswith("private"):
745+
config = root / "config"
746+
config.mkdir()
747+
if root_kind == "private-link":
748+
alias = tmp_path / "config-link"
749+
alias.symlink_to(config, target_is_directory=True)
750+
config = alias
751+
monkeypatch.setenv("XDG_CONFIG_HOME", str(config))
752+
link = bins / "sh"
753+
link.symlink_to(target)
754+
if root_kind == "filesystem":
755+
# Model an unmerged /bin on hosts where /bin resolves to /usr/bin.
756+
resolve = pathlib.Path.resolve
757+
758+
def unmerged(path: pathlib.Path, strict: bool = False) -> pathlib.Path:
759+
return target if path == link else resolve(path, strict=strict)
760+
761+
monkeypatch.setattr(pathlib.Path, "resolve", unmerged)
762+
if root_kind == "home-link":
763+
alias = tmp_path / "home-link"
764+
alias.symlink_to(home, target_is_directory=True)
765+
home = alias
766+
monkeypatch.setenv("HOME", str(home))
767+
monkeypatch.setattr(tool_paths, "_tool_bin_dirs", lambda: (bins,))
768+
769+
_, mounts = tool_paths.operator_tool_paths()
770+
assert root not in mounts
771+
if root_kind != "filesystem":
772+
assert target.parent in mounts
773+
rows = [r for r in _sandbox_paths._tool_rows() if r.path == target.parent]
774+
assert rows == [
775+
_sandbox_paths.Row(
776+
"ro",
777+
target.parent,
778+
f"{link} links into {target.parent}; install root not widened: {root}",
779+
"tool",
780+
)
781+
]
633782

634783

635784
def test_resource_annotations_follow_explicit_grants(

0 commit comments

Comments
 (0)