Secure reverse-proxy deployments with login and configurable base URL

This commit is contained in:
Dymas committed 2026-10-22 12:01:58 +02:00
1 parent 15f5f96513
commit 400a2d247d
13 files changed
+427 -38

No files matched your search

+3 -1
View File
@@ -12,4 +12,6 @@ venv
env
*.log
_backup_/
_tmp_/
_tmp_/
.env
.env.*
+2
View File
@@ -13,3 +13,5 @@ env/
*.log
_backup_/
_tmp_/
.env
.env.*
+8
View File
@@ -1,5 +1,13 @@
# Changelog
## 0.55.0 - 2026-10-22
- Added configurable `base_url` / `KAIZOKU_BASE_URL` for reverse proxies that forward a complete mount path such as `https://tools.coreplay.eu/kaizoku`. Navigation, APIs, thumbnails, exports, login redirects, and cookies respect the prefix; unrelated paths return 404.
- Require authentication for every client when credentials are configured, including loopback proxy peers. Public base URLs fail closed without credentials. Added login form CSRF validation, per-peer throttling (10 attempts per 15 minutes), same-origin checks using the canonical public URL, and server-side logout revocation.
- Store newly saved config passwords as salted scrypt hashes and keep existing config credentials compatible. Sessions expire after 12 hours; HTTPS cookies use Secure, HttpOnly, SameSite=Strict, and the mount path. Added browser response security headers.
- Added base URL and credential settings under Config → General, and Compose support for `KAIZOKU_BASE_URL`. Existing state, queues, watchlists, thumbnails, downloads, and library files remain in place.
- Checked all three providers against upstream revision `04d3645b926197d0fc3cc51a6413627f6cbb0ee0`; no updates were required and existing Kaizoku patches were preserved.
## 0.54.18 - 2026-10-18
- Added a Queue page size selector beside Previous and Next with 10, 25, 50, and 100 items per page. The queue API now accepts up to 100 items per page.
+31 -1
View File
@@ -34,6 +34,36 @@ Keep **`.kaizoku/`**, `backup/`, downloads, and Jellyfin library folders when up
On the Queue page, choose 10, 25, 50, or 100 items per page beside the Previous and Next buttons. In **Config → Watchlist management**, use each list's **Refresh** checkbox to choose which lists are included in manual and scheduled bulk refreshes, then save the configuration. Watching and Planned are selected by default; custom lists can also be selected.
## VPS login and Nginx Proxy Manager
Set these values in the `.env` file beside `docker-compose.yaml` before starting the container:
```dotenv
KAIZOKU_ALLOW_REMOTE=1
KAIZOKU_BASE_URL=https://tools.coreplay.eu/kaizoku
KAIZOKU_AUTH_USERNAME=your-admin-name
KAIZOKU_AUTH_PASSWORD=replace-with-a-long-unique-password
```
Keep `.env` private. Use **Config → General** to set the public base URL and login credentials instead, or edit `base_url`, `auth_username`, and `auth_password` in `.kaizoku/config.json` with Kaizoku stopped. Environment values take precedence. Config passwords are converted to salted scrypt hashes when settings are saved; a blank password field keeps the saved password. You can use `/kaizoku` as the base URL when the proxy supplies the public Host and `X-Forwarded-Proto` headers; the full HTTPS URL is recommended.
In Nginx Proxy Manager, use a proxy host for `tools.coreplay.eu` with a valid TLS certificate and **Force SSL** enabled. Add a **Custom location** `/kaizoku` pointing to Kaizoku's container/host on port `8421` over HTTP. Forward the request URI unchanged: no prefix stripping, rewrite, or trailing URI on `proxy_pass` is needed. Other locations on the domain can keep their existing backends. The equivalent Nginx location is:
```nginx
location /kaizoku {
proxy_pass http://kaizoku:8421;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
```
Open **https://tools.coreplay.eu/kaizoku/** and sign in. `/kaizoku` redirects to `/kaizoku/`; paths outside the mount return 404. After changing the base URL, reopen the app at the new address. Keep the backend port reachable only by the proxy (for example, on their shared Docker network or behind the VPS firewall).
Configured credentials protect pages and APIs even when the proxy connects over loopback. A configured public base URL without credentials denies access. New sessions last 12 hours, survive restarts, and use path-scoped HttpOnly/SameSite=Strict cookies with Secure for HTTPS. **Sign out** revokes that browser's session; changing credentials revokes existing sessions. Login forms require a valid CSRF value and login attempts are limited to 10 per socket peer per 15 minutes (clients behind one proxy share this limit; limits reset on app restart). API clients can use HTTP Basic authentication over HTTPS; browser mutations must have the public same-origin `Origin` header. The `/kaizoku/status` endpoint also requires authentication when login is configured.
An existing local installation without credentials and without a public base URL retains local-only access. Updates preserve all existing volumes and state; reuse the same mounts when moving the instance to the VPS.
## Documentation
See the **[Kaizoku wiki](https://gitea.coreplay.eu/Dymas/kaizoku/wiki)** for detailed instructions:
@@ -45,6 +75,6 @@ See the **[Kaizoku wiki](https://gitea.coreplay.eu/Dymas/kaizoku/wiki)** for det
- [Data safety](https://gitea.coreplay.eu/Dymas/kaizoku/wiki/Data-Safety)
- [Providers and upstream versions](https://gitea.coreplay.eu/Dymas/kaizoku/wiki/Providers)
Provider parsers are adapted from [TheYogMehta/extensions](https://github.com/TheYogMehta/extensions). Bundled versions are Anikoto **6.0.0**, AniNeko **4.0.0**, and AnimePahe **6.0.1**, checked on 2026-10-18. Anikoto retains Kaizoku search, dub detection, and stream patches; AnimePahe uses only the official `.pw`, `.com`, and `.org` mirrors with bounded search retries and bridge-compatible logging. Upstream hooks that require StrawVerse's browser or mapping database are inactive in Kaizoku.
Provider parsers are adapted from [TheYogMehta/extensions](https://github.com/TheYogMehta/extensions). Bundled versions are Anikoto **6.0.0**, AniNeko **4.0.0**, and AnimePahe **6.0.1**, checked on 2026-10-22. Anikoto retains Kaizoku search, dub detection, and stream patches; AnimePahe uses only the official `.pw`, `.com`, and `.org` mirrors with bounded search retries and bridge-compatible logging. Upstream hooks that require StrawVerse's browser or mapping database are inactive in Kaizoku.
Live source checks on 2026-10-17 returned Anikoto search results; AniNeko returned no matches and all three AnimePahe mirrors returned HTTP 403 from the test host. Current provider code does not guarantee source availability. Kaizoku does not host media.
+1 -1
View File
@@ -1 +1 @@
0.54.18
0.55.0
+4
View File
@@ -51,6 +51,7 @@ from app_support import (
WORKER_SHUTDOWN_TIMEOUT_SECONDS,
background_workers_enabled,
clear_remote_access_sessions,
hash_login_password,
debug_log,
ensure_project_app_root,
load_json,
@@ -3492,6 +3493,9 @@ def save_runtime_config(config):
if isinstance(config, dict):
merged.update(config)
normalized = normalize_config(merged)
if normalized.get("auth_password"):
normalized["auth_password_hash"] = hash_login_password(normalized["auth_password"])
normalized["auth_password"] = ""
previous_fingerprint = remote_access_session_fingerprint(current)
next_fingerprint = remote_access_session_fingerprint(normalized)
scheduler = None
+57 -10
View File
@@ -79,7 +79,7 @@ DISCORD_WEBHOOK_EVENT_LABELS = {
"watchlist_refresh_interrupted": "Refresh interrupted by shutdown or restart",
"runtime_error": "Unexpected runtime errors",
}
REMOTE_ACCESS_SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
REMOTE_ACCESS_SESSION_TTL_SECONDS = 12 * 60 * 60
REMOTE_SESSION_STORE_LOCK = threading.RLock()
@@ -120,6 +120,36 @@ def debug_enabled():
return DEBUG_MODE or env_flag("KAIZOKU_DEBUG")
def normalize_base_url(value):
"""Accept an external HTTP(S) URL or an unambiguous mount path."""
raw = str(value or "").strip().rstrip("/")
if not raw:
return ""
parsed = urlparse(raw)
if parsed.query or parsed.fragment or parsed.params or parsed.username or parsed.password:
raise ValueError("Base URL must not contain credentials, parameters, a query, or a fragment.")
if parsed.scheme or parsed.netloc:
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
raise ValueError("Base URL must use http or https.")
parsed.port # Validate port syntax before using the URL in headers.
elif not raw.startswith("/") or raw.startswith("//"):
raise ValueError("Base URL must be an http(s) URL or a path starting with /.")
path = parsed.path.rstrip("/")
if not re.fullmatch(r"(?:/[A-Za-z0-9_-]+)*", path):
raise ValueError("Base URL path must use letters, digits, hyphens, or underscores.")
return raw
def configured_base_url(config=None):
return normalize_base_url(env_value("KAIZOKU_BASE_URL") or (config or {}).get("base_url", ""))
def hash_login_password(password):
salt = secrets.token_hex(16)
digest = hashlib.scrypt(str(password).encode(), salt=bytes.fromhex(salt), n=16384, r=8, p=1).hex()
return f"scrypt${salt}${digest}"
def remote_access_allowed():
return env_flag("KAIZOKU_ALLOW_REMOTE")
@@ -138,7 +168,7 @@ def remote_access_password(config=None):
if configured:
return configured
if isinstance(config, dict):
return str(config.get("auth_password") or "").strip()
return str(config.get("auth_password") or config.get("auth_password_hash") or "").strip()
return ""
@@ -151,12 +181,19 @@ def remote_access_credentials_match(username, password, config=None):
expected_password = remote_access_password(config)
provided_username = str(username or "").strip()
provided_password = str(password or "").strip()
return bool(
expected_username
and expected_password
and hmac.compare_digest(provided_username, expected_username)
and hmac.compare_digest(provided_password, expected_password)
)
if not expected_username or not expected_password:
return False
username_matches = hmac.compare_digest(provided_username.encode(), expected_username.encode())
if expected_password.startswith("scrypt$"):
try:
_, salt, expected = expected_password.split("$")
actual = hashlib.scrypt(provided_password.encode(), salt=bytes.fromhex(salt), n=16384, r=8, p=1).hex()
password_matches = hmac.compare_digest(actual, expected)
except (ValueError, TypeError):
password_matches = False
else:
password_matches = hmac.compare_digest(provided_password.encode(), expected_password.encode())
return username_matches and password_matches
def remote_access_session_value(config=None):
@@ -238,10 +275,17 @@ def remote_access_session_matches(value, config=None):
return False
return bool(
hmac.compare_digest(str(payload.get("fingerprint") or ""), fingerprint)
and hmac.compare_digest(str(payload.get("username") or ""), username)
and hmac.compare_digest(str(payload.get("username") or "").encode(), username.encode())
)
def revoke_remote_access_session(value):
with REMOTE_SESSION_STORE_LOCK:
sessions = _load_remote_access_sessions_locked()
sessions.pop(_remote_access_session_token_digest(value), None)
_write_remote_access_sessions_locked(sessions)
def clear_remote_access_sessions(config=None):
expected_fingerprint = str(config.get("fingerprint") or "") if isinstance(config, dict) else ""
with REMOTE_SESSION_STORE_LOCK:
@@ -333,10 +377,12 @@ DEFAULT_CONFIG = {
"ai_subtitle_openai_model": "gpt-4.1-mini",
"discord_webhook_url": "",
"discord_webhook_events": [],
"base_url": env_value("KAIZOKU_BASE_URL"),
"auth_password_hash": "",
"auth_username": env_value("KAIZOKU_AUTH_USERNAME"),
"auth_password": env_value("KAIZOKU_AUTH_PASSWORD"),
}
PRIVATE_CONFIG_KEYS = {"auth_username", "auth_password", "ai_subtitle_openai_api_key"}
PRIVATE_CONFIG_KEYS = {"auth_password_hash", "auth_username", "auth_password", "ai_subtitle_openai_api_key"}
def now_iso():
@@ -531,6 +577,7 @@ def normalize_config(data):
normalized_events.append(normalized_name)
config["discord_webhook_url"] = webhook_url
config["discord_webhook_events"] = normalized_events
config["base_url"] = normalize_base_url(config.get("base_url"))
config["auth_username"] = auth_username
config["auth_password"] = auth_password
return config
+13
View File
@@ -542,6 +542,13 @@ CONFIG_HTML = r"""<!doctype html>
</div>
<div class="stack">
<label>Public base URL
<input id="baseUrl" placeholder="https://tools.coreplay.eu/kaizoku">
</label>
<p class="muted">Use the full public URL or a path such as /kaizoku. The proxy must forward this path unchanged. KAIZOKU_BASE_URL overrides this setting. Reload at the new URL after saving.</p>
<label>Login username<input id="authUsername" autocomplete="username" placeholder="Leave blank to keep current username"></label>
<label>New login password<input id="authPassword" type="password" autocomplete="new-password" placeholder="Leave blank to keep current password"></label>
<p class="muted">Login protects all clients, including local proxy connections. Environment credentials override saved credentials. Changing credentials signs out existing sessions.</p>
<label>Default folder
<div class="path-input">
<input id="downloadDir" placeholder="/home/me/Downloads/Anime">
@@ -898,6 +905,7 @@ CONFIG_HTML = r"""<!doctype html>
function formConfigPayload() {
const payload = {
base_url: $("baseUrl").value,
download_dir: $("downloadDir").value,
mode: $("configMode").value,
quality: $("configQuality").value,
@@ -930,6 +938,8 @@ CONFIG_HTML = r"""<!doctype html>
discord_webhook_url: $("discordWebhookUrl").value,
discord_webhook_events: selectedWebhookEvents()
};
if ($("authUsername").value.trim()) payload.auth_username = $("authUsername").value.trim();
if ($("authPassword").value) payload.auth_password = $("authPassword").value;
if ($("aiOpenaiKey").value.trim()) payload.ai_subtitle_openai_api_key = $("aiOpenaiKey").value.trim();
else if ($("aiOpenaiClearKey").checked) payload.ai_subtitle_openai_api_key = "";
return payload;
@@ -960,6 +970,9 @@ CONFIG_HTML = r"""<!doctype html>
function applyConfig(data) {
state.config = data;
$("baseUrl").value = data.base_url || "";
$("authUsername").value = "";
$("authPassword").value = "";
$("downloadDir").value = data.download_dir;
$("configMode").value = data.mode;
$("configQuality").value = data.quality;
+1
View File
@@ -13,6 +13,7 @@ services:
USER_GID: ${USER_GID:-}
KAIZOKU_HOST: 0.0.0.0
KAIZOKU_PORT: 8421
KAIZOKU_BASE_URL: ${KAIZOKU_BASE_URL:-}
KAIZOKU_ALLOW_REMOTE: ${KAIZOKU_ALLOW_REMOTE:-false}
KAIZOKU_AUTH_USERNAME: ${KAIZOKU_AUTH_USERNAME:-}
KAIZOKU_AUTH_PASSWORD: ${KAIZOKU_AUTH_PASSWORD:-}
+172 -23
View File
@@ -2,6 +2,12 @@
"""HTTP handler and route wiring for Kaizoku."""
import hashlib
import hmac
import re
import secrets
import threading
import time
import json
import mimetypes
import shutil
@@ -30,6 +36,8 @@ from app_support import (
VERSION,
client_address_is_local,
configured_remote_path_roots,
configured_base_url,
revoke_remote_access_session,
debug_enabled,
debug_log,
env_value,
@@ -41,11 +49,16 @@ from app_support import (
remote_access_credentials_match,
remote_access_session_matches,
remote_access_session_value,
REMOTE_ACCESS_SESSION_TTL_SECONDS,
sanitize_public_config,
send_discord_webhook_event,
validate_discord_webhook_url,
)
LOGIN_SECRET = secrets.token_bytes(32)
LOGIN_ATTEMPTS = {}
LOGIN_LOCK = threading.Lock()
FAVICON_PATH = PROJECT_ROOT / "favicon.png"
@@ -268,9 +281,66 @@ def queue_clear_failed(runtime, queue_type="all"):
class Handler(BaseHTTPRequestHandler):
server_version = "Kaizoku/0.1"
remote_session_cookie_name = "kaizoku_session"
remote_session_cookie_max_age_seconds = 30 * 24 * 60 * 60
remote_session_cookie_max_age_seconds = REMOTE_ACCESS_SESSION_TTL_SECONDS
quiet_poll_paths = {"/status", "/api/queue", "/api/watchlist/refresh-status", "/api/config/jellyfin/sync-status"}
def _config(self):
config = Handler._context(self).get_config_snapshot()
return config if isinstance(config, dict) else {}
def _base_url(self):
return configured_base_url(Handler._config(self))
def _base_path(self):
return urlparse(Handler._base_url(self)).path.rstrip("/")
def _external_path(self, path):
base = Handler._base_path(self)
if base and (path == base or path.startswith(base + "/")):
return path
return base + path
def _route(self):
"""Keep routing internal while the proxy forwards the complete mount path."""
parsed = urlparse(self.path)
base = Handler._base_path(self)
if base:
if parsed.path == base:
Handler.write_response_bytes(self, b"", HTTPStatus.PERMANENT_REDIRECT,
{"Location": base + "/" + ("?" + parsed.query if parsed.query else "")})
return None
if not parsed.path.startswith(base + "/"):
self.error(HTTPStatus.NOT_FOUND, "Not found")
return None
parsed = parsed._replace(path=parsed.path[len(base):])
return parsed
def _login_token(self):
timestamp = str(int(time.time()) // 600)
return timestamp + "." + hmac.new(LOGIN_SECRET, timestamp.encode(), hashlib.sha256).hexdigest()
def _check_login_token(self, value):
timestamp, _, signature = str(value or "").partition(".")
if timestamp not in {str(int(time.time()) // 600), str(int(time.time()) // 600 - 1)}:
return False
expected = hmac.new(LOGIN_SECRET, timestamp.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(signature, expected)
def _check_login_rate(self):
# Use the socket peer, never attacker-controlled forwarded addresses.
peer = self.client_address[0]
now = time.monotonic()
with LOGIN_LOCK:
for key in list(LOGIN_ATTEMPTS):
if LOGIN_ATTEMPTS[key][1] < now - 900:
del LOGIN_ATTEMPTS[key]
count, _ = LOGIN_ATTEMPTS.get(peer, (0, now))
if count >= 10:
raise Handler._context(self).http_error(
HTTPStatus.TOO_MANY_REQUESTS, "Too many login attempts. Try again in 15 minutes.")
LOGIN_ATTEMPTS[peer] = (count + 1, now)
return True
def _context(self):
context = getattr(self, "handler_context", None) or getattr(type(self), "handler_context", None)
if context is None:
@@ -317,6 +387,9 @@ class Handler(BaseHTTPRequestHandler):
return str(self.headers.get("Authorization") or self.headers.get("authorization") or "").strip()
def _host_header(self):
canonical = urlparse(Handler._base_url(self))
if canonical.netloc:
return canonical.netloc
host = str(self.headers.get("X-Forwarded-Host") or self.headers.get("x-forwarded-host") or "").strip()
if host:
return host.split(",", 1)[0].strip()
@@ -329,6 +402,9 @@ class Handler(BaseHTTPRequestHandler):
return str(self.headers.get("Content-Type") or self.headers.get("content-type") or "").strip()
def _request_is_secure(self):
canonical = urlparse(Handler._base_url(self))
if canonical.scheme:
return canonical.scheme == "https"
forwarded_proto = str(self.headers.get("X-Forwarded-Proto") or self.headers.get("x-forwarded-proto") or "").strip()
if forwarded_proto:
return forwarded_proto.split(",", 1)[0].strip().lower() == "https"
@@ -347,7 +423,8 @@ class Handler(BaseHTTPRequestHandler):
parsed = urlparse(origin)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
return False
return parsed.netloc.lower() == Handler._host_header(self).lower()
return (parsed.netloc.lower() == Handler._host_header(self).lower()
and parsed.scheme == ("https" if Handler._request_is_secure(self) else "http"))
def _basic_auth_credentials(self):
header = Handler._authorization_header(self)
@@ -384,19 +461,34 @@ class Handler(BaseHTTPRequestHandler):
def _remote_credentials_valid(self):
session = Handler._session_cookie(self)
if session and remote_access_session_matches(session):
if session and remote_access_session_matches(session, Handler._config(self)):
return True
return Handler._basic_credentials_valid(self)
def _basic_credentials_valid(self):
username, password = Handler._basic_auth_credentials(self)
return remote_access_credentials_match(username, password)
if not username and not password:
return False
Handler._check_login_rate(self)
valid = remote_access_credentials_match(username, password, Handler._config(self))
if valid:
with LOGIN_LOCK:
LOGIN_ATTEMPTS.pop(self.client_address[0], None)
return valid
def _normalized_next_path(self, value):
raw = str(value or "").strip()
if not raw:
return "/"
if "\\" in raw or any(ord(char) < 32 for char in raw) or raw.startswith("//"):
return "/"
parsed = urlparse(raw)
if parsed.scheme or parsed.netloc:
return "/"
path = parsed.path or "/"
base = Handler._base_path(self)
if base and (path == base or path.startswith(base + "/")):
path = path[len(base):] or "/"
if not path.startswith("/"):
return "/"
if path == "/auth/login":
@@ -414,7 +506,7 @@ class Handler(BaseHTTPRequestHandler):
def _remote_auth_cookie(self, session_value):
attributes = (
f"{Handler.remote_session_cookie_name}={session_value}; "
f"Path=/; HttpOnly; SameSite=Lax; Max-Age={Handler.remote_session_cookie_max_age_seconds}"
f"Path={Handler._base_path(self) or '/'}; HttpOnly; SameSite=Strict; Max-Age={Handler.remote_session_cookie_max_age_seconds}"
)
if Handler._request_is_secure(self):
attributes += "; Secure"
@@ -426,7 +518,7 @@ class Handler(BaseHTTPRequestHandler):
b"",
HTTPStatus.SEE_OTHER,
{
"Location": Handler._normalized_next_path(self, location),
"Location": Handler._external_path(self, Handler._normalized_next_path(self, location)),
"Set-Cookie": Handler._remote_auth_cookie(self, session_value),
},
)
@@ -434,10 +526,16 @@ class Handler(BaseHTTPRequestHandler):
def _is_browser_page_request(self, parsed):
if getattr(self, "command", "") != "GET":
return False
return not str(parsed.path or "").startswith("/api/")
path = parsed.path or ""
base = Handler._base_path(self)
if base and path.startswith(base + "/"):
path = path[len(base):]
return not path.startswith("/api/")
def _render_remote_login_page(self, parsed, message=""):
next_path = Handler._current_path_without_auth_query(self, parsed)
if parsed.path == "/auth/login":
next_path = Handler._normalized_next_path(self, (parse_qs(parsed.query).get("next") or ["/"])[0])
error_html = ""
if message:
error_html = f'<p class="error">{html_escape(message)}</p>'
@@ -537,6 +635,7 @@ class Handler(BaseHTTPRequestHandler):
</div>
{error_html}
<form method="post" action="/auth/login">
<input type="hidden" name="csrf" value="{Handler._login_token(self)}">
<input type="hidden" name="next" value="{html_escape(next_path, quote=True)}">
<label>Username
<input name="username" type="text" autocomplete="username" autofocus required>
@@ -561,13 +660,14 @@ class Handler(BaseHTTPRequestHandler):
def ensure_client_access(self):
client_host = Handler._effective_client_host(self)
if client_address_is_local(client_host):
config = Handler._config(self)
if client_address_is_local(client_host) and not remote_access_credentials_configured(config) and not Handler._base_url(self):
return
if not remote_access_allowed():
if not client_address_is_local(client_host) and not remote_access_allowed():
raise PermissionError(
"Remote access is disabled. Set KAIZOKU_ALLOW_REMOTE=1 to allow non-local clients."
)
if not remote_access_credentials_configured():
if not remote_access_credentials_configured(Handler._config(self)):
raise PermissionError(
"Remote access requires KAIZOKU_AUTH_USERNAME and KAIZOKU_AUTH_PASSWORD for non-local clients."
)
@@ -580,11 +680,10 @@ class Handler(BaseHTTPRequestHandler):
raise PermissionError(
"Remote access is disabled. Set KAIZOKU_ALLOW_REMOTE=1 to allow non-local clients."
)
if not env_value("KAIZOKU_AUTH_USERNAME") or not env_value("KAIZOKU_AUTH_PASSWORD"):
if not remote_access_credentials_configured(Handler._config(self)):
self.error(HTTPStatus.SERVICE_UNAVAILABLE, "Set KAIZOKU_AUTH_USERNAME and KAIZOKU_AUTH_PASSWORD.")
return False
username, password = Handler._basic_auth_credentials(self)
if not remote_access_credentials_match(username, password):
if not Handler._basic_credentials_valid(self):
Handler.write_response_bytes(
self,
b'{"error":"Basic authentication required."}',
@@ -599,6 +698,8 @@ class Handler(BaseHTTPRequestHandler):
return True
def serve_status(self):
if remote_access_credentials_configured(Handler._config(self)) or Handler._base_url(self):
Handler.ensure_client_access(self)
client_host = Handler._effective_client_host(self)
if not client_address_is_local(client_host) and not remote_access_allowed():
raise PermissionError(
@@ -633,18 +734,20 @@ class Handler(BaseHTTPRequestHandler):
raise PermissionError(f"Remote {label} must stay inside the configured remote path roots.")
def do_GET(self):
parsed = urlparse(self.path)
try:
parsed = Handler._route(self)
if parsed is None:
return
if parsed.path == "/status":
Handler.serve_status(self)
return
if parsed.path == "/auth/login":
if Handler._session_cookie(self) and remote_access_session_matches(Handler._session_cookie(self)):
if Handler._session_cookie(self) and remote_access_session_matches(Handler._session_cookie(self), Handler._config(self)):
params = parse_qs(parsed.query, keep_blank_values=True)
next_path = (params.get("next") or ["/"])[0]
Handler._set_remote_auth_cookie_and_redirect(self, Handler._session_cookie(self), next_path)
return
if remote_access_allowed() and remote_access_credentials_configured():
if remote_access_credentials_configured(Handler._config(self)):
Handler._render_remote_login_page(self, parsed)
return
if parsed.path == "/api/watchlist/homepage":
@@ -804,7 +907,10 @@ class Handler(BaseHTTPRequestHandler):
def do_HEAD(self):
try:
if urlparse(self.path).path == "/status":
parsed = Handler._route(self)
if parsed is None:
return
if parsed.path == "/status":
Handler.serve_status(self)
else:
self.ensure_client_access()
@@ -813,26 +919,47 @@ class Handler(BaseHTTPRequestHandler):
self.exception(exc)
def do_POST(self):
parsed = urlparse(self.path)
try:
parsed = Handler._route(self)
if parsed is None:
return
if parsed.path == "/auth/login":
if not remote_access_allowed() or not remote_access_credentials_configured():
if not remote_access_credentials_configured(Handler._config(self)):
raise PermissionError("Remote access sign-in is not available.")
client = Handler._effective_client_host(self)
if not client_address_is_local(client) and not remote_access_allowed():
raise PermissionError("Remote access is disabled.")
if not Handler._check_login_rate(self):
return
payload = Handler.body_form(self)
if not Handler._check_login_token(self, payload.get("csrf")):
raise PermissionError("Sign-in form expired. Reload the page and try again.")
if Handler._origin(self) and not Handler._origin_matches_host(self):
raise PermissionError("Cross-origin sign-in is not allowed.")
username = str(payload.get("username") or "").strip()
password = str(payload.get("password") or "").strip()
next_path = payload.get("next") or "/"
if not remote_access_credentials_match(username, password):
if not remote_access_credentials_match(username, password, Handler._config(self)):
Handler._render_remote_login_page(
self,
urlparse(Handler._normalized_next_path(self, next_path)),
"Username or password missing or invalid.",
)
return
Handler._set_remote_auth_cookie_and_redirect(self, remote_access_session_value(), next_path)
with LOGIN_LOCK:
LOGIN_ATTEMPTS.pop(self.client_address[0], None)
Handler._set_remote_auth_cookie_and_redirect(self, remote_access_session_value(Handler._config(self)), next_path)
return
self.ensure_client_access()
Handler.enforce_same_origin(self)
if parsed.path == "/auth/logout":
token = Handler._session_cookie(self)
revoke_remote_access_session(token)
Handler.write_response_bytes(self, b"", HTTPStatus.SEE_OTHER,
{"Location": Handler._external_path(self, "/auth/login"),
"Set-Cookie": Handler._remote_auth_cookie(self, "").replace(
f"Max-Age={Handler.remote_session_cookie_max_age_seconds}", "Max-Age=0")})
return
if parsed.path.startswith("/api/ai-subtitles/"):
payload = Handler.require_json_object(self, self.body_json())
service = Handler._context(self).ensure_runtime()["ai_subtitles"]
@@ -1010,6 +1137,8 @@ class Handler(BaseHTTPRequestHandler):
merged = dict(current)
merged.update(payload)
config = normalize_config(merged)
if configured_base_url(config) and not remote_access_credentials_configured(config):
raise ValueError("Configure a login username and password before setting a public base URL.")
for key, label in (
("download_dir", "download directory"),
("jellyfin_tv_dir", "Jellyfin TV directory"),
@@ -1121,7 +1250,15 @@ class Handler(BaseHTTPRequestHandler):
)
def json(self, payload, status=HTTPStatus.OK):
data = json.dumps(payload).encode("utf-8")
def mount_urls(value):
if isinstance(value, dict):
return {key: (Handler._external_path(self, item)
if key == "thumbnail_url" and isinstance(item, str) and item.startswith("/api/")
else mount_urls(item)) for key, item in value.items()}
if isinstance(value, list):
return [mount_urls(item) for item in value]
return value
data = json.dumps(mount_urls(payload)).encode("utf-8")
self.write_response_bytes(data, status, {"Content-Type": "application/json"})
def json_attachment(self, payload, filename, status=HTTPStatus.OK):
@@ -1139,6 +1276,18 @@ class Handler(BaseHTTPRequestHandler):
def write_response_bytes(self, payload, status, headers):
try:
headers = dict(headers)
content_type = headers.get("Content-Type", "")
base = Handler._base_path(self)
if base and "text/html" in content_type:
content = payload.decode("utf-8")
content = re.sub(r"([\"'`])/(?=api/|auth/|favicon\.|queue[\"'`?#]|config[\"'`?#]|watchlist[\"'`?#]|ai-subtitles[\"'`?#]|[\"'`])",
lambda match: match[1] + base + "/", content)
payload = content.encode("utf-8")
headers.setdefault("Cache-Control", "no-store")
headers.setdefault("X-Content-Type-Options", "nosniff")
headers.setdefault("Referrer-Policy", "same-origin")
headers.setdefault("Content-Security-Policy", "frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'")
self.send_response(status)
for key, value in headers.items():
self.send_header(key, value)
@@ -1164,7 +1313,7 @@ class Handler(BaseHTTPRequestHandler):
self.error(HTTPStatus.NOT_FOUND, str(exc).strip("'"))
elif isinstance(exc, PermissionError):
parsed = urlparse(getattr(self, "path", "") or "/")
if remote_access_allowed() and remote_access_credentials_configured() and Handler._is_browser_page_request(self, parsed):
if remote_access_credentials_configured(Handler._config(self)) and Handler._is_browser_page_request(self, parsed):
Handler._render_remote_login_page(self, parsed, str(exc))
else:
self.error(HTTPStatus.FORBIDDEN, str(exc))
+1
View File
@@ -87,4 +87,5 @@ def render_page_links(active_page):
for key, label, href in PAGE_LINKS:
class_name = "page-link active" if key == active_page else "page-link"
links.append(f' <a class="{class_name}" href="{href}">{label}</a>')
links.append(' <form method="post" action="/auth/logout"><button type="submit">Sign out</button></form>')
return " <nav class=\"page-links\" aria-label=\"Primary navigation\">\n" + "\n".join(links) + "\n </nav>\n"
+8 -2
View File
@@ -338,7 +338,7 @@ class NetworkGuardTests(unittest.TestCase):
self.assertIn('value="/?next=%22%3E%3Cscript%3Ealert%281%29%3C%2Fscript%3E"', body)
def test_remote_login_post_sets_cookie_and_redirects(self):
body = b"username=demo&password=secret-pass&next=%2Fwatchlist"
body = ("username=demo&password=secret-pass&next=%2Fwatchlist&csrf=" + APP.Handler._login_token(None)).encode()
handler = DummyHandler("/auth/login", body=body, content_length=len(body))
handler.client_address = ("192.168.1.25", 8421)
handler.headers["Content-Type"] = "application/x-www-form-urlencoded"
@@ -416,6 +416,7 @@ class NetworkGuardTests(unittest.TestCase):
handler.client_address = ("192.168.1.25", 8421)
handler.headers["Host"] = "anime.example:8421"
handler.headers["Origin"] = "https://anime.example:8421"
handler.headers["X-Forwarded-Proto"] = "https"
handler.headers["Cookie"] = (
"kaizoku_session="
+ http_handler.remote_access_session_value({"auth_username": "demo", "auth_password": "secret-pass"})
@@ -4986,6 +4987,8 @@ class HandlerRouteTests(unittest.TestCase):
self.assertEqual(handler.json_payload["download_dir"], allowed_root)
def test_config_routes_hide_auth_fields_and_preserve_saved_credentials(self):
previous = APP.get_config_snapshot()
self.addCleanup(APP.save_runtime_config, previous)
APP.save_runtime_config(
{
"download_dir": "/tmp/example",
@@ -4998,15 +5001,18 @@ class HandlerRouteTests(unittest.TestCase):
post_body = b'{"download_dir":"/tmp/updated","mode":"dub","quality":"720"}'
post_handler = DummyHandler("/api/config", body=post_body, content_length=len(post_body))
post_handler.headers["Authorization"] = "Basic " + base64.b64encode(b"demo:secret-pass").decode()
APP.Handler.do_POST(post_handler)
self.assertEqual(post_handler.json_status, HTTPStatus.OK)
self.assertNotIn("auth_username", post_handler.json_payload)
self.assertNotIn("auth_password", post_handler.json_payload)
self.assertEqual(APP.get_config_snapshot()["auth_username"], "demo")
self.assertEqual(APP.get_config_snapshot()["auth_password"], "secret-pass")
self.assertEqual(APP.get_config_snapshot()["auth_password"], "")
self.assertTrue(app_support.remote_access_credentials_match("demo", "secret-pass", APP.get_config_snapshot()))
get_handler = DummyHandler("/api/config")
get_handler.headers["Authorization"] = "Basic " + base64.b64encode(b"demo:secret-pass").decode()
APP.Handler.do_GET(get_handler)
self.assertEqual(get_handler.json_status, HTTPStatus.OK)
self.assertNotIn("auth_username", get_handler.json_payload)
+126
View File
@@ -0,0 +1,126 @@
"""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()