"""Offline browser coverage of the real password-protected administrator boundary. Run: python -B -m unittest ranch_web.tests.browser.test_admin_login_browser -v Only temporary demo accounts and a synthetic administrator password are used. """ from __future__ import annotations import json import re from pathlib import Path import socket import tempfile import threading import time import unittest from unittest.mock import patch from urllib.parse import urlsplit from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates, assert_navigation if AVAILABLE: from playwright.sync_api import expect @unittest.skipUnless(AVAILABLE, "Install Python Playwright and set RANCH_WEB_BROWSER to a system Chromium browser") class AdminLoginBrowserTests(unittest.TestCase): password = "offline-admin-password-not-a-real-credential" @classmethod def setUpClass(cls): import uvicorn from playwright.sync_api import sync_playwright from ranch_web.app import create_app from ranch_web.config import WebConfig from ranch_web.service import WebManager cls.network = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden")) cls.network.start() cls.addClassCleanup(cls.network.stop) cls.temp = tempfile.TemporaryDirectory(prefix="ranch-web-admin-browser-") cls.addClassCleanup(cls.temp.cleanup) cls.manager = WebManager(cls.temp.name, start_scheduler=False) cls.addClassCleanup(cls.manager.close) cls.manager.create_account("管理登录离线演示", demo=True) with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] cls.base = f"http://127.0.0.1:{port}" settings = WebConfig(port=port, data_dir=Path(cls.temp.name), password=cls.password) app = create_app(manager=cls.manager, config=settings, updates=OfflineUpdates()) cls.sessions = next(item.kwargs["sessions"] for item in app.user_middleware if "sessions" in item.kwargs) cls.server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error")) cls.thread = threading.Thread(target=cls.server.run, daemon=True) cls.thread.start() cls.addClassCleanup(cls.stop_server) deadline = time.monotonic() + 15 while not cls.server.started and time.monotonic() < deadline: time.sleep(.02) if not cls.server.started: raise RuntimeError("Temporary protected browser server failed to start") cls.playwright = sync_playwright().start() cls.addClassCleanup(cls.playwright.stop) cls.browser = cls.playwright.chromium.launch(executable_path=str(EDGE), headless=True) cls.addClassCleanup(cls.browser.close) @classmethod def stop_server(cls): cls.server.should_exit = True cls.thread.join(timeout=10) def setUp(self): self.context = self.browser.new_context(viewport={"width": 1280, "height": 800}) self.addCleanup(self.context.close) self.external_requests = [] def offline_only(route): if route.request.url.startswith(self.base + "/"): route.continue_() else: self.external_requests.append(route.request.url) route.abort() self.context.route("**/*", offline_only) self.page = self.context.new_page() self.requests = [] self.script_requests = [] self.errors = [] self.csp_errors = [] self.page.on("request", lambda request: self.requests.append(request.url)) self.page.on("request", lambda request: self.script_requests.append(request.url) if request.resource_type == "script" else None) self.page.on("pageerror", lambda failure: self.errors.append(str(failure))) self.page.on("console", lambda message: self.csp_errors.append(message.text) if message.type == "error" and ("security policy" in message.text.lower() or "csp" in message.text.lower()) else None) def tearDown(self): self.assertEqual(self.errors, []) self.assertEqual(self.csp_errors, []) self.assertEqual(self.external_requests, []) def assert_login_only(self, page=None): page = page or self.page expect(page).to_have_url(self.base + "/login") expect(page.locator("#auth-form")).to_be_visible() expect(page.locator("#admin-password")).to_be_enabled() self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs, #page-host, #auth-dialog").count(), 0) self.assertEqual(page.locator("script:not([src]), [style], [onclick], [onsubmit]").count(), 0) self.assertEqual(page.locator("script").count(), 1) expect(page.locator("script")).to_have_attribute("type", "module") expect(page.locator("script")).to_have_attribute("src", "/static/login.js") def login(self): self.page.goto(self.base + "/", wait_until="networkidle") self.assert_login_only() self.page.locator("#admin-password").fill(self.password) with self.page.expect_response("**/api/auth/login") as pending: self.page.locator('#auth-form button[type="submit"]').click() self.assertEqual(pending.value.status, 200) self.assertEqual(pending.value.request.post_data_json, {"password": self.password}) expect(self.page).to_have_url(re.compile("^" + re.escape(self.base + "/") + r"(?:#.*)?$")) expect(self.page.locator("#app")).to_be_visible() assert_navigation(self.page) expect(self.page.locator('.nav-link[data-page="overview"]')).to_have_attribute("aria-current", "page") expect(self.page.locator("#status-text")).to_contain_text("已连接") self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0) self.console_assets = self.page.locator('script[src], link[rel="stylesheet"], link[rel="modulepreload"]').evaluate_all( "nodes => nodes.map(node => node.src || node.href)") self.assertTrue(self.console_assets) def observe_login_transition(self): snapshots = [] def login_document(route): snapshots.append(route.request.url) # Leave the old document available to prove it was hidden before navigation. route.abort() self.page.route("**/login", login_document) return snapshots def assert_hidden_transition(self, snapshots): expect(self.page.locator("#app")).to_have_count(1) expect(self.page.locator("#app")).to_be_hidden() deadline = time.monotonic() + 5 while not snapshots and time.monotonic() < deadline: self.page.wait_for_timeout(20) self.assertTrue(snapshots) self.assertEqual(self.page.locator("dialog[open]").count(), 0) self.assertTrue(self.page.evaluate("[...document.querySelectorAll('input[type=password]')].every(input => !input.value)")) self.page.unroute("**/login") self.page.goto(self.base + "/login", wait_until="networkidle") def assert_old_cookie_rejected(self, cookies): context = self.browser.new_context() self.addCleanup(context.close) context.add_cookies(cookies) page = context.new_page() requested = [] page.on("request", lambda request: requested.append(request.url) if request.resource_type == "script" else None) page.goto(self.base + "/", wait_until="networkidle") self.assert_login_only(page) self.assertEqual(requested, [self.base + "/static/login.js"]) response = context.request.get(self.base + "/static/index.html", max_redirects=0) self.assertIn(response.status, (302, 303, 307, 401, 403)) self.assertNotIn('id="app"', response.text()) for url in self.console_assets: response = context.request.get(url, max_redirects=0) self.assertIn(response.status, (302, 303, 307, 401, 403), url) def test_fresh_root_serves_only_login_and_public_assets_with_csp(self): response = self.page.goto(self.base + "/", wait_until="networkidle") self.assert_login_only() self.assertEqual(response.status, 200) self.assertNotIn('id="app"', response.text()) policy = response.headers["content-security-policy"] self.assertIn("script-src 'self'", policy) self.assertIn("style-src 'self'", policy) self.assertNotIn("'unsafe-inline'", policy) self.assertIn(self.base + "/api/auth/status", self.requests) scripts = self.page.evaluate("performance.getEntriesByType('resource').filter(item => item.initiatorType === 'script').map(item => new URL(item.name).pathname)") self.assertEqual(scripts, ["/static/login.js"]) self.assertEqual(self.script_requests, [self.base + "/static/login.js"]) for width in (1280, 390): self.page.set_viewport_size({"width": width, "height": 800}) self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width) expect(self.page.get_by_role("button", name="登录", exact=True)).to_be_visible() self.assertEqual(self.context.cookies(), []) def test_login_all_tabs_authenticated_login_redirect_logout_and_revoked_cookie(self): self.login() cookies = self.context.cookies() self.assertEqual(len(cookies), 1) self.assertEqual(cookies[0]["path"], "/") self.assertTrue(cookies[0]["httpOnly"]) self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0) self.assertNotIn(self.password, self.page.url) self.page.goto(self.base + "/login", wait_until="networkidle") self.assertEqual(urlsplit(self.page.url).path, "/") assert_navigation(self.page) snapshots = self.observe_login_transition() self.page.locator('.nav-link[data-page="system"]').click() self.page.locator('[data-command="admin-logout"]').click() self.assert_hidden_transition(snapshots) self.assert_login_only() self.assertEqual(self.context.cookies(), []) self.assert_old_cookie_rejected(cookies) def test_wrong_password_clears_input_without_loading_workbench(self): self.page.goto(self.base + "/", wait_until="networkidle") self.assert_login_only() self.page.locator("#admin-password").fill("offline-wrong-admin-password") with self.page.expect_response("**/api/auth/login") as pending: self.page.get_by_role("button", name="登录", exact=True).click() self.assertEqual(pending.value.status, 401) expect(self.page.locator("#auth-error")).to_contain_text("管理密码错误") self.assertEqual(self.page.locator("#admin-password").input_value(), "") expect(self.page.locator("#admin-password")).to_be_focused() self.assert_login_only() self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0) self.assertFalse(any("offline-wrong-admin-password" in url for url in self.requests)) self.assertEqual(self.script_requests, [self.base + "/static/login.js"]) def test_expired_server_session_hides_workbench_and_rejects_old_cookie(self): self.login() cookies = self.context.cookies() self.page.locator('.nav-link[data-page="system"]').click() self.page.locator('[data-command="about"]').click() expect(self.page.locator("#action-dialog")).to_be_visible() snapshots = self.observe_login_transition() # Expire only this disposable server's in-memory sessions; no 60s sleep. with self.sessions.lock: for digest in self.sessions.sessions: self.sessions.sessions[digest] = 0.0 self.assert_hidden_transition(snapshots) self.assert_login_only() self.assert_old_cookie_rejected(cookies) def test_explicit_action_401_clears_password_and_redirects(self): self.login() snapshots = self.observe_login_transition() def unauthorized(route): self.assertEqual(self.context.request.post(self.base + "/api/auth/logout", data={}).status, 200) route.fulfill(status=401, content_type="application/json", body=json.dumps({"detail": "会话已失效"})) self.page.route("**/api/accounts/*/actions/refresh", unauthorized) self.page.locator('.nav-link[data-page="login"]').click() expect(self.page.locator('.page-panel[data-page="login"]:not([hidden]) .page-loading[data-loading="false"]')).to_have_count(1) self.page.locator('#page-host input[type="password"]').fill("unsent-offline-game-password") self.page.locator("#refresh").click() self.assert_hidden_transition(snapshots) self.assert_login_only() def test_bootstrap_status_401_keeps_workbench_hidden(self): self.assertEqual(self.context.request.post(self.base + "/api/auth/login", data={"password": self.password}).status, 200) initial_status = [] def unauthorized_status(route): if not initial_status: initial_status.append(route) else: route.fulfill(status=401, content_type="application/json", body='{"detail":"会话已失效"}') self.page.route("**/api/auth/status", unauthorized_status) self.page.add_init_script("""window.workbenchVisible = false; new MutationObserver(() => { const app = document.querySelector('#app'); if (app && !app.hidden) window.workbenchVisible = true; }).observe(document, {subtree: true, childList: true, attributes: true, attributeFilter: ['hidden']});""") self.page.goto(self.base + "/", wait_until="domcontentloaded") expect(self.page.locator("#app")).to_have_count(1) expect(self.page.locator("#app")).to_be_hidden() deadline = time.monotonic() + 5 while not initial_status and time.monotonic() < deadline: self.page.wait_for_timeout(20) self.assertTrue(initial_status) self.assertFalse(self.page.evaluate("window.workbenchVisible")) self.assertEqual(self.context.request.post(self.base + "/api/auth/logout", data={}).status, 200) initial_status[0].fulfill(status=401, content_type="application/json", body='{"detail":"会话已失效"}') self.assert_login_only() expect(self.page.locator("#auth-error")).to_contain_text("会话已失效") def test_javascript_disabled_still_contains_only_login_form(self): context = self.browser.new_context(java_script_enabled=False) self.addCleanup(context.close) page = context.new_page() response = page.goto(self.base + "/", wait_until="networkidle") expect(page).to_have_url(self.base + "/login") self.assertNotIn('id="app"', response.text()) self.assertEqual(page.locator("#app, nav, #sidebar, #topbar, #account-select, #account-tabs, #page-tabs").count(), 0) expect(page.locator("#auth-form")).to_be_visible() expect(page.locator("#auth-form button")).to_be_disabled() expect(page.locator("noscript")).to_be_visible() if __name__ == "__main__": unittest.main()