from __future__ import annotations import json import subprocess from pathlib import Path import pytest from k1link.device_plugins.xgrids_k1 import macos_wifi TEST_PASSWORD = "fixture-only-network-secret" def _helper(tmp_path: Path) -> Path: helper = tmp_path / "associate_wifi.swift" helper.write_text("// offline fixture\n", encoding="utf-8") return helper def test_association_passes_secret_only_through_stdin( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: monkeypatch.setattr(macos_wifi.sys, "platform", "darwin") calls: list[dict[str, object]] = [] live_inputs: list[bytearray] = [] def fake_runner(argv: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]: assert isinstance(kwargs["input"], bytearray) live_inputs.append(kwargs["input"]) calls.append( { "argv": argv, **kwargs, "input": bytes(kwargs["input"]), } ) return subprocess.CompletedProcess( argv, 0, stdout=b'{"ok":true,"already_associated":false}', stderr=b"", ) result = macos_wifi.associate_with_wifi_once( _helper(tmp_path), "XGR-OFFLINE", TEST_PASSWORD, runner=fake_runner, ) assert result == { "schema_version": 1, "adapter": "CoreWLAN", "outcome": "associated", "already_associated": False, } assert len(calls) == 1 call = calls[0] assert call["argv"][:2] == ["/usr/bin/xcrun", "swift"] assert TEST_PASSWORD not in " ".join(call["argv"]) request = json.loads(bytes(call["input"]).decode("utf-8")) assert request == {"ssid": "XGR-OFFLINE", "password": TEST_PASSWORD} assert call["check"] is False assert call["timeout"] == 45.0 assert live_inputs and not any(live_inputs[0]) def test_association_reports_only_sanitized_helper_reason( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ) -> None: monkeypatch.setattr(macos_wifi.sys, "platform", "darwin") def fake_runner(argv: list[str], **_: object) -> subprocess.CompletedProcess[bytes]: return subprocess.CompletedProcess( argv, 1, stdout=b'{"ok":false,"reason_code":"network-not-found"}', stderr=f"private diagnostic {TEST_PASSWORD}".encode(), ) with pytest.raises( macos_wifi.HostWifiAssociationError, match="network-not-found", ) as raised: macos_wifi.associate_with_wifi_once( _helper(tmp_path), "XGR-OFFLINE", TEST_PASSWORD, runner=fake_runner, ) assert TEST_PASSWORD not in str(raised.value) def test_association_is_macos_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(macos_wifi.sys, "platform", "linux") with pytest.raises( macos_wifi.HostWifiAssociationError, match="unsupported-platform", ): macos_wifi.associate_with_wifi_once( _helper(tmp_path), "XGR-OFFLINE", TEST_PASSWORD, )