Coverage for app / util / web_domains.py: 100%
107 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2The web sources a governed run may use — one module, carried by both services.
4A workspace's **Tools** rules say where its agents may look things up: sources
5to prefer (``trusted_sources``), optionally the only ones to use, and sources
6never to use (``blocked_sources``). svc-core resolves a turn's rules into one
7:class:`WebPolicy` and sends it on every svc-ai call the turn makes
8(``X-Web-Policy``); svc-ai folds it into each web tool the platform wrote, at
9the moment the tool checks a URL (``DomainPolicy.for_run``). The two files are
10held byte-identical (``tools/test_shared_modules.py``), so the domain a rule
11names is exactly the domain a tool compares.
13**A domain covers itself and every subdomain**: ``gov.uk`` covers
14``www.gov.uk`` and ``hmrc.gov.uk``. A domain is stored as
15:func:`normalise_domain` gives it — lowercase, ASCII, without a scheme, a path,
16``www.`` or a wildcard — so a pasted link and a typed name are one value.
18**It fails closed.** A policy is a restriction somebody wrote; reading one
19wrongly as no restriction would quietly let a run use what a rule forbids. So
20a policy too large to send is sent as one that allows nothing
21(:meth:`WebPolicy.encode`), and a header that cannot be read is read as one
22(:meth:`WebPolicy.decode`): the run answers without the web, and says so.
23"""
25from __future__ import annotations
27import json
28import re
29from collections.abc import Iterable
30from dataclasses import dataclass
32#: The most domains one action of one rule may name.
33MAX_DOMAINS = 50
35#: The most characters a policy may take on the wire. Several rules' lists
36#: are merged, and a header has a size limit; past this the policy is sent
37#: closed rather than cut (see :meth:`WebPolicy.encode`).
38MAX_ENCODED_CHARS = 6_000
40#: The wire format's version. A header naming another is read closed.
41VERSION = 1
43_LABEL = re.compile(r"^(?!-)[a-z0-9-]{1,63}(?<!-)$")
44_SEPARATORS = re.compile(r"[\s,;]+")
47def normalise_domain(raw: object) -> str:
48 """The domain ``raw`` names, as rules store and tools compare it — or
49 ``""`` when it names none.
51 Takes what a person pastes as well as what they type: a bare name, a
52 wildcard (``*.example.com``) or a link (``https://www.example.com/a``).
53 The result is lowercase and ASCII (an internationalised name in its
54 punycode form), with no scheme, path, port, ``www.`` or wildcard. It must
55 have at least two labels (``gov.uk``, never ``uk`` alone, which would
56 cover a whole country's sites) and may not be an IP address.
57 """
58 text = str(raw or "").strip().lower()
59 if "://" in text:
60 text = text.split("://", 1)[1]
61 text = re.split(r"[/?#]", text, maxsplit=1)[0]
62 text = text.rsplit("@", 1)[-1]
63 if text.startswith("["):
64 return ""
65 text = text.split(":", 1)[0].strip(".")
66 text = text.removeprefix("*.").removeprefix("www.")
67 if not text:
68 return ""
69 try:
70 text = text.encode("idna").decode("ascii")
71 except UnicodeError:
72 return ""
73 labels = text.split(".")
74 if len(labels) < 2 or len(text) > 253:
75 return ""
76 if not all(_LABEL.match(label) for label in labels):
77 return ""
78 if labels[-1].isdigit():
79 return ""
80 return text
83def _entries(values: Iterable[object] | str | None) -> list[str]:
84 """Each entry ``values`` holds: a list's items, or a string's parts (the
85 builder's comma-separated text)."""
86 if values is None:
87 return []
88 if isinstance(values, str):
89 return [part for part in _SEPARATORS.split(values) if part]
90 return [str(value).strip() for value in values if str(value).strip()]
93def normalise_domains(values: Iterable[object] | str | None) -> tuple[str, ...]:
94 """Every domain ``values`` names, normalised, in order, each once.
95 Entries that name no domain are left out (:func:`invalid_domains` lists
96 them)."""
97 seen: dict[str, None] = {}
98 for entry in _entries(values):
99 domain = normalise_domain(entry)
100 if domain:
101 seen.setdefault(domain, None)
102 return tuple(seen)
105def invalid_domains(values: Iterable[object] | str | None) -> list[str]:
106 """The entries in ``values`` that name no domain, as written."""
107 return [entry for entry in _entries(values) if not normalise_domain(entry)]
110def host_matches(hostname: str, domain: str) -> bool:
111 """Whether ``hostname`` is ``domain`` or one of its subdomains."""
112 return hostname == domain or hostname.endswith("." + domain)
115def covered(hostname: str, domains: Iterable[str]) -> bool:
116 """Whether any of ``domains`` covers ``hostname``."""
117 return any(host_matches(hostname, domain) for domain in domains)
120def intersect_domains(first: Iterable[str], second: Iterable[str]) -> frozenset[str]:
121 """What both sets cover: each domain of one that lies within the other.
123 ``{gov.uk}`` and ``{hmrc.gov.uk, bbc.co.uk}`` share ``hmrc.gov.uk`` — a
124 subdomain is a narrowing, not a stranger.
125 """
126 one, two = frozenset(first), frozenset(second)
127 return frozenset(d for d in one if covered(d, two)) | frozenset(
128 d for d in two if covered(d, one)
129 )
132@dataclass(frozen=True)
133class WebPolicy:
134 """Which web sources one governed run may use.
136 ``allowed`` is None when the rules leave the tool's own policy alone, and
137 a set when they name the only sources to use — an empty set when no
138 source is left, which turns the web off (:attr:`closed`). ``preferred``
139 are put first wherever results are ranked; ``blocked`` are never used,
140 whatever else allows them.
141 """
143 allowed: frozenset[str] | None = None
144 preferred: frozenset[str] = frozenset()
145 blocked: frozenset[str] = frozenset()
147 @property
148 def restricts(self) -> bool:
149 """Whether this policy changes anything a tool would do."""
150 return self.allowed is not None or bool(self.preferred or self.blocked)
152 @property
153 def closed(self) -> bool:
154 """No source is left: the run may not use the web at all."""
155 return self.allowed is not None and not self.allowed
157 def merge(self, other: WebPolicy | None) -> WebPolicy:
158 """Both policies at once — what two rules leave, or a turn's first
159 part and its re-check. Only what both allow, everything either
160 prefers or blocks: merging can only tighten."""
161 if other is None:
162 return self
163 if self.allowed is None:
164 allowed = other.allowed
165 elif other.allowed is None:
166 allowed = self.allowed
167 else:
168 allowed = intersect_domains(self.allowed, other.allowed)
169 return WebPolicy(
170 allowed=allowed,
171 preferred=self.preferred | other.preferred,
172 blocked=self.blocked | other.blocked,
173 )
175 def permits(self, hostname: str) -> bool:
176 """Whether a run under this policy may use ``hostname``."""
177 if covered(hostname, self.blocked):
178 return False
179 return self.allowed is None or covered(hostname, self.allowed)
181 def prefers(self, hostname: str) -> bool:
182 """Whether ``hostname`` is a source to put first (and may be used)."""
183 return covered(hostname, self.preferred) and self.permits(hostname)
185 def encode(self) -> str:
186 """The policy as the header carries it: compact JSON, lists sorted.
187 One that would be longer than :data:`MAX_ENCODED_CHARS` is sent as a
188 closed policy — a rule asked for a restriction, and a cut list would
189 quietly loosen it."""
190 text = _dumps(self)
191 if len(text) > MAX_ENCODED_CHARS:
192 return _dumps(CLOSED)
193 return text
195 @classmethod
196 def decode(cls, raw: str | None) -> WebPolicy | None:
197 """The policy a header carries: None when there is none; a closed
198 policy when it cannot be read, or names another version."""
199 if raw is None or not str(raw).strip():
200 return None
201 try:
202 data = json.loads(raw)
203 except (TypeError, ValueError):
204 return CLOSED
205 if not isinstance(data, dict) or data.get("v") != VERSION:
206 return CLOSED
207 allowed = data.get("a")
208 lists = (data.get("p", []), data.get("b", []))
209 if allowed is not None and not isinstance(allowed, list):
210 return CLOSED
211 if not all(isinstance(value, list) for value in lists):
212 return CLOSED
213 return cls(
214 allowed=None if allowed is None else frozenset(normalise_domains(allowed)),
215 preferred=frozenset(normalise_domains(lists[0])),
216 blocked=frozenset(normalise_domains(lists[1])),
217 )
220#: A policy that allows no source.
221CLOSED = WebPolicy(allowed=frozenset())
224def _dumps(policy: WebPolicy) -> str:
225 return json.dumps(
226 {
227 "v": VERSION,
228 "a": None if policy.allowed is None else sorted(policy.allowed),
229 "p": sorted(policy.preferred),
230 "b": sorted(policy.blocked),
231 },
232 separators=(",", ":"),
233 )