Debian Codegraph @

test/pytest/ws/mocksessionsocket.py

raw
1 # Copyright (C) 2026 Red Hat, Inc.
2 # SPDX-License-Identifier: GPL-3.0-or-later
3
4 import argparse
5 import asyncio
6 import contextlib
7 import json
8 import logging
9 import os
10 import secrets
11 import socket
12 import sys
13 from collections.abc import Awaitable, Callable, Sequence
14 from pathlib import Path
15
16 from cockpit.bridge import Bridge
17 from cockpit.jsonutil import JsonObject, get_str, typechecked
18
19 from . import authorize
20
21 logger = logging.getLogger(__name__)
22
23
24 AuthorizeFunction = Callable[[socket.socket], Awaitable[bool]]
25
26
27 async def send_control(sock: socket.socket, msg: JsonObject) -> None:
28 """Send a control message."""
29 data = b"\n" + json.dumps(msg).encode()
30 frame = f"{len(data)}\n".encode() + data
31 logger.debug("send_control: %r", msg)
32 await asyncio.get_running_loop().sock_sendall(sock, frame)
33
34
35 async def recv_control(sock: socket.socket) -> JsonObject:
36 """Receive a control message."""
37 loop = asyncio.get_running_loop()
38
39 async def recv_exact(buf: memoryview) -> None:
40 while len(buf) > 0:
41 n = await loop.sock_recv_into(sock, buf)
42 logger.debug("recv_control: received %r bytes of %r", n, len(buf))
43 if n == 0:
44 raise EOFError
45 buf = buf[n:]
46
47 # "15\n\n{"command":""}" is the smallest conceivable message we could get
48 # here and it's already 18 bytes, but the maximum size is 2**32 which fits
49 # into 10 bytes (or 11, with the '\n' separator). It's always safe to read
50 # those first bytes.
51 start = bytearray(16)
52 await recv_exact(memoryview(start))
53
54 # Figure out the total message size
55 header, nl, initial = start.partition(b"\n")
56 if not nl:
57 raise ValueError("No newline separator in frame header")
58 length = int(header)
59 if len(initial) >= length:
60 raise ValueError("Initial read already exceeds frame length")
61
62 # Receive the rest. NB: bytearray.resize() is 3.14+
63 payload = bytearray(length)
64 payload[: len(initial)] = initial
65 await recv_exact(memoryview(payload)[len(initial) :])
66
67 # Parse the payload
68 if not payload.startswith(b"\n"):
69 raise ValueError("Expected control message (leading newline)")
70 logger.debug("recv_control: %r", payload)
71 msg = typechecked(json.loads(payload), dict)
72 logger.debug("recv_control: %r", msg)
73 return msg
74
75
76 async def challenge(sock: socket.socket, challenge: str = "*") -> str:
77 """Send authorize challenge and return the response."""
78 cookie = secrets.token_hex(16)
79 await send_control(
80 sock,
81 {
82 "command": "authorize",
83 "cookie": cookie,
84 "challenge": challenge,
85 },
86 )
87 msg = await recv_control(sock)
88 if get_str(msg, "command") != "authorize" or get_str(msg, "cookie") != cookie:
89 raise ValueError("Invalid reply to challenge")
90 return get_str(msg, "response", "")
91
92
93 async def authorize_basic(sock: socket.socket, expected: str) -> bool:
94 """Default authorizer: accepts expected credentials via Basic auth."""
95 response = await challenge(sock)
96 try:
97 user, password, _ = authorize.parse_basic(response)
98 creds = f"{user}:{password}"
99 except ValueError:
100 creds = None
101 logger.debug("authorize_basic: creds=%r", creds)
102 if creds != expected:
103 await send_control(
104 sock,
105 {
106 "command": "init",
107 "version": 1,
108 "problem": "authentication-failed",
109 "message": "Invalid credentials",
110 },
111 )
112 return False
113 return True
114
115
116 async def authorize_2fa(sock: socket.socket, expected_code: str) -> bool:
117 """2FA code authorizer."""
118 x_conv_challenge, _ = authorize.build_x_conversation("Enter 2FA code")
119 response = await challenge(sock, x_conv_challenge)
120 try:
121 _, code = authorize.parse_x_conversation(response)
122 except ValueError:
123 code = None
124 logger.debug("authorize_2fa: code=%r", code)
125 if code != expected_code:
126 await send_control(
127 sock,
128 {
129 "command": "init",
130 "version": 1,
131 "problem": "authentication-failed",
132 "message": "Invalid 2FA code",
133 },
134 )
135 return False
136 return True
137
138
139 async def run_internal_bridge(sock: socket.socket) -> None:
140 _transport, bridge = await asyncio.get_running_loop().create_connection(
141 lambda: Bridge(argparse.Namespace(beipack=False, privileged=False)), sock=sock
142 )
143
144 logger.debug("Startup done. Looping until connection closes.")
145
146 try:
147 await bridge.communicate()
148 except (BrokenPipeError, ConnectionResetError):
149 # not unexpected if the peer doesn't hang up cleanly
150 pass
151
152
153 async def run_external_bridge(sock: socket.socket, bridge_cmd: Sequence[str]) -> None:
154 logger.debug("handle_session: spawning bridge")
155 env = {**os.environ, "PYTHONPATH": ":".join(sys.path)}
156 if logger.isEnabledFor(logging.DEBUG):
157 env["COCKPIT_DEBUG"] = "all"
158 proc = await asyncio.create_subprocess_exec(
159 *bridge_cmd,
160 stdin=sock.fileno(),
161 stdout=sock.fileno(),
162 env=env,
163 )
164 logger.debug("handle_session: bridge spawned, pid=%d, closing socket", proc.pid)
165 sock.close()
166
167 try:
168 returncode = await proc.wait()
169 logger.debug("handle_session: bridge exited, returncode=%d", returncode)
170 except asyncio.CancelledError:
171 logger.debug("handle_session: cancelled, killing bridge pid=%d", proc.pid)
172 proc.kill()
173 await proc.wait()
174 raise
175
176
177 async def handle_session(
178 sock: socket.socket,
179 bridge_cmd: list[str],
180 auth_func: AuthorizeFunction | None,
181 ) -> None:
182 """Handle one session connection."""
183 logger.debug("handle_session: new connection, fd=%d", sock.fileno())
184
185 with sock:
186 try:
187 if auth_func is not None and not await auth_func(sock):
188 return
189 except EOFError:
190 logger.debug("handle_session: got unexpected EOF during auth stage")
191 return
192
193 if bridge_cmd:
194 await run_external_bridge(sock, bridge_cmd)
195 else:
196 await run_internal_bridge(sock)
197
198
199 async def run_session_server(
200 socket_path: str | Path,
201 bridge_cmd: list[str] | None = None,
202 auth_func: AuthorizeFunction | None = None,
203 ) -> None:
204 """Run the mock session socket server until cancelled."""
205 if bridge_cmd is None:
206 bridge_cmd = [sys.executable, "-m", "cockpit.bridge"]
207
208 logger.debug("run_session_server: starting on %r", socket_path)
209 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
210 sock.setblocking(False) # needed by .sock_accept() # ruff: ignore[boolean-positional-value-in-call]
211 sock.bind(str(socket_path))
212 sock.listen()
213 logger.debug("run_session_server: listening")
214
215 try:
216 loop = asyncio.get_running_loop()
217 async with asyncio.TaskGroup() as tg:
218 while True:
219 client, _ = await loop.sock_accept(sock)
220 tg.create_task(handle_session(client, bridge_cmd, auth_func))
221 finally:
222 try:
223 os.unlink(socket_path)
224 logger.debug("run_session_server: cleaned up socket %r", socket_path)
225 except OSError as exc:
226 logger.warning(
227 "run_session_server: failed to clean up socket %r: %s", socket_path, exc
228 )
229
230
231 async def main() -> None:
232 import argparse
233 import signal
234
235 parser = argparse.ArgumentParser(description="Mock session socket server")
236 parser.add_argument(
237 "--basic",
238 metavar="USER:PASS",
239 help="Require basic auth credentials",
240 )
241 parser.add_argument(
242 "--2fa",
243 dest="twofa",
244 metavar="CODE",
245 help="Require 2FA code after basic auth",
246 )
247 parser.add_argument(
248 "socket_path",
249 help="Path to Unix socket",
250 )
251 parser.add_argument(
252 "command",
253 nargs="*",
254 help="Bridge command to run (default: internal bridge)",
255 )
256
257 args = parser.parse_args()
258
259 logging.basicConfig(level=logging.DEBUG)
260
261 async def auth(sock: socket.socket) -> bool:
262 return (not args.basic or await authorize_basic(sock, args.basic)) and (
263 not args.twofa or await authorize_2fa(sock, args.twofa)
264 )
265
266 # Remove stale socket if it exists
267 with contextlib.suppress(FileNotFoundError):
268 os.unlink(args.socket_path)
269 logger.debug("deleted previously existing socket %r", args.socket_path)
270
271 task = asyncio.create_task(
272 run_session_server(
273 args.socket_path,
274 args.command,
275 auth if args.basic or args.twofa else None,
276 )
277 )
278
279 loop = asyncio.get_running_loop()
280 loop.add_signal_handler(signal.SIGTERM, task.cancel)
281 loop.add_signal_handler(signal.SIGINT, task.cancel)
282
283 with contextlib.suppress(asyncio.CancelledError):
284 await task
285
286
287 if __name__ == "__main__":
288 asyncio.run(main())