261 lines
15 KiB
Python
261 lines
15 KiB
Python
"""Exercise the public proxy contract without touching an existing installation."""
|
|
import json
|
|
import hashlib
|
|
import io
|
|
from base64 import b64encode
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
import unittest
|
|
from http import HTTPStatus
|
|
from unittest import mock
|
|
from urllib.parse import urlencode
|
|
|
|
from test_app import APP, DummyHandler
|
|
import app_support
|
|
import http_handler
|
|
|
|
|
|
class ProxyAuthTests(unittest.TestCase):
|
|
def test_session_lifetime_environment_values(self):
|
|
for value, expected in (("168", 604800), ("12", 43200), ("1", 3600),
|
|
("", 43200), ("invalid", 43200), ("0", 43200),
|
|
("-1", 43200), ("1.5", 43200)):
|
|
with self.subTest(value=value), mock.patch.dict(
|
|
os.environ, {"KAIZOKU_SESSION_TTL_HOURS": value}):
|
|
self.assertEqual(app_support.remote_access_session_ttl_seconds(), expected)
|
|
|
|
def test_configured_session_expiry_matches_cookie_and_survives_restart(self):
|
|
# A fresh process exercises startup configuration in both modules.
|
|
code = """
|
|
import app_support
|
|
from http_handler import Handler
|
|
config = {"auth_username": "owner", "auth_password": "test-password"}
|
|
assert app_support.REMOTE_ACCESS_SESSION_TTL_SECONDS == 604800
|
|
assert Handler.remote_session_cookie_max_age_seconds == 604800
|
|
from unittest import mock
|
|
with mock.patch.object(app_support.time, "time", return_value=1000000000):
|
|
token = app_support.create_remote_access_session(config)
|
|
assert app_support.remote_access_session_matches(token, config)
|
|
print(token)
|
|
"""
|
|
with tempfile.TemporaryDirectory() as state:
|
|
env = dict(os.environ, KAIZOKU_SESSION_TTL_HOURS="168", KAIZOKU_STATE_ROOT=state)
|
|
result = subprocess.run([sys.executable, "-c", code], env=env,
|
|
check=True, capture_output=True, text=True)
|
|
token = result.stdout.strip()
|
|
sessions = json.loads((Path(state) / "remote-sessions.json").read_text())
|
|
payload = sessions[app_support._remote_access_session_token_digest(token)]
|
|
expiry = payload["expires_at"]
|
|
self.assertEqual(expiry, 1000000000 + 604800)
|
|
code = f"""
|
|
import app_support
|
|
from unittest import mock
|
|
config = {{"auth_username": "owner", "auth_password": "test-password"}}
|
|
with mock.patch.object(app_support.time, "time", return_value={expiry - 1}):
|
|
assert app_support.remote_access_session_matches({token!r}, config)
|
|
with mock.patch.object(app_support.time, "time", return_value={expiry}):
|
|
assert not app_support.remote_access_session_matches({token!r}, config)
|
|
"""
|
|
# A new configured lifetime must not change an existing session's expiry.
|
|
env["KAIZOKU_SESSION_TTL_HOURS"] = "1"
|
|
subprocess.run([sys.executable, "-c", code], env=env,
|
|
check=True, capture_output=True, text=True)
|
|
|
|
def setUp(self):
|
|
self.config = {"base_url": "https://tools.coreplay.eu/kaizoku",
|
|
"auth_username": "owner", "auth_password": "long-test-password"}
|
|
self.env = mock.patch.dict(os.environ, {"KAIZOKU_BASE_URL": "", "KAIZOKU_ALLOW_REMOTE": "1",
|
|
"KAIZOKU_AUTH_USERNAME": "", "KAIZOKU_AUTH_PASSWORD": ""})
|
|
self.env.start()
|
|
self.addCleanup(self.env.stop)
|
|
http_handler.LOGIN_ATTEMPTS.clear()
|
|
|
|
def handler(self, path, payload=None):
|
|
body = urlencode(payload).encode() if payload is not None else b""
|
|
handler = DummyHandler(path, body, len(body))
|
|
handler.command = "POST" if payload is not None else "GET"
|
|
handler.headers.update({"Host": "internal:8421", "Origin": "https://tools.coreplay.eu",
|
|
"Content-Type": "application/x-www-form-urlencoded"})
|
|
handler.handler_context = mock.Mock(get_config_snapshot=lambda: dict(self.config), http_error=APP.HttpError,
|
|
index_html='<a href="/queue">Queue</a><script>api("/api/queue")</script>')
|
|
handler.html = lambda content: APP.Handler.html(handler, content)
|
|
handler.json = lambda payload, status=HTTPStatus.OK: APP.Handler.json(handler, payload, status)
|
|
return handler
|
|
|
|
def test_full_login_navigation_thumbnail_and_logout(self):
|
|
page = self.handler("/kaizoku/")
|
|
APP.Handler.do_GET(page)
|
|
self.assertEqual(page.response_status, 401) # Even though the socket peer is loopback.
|
|
html = page.wfile.getvalue().decode()
|
|
self.assertIn('action="/kaizoku/auth/login"', html)
|
|
csrf = re.search(r'name="csrf" value="([^"]+)"', html)[1]
|
|
login = self.handler("/kaizoku/auth/login", {"username": "owner", "password": "long-test-password",
|
|
"csrf": csrf, "next": "/queue"})
|
|
APP.Handler.do_POST(login)
|
|
self.assertEqual(login.response_status, 303)
|
|
headers = dict(login.response_headers)
|
|
self.assertEqual(headers["Location"], "/kaizoku/queue")
|
|
cookie = headers["Set-Cookie"]
|
|
for attribute in ("Path=/kaizoku", "Secure", "HttpOnly", "SameSite=Strict"):
|
|
self.assertIn(attribute, cookie)
|
|
session = cookie.split(";", 1)[0]
|
|
home = self.handler("/kaizoku/")
|
|
home.headers["Cookie"] = session
|
|
APP.Handler.do_GET(home)
|
|
self.assertEqual(home.response_status, 200)
|
|
self.assertIn(b'href="/kaizoku/queue"', home.wfile.getvalue())
|
|
self.assertIn(b'api("/kaizoku/api/queue")', home.wfile.getvalue())
|
|
image = self.handler("/kaizoku/api/watchlist")
|
|
APP.Handler.json(image, {"thumbnail_url": "/api/watchlist/thumb/show", "download_dir": "/downloads"})
|
|
self.assertEqual(json.loads(image.wfile.getvalue()),
|
|
{"thumbnail_url": "/kaizoku/api/watchlist/thumb/show", "download_dir": "/downloads"})
|
|
logout = self.handler("/kaizoku/auth/logout", {})
|
|
logout.headers["Cookie"] = session
|
|
APP.Handler.do_POST(logout)
|
|
self.assertEqual(logout.response_status, 303)
|
|
self.assertIn("Max-Age=0", dict(logout.response_headers)["Set-Cookie"])
|
|
self.assertFalse(app_support.remote_access_session_matches(session.split("=", 1)[1], self.config))
|
|
denied = self.handler("/kaizoku/api/config")
|
|
denied.headers["Cookie"] = session
|
|
APP.Handler.do_GET(denied)
|
|
self.assertEqual(denied.error_status, 403)
|
|
self.assertEqual(denied.wfile.getvalue(), b"")
|
|
|
|
def test_mount_boundary_and_redirect(self):
|
|
for path in ("/api/config", "/kaizoku-other/api/config"):
|
|
handler = self.handler(path)
|
|
APP.Handler.do_GET(handler)
|
|
self.assertEqual(handler.error_status, 404)
|
|
handler = self.handler("/kaizoku?x=1")
|
|
APP.Handler.do_GET(handler)
|
|
self.assertEqual(dict(handler.response_headers)["Location"], "/kaizoku/?x=1")
|
|
|
|
def test_search_poster_batch_and_image_stay_authenticated_and_mounted(self):
|
|
body = json.dumps({"query": "show", "titles": ["Show"]}).encode()
|
|
auth = "Basic " + b64encode(b"owner:long-test-password").decode()
|
|
batch = self.handler("/kaizoku/api/search/thumbnails")
|
|
batch.command = "POST"
|
|
batch.rfile = io.BytesIO(body)
|
|
batch.headers.update({"Authorization": auth, "Content-Type": "application/json", "Content-Length": str(len(body))})
|
|
batch.handler_context.resolve_search_thumbnails = mock.Mock(return_value={"Show": "/api/search/poster?key=search-123456789abc"})
|
|
APP.Handler.do_POST(batch)
|
|
self.assertEqual(batch.response_status, 200)
|
|
self.assertEqual(json.loads(batch.wfile.getvalue())["thumbnails"][0]["thumbnail_url"],
|
|
"/kaizoku/api/search/poster?key=search-123456789abc")
|
|
denied = self.handler("/kaizoku/api/search/poster?key=search-123456789abc")
|
|
APP.Handler.do_GET(denied)
|
|
self.assertEqual(denied.error_status, 403)
|
|
denied.handler_context.resolve_search_poster.assert_not_called()
|
|
|
|
def test_status_requires_basic_auth_even_with_a_browser_session(self):
|
|
session = app_support.create_remote_access_session(self.config)
|
|
for method in ("GET", "HEAD"):
|
|
for authorization in ("", "Basic invalid", "Basic " + b64encode(b"owner:wrong").decode()):
|
|
with self.subTest(method=method, authorization=authorization):
|
|
handler = self.handler("/kaizoku/status?source=monitor")
|
|
handler.command = method
|
|
handler.headers["Authorization"] = authorization
|
|
handler.headers["Cookie"] = f"{APP.Handler.remote_session_cookie_name}={session}"
|
|
getattr(APP.Handler, f"do_{method}")(handler)
|
|
self.assertEqual(handler.response_status, 401)
|
|
self.assertEqual(dict(handler.response_headers)["WWW-Authenticate"],
|
|
'Basic realm="Kaizoku status", charset="UTF-8"')
|
|
self.assertNotEqual(handler.wfile.getvalue(), b"OK\n")
|
|
|
|
def test_status_accepts_configured_and_hashed_basic_credentials(self):
|
|
for hashed in (False, True):
|
|
self.config["auth_password"] = (app_support.hash_login_password("long-test-password")
|
|
if hashed else "long-test-password")
|
|
for method in ("GET", "HEAD"):
|
|
with self.subTest(hashed=hashed, method=method):
|
|
handler = self.handler("/kaizoku/status")
|
|
handler.command = method
|
|
handler.headers["Authorization"] = "Basic " + b64encode(b"owner:long-test-password").decode()
|
|
getattr(APP.Handler, f"do_{method}")(handler)
|
|
self.assertEqual(handler.response_status, 200)
|
|
self.assertEqual(dict(handler.response_headers)["Content-Type"], "text/plain; charset=utf-8")
|
|
self.assertEqual(dict(handler.response_headers)["Cache-Control"], "no-store")
|
|
self.assertEqual(handler.wfile.getvalue(), b"OK\n" if method == "GET" else b"")
|
|
|
|
def test_bad_password_throttling_and_csrf(self):
|
|
for index in range(11):
|
|
handler = self.handler("/kaizoku/auth/login", {"username": "owner", "password": "wrong",
|
|
"csrf": APP.Handler._login_token(None)})
|
|
APP.Handler.do_POST(handler)
|
|
if index < 10:
|
|
self.assertEqual(handler.response_status, 401)
|
|
else:
|
|
self.assertEqual(handler.error_status, 429)
|
|
http_handler.LOGIN_ATTEMPTS.clear()
|
|
handler = self.handler("/kaizoku/auth/login", {"username": "owner", "password": "long-test-password"})
|
|
APP.Handler.do_POST(handler)
|
|
self.assertEqual(handler.error_status, 403)
|
|
|
|
def test_hash_config_and_unicode_password(self):
|
|
config = {"auth_username": "vlastník", "auth_password_hash": app_support.hash_login_password("české-heslo-🔐")}
|
|
self.assertTrue(app_support.remote_access_credentials_match("vlastník", "české-heslo-🔐", config))
|
|
self.assertFalse(app_support.remote_access_credentials_match("vlastník", "wrong", config))
|
|
self.assertNotIn("auth_password_hash", app_support.sanitize_public_config(config))
|
|
token = app_support.create_remote_access_session(config)
|
|
self.assertTrue(app_support.remote_access_session_matches(token, config))
|
|
app_support.revoke_remote_access_session(token)
|
|
self.assertFalse(app_support.remote_access_session_matches(token, config))
|
|
|
|
def test_successful_basic_auth_polling_does_not_exhaust_login_limit(self):
|
|
import base64
|
|
for _ in range(12):
|
|
handler = self.handler("/kaizoku/api/watchlist/homepage")
|
|
handler.headers["Authorization"] = "Basic " + base64.b64encode(b"owner:long-test-password").decode()
|
|
self.assertTrue(APP.Handler.ensure_dashboard_basic_auth(handler))
|
|
|
|
def test_invalid_mount_and_redirect_values(self):
|
|
for value in ("//evil.test/x", "https://host/a/../b", "https://u:p@host/a", "/foo?x=1", "/foo%2fbar"):
|
|
with self.assertRaises(ValueError, msg=value):
|
|
app_support.normalize_base_url(value)
|
|
handler = self.handler("/kaizoku/")
|
|
for value in ("//evil.test", "/\\evil.test", "https://evil.test", "/\r\nLocation: bad"):
|
|
self.assertEqual(APP.Handler._normalized_next_path(handler, value), "/")
|
|
|
|
def test_public_proxy_loopback_cannot_bypass_filesystem_roots(self):
|
|
handler = self.handler("/kaizoku/api/fs/browse")
|
|
with mock.patch.object(http_handler, "configured_remote_path_roots", return_value=[]):
|
|
with self.assertRaises(PermissionError):
|
|
APP.Handler.validate_remote_path(handler, "/etc", "download directory")
|
|
self.assertFalse(APP.Handler._unrestricted_local_paths(handler))
|
|
with mock.patch.object(http_handler, "configured_remote_path_roots", return_value=["/downloads"]):
|
|
with self.assertRaises(PermissionError):
|
|
APP.Handler.validate_remote_path(handler, "/etc", "download directory")
|
|
APP.Handler.validate_remote_path(handler, "/downloads/show", "download directory")
|
|
|
|
def test_csp_authorizes_only_trusted_scripts_after_mount_rewriting(self):
|
|
handler = self.handler("/kaizoku/")
|
|
trusted = handler.handler_context.index_html
|
|
APP.Handler.html(handler, trusted)
|
|
headers = dict(handler.response_headers)
|
|
policy = headers["Content-Security-Policy"]
|
|
script = re.search(r"<script>(.*?)</script>", handler.wfile.getvalue().decode(), re.S)[1]
|
|
digest = b64encode(hashlib.sha256(script.encode()).digest()).decode()
|
|
self.assertIn("'sha256-" + digest + "'", policy)
|
|
self.assertNotIn("'unsafe-inline'", policy.split("style-src")[0])
|
|
self.assertEqual(headers["Strict-Transport-Security"], "max-age=31536000")
|
|
injected = self.handler("/kaizoku/")
|
|
APP.Handler.html(injected, '<script>alert("injected")</script>')
|
|
self.assertNotIn("sha256-", dict(injected.response_headers)["Content-Security-Policy"])
|
|
|
|
def test_cross_site_metadata_and_untrusted_forwarded_host_are_rejected(self):
|
|
handler = self.handler("/kaizoku/")
|
|
handler.headers["Sec-Fetch-Site"] = "cross-site"
|
|
with self.assertRaises(PermissionError):
|
|
APP.Handler.enforce_same_origin(handler)
|
|
self.config["base_url"] = ""
|
|
handler.headers.update({"X-Forwarded-Host": "evil.example", "Origin": "http://evil.example"})
|
|
self.assertFalse(APP.Handler._origin_matches_host(handler))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|