Python
A site allowed on the card opens on the running sandbox too
Rohit C Prasade45402b3ab9f
diff --git a/coworker/agent.py b/coworker/agent.pyindex 2d7fd078..27592ae3 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -740,7 +740,20 @@ def build_engine(def _grant_site(host: str) -> list[str]:return _sandbox_settings.add_site(host)+ def _open_site(host: str) -> None:+ # The running sandbox takes the site too, so commands reach it from now on. A+ # failure here must not undo the person's choice for the web tools: log it.+ import logging++ from .sandbox.network_profiles import clean_host++ try:+ sandbox_workspace.add_hosts([clean_host(host)])+ except Exception as exc: # noqa: BLE001+ logging.getLogger(__name__).warning("could not open %s on the session's sandbox: %s", host, exc)+engine.permissions.grant_site = _grant_site+ engine.permissions.open_site = _open_siteengine.todo = todo # type: ignore[attr-defined]engine.agent_name = agent.name # type: ignore[attr-defined]engine.roots = root_list # type: ignore[attr-defined] # shared list; Slice C mutates in placediff --git a/coworker/engine.py b/coworker/engine.pyindex daec5b24..72afe142 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -1819,7 +1819,7 @@ class TurnEngine:ApprovalOutcome.ALWAYS_TOOL,ApprovalOutcome.ALWAYS_DOMAIN,):- self.permissions.allow_domain_for_session(decision.site)+ self.permissions.allow_site_for_session(decision.site)elif outcome is ApprovalOutcome.READONLY_SESSION:self.permissions.allow_readonly_for_session()elif outcome is ApprovalOutcome.ALWAYS_TRUST:diff --git a/coworker/permissions.py b/coworker/permissions.pyindex 58fdc384..dbaf7ed9 100644--- a/coworker/permissions.py+++ b/coworker/permissions.py@@ -313,6 +313,8 @@ class PermissionEngine:# Persists a site the user chose to always allow (adds it to the machine's list) and# returns that list, so this session's copy carries the same entries.grant_site: Optional[Callable[[str], Optional[list[str]]]] = None+ # Opens a site on the session's running sandbox, so commands reach it too (OPE-219).+ open_site: Optional[Callable[[str], None]] = None# Session-wide read-only grant (owner ask 2026-08-11): auto-allow shell commands the# conservative classifier (coworker/readonly.py) accepts. User-elected per session.session_readonly: bool = False@@ -626,6 +628,18 @@ class PermissionEngine:self.sandbox_sites[:] = [str(x) for x in stored]else:self.session_allow_domains.add(host)+ if self.open_site is not None:+ self.open_site(host)++ def allow_site_for_session(self, url_or_domain: str) -> None:+ """"Allow for this session" on the allowed-sites card: the web tools and, through the+ running sandbox, the commands of this session reach the site; nothing is stored."""+ host = _host_of(url_or_domain)+ if not host:+ return+ self.allow_domain_for_session(host)+ if self.open_site is not None:+ self.open_site(host)def egress_host(self, tool_name: str, arguments: dict[str, Any]) -> str:"""Where an egress tool is going: its url's host, or for `web_search` (a fixeddiff --git a/coworker/sandbox/netproxy.py b/coworker/sandbox/netproxy.pyindex 9c78ae98..f4720bce 100644--- a/coworker/sandbox/netproxy.py+++ b/coworker/sandbox/netproxy.py@@ -37,10 +37,7 @@ class AllowListProxy:self.profile = network_profiles.check(profile)self._hosts = {h.lower() for h in network_profiles.hosts(profile)}self._extra: set[tuple[str, int]] = set()- for item in extra_hosts:- host, _, port = str(item).rpartition(":")- if host and port.isdigit():- self._extra.add((host.lower().rstrip("."), int(port)))+ self.add_hosts(extra_hosts)self.denied: deque[str] = deque(maxlen=50) # recent refusals, newest lastself._server = _listen()self._server.listen(64)@@ -48,6 +45,14 @@ class AllowListProxy:self._closed = Falsethreading.Thread(target=self._accept, name=f"sandbox-proxy-{profile}", daemon=True).start()+ def add_hosts(self, hosts: Sequence[str]) -> None:+ """Let more "host:port" entries out, from now on: the person allowed a site for this+ session or for good (OPE-219). The list only grows while a sandbox runs."""+ for item in hosts:+ host, _, port = str(item).rpartition(":")+ if host and port.isdigit():+ self._extra.add((host.lower().rstrip("."), int(port)))+@propertydef url(self) -> str:return f"http://127.0.0.1:{self.port}"diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.pyindex e752fd38..4f1da7c9 100644--- a/coworker/sandbox/providers/openshell.py+++ b/coworker/sandbox/providers/openshell.py@@ -229,6 +229,7 @@ class OpenShellProvider:self.cwd = str(Path(cwd).expanduser().resolve()) if cwd else self.roots[0]["path"]self.profile = policy.network_profiles.check(profile)self.extra_hosts = list(extra_hosts)+ self._identity: tuple = (None, None, None) # uid, gid, home; set when the sandbox is madeself.image = image or sandbox_image()# A label value may hold letters, digits, '-', '_' and '.', and at most 63 characters.self.label = "".join(c if c.isalnum() or c in "-_." else "-" for c in label)[:63].strip("-_.")@@ -277,9 +278,8 @@ class OpenShellProvider:# git's settings, and HOME stays the runtime folder.self.copied = creds.copy_in(self.grants, self._tmp) if self.grants else Nonehome = self.copied.home if self.copied is not None else None- extra_hosts = sorted({*self.extra_hosts, *(self.copied.hosts if self.copied is not None else [])})- policy_file = Path(self._tmp) / "policy.yaml"- policy_file.write_text(yaml.safe_dump(policy.render(self.roots, profile=self.profile, uid=uid, gid=gid, home=home, extra_hosts=extra_hosts), sort_keys=False), encoding="utf-8")+ self._identity = (uid, gid, home)+ policy_file = self._write_policy()driver_config = json.dumps(policy.mounts(self.roots, str(self._runner.parent), home))command = [policy.PYTHON, "-S", f"{policy.RUNNER_MOUNT}/{self._runner.name}", "serve", "--socket", _SOCKET, "--cwd", self.cwd]env = {"HOME": policy.RUNTIME_DIR, **(self.copied.env if self.copied is not None else {})}@@ -344,6 +344,28 @@ class OpenShellProvider:if "entries" not in info:raise RuntimeError(f"the folder {root['path']} is not reachable inside the sandbox")+ def _write_policy(self) -> Path:+ """The whole policy as it stands: folders, identity, the network list with the+ machine's additions and the hosts the copied credentials need."""+ uid, gid, home = self._identity+ extra_hosts = sorted({*self.extra_hosts, *(self.copied.hosts if self.copied is not None else [])})+ policy_file = Path(self._tmp) / "policy.yaml"+ policy_file.write_text(yaml.safe_dump(policy.render(self.roots, profile=self.profile, uid=uid, gid=gid, home=home, extra_hosts=extra_hosts), sort_keys=False), encoding="utf-8")+ return policy_file++ def add_hosts(self, hosts: Sequence[str]) -> None:+ """Let the running sandbox reach more "host:port" entries (OPE-219: the person allowed+ a site for this session or for good). OpenShell hot-reloads the network section of a+ policy, so the whole policy is rendered again and set on the sandbox; the static+ sections are the same, `--wait` returns once the sandbox has loaded it."""+ new = [str(h) for h in hosts if str(h) not in self.extra_hosts]+ if not new:+ return+ self.extra_hosts.extend(new)+ if not getattr(self, "_create_tried", False):+ return # not made yet: the next create renders the list as it stands+ _cli("policy", "set", self.sandbox_name, "--policy", str(self._write_policy()), "--wait", timeout=120)+def regrant(self, roots: Sequence[dict[str, Any]], *, before_create: Optional[Callable[[], None]] = None) -> None:"""The session's folders changed. Mounts and the file policy are fixed when a sandboxis created, so this one is deleted and a new one is created with the new folders.diff --git a/coworker/sandbox/providers/seatbelt.py b/coworker/sandbox/providers/seatbelt.pyindex 40ca25c8..6984afb5 100644--- a/coworker/sandbox/providers/seatbelt.py+++ b/coworker/sandbox/providers/seatbelt.py@@ -165,8 +165,8 @@ class SeatbeltProvider:os.makedirs(os.path.join(self._dir, "tmp", "cache"), exist_ok=True)if self.network and not network_profiles.is_open(self.profile):hosts = sorted({*self.extra_hosts, *(h for g in self.grants for h in g.hosts)})- # A session with grants or added hosts gets its own proxy: its allow list is its own.- self._proxy = netproxy.AllowListProxy(self.profile, extra_hosts=hosts) if hosts else netproxy.shared(self.profile)+ # Each session has its own proxy: its allow list can grow while it runs (add_hosts).+ self._proxy = netproxy.AllowListProxy(self.profile, extra_hosts=hosts)else:self._proxy = None # `open`: the profile lets everything out, nothing to routeself.copied = creds.copy_in(@@ -223,6 +223,14 @@ class SeatbeltProvider:returnraise SeatbeltUnavailable("the sandbox did not take effect: the home folder can be listed from inside")+ def add_hosts(self, hosts: Sequence[str]) -> None:+ """Let the running sandbox reach more "host:port" entries (OPE-219): the session's+ own proxy takes them at once; a sandbox not made yet gets them at creation."""+ new = [str(h) for h in hosts if str(h) not in self.extra_hosts]+ self.extra_hosts.extend(new)+ if new and self._proxy is not None:+ self._proxy.add_hosts(new)+def regrant(self, roots: Sequence[dict[str, Any]], *, before_create: Optional[Callable[[], None]] = None) -> None:"""The session's folders changed. A profile is fixed when a process starts, so thedaemon is started again with a new one; the client sees a runner restart.diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.pyindex a755a523..2c406bbe 100644--- a/coworker/sandbox/providers/windows.py+++ b/coworker/sandbox/providers/windows.py@@ -157,7 +157,8 @@ class WindowsProvider:hosts = sorted({*self.extra_hosts, *(h for g in self.grants for h in g.hosts)})if self.network and not self.open_network:- self._proxy = netproxy.AllowListProxy(self.profile, extra_hosts=hosts) if hosts else netproxy.shared(self.profile)+ # Each session has its own proxy: its allow list can grow while it runs (add_hosts).+ self._proxy = netproxy.AllowListProxy(self.profile, extra_hosts=hosts)for entry in self._wanted_entries():self._grant(*entry)self._desktop = winsec.Desktop(self.session_sid)@@ -320,6 +321,14 @@ class WindowsProvider:# -- changes ------------------------------------------------------------------------restarts_on_regrant = False+ def add_hosts(self, hosts: Sequence[str]) -> None:+ """Let the running sandbox reach more "host:port" entries (OPE-219): the session's+ own proxy takes them at once; a sandbox not made yet gets them at creation."""+ new = [str(h) for h in hosts if str(h) not in self.extra_hosts]+ self.extra_hosts.extend(new)+ if new and self._proxy is not None:+ self._proxy.add_hosts(new)+def regrant(self, roots: Sequence[dict[str, Any]]) -> None:"""The session's folders changed. The confinement is per sandbox, not per folder,so the entries move and the daemon stays: a new folder is usable at once, a removeddiff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.pyindex f0d52cd8..31bd2445 100644--- a/coworker/sandbox/workspace.py+++ b/coworker/sandbox/workspace.py@@ -16,7 +16,7 @@ import osimport threadingfrom abc import ABC, abstractmethodfrom pathlib import Path-from typing import Any, Optional+from typing import Any, Optional, Sequencefrom .runner.executor import Executor@@ -214,6 +214,13 @@ class RunnerWorkspace(Workspace):def describe(self) -> dict[str, Any]:return {**self.provider.describe(), "runner": {k: self.hello.get(k) for k in ("runner_version", "os", "machine", "instance_id")}}+ def add_hosts(self, hosts: Sequence[str]) -> None:+ """The person allowed a site (OPE-219): the sandbox's network list grows at once, for+ commands as well as the web tools. Under the start lock, so a sandbox being made+ takes the list as it stands afterwards."""+ with self._start_lock:+ self.provider.add_hosts(hosts)+def close(self) -> None:if not self.started:self.client.close()diff --git a/docs/macos-sandbox.md b/docs/macos-sandbox.mdindex e293c6ad..e2ffeec5 100644--- a/docs/macos-sandbox.md+++ b/docs/macos-sandbox.md@@ -74,10 +74,10 @@ A credential entry (below) also lets through the sites its tool needs.The coworker's **web search** and **web fetch** tools run in the OpenWorker app, not in thesandbox, and follow the same list. A site that is not on it asks you first; the card offersonce, this session, or **Always allow**, which adds the site to the list. With full access-(no approvals) the fetch is refused instead. A site added this way is open to the web tools-at once; commands reach it from the next session, because the running sandbox keeps the-list it started with. Connectors and MCP servers are not covered by the list; each has its-own approval.+(no approvals) the fetch is refused instead. "This session" and "Always allow" also open the+site for the session's commands, at once: the running sandbox takes the new entry without a+restart. "Once" is that one web call only. Connectors and MCP servers are not covered by the+list; each has its own approval.## Sharing a credential on purposediff --git a/docs/openshell.md b/docs/openshell.mdindex d53bc86e..49a4751f 100644--- a/docs/openshell.md+++ b/docs/openshell.md@@ -132,10 +132,10 @@ A credential entry (below) also lets through the sites its tool needs.The coworker's **web search** and **web fetch** tools run in the OpenWorker app, not in thesandbox, and follow the same list. A site that is not on it asks you first; the card offersonce, this session, or **Always allow**, which adds the site to the list. With full access-(no approvals) the fetch is refused instead. A site added this way is open to the web tools-at once; commands reach it from the next session, because the running sandbox keeps the-list it started with. Connectors and MCP servers are not covered by the list; each has its-own approval.+(no approvals) the fetch is refused instead. "This session" and "Always allow" also open the+site for the session's commands, at once: the running sandbox takes the new entry without a+restart. "Once" is that one web call only. Connectors and MCP servers are not covered by the+list; each has its own approval.OpenShell enforces the list in the container.diff --git a/docs/windows-sandbox.md b/docs/windows-sandbox.mdindex 1d0c9df4..4a02a3d1 100644--- a/docs/windows-sandbox.md+++ b/docs/windows-sandbox.md@@ -143,10 +143,10 @@ A credential entry (below) also lets through the sites its tool needs.The coworker's **web search** and **web fetch** tools run in the OpenWorker app, not in thesandbox, and follow the same list. A site that is not on it asks you first; the card offersonce, this session, or **Always allow**, which adds the site to the list. With full access-(no approvals) the fetch is refused instead. A site added this way is open to the web tools-at once; commands reach it from the next session, because the running sandbox keeps the-list it started with. Connectors and MCP servers are not covered by the list; each has its-own approval.+(no approvals) the fetch is refused instead. "This session" and "Always allow" also open the+site for the session's commands, at once: the running sandbox takes the new entry without a+restart. "Once" is that one web call only. Connectors and MCP servers are not covered by the+list; each has its own approval.Choosing a mode never touches the firewall. The rules are written once at setup; OpenWorkerpicks the account. In the closed mode a sandbox can still **listen** on a local port (a devdiff --git a/tests/test_sandbox_openshell.py b/tests/test_sandbox_openshell.pyindex 24ead3ae..04dd232c 100644--- a/tests/test_sandbox_openshell.py+++ b/tests/test_sandbox_openshell.py@@ -257,6 +257,32 @@ def test_a_sandbox_is_created_with_its_registry_label(tmp_path, monkeypatch):assert openshell.OpenShellProvider(roots=[{"path": str(project), "writable": True}]).registry == registry_id() == SandboxRegistry().id+def test_adding_a_site_sets_the_policy_on_the_running_sandbox(tmp_path, monkeypatch):+ """OPE-219: the network section of an OpenShell policy reloads on a running sandbox, so+ a site the person allows is rendered into the whole policy and set with `--wait`."""+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))+ monkeypatch.setattr(openshell, "build_runner_zipapp", lambda: tmp_path / "sandbox" / "runner" / "runner-x.pyz")+ project = tmp_path / "project"+ project.mkdir()+ seen: list = []+ monkeypatch.setattr(openshell, "_cli", lambda *args, **kw: seen.append(args))+ provider = openshell.OpenShellProvider(roots=[{"path": str(project), "writable": True}], extra_hosts=["github.com:443"], registry="abc123")+ # Not made yet: the list grows and nothing is asked of the gateway.+ provider.add_hosts(["pypi.org:443"])+ assert provider.extra_hosts == ["github.com:443", "pypi.org:443"] and seen == []+ provider._create_tried = True+ provider._identity = (1000, 1000, None)+ provider.add_hosts(["weather.com:443", "github.com:443"])+ (call,) = seen+ assert call[:3] == ("policy", "set", provider.sandbox_name) and call[-1] == "--wait"+ written = yaml.safe_load(Path(call[call.index("--policy") + 1]).read_text())+ hosts = {e["host"] for rule in written["network_policies"].values() for e in rule["endpoints"]}+ assert {"github.com", "pypi.org", "weather.com"} <= hosts+ assert written["process"] == {"run_as_user": "1000", "run_as_group": "1000"} # the static sections are unchanged+ provider.add_hosts(["weather.com:443"]) # already there: no second call+ assert len(seen) == 1++def test_a_workspace_reserves_its_name_before_creating_the_sandbox(tmp_path):from coworker.sandbox import registry as registry_modfrom coworker.sandbox.workspace import RunnerWorkspacediff --git a/tests/test_sandbox_seatbelt.py b/tests/test_sandbox_seatbelt.pyindex a72c1c83..093b7a00 100644--- a/tests/test_sandbox_seatbelt.py+++ b/tests/test_sandbox_seatbelt.py@@ -174,6 +174,20 @@ def test_a_machines_own_hosts_are_cleaned_and_join_the_list():proxy.close()+def test_a_running_proxy_takes_more_hosts():+ """The person allowed a site while the session runs (OPE-219): its proxy lets the host+ out from then on, and only that proxy, since every session has its own."""+ proxy, other = netproxy.AllowListProxy("allowlist"), netproxy.AllowListProxy("allowlist")+ try:+ assert not proxy.allows("weather.com", 443)+ proxy.add_hosts(["weather.com:443", "not a host"])+ assert proxy.allows("weather.com", 443) and not proxy.allows("weather.com", 80)+ assert not other.allows("weather.com", 443)+ finally:+ proxy.close()+ other.close()++def test_the_open_profile_has_no_list_and_is_the_default_on_windows_only(tmp_path):assert network_profiles.hosts("open") == [] and network_profiles.is_open("open")assert network_profiles.default_profile("win32") == "open"diff --git a/tests/test_site_wall.py b/tests/test_site_wall.pyindex d2e47ded..d0043a04 100644--- a/tests/test_site_wall.py+++ b/tests/test_site_wall.py@@ -159,3 +159,20 @@ def test_session_sandbox_summary(tmp_path, monkeypatch):# ...and "not sandboxed" when the machine is now set to use one (opened before the switch).(tmp_path / "config.toml").write_text('sandbox_provider = "openshell"\n')assert settings.session_sandbox(plain) == {"state": "not_sandboxed", "provider": "openshell"}+++def test_a_session_or_always_choice_opens_the_site_on_the_running_sandbox(tmp_path):+ """The card's lasting choices reach commands too: the engine tells the sandbox. "Allow+ once" is one web-tool call and never touches it."""+ opened: list[str] = []+ eng = engine(tmp_path, Mode.INTERACTIVE, open_site=opened.append, grant_site=lambda host: [*SITES, f"{host}:443"])+ eng.allow_site_for_session("https://www.weather.com/today")+ assert opened == ["www.weather.com"]+ assert eng.evaluate("web_fetch", {"url": "https://weather.com/x"}, None).allowed+ assert "weather.com:443" not in eng.sandbox_sites # this session only: nothing stored+ eng.allow_site_always("https://docs.python.org/3/")+ assert opened == ["www.weather.com", "docs.python.org"] and "docs.python.org:443" in eng.sandbox_sites+ # No sandbox hook (an engine without a sandbox): the choices still work for the web tools.+ plain = engine(tmp_path, Mode.INTERACTIVE)+ plain.allow_site_for_session("https://weather.com/")+ assert plain.evaluate("web_fetch", {"url": "https://weather.com/x"}, None).allowed