198 lines
12 KiB
Python
198 lines
12 KiB
Python
"""Administrator sessions and browser boundary checks, entirely offline."""
|
|
|
|
import asyncio
|
|
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()
|
|
|
|
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)
|
|
return self.enterContext(TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50000), **kwargs))
|
|
|
|
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)
|
|
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"])
|
|
|
|
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)
|
|
cookie = response.headers["set-cookie"].lower()
|
|
self.assertIn("httponly", cookie)
|
|
self.assertIn("samesite=strict", cookie)
|
|
self.assertIn("path=/api", cookie)
|
|
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()
|