Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 116 additions & 5 deletions src/inferrsi/box/kernel/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

from __future__ import annotations

import os
import sys
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from functools import cache, partial
from graphlib import CycleError, TopologicalSorter
from importlib.machinery import all_suffixes
from importlib.machinery import PathFinder, all_suffixes
from itertools import chain
from pathlib import Path
from time import monotonic
Expand All @@ -22,6 +23,105 @@
from .swap import ManagedModule, SourcePlan, _has_alias, _resolve, validate_method_removals


def _path_finder(entry: str, finder_cache: dict[str, object]):
if entry in finder_cache:
return finder_cache[entry]
finder = None
for hook in sys.path_hooks:
try:
finder = hook(entry)
break
except ImportError:
continue
finder_cache[entry] = finder
return finder


def _find_spec_in_paths(
fullname: str, locations: tuple[str, ...] | None, finder_cache: dict[str, object]
) -> tuple[bool, tuple[str, ...] | None]:
namespace_path: list[str] = []
entries = sys.path if locations is None else locations
for entry in entries:
if not isinstance(entry, str):
continue
if entry == "":
try:
entry = os.getcwd()
except OSError:
continue
finder = _path_finder(entry, finder_cache)
if finder is None or not hasattr(finder, "find_spec"):
continue
spec = finder.find_spec(fullname)
if spec is None:
continue
if spec.loader is not None:
sub_locs = spec.submodule_search_locations
return True, tuple(sub_locs) if sub_locs is not None else None
if spec.submodule_search_locations:
namespace_path.extend(spec.submodule_search_locations)
if namespace_path:
return True, tuple(namespace_path)
return False, None


def _static_find_spec(
fullname: str, locations: tuple[str, ...] | None, finder_cache: dict[str, object]
) -> tuple[bool, tuple[str, ...] | None]:
search = None if locations is None else list(locations)
for finder in sys.meta_path:
if finder is PathFinder:
found, sub_locs = _find_spec_in_paths(fullname, locations, finder_cache)
if found:
return True, sub_locs
continue
if not hasattr(finder, "find_spec"):
continue
try:
spec = finder.find_spec(fullname, search)
except ImportError:
return False, None
if spec is not None:
sub_locs = spec.submodule_search_locations
return True, tuple(sub_locs) if sub_locs is not None else None
return False, None


def _package_search_locations(
name: str, finder_cache: dict[str, object]
) -> tuple[str, ...] | None:
locations: tuple[str, ...] | None = None
prefix = ""
for part in name.split("."):
prefix = f"{prefix}.{part}" if prefix else part
if prefix in sys.modules:
existing = sys.modules[prefix]
if not isinstance(existing, ModuleType):
return None
namespace = syntax.raw_namespace(existing)
if "__path__" not in namespace:
return None
paths = namespace["__path__"]
is_ns_path = (
type(paths).__module__ == "_frozen_importlib_external"
and type(paths).__name__ == "_NamespacePath"
)
if not syntax.exact_type(paths, list, tuple) and not is_ns_path:
syntax.reject("parent import paths cannot be inspected statically")
items = tuple(paths)
if not all(isinstance(item, str) for item in items):
syntax.reject("parent import paths cannot be inspected statically")
locations = items
continue
_, locations = _static_find_spec(prefix, locations, finder_cache)
if locations is None:
return None
if not all(isinstance(item, str) for item in locations):
syntax.reject("parent import paths cannot be inspected statically")
return locations


class RequestState(Protocol):
"""State owned by the profile while its workload admission is closed."""

Expand Down Expand Up @@ -170,6 +270,7 @@ def _created_modules(self, candidates):

def _order_changes(self, changes, created):
order = TopologicalSorter()
finder_cache: dict[str, object] = {}

def allowed(name):
return (
Expand All @@ -186,12 +287,22 @@ def allowed(name):
loaded = sys.modules.get(source)
namespace = syntax.raw_namespace(loaded) if loaded is not None else {}
exports = changes[source].plan.exports if source in changes else ()
locations = None
if loaded is None and source not in created and members and allowed(source):
locations = _package_search_locations(source, finder_cache)
for member in members:
child = f"{source}.{member}"
if child in changes or (
"__path__" in namespace
and member not in namespace
and member not in exports
if (
child in changes
or (
"__path__" in namespace
and member not in namespace
and member not in exports
)
or (
locations is not None
and _static_find_spec(child, locations, finder_cache)[0]
)
):
names.add(child)
if any(not allowed(item) for item in names):
Expand Down
155 changes: 155 additions & 0 deletions tests/box/conformance/test_structural_transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import importlib
import linecache
import sys
import zipfile
from contextlib import closing
from pathlib import Path
from time import monotonic
Expand Down Expand Up @@ -2059,3 +2060,157 @@ def test_failed_construction_leaking_new_closure_isolates(setup, action):
create=creating,
)
assert box.install(leak_fail)["code"] == "in_doubt" and box.isolated and len(leaked) == 1


def test_unloaded_package_from_import_enforces_allowed_import_policy(setup, tmp_path, monkeypatch):
module, _, endpoint, box = setup
suffix = uuid4().hex[:8]
pkg = f"allowed_pkg_{suffix}"
ns_pkg = f"ns_pkg_{suffix}"
zip_pkg = f"zip_pkg_{suffix}"
rel_pkg = f"{module.__package__}.rel_sub"
marker = tmp_path / "import_executed.txt"
touch_marker = (
f"from pathlib import Path\n"
f"Path({str(marker)!r}).write_text('executed', encoding='utf-8')\n"
)

pkg_dir = tmp_path / pkg
pkg_dir.mkdir()
(pkg_dir / "__init__.py").write_text(touch_marker + "PUBLIC = 7\n", encoding="utf-8")
(pkg_dir / "forbidden.py").write_text(touch_marker + "SECRET = 99\n", encoding="utf-8")
sub_dir = pkg_dir / "sub"
sub_dir.mkdir()
(sub_dir / "__init__.py").write_text(touch_marker + "SUB_PUBLIC = 11\n", encoding="utf-8")
(sub_dir / "forbidden.py").write_text(touch_marker + "SUB_SECRET = 88\n", encoding="utf-8")
ns_sub_dir = pkg_dir / "ns_sub"
ns_sub_dir.mkdir()
(ns_sub_dir / "forbidden.py").write_text(
touch_marker + "NS_SUB_SECRET = 77\n", encoding="utf-8"
)

ns_dir = tmp_path / ns_pkg
ns_dir.mkdir()
(ns_dir / "forbidden.py").write_text(touch_marker + "NS_SECRET = 66\n", encoding="utf-8")
(ns_dir / "allowed_mod.py").write_text("NS_PUBLIC = 17\n", encoding="utf-8")

archive = tmp_path / f"{zip_pkg}.zip"
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr(f"{zip_pkg}/__init__.py", touch_marker + "ZIP_PUBLIC = 19\n")
bundle.writestr(f"{zip_pkg}/forbidden.py", touch_marker + "ZIP_SECRET = 44\n")

rel_dir = Path(module.__file__).parent / "rel_sub"
rel_dir.mkdir()
(rel_dir / "__init__.py").write_text(touch_marker + "REL_PUBLIC = 13\n", encoding="utf-8")
(rel_dir / "forbidden.py").write_text(touch_marker + "REL_SECRET = 55\n", encoding="utf-8")

monkeypatch.syspath_prepend(str(archive))
monkeypatch.syspath_prepend(str(tmp_path))
endpoint.log.allowed_import = {
pkg,
f"{pkg}.sub",
f"{pkg}.ns_sub",
ns_pkg,
f"{ns_pkg}.allowed_mod",
zip_pkg,
rel_pkg,
}.__contains__

try:
before_cache = dict(sys.path_importer_cache)
denied_cases = [
(f"from {pkg} import forbidden\n", (pkg, f"{pkg}.forbidden")),
(f"from {pkg}.sub import forbidden\n", (pkg, f"{pkg}.sub", f"{pkg}.sub.forbidden")),
(
f"from {pkg}.ns_sub import forbidden\n",
(pkg, f"{pkg}.ns_sub", f"{pkg}.ns_sub.forbidden"),
),
(f"from {ns_pkg} import forbidden\n", (ns_pkg, f"{ns_pkg}.forbidden")),
(f"from {zip_pkg} import forbidden\n", (zip_pkg, f"{zip_pkg}.forbidden")),
("from .rel_sub import forbidden\n", (rel_pkg, f"{rel_pkg}.forbidden")),
]
for index, (stmt, unloaded) in enumerate(denied_cases):
candidate = patch(box, module.__name__, stmt + BASE, name=f"deny-{index}")
assert box.install(candidate)["code"] == "restart_required"
assert all(mod_name not in sys.modules for mod_name in unloaded)
assert not marker.exists()
assert sys.path_importer_cache == before_cache

ok_top = patch(
box,
module.__name__,
f"from {pkg} import PUBLIC\n" + BASE.replace("return x + G", "return x + PUBLIC"),
name="allow-top",
)
assert box.install(ok_top)["code"] == "ok" and module.value(1) == 8
assert marker.exists()
assert box.uninstall()["code"] == "ok" and pkg not in sys.modules

ok_sub = patch(
box,
module.__name__,
f"from {pkg}.sub import SUB_PUBLIC\n"
+ BASE.replace("return x + G", "return x + SUB_PUBLIC"),
name="allow-sub",
)
assert box.install(ok_sub)["code"] == "ok" and module.value(1) == 12
assert box.uninstall()["code"] == "ok" and f"{pkg}.sub" not in sys.modules

ok_ns = patch(
box,
module.__name__,
f"from {ns_pkg} import allowed_mod\n"
+ BASE.replace("return x + G", "return x + allowed_mod.NS_PUBLIC"),
name="allow-ns",
)
assert box.install(ok_ns)["code"] == "ok" and module.value(1) == 18
assert (
box.uninstall()["code"] == "ok"
and ns_pkg not in sys.modules
and f"{ns_pkg}.allowed_mod" not in sys.modules
)

ok_zip = patch(
box,
module.__name__,
f"from {zip_pkg} import ZIP_PUBLIC\n"
+ BASE.replace("return x + G", "return x + ZIP_PUBLIC"),
name="allow-zip",
)
assert box.install(ok_zip)["code"] == "ok" and module.value(1) == 20
assert box.uninstall()["code"] == "ok" and zip_pkg not in sys.modules

std_pkg, std_sub = next(
pair
for pair in (("wsgiref", "headers"), ("xmlrpc", "client"), ("pydoc_data", "topics"))
if pair[0] not in sys.modules
)
ok_std = patch(
box,
module.__name__,
f"from {std_pkg} import {std_sub}\n"
+ BASE.replace("return x + G", f"return x + int({std_sub} is not None)"),
name="allow-stdlib",
)
assert box.install(ok_std)["code"] == "ok" and module.value(1) == 2
assert (
box.uninstall()["code"] == "ok"
and std_pkg not in sys.modules
and f"{std_pkg}.{std_sub}" not in sys.modules
)
finally:
for key in list(sys.modules):
if (
key == pkg
or key.startswith(f"{pkg}.")
or key == ns_pkg
or key.startswith(f"{ns_pkg}.")
or key == zip_pkg
or key.startswith(f"{zip_pkg}.")
or key == rel_pkg
or key.startswith(f"{rel_pkg}.")
):
sys.modules.pop(key, None)
sys.path_importer_cache.pop(str(archive), None)
sys.path_importer_cache.pop(str(tmp_path), None)
importlib.invalidate_caches()
Loading