Coverage for app / tools / web / policy.py: 91%
168 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2Domain policy for the web tools: safety blocklists, operator allowlists,
3the workspace's Tools rules, authority tiers, and URL canonicalisation.
5Shared by ``web_search`` (filters and ranks results), ``url_fetch`` (gates
6which pages an agent may read) and ``render_document`` (the images a
7document embeds), so an operator's allowlist — or a rule's — cannot be
8sidestepped by fetching an arbitrary URL directly.
10A domain is read as the Tools rules read it (``app/util/web_domains.py``,
11shared byte for byte with svc-core): lowercase, no ``www.`` or wildcard, and
12covering its subdomains.
13"""
15from __future__ import annotations
17import urllib.parse
18from collections.abc import Iterable, Mapping
19from enum import Enum
20from typing import Any
22from app.common import web_policy as governed_web
23from app.tools.web import platform_sources
24from app.util import web_domains
25from app.util.web_domains import WebPolicy, host_matches
26from app.util.web_search_report import SourcesSetBy
28__all__ = [
29 "DomainPolicy",
30 "Verdict",
31 "canonical_key",
32 "domain_quality_score",
33 "host_matches",
34 "hostname_of",
35 "strip_tracking",
36]
39def _normalise_domains(domains: Iterable[str] | None) -> frozenset[str]:
40 return frozenset(web_domains.normalise_domains(domains))
43def hostname_of(url: str) -> str:
44 try:
45 return (urllib.parse.urlparse(url).hostname or "").lower()
46 except ValueError:
47 return ""
50# ---------------------------------------------------------------------------
51# Authority tiers (0–4). Used as a *tie-breaker* on top of the provider's
52# relevance order — never as the primary sort key — and persisted with
53# citations for the web-search domain stats.
54# ---------------------------------------------------------------------------
56# Tier 4 — explicit high-quality domains (news wires, reference, tech docs).
57QUALITY_DOMAINS: frozenset[str] = frozenset(
58 {
59 "bbc.co.uk",
60 "bbc.com",
61 "reuters.com",
62 "apnews.com",
63 "theguardian.com",
64 "nytimes.com",
65 "washingtonpost.com",
66 "ft.com",
67 "economist.com",
68 "bloomberg.com",
69 "wsj.com",
70 "techcrunch.com",
71 "wired.com",
72 "arstechnica.com",
73 "theregister.com",
74 "zdnet.com",
75 "thenextweb.com",
76 "ieee.org",
77 "acm.org",
78 "arxiv.org",
79 "nature.com",
80 "science.org",
81 "ncbi.nlm.nih.gov",
82 "who.int",
83 "europa.eu",
84 "wikipedia.org",
85 "stackoverflow.com",
86 "github.com",
87 "developer.mozilla.org",
88 "docs.python.org",
89 "learn.microsoft.com",
90 "docs.microsoft.com",
91 "developer.apple.com",
92 "cloud.google.com",
93 "aws.amazon.com",
94 }
95)
97# Tier 3 — government and academic suffixes.
98QUALITY_TLDS_3: frozenset[str] = frozenset(
99 {
100 ".gov",
101 ".gov.uk",
102 ".nhs.uk",
103 ".gov.au",
104 ".govt.nz",
105 ".gov.ie",
106 ".gc.ca",
107 ".edu",
108 ".ac.uk",
109 ".edu.au",
110 }
111)
113# Tier 2 — non-profit / organisational suffixes.
114QUALITY_TLDS_2: frozenset[str] = frozenset({".org", ".org.uk", ".org.au", ".int"})
116# Tier 1 — mainstream commercial / national suffixes. Everything else that
117# survives the blocklist scores 0 (still returned, just never boosted).
118QUALITY_TLDS_1: frozenset[str] = frozenset(
119 {
120 ".com",
121 ".net",
122 ".io",
123 ".co",
124 ".uk",
125 ".eu",
126 ".ie",
127 ".de",
128 ".fr",
129 ".nl",
130 ".ca",
131 ".au",
132 ".nz",
133 ".dev",
134 ".ai",
135 }
136)
139def domain_quality_score(url: str) -> int:
140 """Return an authority score 0–4 for *url*'s domain; higher is more authoritative."""
141 hostname = hostname_of(url)
142 if not hostname:
143 return 0
144 if any(host_matches(hostname, d) for d in QUALITY_DOMAINS):
145 return 4
146 if any(hostname.endswith(tld) for tld in QUALITY_TLDS_3):
147 return 3
148 if any(hostname.endswith(tld) for tld in QUALITY_TLDS_2):
149 return 2
150 if any(hostname.endswith(tld) for tld in QUALITY_TLDS_1):
151 return 1
152 return 0
155# ---------------------------------------------------------------------------
156# URL canonicalisation
157# ---------------------------------------------------------------------------
159_TRACKING_PARAMS: frozenset[str] = frozenset(
160 {
161 "gclid",
162 "fbclid",
163 "msclkid",
164 "dclid",
165 "yclid",
166 "mc_cid",
167 "mc_eid",
168 "igshid",
169 "ref_src",
170 "_hsenc",
171 "_hsmi",
172 }
173)
176def strip_tracking(url: str) -> str:
177 """Drop analytics parameters (utm_*, gclid, …) and the fragment."""
178 try:
179 parts = urllib.parse.urlsplit(url)
180 except ValueError:
181 return url
182 query = [
183 (k, v)
184 for k, v in urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
185 if not (k.lower().startswith("utm_") or k.lower() in _TRACKING_PARAMS)
186 ]
187 return urllib.parse.urlunsplit(
188 (parts.scheme, parts.netloc, parts.path, urllib.parse.urlencode(query), "")
189 )
192def canonical_key(url: str) -> str:
193 """Identity key for de-duplication: scheme-, www-, slash- and tracking-insensitive."""
194 cleaned = strip_tracking(url)
195 try:
196 parts = urllib.parse.urlsplit(cleaned)
197 except ValueError:
198 return cleaned
199 host = (parts.hostname or "").lower().removeprefix("www.")
200 path = parts.path.rstrip("/") or "/"
201 return f"{host}{path}?{parts.query}" if parts.query else f"{host}{path}"
204# ---------------------------------------------------------------------------
205# DomainPolicy
206# ---------------------------------------------------------------------------
209class Verdict(str, Enum):
210 """Whether a URL may be used, and when not, whose check refused it — so a
211 search that keeps nothing can say what removed its results, and never
212 blame a check that did not act."""
214 PERMITTED = "permitted"
215 # The built-in safety checks: the scheme (and HTTPS), link shorteners,
216 # disposable domains.
217 SAFETY = "safety"
218 # The tool's own configuration: an operator's blocked list or allowlist.
219 TOOL_CONFIG = "tool_config"
220 # The workspace's Tools rules: a source they rule out, or one outside the
221 # only ones they allow.
222 RULES_BLOCKED = "rules_blocked"
223 RULES_NOT_ALLOWED = "rules_not_allowed"
224 # Outside the ``domains`` the model asked this call to search.
225 NOT_REQUESTED = "not_requested"
228def _sets_sources(policy: WebPolicy) -> bool:
229 """Whether the workspace's rules chose the sources themselves — put some
230 first, or allowed only some — so the platform's own list gives way."""
231 return bool(policy.preferred) or policy.allowed is not None
234class DomainPolicy:
235 """Decides which URLs an agent may see or fetch.
237 Three layers of domain control:
239 - ``allowed_domains`` (operator config): hard ceiling. When non-empty,
240 only those domains and their subdomains are permitted.
241 - the workspace's **Tools rules**, for a policy made with
242 :meth:`for_run`: sources never to use, the only ones to use (a further
243 ceiling) and ones to put first — read from the request
244 (``app/common/web_policy.py``) each time a URL is checked, so they hold
245 however the tool was reached.
246 - call-time ``domains`` (LLM-supplied): further narrows the ceiling. A
247 call-time domain is honoured when it lies within the ceiling (itself or
248 a subdomain of an allowed domain) — ``news.bbc.co.uk`` is a valid
249 narrowing of ``bbc.co.uk``.
251 Safety blocklists (URL shorteners, disposable TLDs, operator extras)
252 always apply.
253 """
255 # Free / disposable TLDs routinely abused for phishing and malware.
256 BLOCKED_TLDS: frozenset[str] = frozenset(
257 {
258 ".tk",
259 ".ml",
260 ".ga",
261 ".cf",
262 ".gq",
263 ".xyz",
264 ".top",
265 ".click",
266 ".download",
267 ".stream",
268 ".racing",
269 ".win",
270 ".loan",
271 ".date",
272 ".faith",
273 ".review",
274 ".trade",
275 ".accountant",
276 ".science",
277 ".work",
278 ".men",
279 ".cam",
280 }
281 )
283 # URL shorteners hide the real destination, defeating every other check.
284 BLOCKED_DOMAINS: frozenset[str] = frozenset(
285 {
286 "bit.ly",
287 "tinyurl.com",
288 "t.co",
289 "goo.gl",
290 "ow.ly",
291 "is.gd",
292 "buff.ly",
293 "adf.ly",
294 }
295 )
297 def __init__(
298 self,
299 allowed_domains: Iterable[str] | None = None,
300 blocked_domains: Iterable[str] | None = None,
301 require_https: bool = True,
302 *,
303 governed: bool = False,
304 ) -> None:
305 self.allowed: frozenset[str] = _normalise_domains(allowed_domains)
306 self._blocked: frozenset[str] = self.BLOCKED_DOMAINS | _normalise_domains(
307 blocked_domains
308 )
309 self.require_https = require_https
310 self._governed = governed
312 @classmethod
313 def from_config(cls, config: Mapping[str, Any]) -> DomainPolicy:
314 return cls(
315 allowed_domains=config.get("allowed_domains") or [],
316 blocked_domains=config.get("blocked_domains") or [],
317 require_https=bool(config.get("require_https", True)),
318 )
320 @classmethod
321 def for_run(
322 cls, config: Mapping[str, Any] | None = None, *, require_https: bool = True
323 ) -> DomainPolicy:
324 """The policy a web tool the platform wrote fetches under in a run:
325 its config's, and the workspace's Tools rules for the request it is
326 part of, read at each check (:meth:`governing`). Every web tool's
327 factory builds its policy here (``tests/tools/test_governed_web_policy.py``
328 holds them to it), so no tool path can reach the web without them.
329 """
330 config = config or {}
331 return cls(
332 allowed_domains=config.get("allowed_domains") or [],
333 blocked_domains=config.get("blocked_domains") or [],
334 require_https=bool(config.get("require_https", require_https)),
335 governed=True,
336 )
338 def governing(self) -> WebPolicy | None:
339 """The Tools rules' policy this check is held to: the request's, for
340 a policy made with :meth:`for_run`; None otherwise, or when no rule
341 restricts the web."""
342 if not self._governed:
343 return None
344 policy = governed_web.current()
345 return policy if policy is not None and policy.restricts else None
347 def ceiling(self) -> frozenset[str] | None:
348 """The domains a URL must lie within: the operator's allowlist and
349 the rules' only-these sources, both — None when neither restricts,
350 an empty set when nothing is left."""
351 governed = self.governing()
352 rules = governed.allowed if governed is not None else None
353 if rules is None:
354 return self.allowed or None
355 if not self.allowed:
356 return rules
357 return web_domains.intersect_domains(self.allowed, rules)
359 def preferred(self) -> frozenset[str]:
360 """Sources put first: the workspace's rules', when they put any
361 first or allow only some — they replace the platform's — else the
362 platform's own for this run (``platform_sources``), less what the
363 tool's configuration or the rules rule out. None when the rules
364 leave no source."""
365 governed = self.governing()
366 if governed is not None and _sets_sources(governed):
367 return governed.preferred
368 return self._platform_preferred(governed)
370 def preferred_set_by(self) -> SourcesSetBy | None:
371 """Who chose the sources :meth:`preferred` puts first: the
372 workspace's rules, the platform, or nobody."""
373 governed = self.governing()
374 if governed is not None and _sets_sources(governed):
375 return SourcesSetBy.rules if governed.preferred else None
376 return SourcesSetBy.platform if self._platform_preferred(governed) else None
378 def _platform_preferred(self, governed: WebPolicy | None) -> frozenset[str]:
379 if not self._governed:
380 return frozenset()
381 sources = platform_sources.current()
382 if not sources or (governed is not None and governed.closed):
383 return frozenset()
384 return platform_sources.usable(
385 sources,
386 blocked=self._blocked | (governed.blocked if governed else frozenset()),
387 allowed=self.allowed,
388 )
390 def prefers(self, url: str) -> bool:
391 """Whether *url* is a trusted source this policy also permits."""
392 hostname = hostname_of(url)
393 return (
394 bool(hostname)
395 and web_domains.covered(hostname, self.preferred())
396 and self.is_permitted(url)
397 )
399 @property
400 def closed(self) -> bool:
401 """Whether the rules leave no web source at all."""
402 governed = self.governing()
403 return governed is not None and governed.closed
405 def refusal(self, hostname: str) -> str:
406 """Why *hostname* may not be used — the rules' reason when it is
407 theirs, so the model is not told to try a tool setting it cannot
408 change."""
409 governed = self.governing()
410 if governed is not None and governed.closed:
411 return (
412 "no web source is permitted for this request by the workspace's rules"
413 )
414 if governed is not None and not governed.permits(hostname):
415 return f"'{hostname}' is not a source the workspace's rules allow"
416 return f"'{hostname}' is blocked by the domain policy for this tool"
418 def to_config(self) -> dict[str, Any]:
419 """Round-trippable config, used to hand url_fetch the same policy."""
420 return {
421 "allowed_domains": sorted(self.allowed),
422 "blocked_domains": sorted(self._blocked - self.BLOCKED_DOMAINS),
423 "require_https": self.require_https,
424 }
426 # ------------------------------------------------------------------
428 def effective_domains(
429 self, call_domains: Iterable[str] | None
430 ) -> frozenset[str] | None:
431 """The domain restriction for one call.
433 Returns ``None`` when unrestricted, otherwise the set of domains a
434 result must match. An empty set means the call-time request lies
435 entirely outside the operator allowlist — nothing can match.
436 """
437 ceiling = self.ceiling()
438 requested = _normalise_domains(call_domains)
439 if not requested:
440 return ceiling
441 if ceiling is None:
442 return requested
443 return frozenset(d for d in requested if web_domains.covered(d, ceiling))
445 def is_blocked_host(self, hostname: str) -> bool:
446 if any(host_matches(hostname, d) for d in self._blocked):
447 return True
448 governed = self.governing()
449 if governed is not None and web_domains.covered(hostname, governed.blocked):
450 return True
451 return any(hostname.endswith(tld) for tld in self.BLOCKED_TLDS)
453 def is_permitted(self, url: str, call_domains: Iterable[str] | None = None) -> bool:
454 """Return True iff *url* passes all safety and allowlist checks."""
455 return self.verdict(url, call_domains) is Verdict.PERMITTED
457 def verdict(self, url: str, call_domains: Iterable[str] | None = None) -> Verdict:
458 """Whether *url* may be used, and when not, the first check that
459 refused it, in the order they are applied: safety, the tool's
460 configuration, the workspace's rules, then the call's own domains."""
461 try:
462 parsed = urllib.parse.urlparse(url)
463 hostname = (parsed.hostname or "").lower()
464 except ValueError:
465 return Verdict.SAFETY
466 if parsed.scheme not in ("https", "http"):
467 return Verdict.SAFETY
468 if self.require_https and parsed.scheme != "https":
469 return Verdict.SAFETY
470 if not hostname:
471 return Verdict.SAFETY
472 if any(host_matches(hostname, d) for d in self.BLOCKED_DOMAINS) or any(
473 hostname.endswith(tld) for tld in self.BLOCKED_TLDS
474 ):
475 return Verdict.SAFETY
476 if any(host_matches(hostname, d) for d in self._blocked):
477 return Verdict.TOOL_CONFIG
478 governed = self.governing()
479 if governed is not None and web_domains.covered(hostname, governed.blocked):
480 return Verdict.RULES_BLOCKED
481 if self.allowed and not any(host_matches(hostname, d) for d in self.allowed):
482 return Verdict.TOOL_CONFIG
483 if governed is not None and governed.allowed is not None:
484 if not web_domains.covered(hostname, governed.allowed):
485 return Verdict.RULES_NOT_ALLOWED
486 if _normalise_domains(call_domains):
487 effective = self.effective_domains(call_domains) or frozenset()
488 if not any(host_matches(hostname, d) for d in effective):
489 return Verdict.NOT_REQUESTED
490 return Verdict.PERMITTED