127 lines
6.7 KiB
Python
127 lines
6.7 KiB
Python
"""Exercise the public proxy contract without touching an existing installation."""
|
|
import json
|
|
import os
|
|
import re
|
|
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 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_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), "/")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|