feat: require standalone admin login before the web workbench

This commit is contained in:
AttilaNet
2026-11-10 19:03:22 +08:00
parent 664db51d3b
commit 0230a933b0
12 changed files with 710 additions and 41 deletions
@@ -0,0 +1,282 @@
"""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
from pathlib import Path
import socket
import tempfile
import threading
import time
import unittest
from unittest.mock import patch
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates
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.errors = []
self.csp_errors = []
self.page.on("request", lambda request: self.requests.append(request.url))
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, #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(self.base + "/")
expect(self.page.locator("#app")).to_be_visible()
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
expect(self.page.locator("#status-text")).to_have_text("工作台已连接")
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
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))
page.goto(self.base + "/", wait_until="networkidle")
self.assert_login_only(page)
self.assertFalse(any(url.endswith("/static/app.js") for url in requested))
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())
response = context.request.get(self.base + "/static/app.js", max_redirects=0)
self.assertIn(response.status, (302, 303, 307, 401, 403))
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.assertFalse(any(url.endswith(("/app.js", "/api.js", "/pages.js", "/dom.js", "/ui.js")) for url in self.requests))
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")
expect(self.page).to_have_url(self.base + "/")
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
snapshots = self.observe_login_transition()
self.page.locator(".menu > summary").first.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 or url.endswith("/app.js") for url in self.requests))
def test_expired_server_session_hides_workbench_and_rejects_old_cookie(self):
self.login()
cookies = self.context.cookies()
self.page.locator(".menu > summary").nth(3).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('#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, #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()
@@ -124,6 +124,14 @@ class WorkbenchBrowserTests(unittest.TestCase):
def fulfill(route, data):
route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False))
def test_local_no_password_login_route_returns_to_workbench(self):
self.page.goto(self.base + "/login", wait_until="networkidle")
expect(self.page).to_have_url(self.base + "/")
expect(self.page.locator("#app")).to_be_visible()
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
self.assertEqual(self.errors, [])
def test_all_pages_are_read_only_csp_clean_and_responsive(self):
self.open()
writes = []
+11 -5
View File
@@ -513,12 +513,18 @@ class ApiTests(unittest.TestCase):
for url in ("/static/.env", "/static/config.py", "/static/../app.py", "/static/%2e%2e/requirements.txt"):
with self.subTest(url=url):
self.assertEqual(self.client.get(url).status_code, 404)
response = self.client.get("/")
self.assertIn(response.status_code, (200, 503))
if response.status_code == 200:
for url in ("/", "/static/index.html", "/static/app.js"):
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers["cache-control"], "no-store")
self.assertEqual(response.headers["x-content-type-options"], "nosniff")
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
for url in ("/", "/static/index.html"):
response = self.client.get(url)
self.assertIn("text/html", response.headers["content-type"])
self.assertEqual(response.headers["x-content-type-options"], "nosniff")
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
response = self.client.get("/login", follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/")
def test_cli_help_and_factory_do_not_import_qt_or_open_private_state(self):
project = Path(__file__).resolve().parents[2]
+180 -5
View File
@@ -1,6 +1,7 @@
"""Administrator sessions and browser boundary checks, entirely offline."""
import asyncio
from http.cookies import SimpleCookie
from pathlib import Path
import tempfile
import threading
@@ -21,21 +22,190 @@ class AuthTests(unittest.TestCase):
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": '<html><nav>WORKBENCH_ONLY</nav><script src="/static/app.js"></script></html>',
"login.html": '<html><form>ADMIN_LOGIN_ONLY</form><script src="/static/login.js"></script></html>',
"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)
app = create_app(manager=self.manager, updates=self.updates, config=settings)
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",)}):
@@ -50,10 +220,15 @@ class AuthTests(unittest.TestCase):
response = client.post("/api/auth/login", json={"password": "离线管理密码"})
self.assertEqual(response.status_code, 200)
self.assertNotIn("离线管理密码", response.text)
cookie = response.headers["set-cookie"].lower()
self.assertIn("httponly", cookie)
self.assertIn("samesite=strict", cookie)
self.assertIn("path=/api", cookie)
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)