Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions api/core/wininspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 1985
# Wire protocol and product release are independent. Never infer either from
# the other; the actual provider artifact is a separate qualification gate.
WININSPECT_PROTOCOL_VERSION = "0.4.0"
DEFAULT_TIMEOUT_SECONDS = 3.0
MAX_MESSAGE_SIZE = 10 * 1024 * 1024
READ_ONLY_METHODS = {
Expand Down Expand Up @@ -278,6 +281,10 @@ def _write_frame(sock: socket.socket, payload: dict[str, Any]) -> None:
def request(method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
if method not in READ_ONLY_METHODS and method not in MUTATION_METHODS:
raise WinInspectError(f"WinInspect method is not allowed by WineBot: {method}")
# Deny a caller-supplied protocol override before process or socket effects.
if params is not None and "protocol_version" in params:
if params["protocol_version"] != WININSPECT_PROTOCOL_VERSION:
raise WinInspectError("WinInspect request protocol mismatch")
state = ensure_daemon(start=True)
if not state.get("running"):
raise WinInspectError(str(state.get("error") or "WinInspect daemon is not running"))
Expand All @@ -287,20 +294,26 @@ def request(method: str, params: dict[str, Any] | None = None) -> dict[str, Any]
"id": request_id,
"method": method,
"params": {
"protocol_version": "0.4.0",
**(params or {}),
"protocol_version": WININSPECT_PROTOCOL_VERSION,
},
}
with socket.create_connection((host(), port()), timeout=timeout_seconds()) as sock:
sock.settimeout(timeout_seconds())
hello = _read_frame(sock)
if (hello.get("type") != "hello"
or hello.get("version") != WININSPECT_PROTOCOL_VERSION):
# Do not expose untrusted version/identity data or send RPC bytes.
raise WinInspectError("WinInspect hello protocol mismatch")
_write_frame(sock, payload)
response = _read_frame(sock)

if response.get("id") != request_id:
# Never expose untrusted daemon hello identity in API-visible errors.
raise WinInspectError("WinInspect response correlation failed")
if not response.get("ok"):
if type(response.get("ok")) is not bool:
raise WinInspectError("WinInspect response status invalid")
if response["ok"] is False:
error = response.get("error") or {}
if isinstance(error, dict):
code = error.get("code")
Expand Down
82 changes: 74 additions & 8 deletions tests/test_wininspect_error_redaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@


class Socket:
def __init__(self, response):
hello = {
"type": "hello", "version": "0.3.0",
"hostname": "SYNTHETIC_HOST_NEVER_ECHO",
"name": "SYNTHETIC_PERSON_NEVER_ECHO",
"uuid": "SYNTHETIC_UUID_NEVER_ECHO",
}
def __init__(self, response, hello=None):
if hello is None:
hello = {
"type": "hello", "version": "0.4.0",
"hostname": "SYNTHETIC_HOST_NEVER_ECHO",
"name": "SYNTHETIC_PERSON_NEVER_ECHO",
"uuid": "SYNTHETIC_UUID_NEVER_ECHO",
}
self.sent = bytearray()
self.incoming = bytearray()
for item in (hello, response):
raw = json.dumps(item).encode()
Expand All @@ -31,7 +33,7 @@ def settimeout(self, timeout):
pass

def sendall(self, value):
pass
self.sent.extend(value)

def __enter__(self):
return self
Expand All @@ -57,3 +59,67 @@ def test_mismatched_correlation_refuses_without_hello_disclosure(bad_reply):
for token in ("SYNTHETIC_HOST", "SYNTHETIC_PERSON", "SYNTHETIC_UUID",
"different-request"):
assert token not in str(error.value)



@pytest.mark.parametrize("hello", [
{},
{"type": "not-hello", "version": "0.4.0"},
{"type": "hello", "version": "0.3.0"},
{"type": "hello", "version": "SYNTHETIC_VERSION_NEVER_ECHO"},
{"type": "hello", "version": ["0.4.0"]},
{"type": "hello"},
])
def test_wrong_hello_refuses_before_any_rpc(hello):
sock = Socket({}, hello=hello)
with (
patch.object(wi, "ensure_daemon", return_value={"running": True}),
patch.object(wi.socket, "create_connection", return_value=sock),
):
with pytest.raises(wi.WinInspectError) as error:
wi.request("daemon.capabilities")
assert str(error.value) == "WinInspect hello protocol mismatch"
assert not sock.sent


@pytest.mark.parametrize("version", ["0.3.0", "0.5.0", None, True, ["0.4.0"]])
def test_protocol_override_refuses_before_process_or_socket(version):
with (
patch.object(wi, "ensure_daemon") as ensure,
patch.object(wi.socket, "create_connection") as connect,
):
with pytest.raises(wi.WinInspectError) as error:
wi.request("daemon.capabilities", {"protocol_version": version})
assert str(error.value) == "WinInspect request protocol mismatch"
ensure.assert_not_called()
connect.assert_not_called()


def test_exact_protocol_and_correlation_are_required():
sock = Socket({"id": "winebot-abc123456789", "ok": True, "result": {}})
with (
patch.object(wi, "ensure_daemon", return_value={"running": True}),
patch.object(wi.socket, "create_connection", return_value=sock),
patch.object(wi.uuid, "uuid4") as mock_uuid,
):
mock_uuid.return_value.hex = "abc1234567890"
result = wi.request("daemon.capabilities", {"protocol_version": "0.4.0"})
assert result["result"] == {}
size = struct.unpack("!I", sock.sent[:4])[0]
assert size == len(sock.sent) - 4
request = json.loads(sock.sent[4:])
assert request["params"]["protocol_version"] == "0.4.0"


@pytest.mark.parametrize("status", [None, 0, 1, "true", {}, []])
def test_non_boolean_reply_status_refuses(status):
sock = Socket({"id": "winebot-abc123456789", "ok": status, "result": {}})
with (
patch.object(wi, "ensure_daemon", return_value={"running": True}),
patch.object(wi.socket, "create_connection", return_value=sock),
patch.object(wi.uuid, "uuid4") as mock_uuid,
):
mock_uuid.return_value.hex = "abc1234567890"
with pytest.raises(wi.WinInspectError) as error:
wi.request("daemon.capabilities")
assert str(error.value) == "WinInspect response status invalid"
2 changes: 1 addition & 1 deletion tests/test_wininspect_observer_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def test_malformed_event_envelope_fails_closed(monkeypatch, payload):
class Socket:
def __init__(self, response):
self.data = bytearray()
for message in ({"type": "hello", "name": "NEVER_RETURN_IDENTITY"}, response):
for message in ({"type": "hello", "version": "0.4.0", "name": "NEVER_RETURN_IDENTITY"}, response):
raw = json.dumps(message).encode("utf-8")
self.data += struct.pack("!I", len(raw)) + raw

Expand Down