glovebox-core 0.1.2__py3-none-any.whl

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,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"