"""Administrator sessions and browser boundary checks, entirely offline.""" import asyncio from http.cookies import SimpleCookie from pathlib import Path import tempfile import threading import unittest from unittest.mock import patch import httpx from fastapi.testclient import TestClient from ranch_web.app import create_app from ranch_web.config import COOKIE_NAME, WebConfig, hash_password, verify_password from ranch_web.tests.test_api import FakeManager, FakeUpdates class AuthTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory(prefix="ranch-web-auth-") self.addCleanup(self.temporary.cleanup) self.root = Path(self.temporary.name) self.manager, self.updates = FakeManager(), FakeUpdates() self.assets = self.root / "static" self.assets.mkdir() for name, content in { "index.html": '', "login.html": '
ADMIN_LOGIN_ONLY
', "login.js": "// LOGIN_SCRIPT_ONLY", "login.css": "/* LOGIN_STYLE_ONLY */", "styles.css": "/* SHARED_STYLE_ONLY */", "dom.js": "// SHARED_DOM_ONLY", **{name: "// WORKBENCH_ONLY" for name in ("app.js", "api.js", "pages.js", "ui.js", "table.js", "forms.js", "future.mjs")}, }.items(): (self.assets / name).write_text(content, encoding="utf-8") self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("No real network access"))) def client(self, settings=None, **kwargs): settings = settings or WebConfig(data_dir=self.root) with patch("ranch_web.app.__file__", str(self.root / "app.py")): app = create_app(manager=self.manager, updates=self.updates, config=settings) return self.enterContext(TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50000), **kwargs)) def cookie_headers(self, response): cookies = [] for header in response.headers.get_list("set-cookie"): parsed = SimpleCookie() parsed.load(header) cookies.append(parsed[COOKIE_NAME]) return cookies def test_unauthenticated_workbench_and_scripts_redirect_before_file_access(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) with patch("ranch_web.app.FileResponse", side_effect=AssertionError("Workbench HTML must stay unopened")), \ patch("ranch_web.app._Assets.lookup_path", side_effect=AssertionError("Workbench assets must stay unopened")): for path in ("/", "/?next=/api/accounts", "/static/index.html", "/static/app.js", "/static/api.js", "/static/pages.js", "/static/ui.js", "/static/table.js", "/static/forms.js", "/static/future.mjs", "/static//index.html", "/static/%69ndex.html", "/static/login.js/../app.js"): with self.subTest(path=path): response = client.get(path, follow_redirects=False) self.assertEqual(response.status_code, 303) self.assertEqual(response.headers["location"], "/login") self.assertEqual(response.headers["cache-control"], "no-store") self.assertNotIn("WORKBENCH_ONLY", response.text) self.assertEqual(response.headers["x-content-type-options"], "nosniff") self.assertEqual(self.manager.calls, []) self.assertEqual(self.updates.calls, []) def test_login_page_and_shared_assets_are_public_without_workbench(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) for path in ("/login", "/static/login.html"): with self.subTest(path=path): response = client.get(path) self.assertEqual(response.status_code, 200) self.assertIn("text/html", response.headers["content-type"]) self.assertIn("ADMIN_LOGIN_ONLY", response.text) self.assertNotIn("WORKBENCH_ONLY", response.text) self.assertEqual(response.headers["cache-control"], "no-store") for name in ("login.js", "login.css", "styles.css", "dom.js"): with self.subTest(name=name): response = client.get("/static/" + name) self.assertEqual(response.status_code, 200) self.assertNotIn("WORKBENCH_ONLY", response.text) self.assertEqual(self.manager.calls, []) self.assertEqual(self.updates.calls, []) def test_authenticated_login_redirects_home_and_workbench_assets_are_private(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}).status_code, 200) for path in ("/login", "/static/login.html"): with self.subTest(path=path): response = client.get(path, follow_redirects=False) self.assertEqual(response.status_code, 303) self.assertEqual(response.headers["location"], "/") self.assertEqual(response.headers["cache-control"], "no-store") for path in ("/", "/static/index.html", "/static/app.js", "/static/api.js", "/static/pages.js", "/static/future.mjs"): with self.subTest(path=path): response = client.get(path) self.assertEqual(response.status_code, 200) self.assertIn("WORKBENCH_ONLY", response.text) self.assertEqual(response.headers["cache-control"], "no-store") self.assertEqual(self.manager.calls, []) self.assertEqual(self.updates.calls, []) def test_ui_gate_preserves_public_api_and_json_unauthorized_responses(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) for path in ("/api/health", "/api/meta", "/api/auth/status"): with self.subTest(path=path): self.assertEqual(client.get(path).status_code, 200) for method, path in (("GET", "/api/accounts"), ("GET", "/api/schema"), ("POST", "/api/accounts")): with self.subTest(method=method, path=path): response = client.request(method, path, follow_redirects=False) self.assertEqual(response.status_code, 401) self.assertNotIn("location", response.headers) self.assertEqual(response.json()["error"]["code"], "authentication_required") self.assertEqual(client.post("/api/auth/logout").status_code, 200) self.assertEqual(self.manager.calls, []) def test_invalid_and_expired_sessions_cannot_open_workbench(self): settings = WebConfig(data_dir=self.root, password="correct", session_ttl=60) client = self.client(settings) for token in ("invalid", "A" * 43): with self.subTest(token=token): response = client.get("/", headers={"Cookie": f"{COOKIE_NAME}={token}"}, follow_redirects=False) self.assertEqual(response.status_code, 303) self.assertEqual(response.headers["location"], "/login") with patch("ranch_web.app.time.monotonic", return_value=0): self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}).status_code, 200) for path in ("/", "/static/index.html", "/static/app.js"): with self.subTest(path=path): response = client.get(path, follow_redirects=False) self.assertEqual(response.status_code, 303) self.assertEqual(response.headers["location"], "/login") self.assertEqual(client.get("/api/accounts").status_code, 401) self.assertIn("ADMIN_LOGIN_ONLY", client.get("/login").text) def test_missing_login_asset_returns_unavailable_without_workbench_fallback(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) (self.assets / "login.html").unlink() response = client.get("/login") self.assertEqual(response.status_code, 503) self.assertNotIn("WORKBENCH_ONLY", response.text) response = client.get("/", follow_redirects=False) self.assertEqual(response.status_code, 303) self.assertEqual(response.headers["location"], "/login") def test_login_migrates_legacy_api_cookie_and_revokes_previous_session(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) client.post("/api/auth/login", json={"password": "correct"}) token = client.cookies.get(COOKIE_NAME) domain = next(iter(client.cookies.jar)).domain client.cookies.clear() client.cookies.set(COOKIE_NAME, token, domain=domain, path="/api") self.assertEqual(client.get("/", follow_redirects=False).status_code, 303) response = client.post("/api/auth/login", json={"password": "correct"}) self.assertEqual(response.status_code, 200) cookies = {cookie["path"]: cookie for cookie in self.cookie_headers(response)} self.assertEqual(set(cookies), {"/", "/api"}) self.assertEqual(cookies["/api"]["max-age"], "0") self.assertEqual(cookies["/api"].value, "") self.assertNotEqual(cookies["/"].value, token) self.assertEqual([(cookie.name, cookie.path) for cookie in client.cookies.jar], [(COOKIE_NAME, "/")]) self.assertEqual(client.get("/").status_code, 200) self.assertEqual(client.get("/api/accounts").status_code, 200) self.assertEqual(client.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401) def test_logout_clears_root_and_legacy_cookies_and_blocks_ui_replay(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) client.post("/api/auth/login", json={"password": "correct"}) token = client.cookies.get(COOKIE_NAME) domain = next(iter(client.cookies.jar)).domain client.cookies.set(COOKIE_NAME, "stale-legacy-cookie", domain=domain, path="/api") response = client.post("/api/auth/logout") self.assertEqual(response.status_code, 200) cookies = {cookie["path"]: cookie for cookie in self.cookie_headers(response)} self.assertEqual(set(cookies), {"/", "/api"}) for cookie in cookies.values(): self.assertEqual(cookie.value, "") self.assertEqual(cookie["max-age"], "0") self.assertTrue(cookie["httponly"]) self.assertEqual(cookie["samesite"], "strict") self.assertEqual(list(client.cookies.jar), []) for path in ("/", "/static/index.html", "/static/app.js"): with self.subTest(path=path): self.assertEqual(client.get(path, follow_redirects=False).status_code, 303) response = client.get(path, headers={"Cookie": f"{COOKIE_NAME}={token}"}, follow_redirects=False) self.assertEqual(response.status_code, 303) self.assertEqual(response.headers["location"], "/login") self.assertFalse(client.get("/api/auth/status").json()["authenticated"]) self.assertEqual(client.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401) def test_loopback_bypass_is_local_and_has_no_password_cookie(self): client = self.client() self.assertEqual(client.get("/api/auth/status").json(), {"required": False, "authenticated": True, "access_mode": "local"}) response = client.post("/api/accounts", json={"demo": True}, headers={"Origin": "http://localhost"}) self.assertEqual(response.status_code, 201) self.assertNotIn("set-cookie", response.headers) self.assertIn("WORKBENCH_ONLY", client.get("/").text) self.assertEqual(client.get("/login", follow_redirects=False).headers["location"], "/") remote = self.enterContext(TestClient(create_app(manager=self.manager, updates=self.updates, config=WebConfig(data_dir=self.root)), base_url="http://localhost", client=("192.0.2.1", 50001))) self.assertEqual(remote.get("/api/accounts").status_code, 403) self.assertFalse(remote.get("/api/auth/status").json()["authenticated"]) for path in ("/", "/static/index.html", "/static/app.js"): with self.subTest(path=path): response = remote.get(path, follow_redirects=False) self.assertEqual(response.status_code, 303) self.assertEqual(response.headers["location"], "/login") def test_remote_bind_and_public_proxy_names_require_password(self): for values in ({"host": "0.0.0.0"}, {"host": "::"}, {"host": "192.0.2.10"}, {"allowed_hosts": ("ranch.example",)}, {"allowed_origins": ("https://ranch.example",)}): with self.subTest(values=values), self.assertRaises(ValueError): WebConfig(data_dir=self.root, **values) def test_plain_password_cookie_login_logout_and_replay(self): client = self.client(WebConfig(data_dir=self.root, password="离线管理密码")) self.assertEqual(client.get("/api/accounts").status_code, 401) self.assertFalse(client.get("/api/auth/status").json()["authenticated"]) self.assertEqual(client.post("/api/auth/login", json={"password": "错误"}).status_code, 401) response = client.post("/api/auth/login", json={"password": "离线管理密码"}) self.assertEqual(response.status_code, 200) self.assertNotIn("离线管理密码", response.text) cookies = {cookie["path"]: cookie for cookie in self.cookie_headers(response)} cookie = cookies["/"] self.assertTrue(cookie["httponly"]) self.assertEqual(cookie["samesite"], "strict") self.assertEqual(cookie["max-age"], str(client.app.state.config.session_ttl)) self.assertFalse(cookie["secure"]) self.assertFalse(cookie["domain"]) self.assertEqual(cookies["/api"]["max-age"], "0") self.assertEqual(client.get("/").status_code, 200) self.assertEqual(client.get("/api/accounts").status_code, 200) token = client.cookies.get(COOKIE_NAME) self.assertEqual(len(token), 43) self.assertEqual(client.post("/api/auth/logout").status_code, 200) self.assertEqual(client.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401) def test_hash_password_authentication_and_secure_proxy_cookie(self): encoded = hash_password("offline-password", iterations=100_000) settings = WebConfig(data_dir=self.root, host="0.0.0.0", password_hash=encoded, secure_cookie=True, allowed_hosts=("ranch.example",), allowed_origins=("https://ranch.example",)) app = create_app(manager=self.manager, updates=self.updates, config=settings) client = self.enterContext(TestClient(app, base_url="https://ranch.example", client=("192.0.2.1", 50000))) response = client.post("/api/auth/login", json={"password": "offline-password"}, headers={"Origin": "https://ranch.example"}) self.assertEqual(response.status_code, 200) self.assertIn("Secure", response.headers["set-cookie"]) self.assertEqual(client.get("/api/accounts").status_code, 200) self.assertNotIn(encoded, repr(settings)) def test_wrong_password_is_rate_limited_without_changing_accounts(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) for _ in range(10): self.assertEqual(client.post("/api/auth/login", json={"password": "wrong"}).status_code, 401) response = client.post("/api/auth/login", json={"password": "wrong"}) self.assertEqual(response.status_code, 429) self.assertEqual(self.manager.calls, []) def test_concurrent_wrong_passwords_reserve_slots_without_serializing_other_peers(self): client = self.client(WebConfig(data_dir=self.root, password_hash=hash_password("correct", iterations=100_000))) self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}).status_code, 200) cookie = client.cookies.get(COOKIE_NAME) entered, release, counter_lock = threading.Event(), threading.Event(), threading.Lock() verifying = 0 def blocked_verification(password, configured): nonlocal verifying if password == "wrong": with counter_lock: verifying += 1 if verifying >= 10: entered.set() if not release.wait(5): raise AssertionError("password verification gate timed out") return verify_password(password, configured) async def scenario(): transport = httpx.ASGITransport(app=client.app, client=("127.0.0.1", 50001)) other_transport = httpx.ASGITransport(app=client.app, client=("127.0.0.2", 50002)) async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as http, httpx.AsyncClient(transport=other_transport, base_url="http://localhost") as other: rejected = 0 rejected_two = asyncio.Event() async def attempt(): nonlocal rejected response = await http.post("/api/auth/login", json={"password": "wrong"}) if response.status_code == 429: rejected += 1 if rejected == 2: rejected_two.set() return response.status_code tasks = [asyncio.create_task(attempt()) for _ in range(12)] try: self.assertTrue(await asyncio.to_thread(entered.wait, 2), "ten verifications must run concurrently") await asyncio.wait_for(rejected_two.wait(), 2) with counter_lock: self.assertEqual(verifying, 10) authenticated = await asyncio.wait_for(http.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={cookie}"}), 2) self.assertEqual(authenticated.status_code, 200) unrelated = await asyncio.wait_for(other.post("/api/auth/login", json={"password": "correct"}), 2) self.assertEqual(unrelated.status_code, 200) finally: release.set() outcomes = await asyncio.gather(*tasks) self.assertEqual(outcomes.count(401), 10) self.assertEqual(outcomes.count(429), 2) self.assertEqual((await http.post("/api/auth/login", json={"password": "wrong"})).status_code, 429) with counter_lock: self.assertEqual(verifying, 10) with patch("ranch_web.app.verify_password", side_effect=blocked_verification): asyncio.run(scenario()) self.assertEqual(self.manager.calls, ["list"]) def test_admin_password_does_not_corrupt_public_identifiers_or_versions(self): client = self.client(WebConfig(data_dir=self.root, password="1")) self.assertEqual(client.post("/api/auth/login", json={"password": "1"}).status_code, 200) self.assertEqual(client.get("/api/meta").json()["version"], "2.0.0.dev1") account = client.post("/api/accounts", json={"demo": True}).json() self.assertEqual(account["id"], "account_1") self.assertEqual(client.get("/api/accounts/account_1/status").status_code, 200) def test_dns_rebinding_and_forwarded_host_cannot_bypass_host_allowlist(self): client = self.client() for hostname in ("attacker.example", "localhost.attacker.example", "127.0.0.1.attacker.example", "attacker.example:8765", "localhost@attacker.example", "localhost/evil", "localhost:bad"): with self.subTest(hostname=hostname): response = client.post("/api/accounts", headers={"Host": hostname, "X-Forwarded-Host": "localhost"}, json={"demo": True}) self.assertEqual(response.status_code, 400) self.assertEqual(self.manager.calls, []) def test_cross_site_writes_including_auth_are_blocked_before_dispatch(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) for endpoint, payload in (("/api/auth/login", {"password": "correct"}), ("/api/auth/logout", {}), ("/api/accounts", {"demo": True}), ("/api/system/updates/apply", {})): for origin in ("https://attacker.example", "http://localhost.attacker.example", "null", "file://"): with self.subTest(endpoint=endpoint, origin=origin): self.assertEqual(client.post(endpoint, json=payload, headers={"Origin": origin}).status_code, 403) self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}, headers={"Sec-Fetch-Site": "cross-site"}).status_code, 403) self.assertEqual(self.manager.calls, []) def test_origin_includes_port_and_never_uses_forwarded_header(self): client = self.client() self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "http://localhost:8765"}).status_code, 403) self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "https://localhost", "X-Forwarded-Proto": "https"}).status_code, 403) self.assertEqual(client.post("/api/accounts", json={}, headers={"Origin": "http://localhost:80"}).status_code, 201) def test_no_wildcard_cors_and_errors_do_not_echo_password(self): client = self.client(WebConfig(data_dir=self.root, password="correct")) response = client.options("/api/accounts", headers={"Origin": "https://attacker.example", "Access-Control-Request-Method": "POST"}) self.assertNotIn("access-control-allow-origin", response.headers) response = client.post("/api/auth/login", json={"password": "SENSITIVE" * 1000}) self.assertEqual(response.status_code, 422) self.assertNotIn("SENSITIVE", response.text) def test_cookie_from_another_application_instance_is_invalid(self): settings = WebConfig(data_dir=self.root, password="correct") client = self.client(settings) client.post("/api/auth/login", json={"password": "correct"}) token = client.cookies.get(COOKIE_NAME) another = self.client(settings) self.assertEqual(another.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401) def test_environment_and_cli_overrides_use_same_names(self): settings = WebConfig.from_env({"RANCH_WEB_HOST": "0.0.0.0", "RANCH_WEB_PORT": "8766", "RANCH_WEB_DATA_DIR": str(self.root / "env"), "RANCH_WEB_PASSWORD": "offline", "RANCH_WEB_SECURE_COOKIE": "1"}, port=8767, data_dir=self.root / "override") self.assertEqual(settings.host, "0.0.0.0") self.assertEqual(settings.port, 8767) self.assertEqual(settings.data_dir, self.root / "override") self.assertTrue(settings.secure_cookie) self.assertNotIn("offline", repr(settings)) if __name__ == "__main__": unittest.main()