Coverage for src/copytrading_engine/headless/sockets.py: 82%
117 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""The server's two local sockets: agents (the app's control contract) and the owner.
3Both live in an owner-only directory. The agent socket answers exactly what the app's does,
4at the access the owner chose. The owner socket carries what the app does after Touch ID:
5approving proposals, turning entries on, pausing and resuming. On a server there is no
6Touch ID, so the owner socket trusts the operating-system user who started the server.
7"""
9import asyncio
10import contextlib
11import os
12import socket
13import stat
14import struct
15import sys
16from collections.abc import Awaitable, Callable
17from pathlib import Path
19from pydantic import ValidationError
21from copytrading_engine.control.wire import MAX_LINE_BYTES
22from copytrading_engine.headless.engine import EngineRefused, HeadlessEngine
23from copytrading_engine.headless.owner import (
24 OWNER_ANSWER,
25 OWNER_REQUEST,
26 OwnerAnswer,
27 OwnerRequest,
28 Refused,
29)
31MAX_OWNER_LINE_BYTES = 64 * 1024
33type OwnerHandler = Callable[[OwnerRequest], Awaitable[OwnerAnswer]]
36class UnsafeStateDirectory(Exception):
37 """The control directory is not private to this user, so no socket is opened in it."""
40def prepare_private_directory(path: Path) -> None:
41 """Create the directory owner-only, and refuse one someone else could read or replace."""
42 path.mkdir(mode=0o700, parents=True, exist_ok=True)
43 entry = os.lstat(path)
44 if not stat.S_ISDIR(entry.st_mode) or entry.st_uid != os.getuid(): 44 ↛ 45line 44 didn't jump to line 45 because the condition on line 44 was never true
45 raise UnsafeStateDirectory(str(path))
46 if entry.st_mode & 0o077: 46 ↛ 47line 46 didn't jump to line 47 because the condition on line 46 was never true
47 os.chmod(path, 0o700)
50def remove_stale_socket(path: Path) -> None:
51 """Remove a socket left by a server that is no longer running; refuse anything else."""
52 try:
53 entry = os.lstat(path)
54 except FileNotFoundError:
55 return
56 if not stat.S_ISSOCK(entry.st_mode) or entry.st_uid != os.getuid():
57 raise UnsafeStateDirectory(f"{path} exists and is not this server's socket")
58 probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
59 try:
60 probe.connect(str(path))
61 except ConnectionRefusedError, FileNotFoundError:
62 path.unlink(missing_ok=True)
63 return
64 finally:
65 probe.close()
66 raise UnsafeStateDirectory(f"another server is already listening on {path}")
69def peer_pid(writer: asyncio.StreamWriter) -> int | None:
70 """The connecting process, for the audit trail; None where the system will not say."""
71 sock = writer.get_extra_info("socket")
72 if sock is None: 72 ↛ 73line 72 didn't jump to line 73 because the condition on line 72 was never true
73 return None
74 try:
75 if sys.platform == "darwin": 75 ↛ 78line 75 didn't jump to line 78 because the condition on line 75 was always true
76 # SOL_LOCAL, LOCAL_PEERPID
77 return int(sock.getsockopt(0, 0x002)) or None
78 if hasattr(socket, "SO_PEERCRED"):
79 data = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
80 pid, _uid, _gid = struct.unpack("3i", data)
81 return pid or None
82 except OSError:
83 return None
84 return None
87async def _read_line(reader: asyncio.StreamReader, limit: int) -> bytes | None:
88 try:
89 line = await asyncio.wait_for(reader.readuntil(b"\n"), timeout=30)
90 except asyncio.IncompleteReadError, asyncio.LimitOverrunError, TimeoutError:
91 return None
92 return line if len(line) <= limit + 1 else None
95async def _finish(writer: asyncio.StreamWriter, payload: bytes) -> None:
96 with contextlib.suppress(ConnectionError):
97 writer.write(payload)
98 await writer.drain()
99 writer.close()
100 with contextlib.suppress(ConnectionError):
101 await writer.wait_closed()
104def agent_handler(
105 engine: HeadlessEngine,
106) -> Callable[[asyncio.StreamReader, asyncio.StreamWriter], Awaitable[None]]:
107 async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
108 line = await _read_line(reader, MAX_LINE_BYTES)
109 if line is None: 109 ↛ 110line 109 didn't jump to line 110 because the condition on line 109 was never true
110 await _finish(writer, b"")
111 return
112 try:
113 answer = await engine.relay_agent_line(line.decode().rstrip("\n"), peer_pid(writer))
114 except EngineRefused, UnicodeDecodeError:
115 # The client reads an empty answer as "not available".
116 await _finish(writer, b"")
117 return
118 await _finish(writer, answer.encode() + b"\n")
120 return handle
123def owner_handler(
124 handle_request: OwnerHandler,
125) -> Callable[[asyncio.StreamReader, asyncio.StreamWriter], Awaitable[None]]:
126 async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
127 line = await _read_line(reader, MAX_OWNER_LINE_BYTES)
128 if line is None:
129 await _finish(writer, b"")
130 return
131 answer: OwnerAnswer
132 try:
133 answer = await handle_request(OWNER_REQUEST.validate_json(line))
134 except ValidationError:
135 answer = Refused(reason="That is not a request this server understands.")
136 except EngineRefused as refused:
137 answer = Refused(reason=str(refused))
138 await _finish(writer, OWNER_ANSWER.dump_json(answer) + b"\n")
140 return handle
143async def open_socket(
144 path: Path,
145 handler: Callable[[asyncio.StreamReader, asyncio.StreamWriter], Awaitable[None]],
146 *,
147 limit: int,
148) -> asyncio.Server:
149 remove_stale_socket(path)
150 server = await asyncio.start_unix_server(handler, path=str(path), limit=limit + 2)
151 os.chmod(path, 0o600)
152 return server
155async def ask_owner_socket(
156 path: Path, request: OwnerRequest, *, timeout: float = 180
157) -> OwnerAnswer:
158 """Send one owner request to a running server and return its checked answer."""
159 try:
160 reader, writer = await asyncio.wait_for(
161 asyncio.open_unix_connection(str(path), limit=8 * 1024 * 1024), timeout=10
162 )
163 except (ConnectionRefusedError, FileNotFoundError, TimeoutError) as exc:
164 raise ServerNotRunning(str(path)) from exc
165 try:
166 writer.write(OWNER_REQUEST.dump_json(request) + b"\n")
167 await writer.drain()
168 line = await asyncio.wait_for(reader.readline(), timeout=timeout)
169 finally:
170 writer.close()
171 with contextlib.suppress(ConnectionError):
172 await writer.wait_closed()
173 if not line: 173 ↛ 174line 173 didn't jump to line 174 because the condition on line 173 was never true
174 raise ServerNotRunning(str(path))
175 answer = OWNER_ANSWER.validate_json(line)
176 if isinstance(answer, Refused):
177 raise OwnerRequestFailed(answer.reason)
178 return answer
181class ServerNotRunning(Exception):
182 """No server answered on the owner socket."""
185class OwnerRequestFailed(Exception):
186 """The server refused the owner's request."""