glovebox-core 0.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,206 @@
1
+ .worktrees
2
+ .claude/worktrees/
3
+ .agents/
4
+ .codex/
5
+
6
+ # vm agent-entrypoint boot trace — a runtime log appended into the workspace by
7
+ # gb_boot_trace; a diagnostic artifact, never committed.
8
+ .gb-agent-boot-trace
9
+
10
+ # Dependencies
11
+ # Tool-managed dirs use the BARE name (no trailing slash). A `foo/` pattern
12
+ # matches only a *directory*, so a symlink named `foo` — e.g. one linked into a
13
+ # git worktree to run tests — slips past it and `git add -A` stages it (how a
14
+ # node_modules symlink twice reached CI this repo's history). The bare name
15
+ # matches the dir AND a same-named symlink/file, so tool output can't be
16
+ # committed by accident. Only applied to names that are never a legitimately
17
+ # tracked file (dependency/venv/cache/report dirs); generic names like dist/ or
18
+ # build/ keep the trailing slash so they don't over-ignore a real file.
19
+ node_modules
20
+ .pnpm-store
21
+
22
+ # Build outputs
23
+ dist/
24
+ build/
25
+ out/
26
+
27
+ # Environment files
28
+ .env
29
+ .env.local
30
+ .env.*.local
31
+
32
+ # IDE
33
+ .idea/
34
+ .vscode/
35
+ *.swp
36
+ *.swo
37
+
38
+ # OS
39
+ .DS_Store
40
+ Thumbs.db
41
+
42
+ # Logs
43
+ *.log
44
+ npm-debug.log*
45
+ pnpm-debug.log*
46
+
47
+ # Coverage
48
+ coverage/
49
+ coverage.json
50
+ .c8-output
51
+ .coverage
52
+ .coverage.*
53
+ .py-coverage.lock
54
+ htmlcov
55
+
56
+ # Mutation testing (Stryker): sandbox, HTML report, and the incremental cache
57
+ .stryker-tmp
58
+ reports/
59
+
60
+ # Python
61
+ __pycache__
62
+ *.pyc
63
+ .venv
64
+ .uv
65
+ .pytest_cache
66
+
67
+ # `uv run` inside inspect-glovebox/, glovebox-monitor/, glovebox-driver/ or glovebox-ranges/ writes a lock
68
+ # beside that pyproject.toml. Each wheel is a library, so it pins nothing; committing one
69
+ # adds a `uv.lock -merge` path that scripts/lib-regen-rules.mjs owns no rule for, which
70
+ # reds the JS suite.
71
+ /inspect-glovebox/uv.lock
72
+ /glovebox-monitor/uv.lock
73
+ /glovebox-driver/uv.lock
74
+ /glovebox-ranges/uv.lock
75
+ # pytest scratch (repo-relative --basetemp): throwaway fixture files, including
76
+ # fake executables the suite writes (keyprobe, docker stubs). Ignored so they never
77
+ # surface as uncommitted changes or get captured onto a session-end review branch.
78
+ .pytest-tmp
79
+
80
+ # Fuzzer crash reproducers (jazzer.js / atheris drop these in the repo root, which
81
+ # is their cwd). Anchored with a leading slash: an unanchored `crash-*` matches at
82
+ # ANY depth, so it silently swallowed bin/checks/vm/crash-resilience-int.bash — a
83
+ # `git add` of a legitimately-named source file that reports success and stages
84
+ # nothing.
85
+ /crash-*
86
+ /timeout-*
87
+ /oom-*
88
+ /leak-*
89
+
90
+ # History working files — each lives on the perf-history or ci-timings branch and is
91
+ # seeded into the checkout by persist-perf-history.sh read or record-setup-timing.sh;
92
+ # never committed to main or a feature branch. A glob, not a list: a tool that walks
93
+ # "tracked plus untracked-not-ignored" takes a seeded file for a repository file, and
94
+ # a per-metric list leaves the next metric's file out of the pattern.
95
+ .github/*-history.json
96
+ .github/*-history.jsonl
97
+
98
+ # pytest --basetemp droppings (used where /tmp is noexec)
99
+ .pytest-exec-tmp
100
+
101
+ # Hypothesis property-testing example database (regenerated locally; never committed)
102
+ .hypothesis/
103
+
104
+ # CI timing maps that balance the shard fan-outs. They live in R2 (uploaded only by
105
+ # main runs, fetched best-effort by CI — see .github/ci-durations.json) and are never
106
+ # committed; ignored so a CI fetch or a local `uv run pytest --store-durations` /
107
+ # vm-live run can't accidentally stage them.
108
+ tests/.gb-test-durations.json
109
+ tests/.gb-test-uninstrumented-durations.json
110
+ tests/.gb-kcov-durations.json
111
+ tests/.gb-drvfs-durations.json
112
+ tests/.gb-macos-durations.json
113
+ # The plan job's published shard assignment, one per leg (keyed by that leg's
114
+ # duration-map name): derived from the fetched map, shipped to the shards in the
115
+ # same artifact, never committed.
116
+ tests/.gb-*-shard-assignment.json
117
+ tests/.gb-select-maps.json
118
+ .github/vm-live/durations.json
119
+ .github/kata-live/durations.json
120
+ .github/kata-live/reads.json
121
+
122
+ # The pinned scanner binary that .github/scripts/python-deps-vuln-scan.sh downloads
123
+ # into the repo root (~56 MB). Running that script locally to reproduce a red
124
+ # osv-scanner check is the documented response to one, so the artifact lands in
125
+ # every contributor's tree; ignored so it can't be staged by a `git add -A`.
126
+ /osv-scanner
127
+
128
+ # esbuild output — every artifact scripts/build-hook-bundles.mjs or
129
+ # scripts/build-vm-dispatcher.mjs writes, wherever its home. Built once per tree by
130
+ # `pnpm install`'s postinstall, by setup.bash at install time, in the nix buildPhase and
131
+ # in the image's own bundler stage, so the reviewable surface is the sources plus
132
+ # pnpm-lock.yaml. Suffix, not a directory or a member list: a bundle whose home the
133
+ # pattern misses leaves every tree that builds it permanently dirty.
134
+ *.bundle.mjs
135
+ # The per-agent hook rows scripts/build-vm-dispatcher.mjs writes beside the guest validator.
136
+ /vm-kit/image/lib/agent-hooks.json
137
+
138
+ # Sharded mutation configs are deterministic build output. The planner and
139
+ # `pnpm install` render them from config/mutation-sessions.json.
140
+ /tools/mutation/*of*.toml
141
+
142
+ # The pinned kcov binary that tests/install-kcov-local.sh builds into the repo
143
+ # root — the same path .github/actions/install-kcov caches to, so tests/run-kcov.sh
144
+ # finds a local build with no PATH edit. Reproducing a red "Bash coverage (kcov)"
145
+ # check locally is the documented response to one, so the artifact lands in every
146
+ # contributor's tree; ignored so it can't be staged by a `git add -A`.
147
+ /kcov-bin/
148
+ .claude/.hookpin-*/
149
+
150
+ # synced-deps.test.mjs's untracked-file probe, mkdtemp'd under a synced path on
151
+ # purpose. Ignored so a concurrent `git add -A` elsewhere in this checkout can't
152
+ # stage it mid-test: staged, it would pass trackedUnder()'s check and leave an
153
+ # AD entry in the shared index once the test deletes it from disk.
154
+ .claude/consumer-probe-*/
155
+
156
+ # `ct settings pull` writes this per-checkout pin cache into the repo root. The pin this
157
+ # harness measures lives in evals/control_tower/ct-settings-pin.txt; a committed copy here
158
+ # would be a second one that drifts.
159
+ .settings.local.yml
160
+
161
+ # `gh` writes its per-machine state here when it runs with the repo root as the
162
+ # XDG state home — a device identifier, which no checkout should carry.
163
+ /.local/
164
+
165
+ # Generated doc pages, published to the CDN instead of committed
166
+ # (scripts/render-doc-site.py, .github/workflows/docs-publish.yaml). A committed
167
+ # page is re-derived by every branch that touches its generator's inputs, which
168
+ # made these the busiest files in the history and conflicted branches on bytes
169
+ # nobody typed. Their generators still run, and still refuse a bad input; only
170
+ # the output stays out of the tree.
171
+ /docs/architecture-callgraph.md
172
+ /docs/ci-map.generated.md
173
+ /docs/inspect-evals-coverage.generated.md
174
+ /docs/tla/configs.md
175
+ /docs/tla/reachable-subsets.md
176
+ /docs/tla/diagrams/
177
+ /docs/tla/modules/
178
+ # TLC's own scratch metadir, written here by a run given no -metadir.
179
+ /docs/tla/states/
180
+
181
+ # The eval time series live on the `metrics-history` branch, which `main` never
182
+ # merges (.github/scripts/eval-series.sh). A tracker or a local run materializes its
183
+ # own working copy here; committing one would put the series back on the merge path.
184
+ metrics/monitor-eval.jsonl
185
+ metrics/sabotage-eval.jsonl
186
+ metrics/breakout-ctf.jsonl
187
+
188
+ # A local breakout-CTF transcript dump, written into the working tree by
189
+ # evals/ctf/dump_transcript.py for a web session to read. A paid-run artifact
190
+ # the viewer page on R2 already owns, so it is a scratch view, never committed.
191
+ /ctf-*-transcript.txt
192
+
193
+ # `nix build` links its output here.
194
+ /result
195
+ /result-*
196
+
197
+ # go build output of the guest network daemon
198
+ bin/lib/kata/netd/netd
199
+
200
+ # The symlink chains tests/_glovebox_launch_helpers.py:sibling_symlink_chain parks beside a
201
+ # wrapper while a test runs; a background coverage run reads an untracked one as a moved tree.
202
+ /bin/**/*-link[12]-[0-9]*
203
+
204
+ # The digest of the candidate guest image a Kata grade shard admits, written into its own
205
+ # checkout by .github/scripts/kata-live/load-candidate-image.sh (bin/lib/kata/candidate-image.bash).
206
+ /kata-candidate-image.digest
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.5
2
+ Name: glovebox-core
3
+ Version: 0.1.2
4
+ Summary: Glovebox's security decisions as pure functions: the host rules, the JSON reader and the egress verdict
5
+ Project-URL: Homepage, https://github.com/AlexanderMattTurner/agent-glovebox
6
+ Project-URL: Source, https://github.com/AlexanderMattTurner/agent-glovebox
7
+ Author: AlexanderMattTurner
8
+ License-Expression: Apache-2.0
9
+ Keywords: egress,glovebox,hostname,policy,sandbox
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Security
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: graphql-core==3.2.12
16
+ Description-Content-Type: text/markdown
17
+
18
+ # glovebox-core
19
+
20
+ Glovebox's security decisions as pure functions: the host rules, the JSON reader and the egress verdict. No module here reads a file, a socket, a subprocess, the clock, a thread or the environment. An input that needs one arrives as an argument: a `Protocol` the caller implements, or a value the caller read. `tests/core/test_purity.py` refuses any other import.
21
+
22
+ ## Host rules
23
+
24
+ `glovebox_core.host_rules` is the one answer to "which host is this" that every part of glovebox uses: the egress proxy's verdict service, the launcher, the WebFetch hook, the session driver and the evals. A host is compared in one spelling: ASCII only, surrounding whitespace removed, lowercased, and an IP literal in its standard form. A name that is not ASCII, or that starts or ends with a dot, is refused rather than folded, so two readers can never disagree about it.
25
+
26
+ `pod_grants` is the one reader of a Kata pod's `glovebox.dev/egress-grants` annotation, and the node calls it. It returns the granted hosts at their tiers, the address grants and the port grants. It raises `GrantRefused` with the node's own message for the first entry the node refuses. How wide an address grant may be is each node's own setting, so it is not checked here.
27
+
28
+ A host with a port, such as `{"host": "git.example.com:22", "rw": true}`, is a port grant. The node relays a raw stream to that port on the name's public addresses, so it needs `"rw": true`. A host without a port keeps its plain host meaning.
29
+
30
+ A grant may not name a `*.` wildcard over a public suffix, or over a name with one below it. `pod_grants` takes the Public Suffix List as an argument: `glovebox_hosts.BUNDLED_SUFFIXES` is the list `tldextract` bundles. Where the list cannot be read, every name is refused.
31
+
32
+ ```python
33
+ >>> from glovebox_core.host_rules import pod_grants
34
+ >>> from glovebox_hosts import BUNDLED_SUFFIXES
35
+ >>> granted = pod_grants('["httpbin.org", {"host": "git.example.com:22", "rw": true}]', BUNDLED_SUFFIXES)
36
+ >>> granted.hosts
37
+ {'httpbin.org': 'ro'}
38
+ >>> granted.ports
39
+ [PortGrant(host='git.example.com', port=22)]
40
+ >>> pod_grants('["*.amazonaws.com"]', BUNDLED_SUFFIXES)
41
+ Traceback (most recent call last):
42
+ ...
43
+ glovebox_core.host_rules.GrantRefused: glovebox.dev/egress-grants: '*.amazonaws.com' is a wildcard over a name with the public suffix ...
44
+ ```
45
+
46
+ `encode_pod_grants` is the writer for the same annotation. It writes each entry as a bare read-only string, sorted and once, and never adds `"rw"`. It raises `GrantRefused` for an address or `HOST:PORT`, which opens a raw tunnel that only a person grants, read-write, on the node. It reads its text back with `pod_grants`, so it also raises for any other entry the node would refuse.
47
+
48
+ A runner that writes the annotation checks each entry before it asks for a pod. `grant_host_refusal(host, suffixes)` gives the node's reason for refusing a host name, or None. `address_grant(entry)` reads an address entry as an `AddressGrant`, returns None for a host name, and raises `GrantRefused` for a malformed one.
49
+
50
+ The host rules and `glovebox_core.json_object` import only the standard library, so they run under Python 3.9. The egress modules need Python 3.11.
51
+
52
+ ## Egress verdict
53
+
54
+ `glovebox_core.verdict.decide` rules where one request Envoy asks about may go. The caller passes what it read as `Facts`, such as the setup window, and every address screen as a `Screen`. The verdict resolves no name and writes no record.
@@ -0,0 +1,37 @@
1
+ # glovebox-core
2
+
3
+ Glovebox's security decisions as pure functions: the host rules, the JSON reader and the egress verdict. No module here reads a file, a socket, a subprocess, the clock, a thread or the environment. An input that needs one arrives as an argument: a `Protocol` the caller implements, or a value the caller read. `tests/core/test_purity.py` refuses any other import.
4
+
5
+ ## Host rules
6
+
7
+ `glovebox_core.host_rules` is the one answer to "which host is this" that every part of glovebox uses: the egress proxy's verdict service, the launcher, the WebFetch hook, the session driver and the evals. A host is compared in one spelling: ASCII only, surrounding whitespace removed, lowercased, and an IP literal in its standard form. A name that is not ASCII, or that starts or ends with a dot, is refused rather than folded, so two readers can never disagree about it.
8
+
9
+ `pod_grants` is the one reader of a Kata pod's `glovebox.dev/egress-grants` annotation, and the node calls it. It returns the granted hosts at their tiers, the address grants and the port grants. It raises `GrantRefused` with the node's own message for the first entry the node refuses. How wide an address grant may be is each node's own setting, so it is not checked here.
10
+
11
+ A host with a port, such as `{"host": "git.example.com:22", "rw": true}`, is a port grant. The node relays a raw stream to that port on the name's public addresses, so it needs `"rw": true`. A host without a port keeps its plain host meaning.
12
+
13
+ A grant may not name a `*.` wildcard over a public suffix, or over a name with one below it. `pod_grants` takes the Public Suffix List as an argument: `glovebox_hosts.BUNDLED_SUFFIXES` is the list `tldextract` bundles. Where the list cannot be read, every name is refused.
14
+
15
+ ```python
16
+ >>> from glovebox_core.host_rules import pod_grants
17
+ >>> from glovebox_hosts import BUNDLED_SUFFIXES
18
+ >>> granted = pod_grants('["httpbin.org", {"host": "git.example.com:22", "rw": true}]', BUNDLED_SUFFIXES)
19
+ >>> granted.hosts
20
+ {'httpbin.org': 'ro'}
21
+ >>> granted.ports
22
+ [PortGrant(host='git.example.com', port=22)]
23
+ >>> pod_grants('["*.amazonaws.com"]', BUNDLED_SUFFIXES)
24
+ Traceback (most recent call last):
25
+ ...
26
+ glovebox_core.host_rules.GrantRefused: glovebox.dev/egress-grants: '*.amazonaws.com' is a wildcard over a name with the public suffix ...
27
+ ```
28
+
29
+ `encode_pod_grants` is the writer for the same annotation. It writes each entry as a bare read-only string, sorted and once, and never adds `"rw"`. It raises `GrantRefused` for an address or `HOST:PORT`, which opens a raw tunnel that only a person grants, read-write, on the node. It reads its text back with `pod_grants`, so it also raises for any other entry the node would refuse.
30
+
31
+ A runner that writes the annotation checks each entry before it asks for a pod. `grant_host_refusal(host, suffixes)` gives the node's reason for refusing a host name, or None. `address_grant(entry)` reads an address entry as an `AddressGrant`, returns None for a host name, and raises `GrantRefused` for a malformed one.
32
+
33
+ The host rules and `glovebox_core.json_object` import only the standard library, so they run under Python 3.9. The egress modules need Python 3.11.
34
+
35
+ ## Egress verdict
36
+
37
+ `glovebox_core.verdict.decide` rules where one request Envoy asks about may go. The caller passes what it read as `Facts`, such as the setup window, and every address screen as a `Screen`. The verdict resolves no name and writes no record.
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "glovebox-core"
3
+ version = "0.1.2"
4
+ description = "Glovebox's security decisions as pure functions: the host rules, the JSON reader and the egress verdict"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = "Apache-2.0"
8
+ authors = [{ name = "AlexanderMattTurner" }]
9
+ keywords = ["glovebox", "sandbox", "egress", "hostname", "policy"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: Science/Research",
13
+ "Programming Language :: Python :: 3",
14
+ "Topic :: Security",
15
+ ]
16
+ # Pinned, as in the root pyproject: the GitHub write rule parses a GraphQL body with
17
+ # graphql-core's parser alone. The host rules and the JSON reader import only the standard
18
+ # library, so the WebFetch hook loads them under a stock Mac's python 3.9; the egress
19
+ # verdict's modules need 3.11.
20
+ dependencies = ["graphql-core==3.2.12"]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/AlexanderMattTurner/agent-glovebox"
24
+ Source = "https://github.com/AlexanderMattTurner/agent-glovebox"
25
+
26
+ [build-system]
27
+ # scripts/write-python-pins.mjs writes this version from the root pyproject's dev pin;
28
+ # an edit here is overwritten by the next `pnpm install` or commit.
29
+ requires = ["hatchling==1.32.0"]
30
+ build-backend = "hatchling.build"
31
+
32
+ [tool.hatch.build.targets.wheel]
33
+ packages = ["src/glovebox_core"]
@@ -0,0 +1,6 @@
1
+ """Glovebox's security decisions as pure functions, in one package a reviewer can audit.
2
+
3
+ No module here reads a file, a socket, a subprocess, the clock, a thread or the
4
+ environment. An input that needs one arrives as an argument: a `Protocol` the caller
5
+ implements, or a value it read. `tests/core/test_purity.py` refuses any other import.
6
+ """
@@ -0,0 +1,185 @@
1
+ """Assemble the session's outgoing-traffic allow rules, and guard the allowlist.
2
+
3
+ Each rule `assemble` returns is one `host:port` the sandbox may reach. That set
4
+ IS the firewall, so this file refuses every input it cannot read rather than
5
+ returning a shorter list. `guarded_domains` is the ONE reader of the allowlist's
6
+ tier map, so the firewall's host set and the filter's tier table (rendered by
7
+ `policy`, which calls it) cannot disagree about what a document says.
8
+
9
+ PROBLEM CLASS — the same hostname arrives spelled several ways and must become
10
+ ONE rule: DNS is case-insensitive but a policy engine compares bytes.
11
+ Hostnames come from workspace-controlled files, so folding happens HERE, once,
12
+ after every source is joined — a per-source fold is one a new source can forget.
13
+
14
+ Standard library plus `glovebox_core`, which holds the host rule: the launcher's
15
+ `egress rules` verb imports it on the user's machine at launch.
16
+ """
17
+
18
+ import json
19
+
20
+ from .host_rules import (
21
+ TIERS,
22
+ HostError,
23
+ canonical_host,
24
+ render_authority,
25
+ split_authority,
26
+ wildcard_suffix,
27
+ )
28
+ from .json_object import is_json_object
29
+
30
+ # The port every allowlist and per-project host is granted on, whatever its
31
+ # tier: the session policy applies a tier's method limit on its own.
32
+ _HTTPS_PORT = 443
33
+
34
+
35
+ # JSON's own names for the shapes, not Python's: the operator's next action is to
36
+ # open a JSON file, where there is no `list` or `dict` to look for.
37
+ _JSON_TYPES: dict[type[object], str] = {
38
+ list: "array",
39
+ dict: "object",
40
+ str: "string",
41
+ bool: "boolean",
42
+ int: "number",
43
+ float: "number",
44
+ }
45
+
46
+
47
+ def json_type(value: object) -> str:
48
+ """JSON's own name for the shape of VALUE."""
49
+ return "null" if value is None else _JSON_TYPES.get(type(value), "unknown")
50
+
51
+
52
+ class _RepeatedHost(ValueError):
53
+ """A JSON object named one key twice."""
54
+
55
+
56
+ def _one_key_each(pairs: list[tuple[str, object]]) -> dict[str, object]:
57
+ """`pairs` as an object, refused when it names a key twice.
58
+
59
+ One host holds one tier, and `json.loads` alone cannot keep that
60
+ true — it takes the LAST of two identical keys and reports nothing. A second
61
+ `"github.com": "rw"` line lower in the allowlist would then turn off the
62
+ refusal that stops the agent pushing with a credential it cannot read, and
63
+ both lines read as correct on their own.
64
+
65
+ `json.loads` applies this to EVERY object in the document, so the message
66
+ names the repeated key and nothing about tiers.
67
+ """
68
+ seen: set[str] = set()
69
+ for key, _ in pairs:
70
+ if key in seen:
71
+ raise _RepeatedHost(f"{key} appears twice")
72
+ seen.add(key)
73
+ return dict(pairs)
74
+
75
+
76
+ def guarded_document(body: str, source: str) -> object:
77
+ """The allowlist document, refused when any object in it names a key twice.
78
+
79
+ The ONE parse of an allowlist: `guarded_domains` reads its `domains` and
80
+ `policy.render_session` its `capabilities`, so the tier a host
81
+ carries and the capability granted to it come from the same bytes. The answer
82
+ is `object` because a JSON file holds any shape; each reader narrows it.
83
+ """
84
+ try:
85
+ return json.loads(body, object_pairs_hook=_one_key_each)
86
+ except _RepeatedHost as repeated:
87
+ raise ValueError(f"{source}: {repeated}") from repeated
88
+
89
+
90
+ def guarded_domains(body: str, source: str) -> dict[str, str]:
91
+ """The allowlist's `domains` map, refused unless every entry names a known
92
+ tier and no host appears twice. `source` names the file in the error."""
93
+ parsed = guarded_document(body, source)
94
+ domains = parsed.get("domains") if is_json_object(parsed) else None
95
+ if not is_json_object(domains):
96
+ # TypeError for a wrong SHAPE, ValueError below for a wrong VALUE — both
97
+ # reach the caller as the same refusal, but the split satisfies ruff's TRY004.
98
+ raise TypeError(
99
+ f"{source}: .domains is {json_type(domains)} — expected an object "
100
+ 'mapping hostname to "ro" or "rw"'
101
+ )
102
+ # Keyed by the canonical host, so `GitHub.com` beside `github.com` is refused as
103
+ # one host written twice rather than collapsing to whichever tier sorted last.
104
+ canonical: dict[str, str] = {}
105
+ spelled: dict[str, str] = {}
106
+ for host, tier in domains.items():
107
+ if tier not in TIERS:
108
+ raise ValueError(
109
+ f'{source}: {host} has tier {json.dumps(tier)} — expected "ro" or "rw"'
110
+ )
111
+ try:
112
+ key = canonical_host(host)
113
+ except HostError as exc:
114
+ raise ValueError(f"{source}: .domains names no host: {exc}") from exc
115
+ if key in canonical:
116
+ raise ValueError(
117
+ f"{source}: {host} and {spelled[key]} are one host — "
118
+ "one host takes one tier"
119
+ )
120
+ canonical[key] = tier
121
+ spelled[key] = host
122
+ return canonical
123
+
124
+
125
+ # The characters that would let ONE rule become several downstream, plus the ones
126
+ # that would let a rule mean something other than a host. The session policy
127
+ # module reads this file's output as one `host:port` rule per line, and each rule
128
+ # becomes a host the verdict service admits. Refusing them HERE is what keeps
129
+ # every consumer's one-rule-per-line assumption true.
130
+ _RULE_DELIMITERS = frozenset(":,;|& \t\r\n/\\\"'`$()<>[]{}*?!#%^~+=")
131
+
132
+
133
+ def _canonical_rule(rule: str, source: str) -> str:
134
+ """RULE as the one canonical `host:port`, refused unless it names exactly one.
135
+
136
+ `source` names where the rule came from, because the operator's next action is
137
+ to open that file and remove the entry. The host takes `canonical_host`'s one
138
+ spelling, so every reader of the rule set keys the same host the same way.
139
+ """
140
+ host, separator, port = rule.rpartition(":")
141
+ if not separator or not host or not port:
142
+ raise ValueError(f"{source}: {rule!r} is not a host:port outgoing-traffic rule")
143
+ # A leading `*.` is a wildcard grant's marker, so only the suffix below it is screened.
144
+ bad = sorted(set(wildcard_suffix(host)) & _RULE_DELIMITERS) + [
145
+ character
146
+ for character in host
147
+ if ord(character) < 0x20 or ord(character) == 0x7F
148
+ ]
149
+ if bad:
150
+ raise ValueError(
151
+ f"{source}: {rule!r} has {''.join(sorted(set(bad)))!r} in its hostname — "
152
+ "one rule names one host"
153
+ )
154
+ try:
155
+ return render_authority(*split_authority(rule))
156
+ except HostError as exc:
157
+ raise ValueError(
158
+ f"{source}: {rule!r} is not a host:port outgoing-traffic rule ({exc}) — "
159
+ "write a non-ASCII hostname in its punycode form (`xn--…`)"
160
+ ) from exc
161
+
162
+
163
+ def _without_scheme(endpoint: str) -> str:
164
+ """A gateway origin as the bare `host:port` every other line already is."""
165
+ _, separator, rest = endpoint.partition("://")
166
+ return rest if separator else endpoint
167
+
168
+
169
+ def assemble(
170
+ domains: dict[str, str],
171
+ project_hosts: list[str],
172
+ rules: list[str],
173
+ mcpgw_endpoints: list[str],
174
+ ) -> list[str]:
175
+ """Every source joined into one sorted, folded, deduplicated rule set.
176
+ `domains`/`project_hosts` are bare hosts granted on :443; `rules` arrive
177
+ complete; `mcpgw_endpoints` lose their scheme first."""
178
+ joined = [f"{host}:{_HTTPS_PORT}" for host in [*domains, *project_hosts]]
179
+ joined += rules
180
+ joined += [_without_scheme(endpoint) for endpoint in mcpgw_endpoints]
181
+ # Fold AFTER the join — see module header — and validate there for the same
182
+ # reason: a per-source check is one a new source can forget, and every rule
183
+ # leaves through this one return.
184
+ source = "outgoing-traffic rules"
185
+ return sorted({_canonical_rule(rule, source) for rule in joined})
@@ -0,0 +1,22 @@
1
+ """The context values Envoy's routes set on a check call, which the verdict reads.
2
+
3
+ `egress_gateway.envoy_bootstrap` writes each into the route it renders, so no client byte
4
+ can choose one. `egress_witness` holds the plain and bump channels.
5
+ """
6
+
7
+ # The setup listener's channel. It is not a witness channel of `egress_witness`: those name
8
+ # the witness a record is written under. This value names WHICH RULE applies — the window's.
9
+ CHANNEL_SETUP = "setup"
10
+ # A session CONNECT's channel: its target is ruled on before the tunnel opens, and the
11
+ # tunnel's own requests are ruled on again once the bump listener decrypts them.
12
+ CHANNEL_CONNECT = "connect"
13
+ # The guest account classes a session listener set names.
14
+ CLIENT_AGENT = "agent"
15
+ CLIENT_COMMAND = "command"
16
+ # The channel and client class of the guest's direct streams, which only the public listener
17
+ # sets: the host relays each TCP connection the guest dials past its proxy as one CONNECT.
18
+ CHANNEL_PUBLIC = "public"
19
+ CLIENT_PUBLIC = "public"
20
+ # The header a bumped request carries its tunnel's flow in, written by Envoy over any copy
21
+ # the client sent.
22
+ FLOW_HEADER = "x-glovebox-flow"