import ctypes import json import os import threading import time import unittest import uuid from kurgan.ai.launcher import token_info from kurgan.hw import pipe from kurgan.hw.protocol import MAX_MESSAGE, PROTOCOL_VERSION, Session, decode_reply, encode_request from kurgan.hw.pipe import PipeClient, PipeError, PipeServer, current_user_sid, pipe_sddl ME = current_user_sid() ELEVATED = token_info()["elevated"] def pipe_name() -> str: return rf"\\.\pipe\kurgan-hw-test-{os.getpid()}-{uuid.uuid4().hex[:8]}" class Calls: def __init__(self): self.ops = [] self.threads = set() self.lock = threading.Lock() def dispatch(self, op, args): with self.lock: self.ops.append(op) self.threads.add(threading.get_ident()) return {"op": op} def session(self): return Session(self.dispatch, "test") def ask(client, op, args=None, request_id=1, timeout=2.0): return decode_reply(client.request(encode_request(op, args, request_id), timeout), request_id) def greet(client): return ask(client, "hello", {"protocol": PROTOCOL_VERSION, "client": "test"}, 0) class PipeTest(unittest.TestCase): def serve(self, sddl=None, **options): name = pipe_name() calls = Calls() server = PipeServer(name, sddl or pipe_sddl(ME, server_sid=ME), calls.session, **options) server.start() self.addCleanup(server.close) return name, server, calls def connect(self, name, **options): options.setdefault("trusted_owners", None) deadline = time.monotonic() + 2 while True: # the listener thread may not have created the pipe yet try: client = PipeClient(name, **options) break except PipeError as e: if e.code != pipe.ERROR_FILE_NOT_FOUND or time.monotonic() > deadline: raise time.sleep(0.02) self.addCleanup(client.close) return client def test_round_trip(self): name, server, calls = self.serve() client = self.connect(name) self.assertEqual(greet(client), {"protocol": PROTOCOL_VERSION, "service": "test"}) self.assertEqual(ask(client, "state", request_id=2)["op"], "state") self.assertEqual(ask(client, "set_profile", {"profile": "quiet"}, request_id=3)["op"], "set_profile") self.assertEqual(calls.ops, ["state", "set_profile"]) def test_several_clients_at_once_each_on_its_own_thread(self): name, server, calls = self.serve() clients = [self.connect(name) for _ in range(3)] for client in clients: greet(client) for i, client in enumerate(clients * 2): # interleaved: each gets its own replies self.assertEqual(ask(client, "state", request_id=i)["op"], "state") self.assertEqual(server.clients, 3) self.assertEqual(len(calls.threads), 3) def test_a_silent_client_is_dropped_without_affecting_the_others(self): name, server, calls = self.serve(read_timeout=0.3) silent = self.connect(name) busy = self.connect(name) greet(busy) for i in range(5): # keeps talking, so keeps its connection time.sleep(0.1) ask(busy, "state", request_id=i) with self.assertRaises(PipeError): ask(silent, "state") ask(busy, "state", request_id=99) def test_a_line_left_unfinished_is_dropped_at_the_timeout(self): name, server, calls = self.serve(read_timeout=0.4) client = self.connect(name) greet(client) handle_event = pipe._event() try: for _ in range(6): # trickles a byte every 0.1 s but never ends the line pipe._write(client._handle, handle_event, b" ", 1.0) time.sleep(0.1) except PipeError: pass # already dropped finally: pipe._k32.CloseHandle(handle_event) with self.assertRaises(PipeError): ask(client, "state") def test_an_oversized_line_gets_an_error_then_the_connection_closes(self): name, server, calls = self.serve() client = self.connect(name) greet(client) reply = json.loads(client.request(b"x" * (MAX_MESSAGE + 10) + b"\n", 2.0)) self.assertEqual((reply["ok"], reply["error"]["code"]), (False, "too_large")) with self.assertRaises(PipeError): ask(client, "state") self.assertEqual(calls.ops, []) def test_closing_the_server_ends_connections_promptly(self): name, server, calls = self.serve() client = self.connect(name) greet(client) started = time.monotonic() server.close() self.assertLess(time.monotonic() - started, 2) with self.assertRaises(PipeError): ask(client, "state") def test_a_pipe_not_owned_by_system_or_administrators_is_refused(self): name, server, calls = self.serve() with self.assertRaisesRegex(PipeError, "not the hardware service"): self.connect(name, trusted_owners=pipe.TRUSTED_OWNERS) self.connect(name, trusted_owners=(ME,)) def test_no_service_means_a_clear_error(self): with self.assertRaisesRegex(PipeError, "isn't running") as caught: PipeClient(pipe_name(), timeout=0.1, trusted_owners=None) self.assertEqual(caught.exception.code, pipe.ERROR_FILE_NOT_FOUND) @unittest.skipIf(ELEVATED, "an elevated test process is an Administrator, which the pipe allows") def test_a_user_not_on_the_access_list_is_refused(self): other = "S-1-5-21-1000000001-1000000002-1000000003-1001" name, server, calls = self.serve(sddl=pipe_sddl(other)) time.sleep(0.2) with self.assertRaises(PipeError) as caught: PipeClient(name, timeout=0.5, trusted_owners=None) self.assertEqual(caught.exception.code, pipe.ERROR_ACCESS_DENIED) @unittest.skipIf(ELEVATED, "an elevated test process is an Administrator, which may add instances") def test_the_user_may_not_add_an_instance_of_the_pipe(self): name, server, calls = self.serve(sddl=pipe_sddl(ME)) self.connect(name) # the user can connect ... handle = pipe._k32.CreateNamedPipeW(name, pipe.PIPE_ACCESS_DUPLEX, 0, 8, 4096, 4096, 0, None) error = ctypes.get_last_error() if handle != pipe.INVALID_HANDLE: pipe._k32.CloseHandle(handle) self.assertEqual((handle, error), (pipe.INVALID_HANDLE, pipe.ERROR_ACCESS_DENIED)) # ... not serve it def test_access_list(self): self.assertEqual(pipe_sddl("S-1-5-21-1-2-3-1001"), "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12018b;;;S-1-5-21-1-2-3-1001)") self.assertEqual(pipe_sddl(None), "D:P(A;;GA;;;SY)(A;;GA;;;BA)") for bad in ("BU", "WD", "S-1-5-21-1-2-3-1001)(A;;GA;;;WD", ""): with self.subTest(bad=bad): with self.assertRaises(ValueError): pipe_sddl(bad) self.assertEqual(pipe.USER_ACCESS & 0x4, 0) # FILE_CREATE_PIPE_INSTANCE if __name__ == "__main__": unittest.main()