fix: support authenticated web deployments under a reverse proxy path
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
"""Offline Edge regressions for externally prefixed deployments.
|
||||
|
||||
Run: python -B -m unittest ranch_web.tests.browser.test_base_path_browser -v
|
||||
Only disposable demo accounts and a synthetic administrator password are used.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
|
||||
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 BasePathBrowserTests(unittest.TestCase):
|
||||
password = "offline-prefix-password-not-a-real-credential"
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
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)
|
||||
|
||||
def check_deployment(self, prefix, *, strip_prefix=False):
|
||||
import uvicorn
|
||||
from ranch_web.app import create_app
|
||||
from ranch_web.config import WebConfig
|
||||
from ranch_web.service import WebManager
|
||||
|
||||
network = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden"))
|
||||
network.start()
|
||||
self.addCleanup(network.stop)
|
||||
temp = tempfile.TemporaryDirectory(prefix="ranch-web-prefix-browser-")
|
||||
self.addCleanup(temp.cleanup)
|
||||
manager = WebManager(temp.name, start_scheduler=False)
|
||||
self.addCleanup(manager.close)
|
||||
account = manager.create_account("Offline prefix demo", demo=True)["id"]
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
origin = f"http://127.0.0.1:{port}"
|
||||
base = origin + prefix
|
||||
app = create_app(manager=manager, config=WebConfig(
|
||||
port=port, data_dir=Path(temp.name), password=self.password, base_path=prefix,
|
||||
), updates=OfflineUpdates())
|
||||
|
||||
async def proxy(scope, receive, send):
|
||||
# Model a proxy that removes the external prefix before forwarding.
|
||||
if strip_prefix and scope["type"] == "http" and scope["path"].startswith(prefix + "/"):
|
||||
scope = {**scope, "path": scope["path"][len(prefix):],
|
||||
"raw_path": scope["raw_path"][len(prefix):]}
|
||||
await app(scope, receive, send)
|
||||
|
||||
server = uvicorn.Server(uvicorn.Config(proxy, host="127.0.0.1", port=port, log_level="error"))
|
||||
thread = threading.Thread(target=server.run, daemon=True)
|
||||
thread.start()
|
||||
|
||||
def stop_server():
|
||||
server.should_exit = True
|
||||
thread.join(timeout=10)
|
||||
|
||||
self.addCleanup(stop_server)
|
||||
deadline = time.monotonic() + 15
|
||||
while not server.started and time.monotonic() < deadline:
|
||||
time.sleep(.02)
|
||||
self.assertTrue(server.started, "Temporary prefixed browser server failed to start")
|
||||
context = self.browser.new_context(viewport={"width": 1280, "height": 800})
|
||||
self.addCleanup(context.close)
|
||||
requests, escapes, errors = [], [], []
|
||||
|
||||
def offline_only(route):
|
||||
if route.request.url.startswith(base + "/"):
|
||||
route.continue_()
|
||||
else:
|
||||
escapes.append(route.request.url)
|
||||
route.abort()
|
||||
|
||||
context.route("**/*", offline_only)
|
||||
context.on("request", lambda request: requests.append(request))
|
||||
page = context.new_page()
|
||||
page.on("pageerror", lambda failure: errors.append(str(failure)))
|
||||
page.on("console", lambda message: errors.append(message.text) if message.type == "error"
|
||||
and ("security policy" in message.text.lower() or "csp" in message.text.lower()) else None)
|
||||
|
||||
def assert_login():
|
||||
expect(page).to_have_url(base + "/login")
|
||||
expect(page.locator("#auth-form")).to_be_visible()
|
||||
expect(page.locator("#admin-password")).to_be_enabled()
|
||||
expect(page.locator("#auth-form")).to_have_attribute("action", prefix + "/api/auth/login")
|
||||
self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs, #page-host").count(), 0)
|
||||
self.assertEqual(page.locator("script").count(), 1)
|
||||
expect(page.locator("script")).to_have_attribute("src", prefix + "/static/login.js")
|
||||
expect(page.locator('link[rel="stylesheet"]')).to_have_attribute("href", prefix + "/static/login.css")
|
||||
expect(page.locator('meta[name="ranch-web-base-path"]')).to_have_attribute("content", prefix)
|
||||
|
||||
response = page.goto(base + "/", wait_until="networkidle")
|
||||
assert_login()
|
||||
self.assertEqual(response.headers["cache-control"], "no-store")
|
||||
self.assertIn("script-src 'self'", response.headers["content-security-policy"])
|
||||
self.assertEqual([urlsplit(request.url).path for request in requests if request.resource_type == "script"],
|
||||
[prefix + "/static/login.js"])
|
||||
self.assertIn(base + "/api/auth/status", [request.url for request in requests])
|
||||
|
||||
page.locator("#admin-password").fill(self.password)
|
||||
with page.expect_response(base + "/api/auth/login") as login:
|
||||
page.locator('#auth-form button[type="submit"]').click()
|
||||
self.assertEqual(login.value.status, 200)
|
||||
self.assertEqual(login.value.request.post_data_json, {"password": self.password})
|
||||
expect(page).to_have_url(base + "/")
|
||||
expect(page.locator("#app")).to_be_visible()
|
||||
expect(page.locator("#status-text")).to_have_text("工作台已连接")
|
||||
expect(page.locator("#save-status")).to_have_text("策略已自动保存")
|
||||
expect(page.locator('link[rel="stylesheet"]')).to_have_attribute("href", prefix + "/static/styles.css")
|
||||
self.assertEqual(context.cookies()[0]["path"], prefix or "/")
|
||||
self.assertEqual(page.evaluate("localStorage.length + sessionStorage.length"), 0)
|
||||
|
||||
for key in "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split():
|
||||
page.locator(f'.page-tab[data-page="{key}"]').click()
|
||||
panel = page.locator(f'.page-panel[data-page="{key}"]:not([hidden])')
|
||||
expect(panel.locator('.page-loading[data-loading="false"]')).to_have_count(1)
|
||||
self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0)
|
||||
|
||||
# The server redirects an authenticated login URL back to this workbench.
|
||||
page.goto(base + "/login", wait_until="networkidle")
|
||||
expect(page).to_have_url(base + "/")
|
||||
expect(page.locator("#status-text")).to_have_text("工作台已连接")
|
||||
cookies = context.cookies()
|
||||
page.locator(".menu > summary").first.click()
|
||||
with page.expect_response(base + "/api/auth/logout") as logout:
|
||||
page.locator('[data-command="admin-logout"]').click()
|
||||
self.assertEqual(logout.value.status, 200)
|
||||
assert_login()
|
||||
self.assertEqual(context.cookies(), [])
|
||||
context.add_cookies(cookies)
|
||||
page.goto(base + "/", wait_until="networkidle")
|
||||
assert_login()
|
||||
self.assertEqual(escapes, [], "Browser requests escaped the configured prefix or local server")
|
||||
self.assertEqual(errors, [], "JavaScript or CSP errors")
|
||||
self.assertTrue(any(request.url == base + "/static/paths.js" for request in requests))
|
||||
|
||||
def test_preserved_prefix(self):
|
||||
self.check_deployment("/ranch")
|
||||
|
||||
def test_proxy_strips_nested_prefix(self):
|
||||
self.check_deployment("/tools/ranch", strip_prefix=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user