diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c0e4152..f6e06f7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -186,6 +186,13 @@ Changes are grouped by software version. Entries under Unreleased describe work ### Fixed +- `Sandbox.wrap` ran a virtual environment's interpreter (`/bin/python`, a link to its base interpreter) by + its real path, so it started without the environment and its packages failed to import. An interpreter whose + environment is granted (the sandbox's `readable` or `writable`, the call's, or `interpreters`) now runs by its own + name, with the links on its way to its installation shown; its `pyvenv.cfg` names no installation to show from a + call's grant, as before. An ungranted one runs as before, and so do one beneath a layout's root (`/w`), one + reached from its grant through a link to a place nothing shows, and one whose links lead to its installation + through a linked directory other than the system's (uv's version alias) (#95). - A redeployment (`hermit deploy` into the same workspace) left a skill the new adapter no longer exports in the host's skills folder (`.codex/skills`, `.claude/skills`, `.pi/skills`, `.opencode/skills`), where the agent still loaded it, and a file a skill no longer has inside its copy. Each exported skill's copy is now replaced, and a diff --git a/docs/_includes/sandbox-build.html b/docs/_includes/sandbox-build.html index acc599c0..a33d941a 100644 --- a/docs/_includes/sandbox-build.html +++ b/docs/_includes/sandbox-build.html @@ -19,7 +19,7 @@ its environment's site-packages, as installed read-only programs -a command's own installation, run by its real path +a command's own installation, run by its real path (a granted venv's python by its name) a CLI under ~/.local/bin and the package it belongs to read-only diff --git a/docs/guides/sandbox.md b/docs/guides/sandbox.md index 5ed25b3f..8d22b329 100644 --- a/docs/guides/sandbox.md +++ b/docs/guides/sandbox.md @@ -62,7 +62,11 @@ The pieces, in the order they are applied: on hermit's environment (unless that directory's `python3` is another version, as on the host). The sandbox's own command is found on the host's `PATH` before it starts: give a Python command as an absolute path (`sys.executable`). -4. **Programs.** A command started by name is run by its real path. Its installation is shown (a CLI under +4. **Programs.** A command started by name is run by its real path, except a virtual environment's interpreter whose + environment is granted (for the sandbox or for the call), does not lie beneath a layout's root (the learner's + `/w`), is reached from its grant only through links to places shown too, and whose links lead to its + installation through no linked directory but the system's (`/bin`, `/lib`; not uv's version alias): it runs by its + own name, so it finds its `pyvenv.cfg` and the environment's packages. Its installation is shown (a CLI under `~/.local/bin` and the package it belongs to, the interpreter its `#!` line names), with that installation's Python packages emptied, unless the program itself runs on Python (a pipx or venv install keeps its own). 5. **Declared paths.** Task paths, the call's work directory, the learner's workspace (bound under `/w`), and the diff --git a/examples/aspire_robosuite/utils/agent/sim.py b/examples/aspire_robosuite/utils/agent/sim.py index 0544b8db..f808317f 100644 --- a/examples/aspire_robosuite/utils/agent/sim.py +++ b/examples/aspire_robosuite/utils/agent/sim.py @@ -122,9 +122,9 @@ def confine(cmd: list[str], *, root: Path, env: dict, writable=(), readable=(), root = Path(root) first = Path(cmd[0]) if (first.parent.parent / "pyvenv.cfg").is_file(): - # A venv's interpreter (the validator's `python -c`): the sandbox runs a command by its real path, and the - # venv's python is a link to its base installation, which would run without the venv's packages; run by its - # own name through a shell, the venv (granted, so its base installation is shown too) is kept. + # A venv's interpreter (the validator's `python -c`), granted so its base installation is shown too. The + # sandbox runs a granted venv's interpreter by its own name (#95); the shell, which runs it by that name + # too, dates from before and is kept. trusted = [first.parent.parent] cmd = ["/bin/sh", "-c", 'exec "$0" "$@"', *cmd] else: diff --git a/hermit/sandbox.py b/hermit/sandbox.py index 7a4003b5..8849f690 100644 --- a/hermit/sandbox.py +++ b/hermit/sandbox.py @@ -437,6 +437,75 @@ def _names(path) -> list[str]: return [given] if real == given else [given, real] +def _venv_root(found: str) -> str | None: + """The virtual environment `found` is the interpreter of (a pyvenv.cfg beside it or one directory up), by the + name it is run by; else None.""" + where = os.path.dirname(os.path.abspath(found)) + return next((d for d in (where, os.path.dirname(where)) if os.path.isfile(os.path.join(d, "pyvenv.cfg"))), None) + + +def _granted_venv(found: str, granted) -> bool: + """Whether `found` is a virtual environment's interpreter whose environment exists inside under the name it is + run by, as is the folder of `found` (_reachable from the places `granted` shows), and whose links lead to its + installation through no linked directory outside it but the system's (a venv made through uv's version alias + names the alias as its `home`, which nothing shows). + Its pyvenv.cfg is not read: the installation is shown, as for any program, by following the interpreter's links + (program_paths, and its links made again as links: _link_hops), never by a `home` a granted place could name.""" + venv = _venv_root(found) + if venv is None: + return False + places = {n.rstrip("/") or "/" for g in granted for n in _names(g)} # a grant shown under both its names + if not any(_beneath(venv, w) for w in places): + return False # granted: shown is not enough (an ungranted one beneath /usr) + places |= set(ALWAYS_SHOWN) # shown whole as it is outside: a grant beneath it is that tree's, not bound + real = os.path.realpath(venv) + return _reachable(venv, places) and _reachable(os.path.dirname(os.path.abspath(found)), places) and not any( + os.path.realpath(h.parent) != str(h.parent) for h in _link_hops(found) + if not _beneath(str(h), venv) and not _beneath(os.path.realpath(h), real) + and not str(h).startswith(SYSTEM_LINKED)) + + +# Shown inside as they are outside: /usr whole, and /lib, /lib64, /bin, /sbin as the same links (or directories). +SYSTEM_LINKED = ("/usr/", "/lib/", "/lib64/", "/bin/", "/sbin/") +ALWAYS_SHOWN = ("/usr",) + + +def _beneath(path: str, root: str) -> bool: + return path == root or path.startswith(root.rstrip("/") + "/") + + +def _reachable(path: str, places) -> bool: + """Whether `path` exists inside: beneath a place shown at its own name, following the links below that place + (whose targets must be beneath a shown place too). A link above the place does not matter: the place is shown at + the name it was given. The outermost place is the one followed: a grant inside a bound one is that one's tree + inside (a linked grant there is not bound on its own).""" + current = os.path.abspath(path) + for _ in range(40): + place = min((w for w in places if _beneath(current, w)), key=len, default=None) + if place is None: + return False + rest, here = Path(current).relative_to(place).parts, Path(place) + for i, part in enumerate(rest): + here = here / part + if here.is_symlink(): + current = os.path.normpath(os.path.join(here.parent, os.readlink(here), *rest[i + 1:])) + break + else: + return True + return False + + +def _link_hops(path: str) -> list[Path]: + """The names on the way from `path`'s link to the file it leads to (a venv's bin/python -> an alias -> the + interpreter), each but `path` and the file itself, that lie outside `path`'s environment (shown with it): each + must exist inside for the first to start.""" + venv = _venv_root(path) + hops = [Path(os.path.abspath(path))] + while hops[-1].is_symlink() and len(hops) < 20: + hops.append(Path(os.path.normpath(hops[-1].parent / os.readlink(hops[-1])))) + return [h for h in hops[1:] if str(h) != os.path.realpath(h) and not (venv and _beneath(str(h), venv))] + + def _venv_paths() -> list[Path]: """The virtual environment's interpreter links and pyvenv.cfg. They are bound at their own path, unresolved: a Python started as the link finds pyvenv.cfg beside it and so its environment; started as the file the link leads @@ -1128,7 +1197,18 @@ def ours(first: str) -> bool: # a venv's python3 is its own bin/'s, not the for first in (shutil.which(name, path=env["PATH"]) for name in ("python3", "python"))): env["PATH"] = os.pathsep.join([own, *(p for p in env["PATH"].split(os.pathsep) if p and p != own)]) found = shutil.which(command[0]) if command else None - if found: # run the program by its real path: PATH entries outside the sandbox do not exist inside + # Not beneath a layout's root, where grants are shown under other names (a call's) or at their own (the + # sandbox's), and a link there may lead to where nothing is shown: such a venv runs as before. + moved = [p for p in [*readable, *writable] if self.layout and self._in_layout(p) + and self.translate(str(p), binds) != str(p)] # a call's grant shown under /w, not its name + by_name = bool(found) and not (self.layout and self._in_layout(os.path.dirname(os.path.abspath(found)))) \ + and _granted_venv(found, [*self.readable, *self.writable, *interpreters, + *(p for p in [*readable, *writable] if p not in moved)]) + if by_name: + # a granted virtual environment's interpreter, run by its own name: its real file is the base + # installation's, which, run as itself, finds no pyvenv.cfg and so not the environment's packages + command = [os.path.abspath(found), *command[1:]] + elif found: # run the program by its real path: PATH entries outside the sandbox do not exist inside real = Path(found).resolve() # ... except this Python, which must keep its environment's path command = [sys.executable if real == Path(sys.executable).resolve() else str(real), *command[1:]] # A path given for this call at its own location but lying under the layout's root is shown where the @@ -1167,7 +1247,7 @@ def bind(paths, flag, out, system=False): if flag == "--bind" and not os.path.lexists(path): # a writable file stays a file Path(path).mkdir(parents=True, exist_ok=True) for name in _names(path): - if not os.path.exists(name) or (name.startswith("/usr") and not system): + if not os.path.exists(name) or (_beneath(name, "/usr") and not system): # not /usr2 continue # A link under a directory bound already (uv's version alias of an interpreter kept inside a # granted checkout) is there through that directory; binding it again fails on a link. @@ -1196,7 +1276,15 @@ def bind(paths, flag, out, system=False): and not any(os.path.realpath(p).startswith(m.rstrip("/") + "/") for m in mine)] sites = list(dict.fromkeys(sites)) visible = self.visible(command, writable) - bind([p for p in [*visible, *interpreters, *trusted] if not any(_under(p, s) for s in sites)], "--ro-bind", ro) + hops = [h for h in (_link_hops(command[0]) if by_name else []) if not str(h).startswith(SYSTEM_LINKED)] + bind([p for p in [*visible, *interpreters, *trusted] if not any(_under(p, s) for s in sites) + and str(p) not in {str(h) for h in hops}], "--ro-bind", ro) + # A granted venv's interpreter reached through links elsewhere: each made again as the link it is, not bound + # (a copy of the interpreter there would take that folder for its $ORIGIN: a Python that loads ../lib's + # libpython would not find it), unless it is there through a directory bound already. + for hop in hops: + if hop.is_symlink() and not any(_beneath(str(hop), b) for b in (*ro, *rw)): + args.extend(["--symlink", os.readlink(hop), str(hop)]) # The interpreter's site directories hold every installed package: each is replaced by an empty directory, # and the distributions this sandbox shows are bound back into it. # A site directory is shown when it lies in a bound path or under /usr (bound whole above: a system Python). diff --git a/tests/core/test_sandbox.py b/tests/core/test_sandbox.py index 473e5bda..a7621d0f 100644 --- a/tests/core/test_sandbox.py +++ b/tests/core/test_sandbox.py @@ -1772,3 +1772,274 @@ def test_bubblewrap_is_started_by_its_path(tmp_path, monkeypatch): str(tmp_path / "bin" / "bwrap") if name == "bwrap" else REAL_WHICH(name, *a, **k)) args, _ = Sandbox(network="open").wrap(["true"]) assert args[0] == str(tmp_path / "bin" / "bwrap") + + +def test_a_granted_venvs_interpreter_is_run_by_its_own_name_and_an_ungranted_one_as_before(tmp_path, monkeypatch): + """A venv's bin/python is a link to its base interpreter, which, run by its real path, finds no pyvenv.cfg and so + none of the venv's packages (#95). Granted (for the sandbox or for one call), it is run by its own name; granted + for one call, its pyvenv.cfg still names no installation to show. Not granted, it runs by its real path, as + before.""" + fake_bwrap(monkeypatch) + secret = tmp_path / "secret" + (secret / "bin").mkdir(parents=True) + venv = tmp_path / "venv" + (venv / "bin").mkdir(parents=True) + (venv / "pyvenv.cfg").write_text(f"home = {secret / 'bin'}\n") + (venv / "bin" / "python").symlink_to(sys.executable) + command = [str(venv / "bin" / "python"), "-c", "pass"] + args, _ = Sandbox(network="isolated", readable=[venv]).wrap(command) # the sandbox's own, trusted grant + assert args[-3:] == command + args, _ = Sandbox(network="isolated").wrap(command, readable=[venv]) # one call's, which shows no home + assert args[-3:] == command and not any(a.startswith(str(secret)) for a in args) + args, _ = Sandbox(network="isolated").wrap(command) + assert args[-3:] == [sys.executable, "-c", "pass"] + + +def test_a_granted_venv_beneath_a_layout_root_or_reached_by_an_ungranted_spelling_runs_as_before(tmp_path, + monkeypatch): + """Beneath a layout's root a call's grant is shown at /w/..., the sandbox's at its own path, and a link there may + lead where nothing is shown: such a venv's interpreter runs as before, whichever way it is granted. Run through a + link to its folder that no grant names, it is not there under that name inside: run as before too.""" + fake_bwrap(monkeypatch) + ws = tmp_path / "ws" + venv = ws / "tool" / ".venv" + (venv / "bin").mkdir(parents=True) + (venv / "pyvenv.cfg").write_text("home = /usr/bin\n") + (venv / "bin" / "python").symlink_to(sys.executable) + command = [str(venv / "bin" / "python"), "-c", "pass"] + for box, call in ((Sandbox(network="isolated", layout=(ws, "/w")), {"readable": [venv]}), + (Sandbox(network="isolated", layout=(ws, "/w"), readable=[venv]), {}), + (Sandbox(network="isolated", layout=(ws, "/w"), writable=[venv]), {}), + (Sandbox(network="isolated", layout=(ws, "/w")), {"interpreters": [venv]})): + args, _ = box.wrap(command, **call) + assert args[-3:] == [sys.executable, "-c", "pass"] + # a call's grant beneath the root is shown under /w only: it shows no venv run by its own name elsewhere + env = tmp_path / "cache" / "env" + (env / "bin").mkdir(parents=True) + (env / "pyvenv.cfg").write_text("home = /usr/bin\n") + (env / "bin" / "python").symlink_to(sys.executable) + (ws / ".venv").symlink_to(env) + for call in ({"readable": [ws / ".venv"]}, {"writable": [ws / ".venv"]}): + args, _ = Sandbox(network="isolated", layout=(ws, "/w")).wrap([str(env / "bin" / "python"), "-c", "pass"], + **call) + assert args[-3:] == [sys.executable, "-c", "pass"] + (tmp_path / "linked").symlink_to(ws) + aliased = tmp_path / "linked" / "tool" / ".venv" / "bin" / "python" + args, _ = Sandbox(network="isolated").wrap([str(aliased), "-c", "pass"], readable=[venv]) + assert args[-3:] == [sys.executable, "-c", "pass"] + + +def test_only_a_granted_venvs_interpreter_is_renamed_and_only_where_it_is_shown(tmp_path, monkeypatch): + """An ordinary command under a layout with a named bind keeps its name (no venv: nothing to rename). A venv whose + folder is a link out of the grant (a .venv linked to a cache) is not there inside: it runs as before.""" + fake_bwrap(monkeypatch) + box = Sandbox(network="isolated", layout=(Path(sys.prefix), "/w"), binds=[Bind(tmp_path, "/w/hosts")]) + args, _ = box.wrap([sys.executable, "-c", "pass"]) + assert args[-3:] == [sys.executable, "-c", "pass"] + cache = tmp_path / "cache" / "venv" + (cache / "bin").mkdir(parents=True) + (cache / "pyvenv.cfg").write_text("home = /usr/bin\n") + (cache / "bin" / "python").symlink_to(sys.executable) + (tmp_path / "project").mkdir() + (tmp_path / "project" / ".venv").symlink_to(cache) + command = [str(tmp_path / "project" / ".venv" / "bin" / "python"), "-c", "pass"] + args, _ = Sandbox(network="isolated").wrap(command, readable=[tmp_path / "project"]) + assert args[-3:] == [sys.executable, "-c", "pass"] + + +def test_a_venv_reached_through_a_linked_directory_outside_it_runs_as_before(tmp_path, monkeypatch): + """A venv made through a linked installation (uv's version alias) names that link as its home, which nothing + shows; one whose folder is reached through two links (.venv -> /cache/env, /cache -> /mnt/cache) has a name on + the way that nothing shows. Each runs as before, and nothing more is shown for it.""" + fake_bwrap(monkeypatch) + install = tmp_path / "cpython-3.12.4" + (install / "bin").mkdir(parents=True) + (install / "bin" / "python3.12").symlink_to(sys.executable) + alias = tmp_path / "cpython-3.12" + alias.symlink_to(install) + venv = tmp_path / "venv" + (venv / "bin").mkdir(parents=True) + (venv / "pyvenv.cfg").write_text(f"home = {alias / 'bin'}\n") + (venv / "bin" / "python").symlink_to(alias / "bin" / "python3.12") + args, _ = Sandbox(network="isolated").wrap([str(venv / "bin" / "python"), "-c", "pass"], readable=[venv]) + assert args[-3] == sys.executable and not any(a.startswith(str(alias)) for a in args) + env = tmp_path / "mnt" / "cache" / "env" + (env / "bin").mkdir(parents=True) + (env / "pyvenv.cfg").write_text("home = /usr/bin\n") + (env / "bin" / "python").symlink_to(sys.executable) + (tmp_path / "cache").symlink_to(tmp_path / "mnt" / "cache") + (tmp_path / "project").mkdir() + (tmp_path / "project" / ".venv").symlink_to(tmp_path / "cache" / "env") + args, _ = Sandbox(network="isolated").wrap([str(tmp_path / "project" / ".venv" / "bin" / "python"), "-c", "pass"], + readable=[tmp_path / "project", tmp_path / "mnt" / "cache"]) + assert args[-3] == sys.executable + + +def test_a_linked_venv_granted_inside_another_grant_is_judged_as_the_outer_grant_shows_it(tmp_path, monkeypatch): + """/project and its .venv (a link to /cache/env, /cache a link to /storage/cache) both granted: the link is not + bound on its own inside the bound project, so .venv leads to /cache, which nothing shows. It runs as before, + whatever order the grants are looked at in.""" + fake_bwrap(monkeypatch) + env = tmp_path / "storage" / "cache" / "env" + (env / "bin").mkdir(parents=True) + (env / "pyvenv.cfg").write_text("home = /usr/bin\n") + (env / "bin" / "python").symlink_to(sys.executable) + (tmp_path / "cache").symlink_to(tmp_path / "storage" / "cache") + project = tmp_path / "project" + project.mkdir() + (project / ".venv").symlink_to(tmp_path / "cache" / "env") + for grants in ([project, project / ".venv"], [project / ".venv", project]): + args, _ = Sandbox(network="isolated").wrap([str(project / ".venv" / "bin" / "python"), "-c", "pass"], + readable=grants) + assert args[-3] == sys.executable + + +def test_a_venv_whose_bin_folder_links_out_of_the_grant_runs_as_before_and_a_system_link_is_no_obstacle( + tmp_path, monkeypatch): + """bin/ a link to a folder nothing shows: the interpreter's name would not exist inside, so it runs as before. + Links through /bin (on a merged /usr, a link the sandbox makes too) lead to a shown installation.""" + fake_bwrap(monkeypatch) + shared = tmp_path / "shared" / "bin" + shared.mkdir(parents=True) + (shared / "python").symlink_to(sys.executable) + env = tmp_path / "env" + env.mkdir() + (env / "pyvenv.cfg").write_text("home = /usr/bin\n") + (env / "bin").symlink_to(shared) + args, _ = Sandbox(network="isolated").wrap([str(env / "bin" / "python"), "-c", "pass"], readable=[env]) + assert args[-3] == sys.executable + system = next((p for p in ("/bin/python3", "/bin/sh") if os.path.islink("/bin") and os.path.exists(p)), None) + if system is None: + return # no merged /usr here + venv = tmp_path / "venv" + (venv / "bin").mkdir(parents=True) + (venv / "pyvenv.cfg").write_text("home = /bin\n") + (venv / "bin" / "python").symlink_to(system) + args, _ = Sandbox(network="isolated").wrap([str(venv / "bin" / "python"), "-c", "pass"], readable=[venv]) + assert args[-3] == str(venv / "bin" / "python") + + +def test_a_venv_interpreters_link_elsewhere_is_made_again_as_a_link_not_bound(tmp_path, monkeypatch): + """bin/python -> /alias/python -> the interpreter: bound, the alias would be a copy of the interpreter, whose + $ORIGIN (where a shared Python looks for ../lib's libpython) would be /alias; made again as a link, it is not.""" + fake_bwrap(monkeypatch) + (tmp_path / "alias").mkdir() + (tmp_path / "alias" / "python").symlink_to(os.path.realpath(sys.executable)) + venv = tmp_path / "venv" + (venv / "bin").mkdir(parents=True) + (venv / "pyvenv.cfg").write_text("home = /usr/bin\n") + (venv / "bin" / "python").symlink_to(tmp_path / "alias" / "python") + args, _ = Sandbox(network="isolated").wrap([str(venv / "bin" / "python"), "-c", "pass"], readable=[venv]) + alias = str(tmp_path / "alias" / "python") + assert args[-3] == str(venv / "bin" / "python") and alias not in binds(args, "--ro-bind") + i = args.index(alias) + assert args[i - 2:i] == ["--symlink", os.path.realpath(sys.executable)] + + +def test_a_venv_beneath_usr_is_judged_by_the_usr_tree_shown_inside(tmp_path, monkeypatch): + """/usr is shown whole, as it is outside, and a grant beneath it is not bound on its own: a venv there linked to + /cache/env (/cache a link nothing shows) leads nowhere inside. It runs as before.""" + fake_bwrap(monkeypatch) + usr = tmp_path / "usr" + monkeypatch.setattr(sandbox_module, "ALWAYS_SHOWN", (str(usr),)) + env = tmp_path / "storage" / "cache" / "env" + (env / "bin").mkdir(parents=True) + (env / "pyvenv.cfg").write_text("home = /usr/bin\n") + (env / "bin" / "python").symlink_to(sys.executable) + (tmp_path / "cache").symlink_to(tmp_path / "storage" / "cache") + (usr / "local").mkdir(parents=True) + (usr / "local" / "env").symlink_to(tmp_path / "cache" / "env") + args, _ = Sandbox(network="isolated").wrap([str(usr / "local" / "env" / "bin" / "python"), "-c", "pass"], + readable=[usr / "local" / "env"]) + assert args[-3] == sys.executable + venv = usr / "local" / "venv" # shown with /usr but granted by nobody: as before too + (venv / "bin").mkdir(parents=True) + (venv / "pyvenv.cfg").write_text("home = /usr/bin\n") + (venv / "bin" / "python").symlink_to(sys.executable) + args, _ = Sandbox(network="isolated").wrap([str(venv / "bin" / "python"), "-c", "pass"]) + assert args[-3] == sys.executable + + +def test_a_grant_whose_path_only_begins_like_usr_is_bound(tmp_path, monkeypatch): + """/usr is shown whole and a grant beneath it is not bound again; a path that only begins with the same letters + (a /usr2 storage mount) is not beneath it and is bound, so a venv granted there exists inside.""" + fake_bwrap(monkeypatch) + real_exists = os.path.exists + monkeypatch.setattr(sandbox_module.os.path, "exists", + lambda p: True if str(p) == "/usr2/project" else real_exists(p)) + args, _ = Sandbox(network="isolated").wrap(["true"], readable=[Path("/usr2/project")]) + assert "/usr2/project" in binds(args, "--ro-bind") + + +def test_a_venv_under_a_sandbox_that_shows_the_whole_filesystem_runs_by_its_own_name(tmp_path, monkeypatch): + """`readable=[/]` (network isolation alone): the venv is shown, under its own name.""" + fake_bwrap(monkeypatch) + venv = tmp_path / "venv" + (venv / "bin").mkdir(parents=True) + (venv / "pyvenv.cfg").write_text("home = /usr/bin\n") + (venv / "bin" / "python").symlink_to(sys.executable) + args, _ = Sandbox(network="isolated", readable=[Path("/")]).wrap([str(venv / "bin" / "python"), "-c", "pass"]) + assert args[-3] == str(venv / "bin" / "python") + + +def test_a_linked_venv_runs_by_its_own_name_with_its_own_packages(tmp_path, monkeypatch): + """A venv granted under a linked name (/cache/env -> /storage/env) whose bin/python goes through its own python3: + it runs by its own name, and its site directory is not emptied as a base installation's.""" + fake_bwrap(monkeypatch) + storage = tmp_path / "storage" / "env" + site = storage / "lib" / "python3.12" / "site-packages" + site.mkdir(parents=True) + (storage / "bin").mkdir() + (storage / "pyvenv.cfg").write_text("home = /usr/bin\n") + (storage / "bin" / "python3").symlink_to(sys.executable) + (storage / "bin" / "python").symlink_to("python3") + (tmp_path / "cache").mkdir() + (tmp_path / "cache" / "env").symlink_to(storage) + venv = tmp_path / "cache" / "env" + args, _ = Sandbox(network="isolated", readable=[venv]).wrap([str(venv / "bin" / "python"), "-c", "pass"]) + assert args[-3] == str(venv / "bin" / "python") + assert not any(a.endswith("site-packages") and "env" in a for a in binds(args, "--tmpfs")) + + +@pytest.mark.skipif(not _bwrap_works(), reason="needs a working bubblewrap (unprivileged user namespaces)") +def test_a_granted_venvs_interpreter_reached_through_another_link_starts_inside(tmp_path): + """bin/python -> a link of its own elsewhere -> this interpreter: that link must exist inside too.""" + venv = tmp_path / "venv" + subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(venv)], check=True, capture_output=True) + [site] = venv.glob("lib/python3*/site-packages") + (site / "marker95.py").write_text("WHERE = 'the venv'\n") + (tmp_path / "alias").mkdir() + (tmp_path / "alias" / "python").symlink_to(os.path.realpath(sys.executable)) + (venv / "bin" / "python").unlink() + (venv / "bin" / "python").symlink_to(tmp_path / "alias" / "python") + box = Sandbox(network="isolated") + try: + args, env = box.wrap([str(venv / "bin" / "python"), "-c", "import marker95; print(marker95.WHERE)"], + readable=[venv]) + out = subprocess.run(args, env=env, capture_output=True, text=True, timeout=120) + finally: + box.close() + assert out.returncode == 0 and out.stdout.strip() == "the venv", out.stderr[-600:] + + +@pytest.mark.skipif(not _bwrap_works(), reason="needs a working bubblewrap (unprivileged user namespaces)") +@pytest.mark.parametrize("base", [sys.executable, "/usr/bin/python3"], + ids=["this-interpreter", "usr-bin-python3"]) +def test_a_granted_venvs_python_imports_the_venvs_packages_inside(tmp_path, base): + """End to end, for a venv made from this interpreter and one made from another: the module installed in the venv + imports inside the sandbox.""" + if not os.path.exists(base) or (base != sys.executable and + Path(base).resolve() == Path(sys.executable).resolve()): + pytest.skip(f"no other interpreter at {base}") + venv = tmp_path / "venv" + subprocess.run([base, "-m", "venv", "--without-pip", str(venv)], check=True, capture_output=True) + [site] = venv.glob("lib/python3*/site-packages") + (site / "marker95.py").write_text("WHERE = 'the venv'\n") + box = Sandbox(network="isolated") + try: + args, env = box.wrap([str(venv / "bin" / "python"), "-c", "import marker95; print(marker95.WHERE)"], + readable=[venv]) + out = subprocess.run(args, env=env, capture_output=True, text=True, timeout=120) + finally: + box.close() + assert out.returncode == 0 and out.stdout.strip() == "the venv", out.stderr[-600:]