"""Regressions for Windows pool permissions and PowerShell output encoding.""" import json import os import shutil import subprocess import sys import pytest import requests from fastapi.testclient import TestClient from studio.api import create_app pytestmark = pytest.mark.skipif(os.name != 'nt', reason='Windows pool process and PowerShell behavior') @pytest.fixture def pool_client(tmp_path): project = tmp_path / "proxy pool" project.mkdir() (project / "manage.ps1").write_text("param([string]$Action)\nWrite-Output '代理池已就绪'\n", encoding="utf-8-sig") app = create_app(tmp_path / "workbench") app.state.settings.update({"pool_project": str(project), "pool_url": "http://127.0.0.1:1"}) with TestClient(app, base_url="http://127.0.0.1:8765") as client: yield client, app, project @pytest.fixture def restricted_pool(pool_client, monkeypatch): client, app, project = pool_client runtime = project / ".runtime" runtime.mkdir() (runtime / "server.pid").write_text("100020") (runtime / "schedule.pid").write_text("100030") # CIM returns no command line when a normal user inspects elevated Python. facts = { "server": {"pid": 100020, "exists": True, "executable": str(project / ".venv/Scripts/python.exe"), "command": None}, "schedule": {"pid": 100030, "exists": True, "executable": str(project / ".venv/Scripts/python.exe"), "command": None}, "redis": {"pid": None, "exists": False}, } def shell(command, **kwargs): if "-EncodedCommand" in command: return subprocess.CompletedProcess(command, 0, json.dumps(facts).encode(), b"") return subprocess.CompletedProcess(command, 1, b"", b"PID 100020 belongs to another process.") def counts(session, url, **kwargs): response = requests.Response() response.status_code = 200 response._content = b'{"count": 12, "http_type": {"https": 4, "http": 8}}' return response monkeypatch.setattr(subprocess, "run", shell) monkeypatch.setattr(requests.Session, "get", counts) return client, app, project def test_restricted_running_pool_status_is_readable_and_keeps_selected_proxy(restricted_pool): client, app, _ = restricted_pool app.state.router.active = "http://1.2.3.4:8080" response = client.post("/api/proxy/manage", json={"action": "status"}) assert response.status_code == 200 result = response.json() assert result["ok"] is True assert result["status"]["api_ready"] is True assert result["status"]["items"][0]["state"] == "restricted" assert result["status"]["can_stop"] is False assert "权限" in result["status"]["warning"] assert "belongs to another process" not in result["output"] assert app.state.router.active == "http://1.2.3.4:8080" def test_start_reuses_existing_restricted_pool_without_duplicate_processes(restricted_pool): client, app, project = restricted_pool app.state.router.failed.add("http://1.2.3.4:8080") result = client.post("/api/proxy/manage", json={"action": "start"}).json() assert result["ok"] is True assert result["changed"] is False assert result["status"]["items"][1]["state"] == "restricted" assert (project / ".runtime/server.pid").read_text() == "100020" assert "http://1.2.3.4:8080" in app.state.router.failed def test_stop_explains_permission_limit_and_preserves_restricted_pid_records(restricted_pool): client, _, project = restricted_pool result = client.post("/api/proxy/manage", json={"action": "stop"}).json() assert result["ok"] is False assert "权限" in result["message"] assert result["changed"] is False assert (project / ".runtime/server.pid").read_text() == "100020" assert (project / ".runtime/schedule.pid").read_text() == "100030" @pytest.mark.skipif(os.name != "nt", reason="Windows PowerShell integration") def test_service_output_retains_chinese_characters(pool_client): client, _, _ = pool_client result = client.post("/api/proxy/manage", json={"action": "start"}).json() assert result["ok"] is True assert "代理池已就绪" in result["output"] assert "\ufffd" not in result["output"] @pytest.mark.skipif(os.name != "nt", reason="Windows process identity integration") def test_wrong_live_pid_is_not_delegated_to_stop_script(pool_client): client, _, project = pool_client runtime = project / ".runtime" runtime.mkdir() (runtime / "server.pid").write_text(str(os.getpid())) (project / "manage.ps1").write_text("param([string]$Action)\nSet-Content -LiteralPath (Join-Path $PSScriptRoot 'stop-was-called') -Value $Action\n", encoding="utf-8-sig") result = client.post("/api/proxy/manage", json={"action": "stop"}).json() assert result["ok"] is False assert result["status"]["items"][0]["state"] == "conflict" assert (runtime / "server.pid").read_text() == str(os.getpid()) assert not (project / "stop-was-called").exists() def test_service_timeout_returns_actionable_result_instead_of_server_error(pool_client, monkeypatch): client, app, _ = pool_client app.state.router.active = "http://1.2.3.4:8080" def shell(command, **kwargs): if "-EncodedCommand" in command: facts = {name: {"pid": None, "exists": False} for name in ("server", "schedule", "redis")} return subprocess.CompletedProcess(command, 0, json.dumps(facts).encode(), b"") raise subprocess.TimeoutExpired(command, 55) monkeypatch.setattr(subprocess, "run", shell) response = client.post("/api/proxy/manage", json={"action": "start"}) assert response.status_code == 200 assert response.json()["ok"] is False assert "超时" in response.json()["message"] assert response.json()["changed"] is True assert app.state.router.active is None def test_stale_pid_is_not_shown_as_the_running_service_pid(restricted_pool, monkeypatch): client, _, project = restricted_pool (project / ".runtime/redis.pid").write_text("100040") def shell(command, **kwargs): facts = { "server": {"pid": 100020, "exists": True, "executable": str(project / ".venv/Scripts/python.exe"), "command": None}, "schedule": {"pid": 100030, "exists": True, "executable": str(project / ".venv/Scripts/python.exe"), "command": None}, "redis": {"pid": 100040, "exists": False}, } return subprocess.CompletedProcess(command, 0, json.dumps(facts).encode(), b"") monkeypatch.setattr(subprocess, "run", shell) result = client.get("/api/proxy/services").json() redis = next(item for item in result["items"] if item["name"] == "redis") assert redis["state"] == "external" assert redis["pid"] is None assert (project / ".runtime/redis.pid").read_text() == "100040" def test_readable_command_line_does_not_imply_permission_to_stop(restricted_pool, monkeypatch): client, _, project = restricted_pool def shell(command, **kwargs): facts = { name: {"pid": pid, "exists": True, "executable": str(project / ".venv/Scripts/python.exe"), "command": f'python.exe -u "{project / "proxyPool.py"}" {name}'} for name, pid in (("server", 100020), ("schedule", 100030)) } facts["redis"] = {"pid": None, "exists": False} return subprocess.CompletedProcess(command, 0, json.dumps(facts).encode(), b"") monkeypatch.setattr(subprocess, "run", shell) monkeypatch.setattr("studio.pool_service._native_process", lambda pid: {"elevated": True, "can_terminate": False}) result = client.get("/api/proxy/services").json() assert result["can_stop"] is False assert result["items"][0]["state"] == "restricted" @pytest.mark.skipif(os.name != "nt" or not shutil.which("pwsh.exe"), reason="PowerShell 7 native-argument integration") def test_pool_python_commands_keep_embedded_quotes(pool_client): client, _, project = pool_client python = sys.executable.replace("'", "''") script = "param([string]$Action)\n$pythonPath = '" + python + "'\n$checkCode = @'\nprint(\"代理池已就绪\")\n'@\n& $pythonPath -X utf8 -c $checkCode\n" (project / "manage.ps1").write_text(script, encoding="utf-8-sig") result = client.post("/api/proxy/manage", json={"action": "start"}).json() assert result["ok"] is True assert "代理池已就绪" in result["output"] @pytest.mark.parametrize("invocation", [ 'python.exe unrelated.py "{entry}" {name}', 'python.exe -c "pass" "{entry}" {name}', 'python.exe -m unrelated "{entry}" {name}', ]) def test_extra_script_argument_cannot_impersonate_pool_process(restricted_pool, monkeypatch, invocation): client, _, project = restricted_pool def shell(command, **kwargs): facts = { name: {"pid": pid, "exists": True, "executable": str(project / ".venv/Scripts/python.exe"), "command": invocation.format(entry=project / "proxyPool.py", name=name)} for name, pid in (("server", 100020), ("schedule", 100030)) } facts["redis"] = {"pid": None, "exists": False} return subprocess.CompletedProcess(command, 0, json.dumps(facts).encode(), b"") monkeypatch.setattr(subprocess, "run", shell) status = client.get("/api/proxy/services").json() assert status["items"][0]["state"] == "conflict" assert status["items"][0]["verified"] is False assert status["can_stop"] is False result = client.post("/api/proxy/manage", json={"action": "stop"}).json() assert result["ok"] is False assert result["changed"] is False @pytest.mark.skipif(os.name != "nt", reason="Windows PowerShell integration") def test_action_uses_one_project_snapshot_when_settings_change(pool_client, monkeypatch): client, app, project = pool_client other = project.parent / "another pool" other.mkdir() script = "param([string]$Action)\nSet-Content -LiteralPath (Join-Path $PSScriptRoot 'ran-here') -Value $Action\n" for root in (project, other): (root / "manage.ps1").write_text(script, encoding="utf-8-sig") def read_processes(root): app.state.settings.update({"pool_project": str(other)}) return {name: {"pid": None, "exists": False} for name in ("server", "schedule", "redis")} monkeypatch.setattr(app.state.pool, "_processes", read_processes) result = client.post("/api/proxy/manage", json={"action": "start"}).json() assert result["ok"] is True assert (project / "ran-here").exists() assert (project / "ran-here").read_text().strip() == "start" assert not (other / "ran-here").exists() @pytest.mark.skipif(os.name != "nt", reason="Windows background process integration") def test_background_service_does_not_keep_management_response_open(pool_client, monkeypatch): from studio.pool_service import _native_process, _powershell client, app, project = pool_client worker = project / "background.py" worker.write_text("import time\ntime.sleep(8)\n", encoding="utf-8") python = sys.executable.replace("'", "''") script = "param([string]$Action)\n$process = Start-Process -FilePath '" + python + "' -ArgumentList ('\"' + (Join-Path $PSScriptRoot 'background.py') + '\"') -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $PSScriptRoot 'worker.out.log') -RedirectStandardError (Join-Path $PSScriptRoot 'worker.err.log')\nSet-Content -LiteralPath (Join-Path $PSScriptRoot 'worker.pid') -Value $process.Id\nWrite-Output 'started'\n" (project / "manage.ps1").write_text(script, encoding="utf-8-sig") monkeypatch.setattr(app.state.pool, "_processes", lambda root: {name: {"pid": None, "exists": False} for name in ("server", "schedule", "redis")}) try: result = client.post("/api/proxy/manage", json={"action": "start"}).json() assert result["ok"] is True pid = int((project / "worker.pid").read_text(encoding="utf-8-sig").strip()) assert _native_process(pid).get("executable"), "Management waited until the background service exited" finally: if (project / "worker.pid").exists(): environment = {**os.environ, "KAOYAN_QA_PID": (project / "worker.pid").read_text(encoding="utf-8-sig").strip(), "KAOYAN_QA_WORKER": str(worker)} subprocess.run([_powershell(), "-NoProfile", "-Command", "$p = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $env:KAOYAN_QA_PID); if ($p -and $p.CommandLine.Contains($env:KAOYAN_QA_WORKER)) { Stop-Process -Id $p.ProcessId }"], env=environment, capture_output=True, timeout=10)