Python
Web tools are held to the sandbox's allowed sites
Rohit C Prasad8cc7ef8a3d13
diff --git a/coworker/agent.py b/coworker/agent.pyindex 92516cf1..77724d79 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -726,6 +726,21 @@ def build_engine(engine.compaction_settings = lambda: dict(_compaction_overrides)engine.executor = executor # type: ignore[attr-defined]engine.sandbox_workspace = sandbox_workspace # type: ignore[attr-defined]+ # OPE-219: a sandboxed session with "Only the sites you allow" holds its web tools to+ # the same list as its commands. They run in this process, outside the sandbox, so the+ # permission engine is the wall for them. No sandbox, or "Allow everything": no wall.+ _sandbox_provider = getattr(sandbox_workspace, "provider", None)+ if _sandbox_provider is not None and getattr(_sandbox_provider, "profile", "") == "allowlist":+ from .sandbox import settings as _sandbox_settings+ from .web import provider_host as _provider_host++ engine.permissions.sandbox_sites = list(getattr(_sandbox_provider, "extra_hosts", None) or [])+ engine.permissions.search_host = lambda: _provider_host(secrets)++ def _grant_site(host: str) -> None:+ _sandbox_settings.add_site(host)++ engine.permissions.grant_site = _grant_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 081b60a0..daec5b24 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -72,6 +72,9 @@ class ApprovalOutcome(str, Enum):ALWAYS_TOOL = "always_tool"ALWAYS_COMMAND = "always_command"ALWAYS_DOMAIN = "always_domain"+ # OPE-219: the allowed-sites card's durable choice. The site joins the machine's+ # sandbox list (Settings > Sandbox), for commands and web tools alike.+ ALWAYS_SITE = "always_site"# Session-wide grant for classifier-approved read-only shell commands (readonly.py).READONLY_SESSION = "readonly_session"# OPE-136 durable trust: persist a per-tool "don't ask" rule for an MCP tool —@@ -1698,6 +1701,9 @@ class TurnEngine:else {}),"category": getattr(metadata, "category", ""),+ # OPE-219: the host the sandbox's allowed-sites wall stopped. The card+ # says so and offers to add the site to the machine's list.+ **({"site_wall": decision.site} if decision.site else {}),# The exact target a standing rule could pin, or None when the call# isn't eligible (no declared target arg / exec risk). Surfaces use it# to offer "Allow every time" on automation-run approval cards only.@@ -1804,6 +1810,16 @@ class TurnEngine:self.permissions.allow_domain_for_session(str(tool_call.arguments.get("url", "")))+ elif outcome is ApprovalOutcome.ALWAYS_SITE and decision.site:+ self.permissions.allow_site_always(decision.site)+ # A session grant given on the allowed-sites card must also open the+ # wall for that site, or the next call would raise the same card+ # (web_search has no url: its site is the search provider's host).+ if decision.site and outcome in (+ ApprovalOutcome.ALWAYS_TOOL,+ ApprovalOutcome.ALWAYS_DOMAIN,+ ):+ self.permissions.allow_domain_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 14020f5e..c3085fd7 100644--- a/coworker/permissions.py+++ b/coworker/permissions.py@@ -258,6 +258,9 @@ class Decision:# Set when a task-scoped standing rule allowed the call ("tool → target") so the# engine can audit the exact rule and the tool card can say so (§25).rule: str = ""+ # The host the sandbox's allowed-sites wall stopped (OPE-219). The card then says why+ # it is asking and offers to add the site to the list.+ site: str = ""def standing_rule_candidate(@@ -297,6 +300,18 @@ class PermissionEngine:# subdomain suffix (see `_domain_allowed`).allowed_domains: list[str] = field(default_factory=list)session_allow_domains: set[str] = field(default_factory=set)+ # The sandbox's allowed sites, as a wall for the web tools too (OPE-219). None: no wall+ # (the session is not sandboxed, or its network setting is "Allow everything"). A list,+ # possibly empty: the session runs with "Only the sites you allow", so `web_fetch`,+ # `web_search` and `browser_open_url` may reach only these hosts ("host[:port]",+ # "*.example.com"), the same list its commands are held to. These tools run in the+ # OpenWorker process, outside the sandbox; before this the list did not apply to them+ # and Bypass reached any site (reported on 0.3.0, 2026-10-02).+ sandbox_sites: Optional[list[str]] = None+ # Where `web_search` goes: the configured provider's host (it has no url argument).+ search_host: Optional[Callable[[], str]] = None+ # Persists a site the user chose to always allow (adds it to the machine's list).+ grant_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@@ -429,6 +444,27 @@ class PermissionEngine:human_only=True, # deferred-execution files: a human sees every one (§ floor))+ # THE ALLOWED-SITES WALL (OPE-219). Like the folder wall, no mode removes it: in+ # Bypass a site that is not on the list is refused outright, with no card (owner+ # ruling 2026-10-02); in the asking modes it reaches a person, never the reviewer,+ # who may not widen the user's list. A site on the list runs without a card.+ walled_site = ""+ on_site_wall = False+ if is_egress and self.sandbox_sites is not None:+ host = self.egress_host(tool_name, arguments)+ if host and self._site_allowed(host):+ on_site_wall = True+ else:+ walled_site = host or "this site"+ if self.mode is Mode.BYPASS_APPROVALS:+ return Decision(+ False,+ f"{walled_site} is not on this machine's allowed sites, so the sandbox "+ "setting blocks it. The user can add it in Settings > Sandbox > Choose sites.",+ needs_user=False,+ site=walled_site,+ )+# Full access.if self.mode is Mode.BYPASS_APPROVALS:return Decision(True, "full access")@@ -467,6 +503,16 @@ class PermissionEngine:self._under_root(t) for t in read_targets(command)):return Decision(True, "read-only command (session grant)")+ if on_site_wall:+ return Decision(True, "site on the allowed sites")+ if walled_site:+ return Decision(+ False,+ f"{walled_site} is not on your allowed sites",+ needs_user=True,+ human_only=True,+ site=walled_site,+ )if is_egress:url = str(arguments.get("url", ""))if self._domain_allowed(url, include_session=honor_session_grants):@@ -564,6 +610,58 @@ class PermissionEngine:if host:self.session_allow_domains.add(host)+ def allow_site_always(self, url_or_domain: str) -> None:+ """"Always allow <site>" on the allowed-sites card: the site joins the machine's+ list (Settings > Sandbox), for commands and web tools alike. Without a store wired+ (ephemeral engines in tests) it degrades to this session."""+ host = _host_of(url_or_domain)+ if not host:+ return+ if self.sandbox_sites is not None and not self._on_site_list(host):+ self.sandbox_sites.append(host)+ if self.grant_site is not None:+ self.grant_site(host)+ else:+ self.session_allow_domains.add(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 fixed+ destination, no url) the configured search provider's host."""+ url = str((arguments or {}).get("url", "") or "")+ if url:+ return _host_of(url)+ if self.search_host is not None:+ try:+ return _host_of(self.search_host() or "")+ except Exception: # noqa: BLE001 - an unknown provider reads as "not allowed"+ return ""+ return ""++ def _on_site_list(self, host: str) -> bool:+ """Whether `host` is on the sandbox's list. The web tools speak HTTP(S) only, so+ the entry's port is not compared; `*.example.com` covers subdomains, as in the+ sandbox's own proxy (netproxy.allows)."""+ for entry in self.sandbox_sites or []:+ name = str(entry).strip().lower()+ if not name:+ continue+ if "://" in name:+ name = _host_of(name)+ name = name.rsplit(":", 1)[0] if ":" in name and not name.endswith("]") else name+ if name.startswith("*."):+ if host.endswith(name[1:]) and host != name[2:]:+ return True+ elif host == name:+ return True+ return False++ def _site_allowed(self, host: str) -> bool:+ """On the machine's list, or granted by the user for this session. A session grant+ counts in every mode here: a person gave it, on a card only a person can answer."""+ if self._on_site_list(host):+ return True+ return any(host == d or host.endswith("." + d) for d in self.session_allow_domains)+# -- helpers ----------------------------------------------------------------def _candidate(self, path: str) -> Path:# Relative paths resolve against the primary (workspace_root); absolute/`~` taken as-is.diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.pyindex 66353e0d..a4516f32 100644--- a/coworker/sandbox/settings.py+++ b/coworker/sandbox/settings.py@@ -305,3 +305,17 @@ def _unset(key: str) -> None:lines = target.read_text(encoding="utf-8").splitlines()kept = [line for line in lines if not re.match(rf"\s*{re.escape(key)}\s*=", line)]target.write_text("\n".join(kept) + "\n", encoding="utf-8")+++def add_site(host: str) -> list[str]:+ """Add one site to the machine's allowed sites (the "Always allow <site>" choice on the+ allowed-sites card, OPE-219) and return the new list. A site already on it changes+ nothing. Raises ValueError for a host the list cannot hold."""+ from .network_profiles import clean_host++ entry = clean_host(host)+ current = list(app_config.load_config().sandbox_network_hosts or [])+ if entry not in current:+ current.append(entry)+ app_config.set_global_list("sandbox_network_hosts", current)+ return currentdiff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 2026c0c4..e6124491 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -156,6 +156,10 @@ def _grant_offered(outcome, request) -> bool:return risk is RiskClass.EXECif outcome is ApprovalOutcome.ALWAYS_DOMAIN:return risk is RiskClass.EGRESS and bool(args.get("url"))+ if outcome is ApprovalOutcome.ALWAYS_SITE:+ # OPE-219: only the allowed-sites card offers it, and only egress tools raise it.+ # (The engine applies it only when the wall named a site for this call.)+ return risk is RiskClass.EGRESSif outcome is ApprovalOutcome.ALWAYS_TRUST:# OPE-136 §4: durable per-tool trust is the MCP family's sanctioned lever —# the coarsest grant knowledge allows there, and offered nowhere else@@ -5942,6 +5946,7 @@ class SessionManager:ApprovalOutcome.ALWAYS_TOOL,ApprovalOutcome.ALWAYS_COMMAND,ApprovalOutcome.ALWAYS_DOMAIN,+ ApprovalOutcome.ALWAYS_SITE,# ALWAYS_TRUST was unlisted (a raw resolve could mint an inert-but-real# trust rule for a non-MCP tool — evaluate ignores those, but the store# shouldn't carry them); THIS_RUN validates like every grant.diff --git a/coworker/web/__init__.py b/coworker/web/__init__.pyindex ae1ec3ef..159de66a 100644--- a/coworker/web/__init__.py+++ b/coworker/web/__init__.py@@ -12,7 +12,7 @@ from .providers import (provider_names,)from .fetch import make_web_fetch_tool-from .tool import make_web_search_tool, provider_name, resolve_provider+from .tool import make_web_search_tool, provider_host, provider_name, resolve_provider__all__ = ["SearchResult",@@ -25,5 +25,6 @@ __all__ = ["make_web_search_tool","make_web_fetch_tool","provider_name",+ "provider_host","resolve_provider",]diff --git a/coworker/web/tool.py b/coworker/web/tool.pyindex d2b845cd..b24d73e6 100644--- a/coworker/web/tool.py+++ b/coworker/web/tool.py@@ -51,6 +51,20 @@ def provider_name(return profile.get("provider") or _config_provider() or default+# Where each provider's queries go. The sandbox's allowed-sites wall checks this host for+# `web_search`, which has no url argument (OPE-219).+PROVIDER_HOSTS = {+ "duckduckgo": "duckduckgo.com",+ "tavily": "api.tavily.com",+ "brave": "api.search.brave.com",+}+++def provider_host(secrets: Optional[SecretStore] = None) -> str:+ """The host the configured search provider talks to; `''` for an unknown provider."""+ return PROVIDER_HOSTS.get(provider_name(secrets), "")++def resolve_provider(secrets: Optional[SecretStore] = None, *, default: str = "duckduckgo") -> WebSearchProvider:diff --git a/tests/test_site_wall.py b/tests/test_site_wall.pynew file mode 100644index 00000000..64a81bd0--- /dev/null+++ b/tests/test_site_wall.py@@ -0,0 +1,118 @@+"""The sandbox's allowed sites hold the web tools too (OPE-219).++Reported on 0.3.0 (2026-10-02): with "Only the sites you allow" and only code hosts ticked,+the agent still searched the web. The list was a wall for commands inside the sandbox; the+web tools run in the OpenWorker process and never looked at it, and Bypass skipped their card.+"""++from __future__ import annotations++from coworker.permissions import Mode, PermissionEngine++SITES = ["github.com", "api.github.com:443", "*.githubusercontent.com"]+++def engine(tmp_path, mode, **kw):+ return PermissionEngine(workspace_root=tmp_path, mode=mode, sandbox_sites=list(SITES), **kw)+++def test_a_site_on_the_list_runs_without_a_card_in_every_asking_mode(tmp_path):+ for mode in (Mode.INTERACTIVE, Mode.AUTO_APPROVE, Mode.BYPASS_APPROVALS):+ eng = engine(tmp_path, mode)+ for url in ("https://github.com/a/b", "https://api.github.com/zen", "https://raw.githubusercontent.com/a/b/x"):+ d = eng.evaluate("web_fetch", {"url": url}, None)+ assert d.allowed and not d.needs_user, (mode, url, d.reason)+ # The wildcard covers subdomains only, as in the sandbox's own proxy.+ assert not engine(tmp_path, Mode.INTERACTIVE).evaluate("web_fetch", {"url": "https://githubusercontent.com/"}, None).allowed+++def test_bypass_refuses_a_site_off_the_list_with_no_card(tmp_path):+ d = engine(tmp_path, Mode.BYPASS_APPROVALS).evaluate("web_fetch", {"url": "https://weather.com/today?x=1"}, None)+ assert not d.allowed and not d.needs_user # a wall, like the folder wall: no mode removes it+ assert d.site == "weather.com" and "allowed sites" in d.reason+++def test_asking_modes_raise_a_card_only_a_person_can_answer(tmp_path):+ for mode in (Mode.INTERACTIVE, Mode.AUTO_APPROVE):+ d = engine(tmp_path, mode).evaluate("web_fetch", {"url": "https://weather.com/today"}, None)+ assert not d.allowed and d.needs_user and d.human_only, mode # never the reviewer+ assert d.site == "weather.com"+++def test_the_wall_wins_over_the_approval_allowlist(tmp_path):+ # `allowed_domains` only waives the card; it is not the sandbox's list.+ eng = engine(tmp_path, Mode.INTERACTIVE, allowed_domains=["weather.com"])+ assert eng.evaluate("web_fetch", {"url": "https://weather.com/"}, None).needs_user+++def test_session_and_always_choices(tmp_path):+ eng = engine(tmp_path, Mode.INTERACTIVE)+ eng.allow_domain_for_session("https://weather.com/today")+ assert eng.evaluate("web_fetch", {"url": "https://weather.com/other"}, None).allowed+ # A session grant holds in Bypass too: a person gave it.+ eng.mode = Mode.BYPASS_APPROVALS+ assert eng.evaluate("web_fetch", {"url": "https://www.weather.com/x"}, None).allowed++ saved: list[str] = []+ eng2 = engine(tmp_path, Mode.INTERACTIVE, grant_site=saved.append)+ eng2.allow_site_always("https://docs.python.org/3/")+ assert saved == ["docs.python.org"] and "docs.python.org" in eng2.sandbox_sites+ assert eng2.evaluate("web_fetch", {"url": "https://docs.python.org/3/library/"}, None).allowed+ assert eng2.evaluate("web_fetch", {"url": "https://python.org/"}, None).needs_user # that host only+++def test_web_search_is_held_to_the_provider_host(tmp_path):+ eng = engine(tmp_path, Mode.BYPASS_APPROVALS, search_host=lambda: "api.search.brave.com")+ d = eng.evaluate("web_search", {"query": "weather"}, None)+ assert not d.allowed and not d.needs_user and d.site == "api.search.brave.com"+ eng.sandbox_sites.append("api.search.brave.com")+ assert eng.evaluate("web_search", {"query": "weather"}, None).allowed+ # In an asking mode an unlisted provider raises the card; with no known provider too.+ ask = engine(tmp_path, Mode.INTERACTIVE, search_host=lambda: "")+ d = ask.evaluate("web_search", {"query": "x"}, None)+ assert d.needs_user and d.human_only+++def test_no_wall_without_a_site_list(tmp_path):+ # Not sandboxed, or "Allow everything": today's behaviour, untouched.+ assert PermissionEngine(workspace_root=tmp_path, mode=Mode.BYPASS_APPROVALS).evaluate("web_fetch", {"url": "https://weather.com/"}, None).allowed+ d = PermissionEngine(workspace_root=tmp_path, mode=Mode.INTERACTIVE).evaluate("web_fetch", {"url": "https://weather.com/"}, None)+ assert d.needs_user and not d.human_only and not d.site+ # An empty list is a wall with nothing ticked.+ empty = PermissionEngine(workspace_root=tmp_path, mode=Mode.BYPASS_APPROVALS, sandbox_sites=[])+ assert not empty.evaluate("web_fetch", {"url": "https://github.com/"}, None).allowed+++def test_other_tools_are_untouched_by_the_wall(tmp_path):+ eng = engine(tmp_path, Mode.BYPASS_APPROVALS)+ assert eng.evaluate("run_shell", {"command": "curl https://weather.com"}, None).allowed # the sandbox holds commands+ assert eng.evaluate("read_file", {"path": "a.txt"}, None).allowed+++# -- the durable choice: server validation and the machine's list ---------------------------+++def test_always_site_is_offered_only_for_egress_tools(tmp_path):+ from types import SimpleNamespace++ from coworker.engine import ApprovalOutcome+ from coworker.server.manager import SessionManager++ manager = SessionManager(workspace=str(tmp_path), data_dir=tmp_path / "state")+ request = lambda tool, args: SimpleNamespace(tool_name=tool, arguments=args, metadata=None) # noqa: E731+ assert manager.approval_outcome("always_site", request("web_fetch", {"url": "https://weather.com/"}), "s1") is ApprovalOutcome.ALWAYS_SITE+ assert manager.approval_outcome("always_site", request("web_search", {"query": "x"}), "s2") is ApprovalOutcome.ALWAYS_SITE+ # A raw resolve for another tool degrades to a single allow, like every other grant.+ assert manager.approval_outcome("always_site", request("write_file", {"path": "a"}), "s3") is ApprovalOutcome.ONCE+++def test_add_site_joins_the_machines_list_once(tmp_path, monkeypatch):+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))+ from coworker import config as app_config+ from coworker.sandbox import settings++ assert settings.add_site("weather.com") == ["weather.com:443"]+ hosts = app_config.load_config().sandbox_network_hosts+ assert hosts == ["weather.com:443"]+ settings.add_site("weather.com")+ assert app_config.load_config().sandbox_network_hosts == hosts # no duplicate