emberpool 0.1.0a1__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.
emberpool/_names.py ADDED
@@ -0,0 +1,272 @@
1
+ """Name validators and the only sanctioned way to run host commands.
2
+
3
+ Every name emberpool passes to `ip`, `nft` or the jailer is checked here at the
4
+ point of use (docs/40-rules.md rule 8). Every external command goes through
5
+ `run_command`: an argument list, no shell, a timeout and capped output
6
+ (rules 7 and 13).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import math
13
+ import os
14
+ import re
15
+ import secrets
16
+ import signal
17
+ from collections.abc import Mapping, Sequence
18
+ from dataclasses import dataclass
19
+
20
+ __all__ = [
21
+ "NAME_PREFIX",
22
+ "MAX_INTERFACE_LEN",
23
+ "validate_vm_id",
24
+ "validate_netns",
25
+ "validate_interface",
26
+ "validate_nft_table",
27
+ "validate_nft_set",
28
+ "validate_domain",
29
+ "new_vm_id",
30
+ "CommandResult",
31
+ "CommandError",
32
+ "CommandTimeout",
33
+ "run_command",
34
+ ]
35
+
36
+ # Every namespace, interface and nftables table emberpool creates starts with
37
+ # this prefix (rule 10). Test prefixes such as "ep-net" satisfy it too.
38
+ NAME_PREFIX = "ep"
39
+
40
+ # Linux IFNAMSIZ is 16 including the trailing NUL.
41
+ MAX_INTERFACE_LEN = 15
42
+
43
+ # Lowercase alphanumerics and single inner hyphens. Also valid as a jailer --id.
44
+ _VM_ID_RE = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?")
45
+ _NETNS_RE = re.compile(r"ep[a-z0-9-]{0,37}[a-z0-9]")
46
+ _INTERFACE_RE = re.compile(r"tap0|ep[a-z0-9-]{0,12}[a-z0-9]")
47
+ _NFT_TABLE_RE = re.compile(r"emberpool|ep[a-z0-9_-]{0,29}[a-z0-9]")
48
+ _NFT_SET_RE = re.compile(r"[a-z][a-z0-9_-]{0,62}")
49
+ _LABEL_RE = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")
50
+
51
+
52
+ def _check(kind: str, value: object, pattern: re.Pattern[str]) -> str:
53
+ if not isinstance(value, str):
54
+ raise ValueError(f"{kind} must be a str, got {type(value).__name__}")
55
+ if pattern.fullmatch(value) is None:
56
+ raise ValueError(f"invalid {kind}: {value!r}")
57
+ return value
58
+
59
+
60
+ def validate_vm_id(value: object) -> str:
61
+ """1-32 chars: lowercase letters, digits, inner hyphens."""
62
+ return _check("vm_id", value, _VM_ID_RE)
63
+
64
+
65
+ def validate_netns(value: object) -> str:
66
+ """Network namespace name: starts with "ep", at most 40 chars."""
67
+ return _check("netns", value, _NETNS_RE)
68
+
69
+
70
+ def validate_interface(value: object) -> str:
71
+ """Interface name: "tap0", or "ep"-prefixed and at most 15 chars."""
72
+ name = _check("interface", value, _INTERFACE_RE)
73
+ if len(name) > MAX_INTERFACE_LEN: # pattern already bounds it; belt and braces
74
+ raise ValueError(f"interface name too long: {name!r}")
75
+ return name
76
+
77
+
78
+ def validate_nft_table(value: object) -> str:
79
+ """nftables table name: "emberpool", or starts with "ep" and at most 32 chars."""
80
+ return _check("nft table", value, _NFT_TABLE_RE)
81
+
82
+
83
+ def validate_nft_set(value: object) -> str:
84
+ """nftables set name: lowercase start, at most 63 chars."""
85
+ return _check("nft set", value, _NFT_SET_RE)
86
+
87
+
88
+ def validate_domain(value: object) -> str:
89
+ """Validate an allowlisted domain name and return it lowercased.
90
+
91
+ ASCII only (IDNs must be given in punycode), at least two labels, no
92
+ wildcards, no IP literals, one optional trailing dot which is removed.
93
+ """
94
+ if not isinstance(value, str):
95
+ raise ValueError(f"domain must be a str, got {type(value).__name__}")
96
+ if not value.isascii():
97
+ raise ValueError(f"invalid domain (non-ASCII, use punycode): {value!r}")
98
+ name = value.lower()
99
+ if name.endswith("."):
100
+ name = name[:-1]
101
+ if not name or len(name) > 253:
102
+ raise ValueError(f"invalid domain length: {value!r}")
103
+ labels = name.split(".")
104
+ if len(labels) < 2:
105
+ raise ValueError(f"domain needs at least two labels: {value!r}")
106
+ for label in labels:
107
+ if _LABEL_RE.fullmatch(label) is None:
108
+ raise ValueError(f"invalid domain label {label!r} in {value!r}")
109
+ if labels[-1].isdigit():
110
+ raise ValueError(f"IP literals are not domain names: {value!r}")
111
+ return name
112
+
113
+
114
+ def new_vm_id() -> str:
115
+ """A fresh random VM id: 8 lowercase hex chars."""
116
+ return secrets.token_hex(4)
117
+
118
+
119
+ # --------------------------------------------------------------------------
120
+ # Host commands
121
+ # --------------------------------------------------------------------------
122
+
123
+ # Fixed environment for host tools: nothing inherited from the caller.
124
+ _COMMAND_ENV: Mapping[str, str] = {
125
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
126
+ "LC_ALL": "C",
127
+ }
128
+ DEFAULT_MAX_OUTPUT = 1 << 20 # bytes kept per stream
129
+ _KILL_WAIT = 5.0
130
+
131
+
132
+ @dataclass(frozen=True, slots=True)
133
+ class CommandResult:
134
+ argv: tuple[str, ...]
135
+ returncode: int
136
+ stdout: bytes
137
+ stderr: bytes
138
+ stdout_truncated: bool = False
139
+ stderr_truncated: bool = False
140
+
141
+
142
+ class CommandError(RuntimeError):
143
+ """The command exited non-zero (only raised with check=True)."""
144
+
145
+ def __init__(self, result: CommandResult) -> None:
146
+ self.result = result
147
+ tail = result.stderr[-500:].decode("utf-8", "replace").strip()
148
+ super().__init__(f"{result.argv[0]} exited {result.returncode}: {tail}")
149
+
150
+
151
+ class CommandTimeout(TimeoutError):
152
+ """The command ran past its timeout and was killed."""
153
+
154
+ def __init__(self, argv: tuple[str, ...], timeout: float) -> None:
155
+ self.argv = argv
156
+ self.timeout = timeout
157
+ super().__init__(f"{argv[0]} timed out after {timeout}s and was killed")
158
+
159
+
160
+ def _check_argv(argv: Sequence[str]) -> tuple[str, ...]:
161
+ if isinstance(argv, (str, bytes)):
162
+ raise TypeError("argv must be a sequence of str, not a single string")
163
+ args = tuple(argv)
164
+ if not args:
165
+ raise ValueError("argv is empty")
166
+ for arg in args:
167
+ if not isinstance(arg, str):
168
+ raise TypeError(f"argv items must be str, got {type(arg).__name__}")
169
+ if "\x00" in arg:
170
+ raise ValueError("argv items must not contain NUL")
171
+ if not args[0]:
172
+ raise ValueError("argv[0] is empty")
173
+ return args
174
+
175
+
176
+ async def _read_capped(stream: asyncio.StreamReader, cap: int) -> tuple[bytes, bool]:
177
+ buf = bytearray()
178
+ truncated = False
179
+ while chunk := await stream.read(65536):
180
+ room = cap - len(buf)
181
+ if room > 0:
182
+ buf += chunk[:room]
183
+ if len(chunk) > room:
184
+ truncated = True # keep draining so the child never blocks
185
+ return bytes(buf), truncated
186
+
187
+
188
+ async def _feed(stream: asyncio.StreamWriter, data: bytes | None) -> None:
189
+ try:
190
+ if data:
191
+ stream.write(data)
192
+ await stream.drain()
193
+ except (BrokenPipeError, ConnectionResetError):
194
+ pass
195
+ finally:
196
+ stream.close()
197
+
198
+
199
+ def _kill_group(proc: asyncio.subprocess.Process) -> None:
200
+ if proc.returncode is not None:
201
+ return
202
+ try:
203
+ os.killpg(proc.pid, signal.SIGKILL)
204
+ except (ProcessLookupError, PermissionError):
205
+ try:
206
+ proc.kill()
207
+ except ProcessLookupError:
208
+ pass
209
+
210
+
211
+ async def run_command(
212
+ argv: Sequence[str],
213
+ *,
214
+ timeout: float,
215
+ stdin: bytes | None = None,
216
+ check: bool = True,
217
+ max_output: int = DEFAULT_MAX_OUTPUT,
218
+ env: Mapping[str, str] | None = None,
219
+ ) -> CommandResult:
220
+ """Run one external command safely.
221
+
222
+ - argv is a list, never a string; no shell is involved.
223
+ - The child gets a fixed minimal environment (plus `env`, if given) and
224
+ its own process group.
225
+ - On timeout or cancellation the whole process group is killed and reaped.
226
+ - stdout and stderr are each capped at `max_output` bytes.
227
+ - With check=True a non-zero exit raises CommandError.
228
+ """
229
+ args = _check_argv(argv)
230
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
231
+ raise TypeError("timeout must be a number")
232
+ if not math.isfinite(timeout) or timeout <= 0:
233
+ raise ValueError("timeout must be positive and finite")
234
+ if max_output < 0:
235
+ raise ValueError("max_output must be >= 0")
236
+
237
+ child_env = dict(_COMMAND_ENV)
238
+ if env:
239
+ child_env.update(env)
240
+
241
+ proc = await asyncio.create_subprocess_exec(
242
+ *args,
243
+ stdin=asyncio.subprocess.PIPE,
244
+ stdout=asyncio.subprocess.PIPE,
245
+ stderr=asyncio.subprocess.PIPE,
246
+ env=child_env,
247
+ start_new_session=True,
248
+ )
249
+ assert proc.stdin and proc.stdout and proc.stderr
250
+ try:
251
+ try:
252
+ async with asyncio.timeout(timeout):
253
+ (out, out_trunc), (err, err_trunc), _, returncode = await asyncio.gather(
254
+ _read_capped(proc.stdout, max_output),
255
+ _read_capped(proc.stderr, max_output),
256
+ _feed(proc.stdin, stdin),
257
+ proc.wait(),
258
+ )
259
+ except TimeoutError:
260
+ raise CommandTimeout(args, timeout) from None
261
+ finally:
262
+ if proc.returncode is None:
263
+ _kill_group(proc)
264
+ try:
265
+ await asyncio.wait_for(asyncio.shield(proc.wait()), _KILL_WAIT)
266
+ except TimeoutError:
267
+ pass # SIGKILL sent; nothing more we can do
268
+
269
+ result = CommandResult(args, returncode, out, err, out_trunc, err_trunc)
270
+ if check and returncode != 0:
271
+ raise CommandError(result)
272
+ return result
emberpool/_protocol.py ADDED
@@ -0,0 +1,255 @@
1
+ """vsock wire format between host and guest agent. Frozen contract.
2
+
3
+ Standard library only, no emberpool imports: the guest agent vendors an exact
4
+ copy of this file.
5
+
6
+ A frame is a 4-byte big-endian unsigned length followed by that many bytes of
7
+ UTF-8 JSON. The length is checked against MAX_FRAME before anything is read
8
+ or allocated.
9
+
10
+ Request {"v": 1, "code": str, "timeout": number, "files": null}
11
+ Response {"v": 1, "stdout": str, "stderr": str, "exit_code": int}
12
+
13
+ "files" is reserved for v0.2. In v0.1 it may be absent or null; anything else
14
+ is rejected. Decoding is strict: exact key sets, exact types, no NaN or
15
+ Infinity, no duplicate keys, unknown versions rejected.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import json
22
+ import math
23
+ import socket
24
+ import struct
25
+ from dataclasses import dataclass
26
+ from typing import Any
27
+
28
+ __all__ = [
29
+ "PROTOCOL_VERSION",
30
+ "HEADER_SIZE",
31
+ "MAX_FRAME",
32
+ "MAX_CODE_BYTES",
33
+ "MAX_OUTPUT_BYTES",
34
+ "MAX_TIMEOUT",
35
+ "ProtocolError",
36
+ "Request",
37
+ "Response",
38
+ "frame",
39
+ "parse_header",
40
+ "encode_request",
41
+ "decode_request",
42
+ "encode_response",
43
+ "decode_response",
44
+ "read_frame",
45
+ "recv_frame",
46
+ ]
47
+
48
+ PROTOCOL_VERSION = 1
49
+ HEADER_SIZE = 4
50
+ _HEADER = struct.Struct(">I")
51
+
52
+ # Hard ceiling on one frame's payload.
53
+ MAX_FRAME = 16 * 1024 * 1024
54
+ # Limits on the content. The agent must truncate stdout and stderr to
55
+ # MAX_OUTPUT_BYTES of UTF-8 each so a response always fits in MAX_FRAME, even
56
+ # when every character is JSON-escaped (up to 6 bytes each).
57
+ MAX_CODE_BYTES = 1024 * 1024
58
+ MAX_OUTPUT_BYTES = 1024 * 1024
59
+ MAX_TIMEOUT = 24 * 3600.0
60
+ _EXIT_CODE_RANGE = (-(2**31), 2**31 - 1)
61
+
62
+ _REQUEST_KEYS = frozenset({"v", "code", "timeout", "files"})
63
+ _REQUEST_REQUIRED = frozenset({"v", "code", "timeout"})
64
+ _RESPONSE_KEYS = frozenset({"v", "stdout", "stderr", "exit_code"})
65
+
66
+
67
+ class ProtocolError(ValueError):
68
+ """Malformed, oversized or unsupported frame."""
69
+
70
+
71
+ @dataclass(frozen=True, slots=True)
72
+ class Request:
73
+ code: str
74
+ timeout: float
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class Response:
79
+ stdout: str
80
+ stderr: str
81
+ exit_code: int
82
+
83
+
84
+ # --------------------------------------------------------------------------
85
+ # Framing
86
+ # --------------------------------------------------------------------------
87
+
88
+
89
+ def frame(payload: bytes, max_size: int = MAX_FRAME) -> bytes:
90
+ """Prefix a payload with its length."""
91
+ if not 0 < len(payload) <= max_size:
92
+ raise ProtocolError(f"frame payload size {len(payload)} out of range 1..{max_size}")
93
+ return _HEADER.pack(len(payload)) + payload
94
+
95
+
96
+ def parse_header(header: bytes, max_size: int = MAX_FRAME) -> int:
97
+ """Return the payload length from a 4-byte header, rejecting bad sizes."""
98
+ if len(header) != HEADER_SIZE:
99
+ raise ProtocolError(f"short frame header: {len(header)} bytes")
100
+ (length,) = _HEADER.unpack(header)
101
+ if length == 0:
102
+ raise ProtocolError("empty frame")
103
+ if length > max_size:
104
+ raise ProtocolError(f"frame too large: {length} > {max_size}")
105
+ return length
106
+
107
+
108
+ async def read_frame(reader: asyncio.StreamReader, max_size: int = MAX_FRAME) -> bytes:
109
+ """Read one frame payload. Callers bound the wait with a timeout."""
110
+ try:
111
+ header = await reader.readexactly(HEADER_SIZE)
112
+ length = parse_header(header, max_size)
113
+ return await reader.readexactly(length)
114
+ except asyncio.IncompleteReadError as e:
115
+ raise ProtocolError(f"short read: got {len(e.partial)} of {e.expected} bytes") from None
116
+
117
+
118
+ def _recv_exactly(sock: socket.socket, n: int) -> bytes:
119
+ buf = bytearray()
120
+ while len(buf) < n:
121
+ chunk = sock.recv(min(n - len(buf), 65536))
122
+ if not chunk:
123
+ raise ProtocolError(f"short read: got {len(buf)} of {n} bytes")
124
+ buf += chunk
125
+ return bytes(buf)
126
+
127
+
128
+ def recv_frame(sock: socket.socket, max_size: int = MAX_FRAME) -> bytes:
129
+ """Blocking read of one frame payload. Callers set a socket timeout."""
130
+ length = parse_header(_recv_exactly(sock, HEADER_SIZE), max_size)
131
+ return _recv_exactly(sock, length)
132
+
133
+
134
+ # --------------------------------------------------------------------------
135
+ # Payloads
136
+ # --------------------------------------------------------------------------
137
+
138
+
139
+ def _reject_constant(value: str) -> Any:
140
+ raise ProtocolError(f"non-finite number: {value}")
141
+
142
+
143
+ def _no_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
144
+ out: dict[str, Any] = {}
145
+ for key, value in pairs:
146
+ if key in out:
147
+ raise ProtocolError(f"duplicate key: {key!r}")
148
+ out[key] = value
149
+ return out
150
+
151
+
152
+ def _loads(payload: bytes) -> dict[str, Any]:
153
+ try:
154
+ text = payload.decode("utf-8")
155
+ except UnicodeDecodeError:
156
+ raise ProtocolError("payload is not valid UTF-8") from None
157
+ try:
158
+ data = json.loads(text, parse_constant=_reject_constant, object_pairs_hook=_no_duplicates)
159
+ except json.JSONDecodeError as e:
160
+ raise ProtocolError(f"invalid JSON: {e.msg}") from None
161
+ except RecursionError:
162
+ raise ProtocolError("JSON nested too deeply") from None
163
+ if not isinstance(data, dict):
164
+ raise ProtocolError("payload must be a JSON object")
165
+ return data
166
+
167
+
168
+ def _dumps(obj: dict[str, Any]) -> bytes:
169
+ return json.dumps(obj, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")
170
+
171
+
172
+ def _check_version(data: dict[str, Any]) -> None:
173
+ v = data["v"]
174
+ if isinstance(v, bool) or v != PROTOCOL_VERSION:
175
+ raise ProtocolError(f"unsupported protocol version: {v!r}")
176
+
177
+
178
+ def _check_str(name: str, value: object, max_bytes: int) -> str:
179
+ if not isinstance(value, str):
180
+ raise ProtocolError(f"{name} must be a string")
181
+ try:
182
+ size = len(value.encode("utf-8"))
183
+ except UnicodeEncodeError:
184
+ raise ProtocolError(f"{name} contains lone surrogates") from None
185
+ if size > max_bytes:
186
+ raise ProtocolError(f"{name} too large: {size} > {max_bytes} bytes")
187
+ return value
188
+
189
+
190
+ def _check_timeout(value: object) -> float:
191
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
192
+ raise ProtocolError("timeout must be a number")
193
+ if not math.isfinite(value) or not 0 < value <= MAX_TIMEOUT:
194
+ raise ProtocolError(f"timeout out of range: {value!r}")
195
+ return float(value)
196
+
197
+
198
+ def _check_exit_code(value: object) -> int:
199
+ if isinstance(value, bool) or not isinstance(value, int):
200
+ raise ProtocolError("exit_code must be an integer")
201
+ lo, hi = _EXIT_CODE_RANGE
202
+ if not lo <= value <= hi:
203
+ raise ProtocolError(f"exit_code out of range: {value}")
204
+ return value
205
+
206
+
207
+ def encode_request(code: str, timeout: float) -> bytes:
208
+ """Build a complete request frame (header included)."""
209
+ req = Request(_check_str("code", code, MAX_CODE_BYTES), _check_timeout(timeout))
210
+ return frame(_dumps({"v": PROTOCOL_VERSION, "code": req.code, "timeout": req.timeout, "files": None}))
211
+
212
+
213
+ def decode_request(payload: bytes) -> Request:
214
+ """Validate a request payload (header already stripped)."""
215
+ data = _loads(payload)
216
+ keys = set(data)
217
+ if not _REQUEST_REQUIRED <= keys or not keys <= _REQUEST_KEYS:
218
+ raise ProtocolError(f"bad request keys: {sorted(keys)}")
219
+ _check_version(data)
220
+ if data.get("files") is not None:
221
+ raise ProtocolError("files is not supported in protocol v1")
222
+ return Request(_check_str("code", data["code"], MAX_CODE_BYTES), _check_timeout(data["timeout"]))
223
+
224
+
225
+ def encode_response(stdout: str, stderr: str, exit_code: int) -> bytes:
226
+ """Build a complete response frame (header included). The caller truncates
227
+ stdout and stderr to MAX_OUTPUT_BYTES first."""
228
+ resp = Response(
229
+ _check_str("stdout", stdout, MAX_OUTPUT_BYTES),
230
+ _check_str("stderr", stderr, MAX_OUTPUT_BYTES),
231
+ _check_exit_code(exit_code),
232
+ )
233
+ return frame(
234
+ _dumps(
235
+ {
236
+ "v": PROTOCOL_VERSION,
237
+ "stdout": resp.stdout,
238
+ "stderr": resp.stderr,
239
+ "exit_code": resp.exit_code,
240
+ }
241
+ )
242
+ )
243
+
244
+
245
+ def decode_response(payload: bytes) -> Response:
246
+ """Validate a response payload (header already stripped). Untrusted input."""
247
+ data = _loads(payload)
248
+ if set(data) != _RESPONSE_KEYS:
249
+ raise ProtocolError(f"bad response keys: {sorted(data)}")
250
+ _check_version(data)
251
+ return Response(
252
+ _check_str("stdout", data["stdout"], MAX_OUTPUT_BYTES),
253
+ _check_str("stderr", data["stderr"], MAX_OUTPUT_BYTES),
254
+ _check_exit_code(data["exit_code"]),
255
+ )