Compare commits

...
3 Commits
Author SHA1 Message Date
imSp4rky 7064d261c2 fix(security): sanitize logs, redact secrets, harden XML parsing
Address actionable CodeQL security-extended findings and extend the same redaction to the debug JSONL logger
2026-06-09 19:08:41 -06:00
imSp4rky 2d43c2601e chore(deps): bump subby to 0.3.30 and pycaption to 2.2.22
- subby pin 1ea6a52 -> a057280: improved missing-line-split handling, duplicate frontal hyphen removal, UTF-8 without BOM output, Python <=3.11 syntax fix
- pycaption 2.2.20 -> 2.2.22: SCC-only fixes, no impact on our SRT/DFXP/WebVTT usage
- pytest: filter third-party warnings (aiohttp NotAppKeyWarning required by pywidevine/pyplayready string app keys, pycaption bs4 deprecations)
2026-06-09 18:49:16 -06:00
imSp4rky 246ff528f5 fix(dl): apply per-service dl config overrides for all options
services.<TAG>.dl values only applied when the key was also set in the global dl: section (equality check against config.dl missed Click's declared defaults). Gate on Click's ParameterSource instead: CLI/env > service dl > global dl > defaults, converted via each option's own type.

- record parameter sources on serve's hand-built context so client values are never clobbered
- accept range/list as natural keys for range_/list_
- harden QualityList (YAML int) and SlowDelayRange (YAML bool) converts
2026-06-09 18:17:29 -06:00
17 changed files with 435 additions and 100 deletions
+12 -8
View File
@@ -32,8 +32,9 @@ There is no `downloader:` config key to set anymore. Setting one to a legacy val
Pre-define default options and switches of the `dl` command.
The values will be ignored if explicitly set in the CLI call.
The Key must be the same value Python click would resolve it to as an argument.
E.g., `@click.option("-r", "--range", "range_", type=...` actually resolves as `range_` variable.
The Key is the option name with dashes as underscores (`--v-lang` -> `v_lang`). `range` and `list`
work as-is; their internal Python names (`range_`, `list_`, suffixed to avoid the builtins) are
also accepted.
For example to set the default primary language to download to German,
@@ -88,7 +89,7 @@ to a CLI option on the `dl` command. CLI arguments always take priority over con
| `abitrate_range` | str | none | Audio bitrate window in kbps, format `MIN-MAX` |
| `real_video_bitrate` | bool | `false` | Probe actual media size to compute true video bitrates, overriding the manifest's declared value (`-rvb`). See [Real bitrate probing](#real-bitrate-probing) |
| `real_audio_bitrate` | bool | `false` | Same as above for audio tracks (`-rab`). Slower than video (more renditions) |
| `range_` | str or list | `SDR` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` |
| `range` (or `range_`) | str or list | `SDR` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` |
| `channels` | float | any | Audio channels (e.g., `5.1`, `7.1`) |
| `worst` | bool | `false` | Select the lowest bitrate track within the specified quality. Requires `quality` |
| `best_available` | bool | `false` | Continue if requested quality is unavailable |
@@ -186,18 +187,21 @@ How it works:
Per-track before→after values are logged at debug level (run with `-d`); the
corrected values always appear in the Available Tracks panel.
You can also set per-service `dl` overrides (see [Service Integration & Authentication Configuration](SERVICE_CONFIG.md)):
You can also set per-service `dl` overrides under the `services` section (see
[Service Integration & Authentication Configuration](SERVICE_CONFIG.md)). Per-service values beat the
global `dl:` section; explicit CLI arguments beat both:
```yaml
dl:
lang: en
downloads: 4
workers: 16
services:
EXAMPLE:
bitrate: CVBR
EXAMPLE2:
worst: true
quality: 1080
dl:
v_lang: [en]
quality: 1080
```
---
+12 -1
View File
@@ -30,7 +30,18 @@ service tag in the `services` section. Supported override keys include: `dl`, `s
`headers`, `proxy_map`, `title_map`, and more.
Overrides are merged with global config (not replaced) -- only specified keys are overridden, others
use global defaults. CLI arguments always take priority over service-specific config.
use global defaults.
Any `dl` command option can be overridden per service. Use the option name with dashes as underscores
(`--v-lang` -> `v_lang`). `range` and `list` work as-is; their internal Python names (`range_`,
`list_`, suffixed to avoid the builtins) are also accepted.
Precedence (highest first):
1. Explicit CLI arguments / environment variables (e.g. `--v-lang en`)
2. Per-service config (`services.<TAG>.dl`)
3. Global `dl:` config
4. Built-in option defaults
For example,
+5 -1
View File
@@ -67,6 +67,7 @@ dependencies = [
"animeapi-py>=0.6.0",
"rnet>=2.4.2",
"bandit>=1.9.4",
"defusedxml>=0.7.1",
]
[project.urls]
@@ -111,6 +112,9 @@ filterwarnings = [
"ignore::DeprecationWarning:click.*",
"ignore::DeprecationWarning:unshackle.core.services",
"ignore::DeprecationWarning:ast",
"ignore::aiohttp.web_exceptions.NotAppKeyWarning",
"ignore::DeprecationWarning:pycaption.*",
"ignore::bs4.XMLParsedAsHTMLWarning",
]
addopts = "-ra --strict-markers"
@@ -154,4 +158,4 @@ skips = [
[tool.uv.sources]
unshackle = { workspace = true }
subby = { git = "https://github.com/vevv/subby.git", rev = "1ea6a52028c5bea8177c8abc91716d74e4d097e1" }
subby = { git = "https://github.com/vevv/subby.git", rev = "a057280f31acd3a0ba5c6dc69eaefbb88aea974e" }
+27 -1
View File
@@ -6,7 +6,7 @@ from __future__ import annotations
import pytest
from unshackle.core.tracks.subtitle import Subtitle
from unshackle.core.utils.click_types import SubtitleCodecChoice
from unshackle.core.utils.click_types import QUALITY_LIST, SLOW_DELAY_RANGE, SubtitleCodecChoice
choice = SubtitleCodecChoice(Subtitle.Codec)
@@ -31,3 +31,29 @@ def test_codecs_still_map(value, expected):
def test_empty_is_none():
assert choice.convert(None) is None
@pytest.mark.parametrize(
"value,expected",
[
(1080, [1080]),
([720, 1080], [1080, 720]),
("1080p", [1080]),
("720,1080", [1080, 720]),
],
)
def test_quality_list_accepts_yaml_native_values(value, expected):
assert QUALITY_LIST.convert(value) == expected
@pytest.mark.parametrize(
"value,expected",
[
(True, (60, 120)),
(False, None),
("20-40", (20, 40)),
((25, 30), (25, 30)),
],
)
def test_slow_delay_range_accepts_bool(value, expected):
assert SLOW_DELAY_RANGE.convert(value, None, None) == expected
+154
View File
@@ -0,0 +1,154 @@
"""Tests for ``apply_service_dl_overrides`` — precedence: CLI/env > service dl > global dl > defaults."""
from __future__ import annotations
import logging
from typing import Any, Optional
import click
import pytest
from click.core import ParameterSource
from unshackle.commands.dl import apply_service_dl_overrides, normalize_dl_config
from unshackle.core.tracks import Video
from unshackle.core.utils.click_types import LANGUAGE_RANGE, MultipleChoice
log = logging.getLogger("test_service_dl_overrides")
def make_ctx(args: Optional[list[str]] = None, default_map: Optional[dict[str, Any]] = None) -> click.Context:
"""Build a parsed context for a mirror of the dl group's option shapes."""
@click.group("dl", invoke_without_command=True)
@click.option("-vl", "--v-lang", type=LANGUAGE_RANGE, default=[])
@click.option(
"-r", "--range", "range_", type=MultipleChoice(Video.Range, case_sensitive=False), default=[Video.Range.SDR]
)
@click.option("--repack", is_flag=True, default=False)
@click.option("--workers", type=int, default=None, envvar="TEST_DL_WORKERS")
def cmd(**__: Any) -> None:
pass
return cmd.make_context("dl", args or [], default_map=default_map)
def test_service_only_key_applies():
"""The reported bug: key set only under services.<TAG>.dl, not under global dl:."""
ctx = make_ctx()
assert ctx.params["v_lang"] == []
apply_service_dl_overrides(ctx, {"v_lang": ["en"]}, log)
assert ctx.params["v_lang"] == ["en"]
def test_cli_value_beats_service_config():
ctx = make_ctx(["-vl", "fr"])
apply_service_dl_overrides(ctx, {"v_lang": ["en"]}, log)
assert ctx.params["v_lang"] == ["fr"]
def test_env_value_beats_service_config(monkeypatch):
monkeypatch.setenv("TEST_DL_WORKERS", "5")
ctx = make_ctx()
apply_service_dl_overrides(ctx, {"workers": 9}, log)
assert ctx.params["workers"] == 5
def test_service_config_beats_global_default_map():
ctx = make_ctx(default_map={"v_lang": "de"})
assert ctx.params["v_lang"] == ["de"]
apply_service_dl_overrides(ctx, {"v_lang": ["en"]}, log)
assert ctx.params["v_lang"] == ["en"]
def test_flag_global_true_service_false():
ctx = make_ctx(default_map={"repack": True})
assert ctx.params["repack"] is True
apply_service_dl_overrides(ctx, {"repack": False}, log)
assert ctx.params["repack"] is False
def test_range_scalar_converts_to_enum_list():
ctx = make_ctx()
apply_service_dl_overrides(ctx, {"range_": "HDR10"}, log)
assert ctx.params["range_"] == [Video.Range.HDR10]
def test_range_alias_applies():
"""`range` in config is an accepted alias for the `range_` parameter."""
ctx = make_ctx()
apply_service_dl_overrides(ctx, {"range": "HDR10"}, log)
assert ctx.params["range_"] == [Video.Range.HDR10]
def test_normalize_dl_config_maps_aliases():
assert normalize_dl_config({"range": "SDR", "list": True, "v_lang": ["en"]}) == {
"range_": "SDR",
"list_": True,
"v_lang": ["en"],
}
def test_unknown_key_warns(caplog):
ctx = make_ctx()
with caplog.at_level(logging.WARNING, logger=log.name):
apply_service_dl_overrides(ctx, {"bogus": 1}, log)
assert any("unknown dl option 'bogus'" in r.message for r in caplog.records)
def test_none_value_is_skipped():
ctx = make_ctx()
apply_service_dl_overrides(ctx, {"v_lang": None}, log)
assert ctx.params["v_lang"] == []
def test_invalid_value_warns_and_keeps_current(caplog):
ctx = make_ctx()
with caplog.at_level(logging.WARNING, logger=log.name):
apply_service_dl_overrides(ctx, {"workers": "abc"}, log)
assert ctx.params["workers"] is None
assert any("Failed to apply service dl override 'workers'" in r.message for r in caplog.records)
def hand_built_ctx(body: dict[str, Any]) -> click.Context:
"""Mirror the serve path: ctx.params set directly, sources recorded manually."""
parsed = make_ctx()
ctx = click.Context(parsed.command)
ctx.params = {"repack": body.get("repack", False)}
for name in ctx.params:
ctx.set_parameter_source(
name, ParameterSource.COMMANDLINE if name in body else ParameterSource.DEFAULT
)
return ctx
def test_hand_built_ctx_default_gets_override():
ctx = hand_built_ctx({})
apply_service_dl_overrides(ctx, {"repack": True}, log)
assert ctx.params["repack"] is True
def test_hand_built_ctx_client_value_wins():
ctx = hand_built_ctx({"repack": False})
apply_service_dl_overrides(ctx, {"repack": True}, log)
assert ctx.params["repack"] is False
def test_hand_built_ctx_missing_param_is_skipped():
"""Known dl option absent from a hand-built context must not raise or be injected."""
ctx = hand_built_ctx({})
apply_service_dl_overrides(ctx, {"v_lang": ["en"]}, log)
assert "v_lang" not in ctx.params
@pytest.mark.parametrize(
"value,expected",
[
(["en", "de"], ["en", "de"]),
("en,de", ["en", "de"]),
("en", ["en"]),
],
)
def test_language_range_yaml_shapes(value, expected):
ctx = make_ctx()
apply_service_dl_overrides(ctx, {"v_lang": value}, log)
assert ctx.params["v_lang"] == expected
+58 -32
View File
@@ -25,6 +25,7 @@ from uuid import UUID
import click
import yaml
from click.core import ParameterSource
from langcodes import Language
from pymediainfo import MediaInfo
from rich.console import Group
@@ -80,6 +81,42 @@ class SkippedSubtitle(TypedDict):
title: str
# Config keys accepted as natural names for params whose Python name dodges a builtin.
DL_OPTION_ALIASES = {"range": "range_", "list": "list_"}
def normalize_dl_config(dl_config: dict[str, Any]) -> dict[str, Any]:
"""Map aliased config keys (e.g. ``range``) to their Click parameter names (``range_``)."""
return {DL_OPTION_ALIASES.get(key, key): value for key, value in dl_config.items()}
def apply_service_dl_overrides(ctx: click.Context, service_dl_config: dict[str, Any], log: logging.Logger) -> None:
"""Apply ``services.<TAG>.dl`` config onto ``ctx.params``. Explicit CLI/env values win;
defaults and global ``dl:`` default_map values are replaced."""
params_by_name = {param.name: param for param in ctx.command.params if param.name}
for name, value in normalize_dl_config(service_dl_config).items():
param = params_by_name.get(name)
if param is None:
log.warning(f"Ignoring unknown dl option '{name}' in service config")
continue
if name not in ctx.params:
log.debug(f"Skipping service dl override '{name}': not present in this context")
continue
if value is None:
continue
source = ctx.get_parameter_source(name)
if source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP):
continue
try:
ctx.params[name] = param.type_cast_value(ctx, value)
log.debug(f"Applied service dl override '{name}': {ctx.params[name]}")
except Exception as e:
log.warning(
f"Failed to apply service dl override '{name}'={value!r}: {e}. "
f"Check that the value is valid for this parameter."
)
def download_tracks_in_passes(
tracks: Iterable[AnyTrack],
max_concurrent: int,
@@ -326,7 +363,9 @@ class dl:
@click.command(
short_help="Download, Decrypt, and Mux tracks for titles from a Service.",
cls=Services,
context_settings=dict(**context_settings, default_map=config.dl, token_normalize_func=Services.get_tag),
context_settings=dict(
**context_settings, default_map=normalize_dl_config(config.dl), token_normalize_func=Services.get_tag
),
)
@click.option(
"-p", "--profile", type=str, default=None, help="Profile to use for Credentials and Cookies (if available)."
@@ -687,37 +726,19 @@ class dl:
self.service = Services.get_tag(ctx.invoked_subcommand)
self.vault_service = Services.get_vault_tag(self.service)
service_dl_config = config.services.get(self.service, {}).get("dl", {})
if service_dl_config:
param_types = {param.name: param.type for param in ctx.command.params if param.name}
apply_service_dl_overrides(ctx, config.services.get(self.service, {}).get("dl", {}), self.log)
for param_name, service_value in service_dl_config.items():
if param_name not in ctx.params:
continue
current_value = ctx.params[param_name]
global_default = config.dl.get(param_name)
param_type = param_types.get(param_name)
try:
if param_type and global_default is not None:
global_default = param_type.convert(global_default, None, ctx)
except Exception as e:
self.log.debug(f"Failed to convert global default for '{param_name}': {e}")
if current_value == global_default or (current_value is None and global_default is None):
try:
converted_value = service_value
if param_type and service_value is not None:
converted_value = param_type.convert(service_value, None, ctx)
ctx.params[param_name] = converted_value
self.log.debug(f"Applied service-specific '{param_name}' override: {converted_value}")
except Exception as e:
self.log.warning(
f"Failed to apply service-specific '{param_name}' override: {e}. "
f"Check that the value '{service_value}' is valid for this parameter."
)
# Refresh locals Click bound before the overrides ran.
no_proxy = ctx.params.get("no_proxy", no_proxy)
profile = ctx.params.get("profile", profile)
proxy = ctx.params.get("proxy", proxy)
repack = ctx.params.get("repack", repack)
tag = ctx.params.get("tag", tag)
tmdb_id = ctx.params.get("tmdb_id", tmdb_id)
imdb_id = ctx.params.get("imdb_id", imdb_id)
animeapi_id = ctx.params.get("animeapi_id", animeapi_id)
enrich = ctx.params.get("enrich", enrich)
output_dir = ctx.params.get("output_dir", output_dir)
self.profile = profile
self.proxy_requested = bool(proxy)
@@ -841,11 +862,16 @@ class dl:
self.service_config = yaml.safe_load(service_config_path.read_text(encoding="utf8"))
self.log.info("Service Config loaded")
if self.debug_logger:
# log key names only -- the full config carries service certificates,
# device fingerprints and endpoints that bloat the log and may be sensitive
self.debug_logger.log(
level="DEBUG",
operation="load_service_config",
service=self.service,
context={"config_path": str(service_config_path), "config": self.service_config},
context={
"config_path": str(service_config_path),
"config_keys": sorted(self.service_config or []),
},
)
except KeyError:
pass
+20 -21
View File
@@ -14,20 +14,16 @@ from enum import Enum
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_text
log = logging.getLogger("download_manager")
def _sanitize_log(value: object) -> str:
"""Sanitize a value for safe logging by removing newlines and control characters."""
return str(value).replace("\n", "").replace("\r", "").replace("\x00", "")
# Job parameters may carry secrets (a raw "user:pass" credential, a proxy URL with embedded
# userinfo). These must never leave the process via the API or logs, so they are masked
# wherever parameters are serialized for a response.
_REDACTED = "***"
_SENSITIVE_PARAM_KEYS = ("credential", "credentials", "password", "token", "api_key")
_PROXY_USERINFO_RE = re.compile(r"(?<=://)[^/@]+@")
def _redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
@@ -37,10 +33,10 @@ def _redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
redacted = dict(parameters)
for key in _SENSITIVE_PARAM_KEYS:
if redacted.get(key):
redacted[key] = _REDACTED
redacted[key] = REDACTED
proxy = redacted.get("proxy")
if isinstance(proxy, str) and "@" in proxy:
redacted["proxy"] = _PROXY_USERINFO_RE.sub(f"{_REDACTED}@", proxy)
redacted["proxy"] = URL_USERINFO_RE.sub(f"{REDACTED}@", proxy)
return redacted
@@ -68,12 +64,7 @@ def _secret_values(parameters: Dict[str, Any]) -> List[str]:
def _redact_text(text: Optional[str], parameters: Dict[str, Any]) -> Optional[str]:
"""Mask proxy userinfo and any known parameter secrets that leaked into a free-text field
(error message / details / traceback / worker stderr) before it is returned via the API."""
if not isinstance(text, str) or not text:
return text
text = _PROXY_USERINFO_RE.sub(f"{_REDACTED}@", text)
for secret in _secret_values(parameters):
text = text.replace(secret, _REDACTED)
return text
return redact_text(text, _secret_values(parameters))
class JobStatus(Enum):
@@ -292,6 +283,14 @@ def _perform_download(
"no_cache": params.get("no_cache", False),
"reset_cache": params.get("reset_cache", False),
}
# Hand-built context: record parameter sources so service dl overrides
# apply to defaults but never clobber client-sent values.
from click.core import ParameterSource
for param_name in ctx.params:
ctx.set_parameter_source(
param_name, ParameterSource.COMMANDLINE if param_name in params else ParameterSource.DEFAULT
)
dl_instance = dl(
ctx=ctx,
@@ -507,7 +506,7 @@ class DownloadQueueManager:
self._jobs[job_id] = job
self._job_queue.put_nowait(job)
log.info(f"Created download job {job_id} for {_sanitize_log(service)}:{_sanitize_log(title_id)}")
log.info(f"Created download job {job_id} for {sanitize_log(service)}:{sanitize_log(title_id)}")
return job
def get_job(self, job_id: str) -> Optional[DownloadJob]:
@@ -527,27 +526,27 @@ class DownloadQueueManager:
if job.status == JobStatus.QUEUED:
job.status = JobStatus.CANCELLED
job.cancel_event.set() # Signal cancellation
log.info(f"Cancelled queued job {_sanitize_log(job_id)}")
log.info(f"Cancelled queued job {sanitize_log(job_id)}")
return True
elif job.status == JobStatus.DOWNLOADING:
# Set the cancellation event first - this will be checked by the download thread
job.cancel_event.set()
job.status = JobStatus.CANCELLED
log.info(f"Signaled cancellation for downloading job {_sanitize_log(job_id)}")
log.info(f"Signaled cancellation for downloading job {sanitize_log(job_id)}")
# Cancel the active download task
task = self._active_downloads.get(job_id)
if task:
task.cancel()
log.info(f"Cancelled download task for job {_sanitize_log(job_id)}")
log.info(f"Cancelled download task for job {sanitize_log(job_id)}")
process = self._download_processes.get(job_id)
if process:
try:
process.terminate()
log.info(f"Terminated worker process for job {_sanitize_log(job_id)}")
log.info(f"Terminated worker process for job {sanitize_log(job_id)}")
except ProcessLookupError:
log.debug(f"Worker process for job {_sanitize_log(job_id)} already exited")
log.debug(f"Worker process for job {sanitize_log(job_id)} already exited")
return True
+14 -14
View File
@@ -7,6 +7,7 @@ from aiohttp import web
from unshackle.core.api.errors import APIError, APIErrorCode, handle_api_exception
from unshackle.core.api.input_bridge import AuthStatus, InputBridge
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.config import config
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_proxy
@@ -17,11 +18,6 @@ from unshackle.core.tracks import Audio, Subtitle, Video
log = logging.getLogger("api")
def sanitize_log(value: object) -> str:
"""Sanitize a value for safe logging by removing newlines and control characters."""
return str(value).replace("\n", "").replace("\r", "").replace("\x00", "")
DEFAULT_DOWNLOAD_PARAMS = {
"profile": None,
"quality": [],
@@ -126,7 +122,9 @@ def load_full_cdm(service: str, profile: Optional[str], cdm_type: Optional[str]
try:
return load_cdm(cdm_name, service_name=service)
except Exception as exc: # noqa: BLE001 - fall back to stub on load failure
log.warning(f"load_cdm({cdm_name!r}) failed for {service}: {exc}; using lightweight stub")
log.warning(
f"load_cdm({sanitize_log(cdm_name)!r}) failed for {sanitize_log(service)}: {exc}; using lightweight stub"
)
return _resolve_server_cdm(service, profile, cdm_type)
@@ -735,7 +733,9 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
wanted = season_range.parse_tokens(*wanted_param)
else:
wanted = season_range.parse_tokens(wanted_param)
log.debug(f"Parsed wanted '{wanted_param}' into {len(wanted)} episodes: {wanted[:10]}...")
log.debug(
f"Parsed wanted '{sanitize_log(wanted_param)}' into {len(wanted)} episodes: {wanted[:10]}..."
)
except (Exception, SystemExit) as e:
raise APIError(
APIErrorCode.INVALID_PARAMETERS,
@@ -1910,13 +1910,13 @@ def _resolve_handler_proxy(data: Dict[str, Any], normalized_service: str) -> tup
server_region = None
if server_region and server_region == client_region.lower():
log.info(f"Server already in client region '{client_region}', no proxy needed")
log.info(f"Server already in client region '{sanitize_log(client_region)}', no proxy needed")
else:
try:
proxy_param = resolve_proxy(client_region, proxy_providers)
log.info(f"Using server proxy for client region '{client_region}'")
log.info(f"Using server proxy for client region '{sanitize_log(client_region)}'")
except ValueError:
log.debug(f"No server proxy available for client region '{client_region}'")
log.debug(f"No server proxy available for client region '{sanitize_log(client_region)}'")
return proxy_param, proxy_providers
@@ -2299,9 +2299,9 @@ async def session_license_handler(
if track_drm_type:
actual_drm_type = track_drm_type
except SystemExit:
log.warning(f"Service exited while resolving keys for track {tid[:12]}, skipping")
log.warning(f"Service exited while resolving keys for track {sanitize_log(tid[:12])}, skipping")
except (Exception, SystemExit) as e:
log.warning(f"Failed to resolve keys for track {tid[:12]}: {e}")
log.warning(f"Failed to resolve keys for track {sanitize_log(tid[:12])}: {e}")
response: Dict[str, Any] = {"keys": all_keys}
if actual_drm_type:
@@ -2347,7 +2347,7 @@ async def session_license_handler(
if mode == "server_cdm":
keys = _handle_single_server_cdm(service, title, track, pssh_b64, drm_type, request)
log.info(f"Server CDM resolved {len(keys)} key(s) for track {track_id[:12]}")
log.info(f"Server CDM resolved {len(keys)} key(s) for track {sanitize_log(track_id[:12])}")
return web.json_response({"keys": keys})
return _handle_proxy_license(service, title, track, challenge_b64, drm_type)
@@ -2357,7 +2357,7 @@ async def session_license_handler(
except SystemExit:
raise APIError(APIErrorCode.SERVICE_ERROR, "Service exited during license request")
except (Exception, SystemExit) as e:
log.exception(f"Error proxying license for track {track_id}")
log.exception(f"Error proxying license for track {sanitize_log(track_id)}")
debug_mode = request.app.get("debug_api", False) if request else False
return handle_api_exception(
e,
+8
View File
@@ -0,0 +1,8 @@
"""Helpers for safely logging user-provided values."""
from __future__ import annotations
def sanitize_log(value: object) -> str:
"""Sanitize a value for safe logging by removing newlines and control characters."""
return str(value).replace("\n", "").replace("\r", "").replace("\x00", "")
+6 -3
View File
@@ -15,6 +15,7 @@ from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from unshackle.core.api.input_bridge import AuthStatus, InputBridge
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.config import config
from unshackle.core.tracks import Track
@@ -84,7 +85,7 @@ class SessionStore:
service_instance=service_instance,
)
self._sessions[session_id] = entry
log.info(f"Created session {session_id} for service {service_tag}")
log.info(f"Created session {sanitize_log(session_id)} for service {sanitize_log(service_tag)}")
return entry
async def get(self, session_id: str) -> Optional[SessionEntry]:
@@ -97,7 +98,9 @@ class SessionStore:
if entry.auth_status not in (AuthStatus.AUTHENTICATING, AuthStatus.PENDING_INPUT):
elapsed = (datetime.now(timezone.utc) - entry.last_accessed).total_seconds()
if elapsed > self._ttl:
log.info(f"Session {session_id} expired (elapsed={elapsed:.0f}s, ttl={self._ttl}s)")
log.info(
f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self._ttl}s)"
)
del self._sessions[session_id]
return None
@@ -112,7 +115,7 @@ class SessionStore:
if entry.input_bridge:
entry.input_bridge.cancel()
self._cleanup_cache_dir(entry.cache_tag)
log.info(f"Deleted session {session_id}")
log.info(f"Deleted session {sanitize_log(session_id)}")
return True
return False
+2 -1
View File
@@ -80,7 +80,8 @@ class PlayReady:
def _extract_kids_from_pssh_b64(self, pssh_b64: str) -> list[UUID]:
"""Extract all KIDs from base64-encoded PSSH data."""
try:
import xml.etree.ElementTree as ET
# PSSH XML comes from third-party manifests; defusedxml guards against entity expansion
import defusedxml.ElementTree as ET
# Decode the PSSH
pssh_bytes = base64.b64decode(pssh_b64)
+12 -2
View File
@@ -31,9 +31,18 @@ from unshackle.core.titles.movie import Movie, Movies
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.track import Track
from unshackle.core.utils.redact import redact_text, safe_display_url
log = logging.getLogger("remote_service")
SENSITIVE_DATA_KEYS = ("credential", "credentials", "password", "token", "api_key")
def redact_secrets(text: str, data: Optional[Dict[str, Any]] = None) -> str:
"""Mask URL userinfo and any request-payload secrets before the text is logged."""
secrets = [v for k in SENSITIVE_DATA_KEYS if isinstance(v := (data or {}).get(k), str) and v]
return redact_text(text, secrets) or ""
class RemoteClient:
"""HTTP client for the unshackle serve API."""
@@ -59,14 +68,15 @@ class RemoteClient:
try:
resp = getattr(self.session, method)(url, json=data, timeout=120 if method == "post" else 30)
except requests.ConnectionError:
log.error(f"Could not connect to remote server at {self.server_url}. Is it running? (unshackle serve)")
server_url = safe_display_url(self.server_url)
log.error(f"Could not connect to remote server at {server_url}. Is it running? (unshackle serve)")
raise SystemExit(1)
except requests.Timeout:
log.error(f"Request to remote server timed out: {endpoint}")
raise SystemExit(1)
result = resp.json()
if resp.status_code >= 400:
error_msg = result.get("message", resp.text)
error_msg = redact_secrets(str(result.get("message", resp.text)), data)
error_code = result.get("error_code", "UNKNOWN")
log.error(f"Server error [{error_code}]: {error_msg}")
raise SystemExit(1)
+12 -4
View File
@@ -30,6 +30,7 @@ from unidecode import unidecode
from unshackle.core.config import config
from unshackle.core.constants import LANGUAGE_EXACT_DISTANCE, LANGUAGE_MAX_DISTANCE
from unshackle.core.utils.redact import redact_text
"""
Utility functions for the unshackle media archival tool.
@@ -836,7 +837,7 @@ class DebugLogger:
if operation:
entry["operation"] = operation
if message:
entry["message"] = message
entry["message"] = redact_text(message)
if service:
entry["service"] = service
if context:
@@ -853,8 +854,10 @@ class DebugLogger:
if error:
entry["error"] = {
"type": type(error).__name__,
"message": str(error),
"traceback": traceback.format_exception(type(error), error, error.__traceback__),
"message": redact_text(str(error)),
"traceback": [
redact_text(line) for line in traceback.format_exception(type(error), error, error.__traceback__)
],
}
for key, value in kwargs.items():
@@ -875,7 +878,12 @@ class DebugLogger:
if data is None:
return None
if isinstance(data, (str, int, float, bool)):
if isinstance(data, str):
# mask URL userinfo and secret-bearing query params that key-based
# redaction can't catch (e.g. a proxy URL inside a non-sensitive field)
return redact_text(data)
if isinstance(data, (int, float, bool)):
return data
if isinstance(data, (list, tuple)):
+11 -4
View File
@@ -254,16 +254,19 @@ class QualityList(click.ParamType):
name = "quality_list"
def convert(
self, value: Union[str, list[str]], param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None
self,
value: Union[str, int, list[Union[str, int]]],
param: Optional[click.Parameter] = None,
ctx: Optional[click.Context] = None,
) -> list[int]:
if not value:
return []
if not isinstance(value, list):
value = value.split(",")
value = str(value).split(",")
resolutions = []
for resolution in value:
try:
resolutions.append(int(resolution.lower().rstrip("p")))
resolutions.append(int(str(resolution).lower().rstrip("p")))
except TypeError:
self.fail(
f"Expected string for int() conversion, got {resolution!r} of type {type(resolution).__name__}",
@@ -370,9 +373,13 @@ class SlowDelayRange(click.ParamType):
name = "delay_range"
def convert(self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]) -> tuple[int, int]:
def convert(
self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]
) -> Optional[tuple[int, int]]:
if isinstance(value, tuple):
return value
if isinstance(value, bool):
return (60, 120) if value else None
match = re.match(r"^(\d+)-(\d+)$", str(value))
if not match:
+39
View File
@@ -0,0 +1,39 @@
"""Helpers for masking secrets in text destined for logs or API responses."""
from __future__ import annotations
import re
from typing import Iterable, Optional
from urllib.parse import urlsplit, urlunsplit
REDACTED = "***"
# user:pass@ userinfo embedded in any URL (proxy URLs, remote server URLs)
URL_USERINFO_RE = re.compile(r"(?<=://)[^/@]+@")
# secret-bearing query parameters in URLs that end up in free text
SENSITIVE_QUERY_PARAM_RE = re.compile(r"(?i)\b(password|passwd|pwd|token|api_key|apikey|secret|auth)=([^&#\s\"']+)")
def redact_text(text: Optional[str], secrets: Iterable[str] = ()) -> Optional[str]:
"""
Mask URL userinfo, secret-bearing query parameters, and any known secret
strings inside a free-text value before it is logged or serialized.
"""
if not isinstance(text, str) or not text:
return text
text = URL_USERINFO_RE.sub(f"{REDACTED}@", text)
text = SENSITIVE_QUERY_PARAM_RE.sub(rf"\1={REDACTED}", text)
# longest first so substrings don't survive partial replacement
for secret in sorted({s for s in secrets if isinstance(s, str) and s}, key=len, reverse=True):
text = text.replace(secret, REDACTED)
return text
def safe_display_url(url: str) -> str:
"""Rebuild a URL from its scheme/host/port/path only, so userinfo can never be logged."""
parts = urlsplit(url)
netloc = parts.hostname or ""
if parts.port:
netloc += f":{parts.port}"
return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
+26 -2
View File
@@ -414,6 +414,13 @@ audio:
# Atmos still trumps codec priority. Valid names: AAC, AC3, EC3, AC4, OPUS, OGG, DTS, ALAC, FLAC.
# codec_priority: [FLAC, ALAC, AC4, EC3, DTS, AC3, OPUS, AAC, OGG]
# Global defaults for the dl command. Any dl option can be set here.
# Use the option name with dashes as underscores (--v-lang -> v_lang).
# range and list work as-is (range_/list_ also accepted).
#
# Any of these can also be overridden per service under services.<TAG>.dl
# (see the services section below). Precedence, highest first:
# CLI arguments > services.<TAG>.dl > this dl section > built-in defaults
dl:
sub_format: srt
downloads: 4
@@ -421,6 +428,14 @@ dl:
lang:
- en
- fr
v_lang: [en] # --v-lang: video language(s), if different from audio
s_lang: [en, de] # --s-lang: subtitle language(s)
range: SDR # --range: SDR, HDR10, HDR10+, DV
quality: [1080] # --quality: resolution(s), int or list
slow: false # --slow: true = random 60-120s delay between titles, or "MIN-MAX" string
# Nesting a SERVICE TAG here provides defaults for that service's OWN command
# options (e.g. a service-defined --bitrate flag) -- NOT for the dl options
# above. To override dl options per service, use services.<TAG>.dl instead.
EXAMPLE:
bitrate: CBR
@@ -624,12 +639,20 @@ services:
# Other services or no service specified will still use random selection
# NEW: Configuration overrides (can be combined with profiles and certificates)
# Override dl command defaults for this service
# Override dl command defaults for this service. ANY dl option works here,
# same key naming as the global dl section (v_lang, range_, list_, ...).
# These beat the global dl section; explicit CLI arguments beat both.
dl:
downloads: 4 # Limit concurrent track downloads (global default: 6)
workers: 8 # Reduce workers per track (global default: 16)
lang: ["en", "es-419"] # Different language priority for this service
v_lang: [en] # Video language differs from audio on this service
s_lang: [all] # Grab every subtitle language here
range: HDR10 # Prefer HDR10 on this service (CLI -r still wins)
quality: 720 # This service rate-limits 1080p; int or list both work
sub_format: srt # Force SRT subtitle format
slow: true # Pace title downloads (60-120s); or "20-40" for a custom range
repack: false # Even if the global dl section sets repack: true
# Override subtitle processing for this service
subtitle:
@@ -671,7 +694,8 @@ services:
# - Only specified keys are overridden, others use global defaults
# - Reserved keys (profiles, api_key, certificate, etc.) are NOT treated as overrides
# - Any dict-type config option can be overridden (dl, subtitle, muxing, headers, etc.)
# - CLI arguments always take priority over service-specific config
# - Any dl option can be overridden; dashes become underscores (--v-lang -> v_lang)
# - Precedence: CLI arguments > service dl override > global dl section > built-in defaults
# External proxy provider services
proxy_providers:
Generated
+17 -6
View File
@@ -456,6 +456,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/94/35/386550fd60316d1e37eccdda609b074113298f23cef5bddb2049823fe666/dacite-1.9.2-py3-none-any.whl", hash = "sha256:053f7c3f5128ca2e9aceb66892b1a3c8936d02c686e707bee96e19deef4bc4a0", size = 16600, upload-time = "2025-02-05T09:27:24.345Z" },
]
[[package]]
name = "defusedxml"
version = "0.7.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/0f/d5/c66da9b79e5bdb124974bfe172b4daf3c984ebd9c2a06e2b8a4dc7331c72/defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69", size = 75520, upload-time = "2021-03-08T10:59:26.269Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" },
]
[[package]]
name = "distlib"
version = "0.4.0"
@@ -1113,16 +1122,16 @@ wheels = [
[[package]]
name = "pycaption"
version = "2.2.20"
version = "2.2.22"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "beautifulsoup4" },
{ name = "cssutils" },
{ name = "lxml" },
]
sdist = { url = "https://files.pythonhosted.org/packages/05/cd/acdbe4195a280bb4e82aa88c094a2f9acae71defec18fc1d2a84dc8f9955/pycaption-2.2.20.tar.gz", hash = "sha256:d436b29dabdd5cc84362d9a21a119a4a8d6115dc88125b401838c8fe6fa2691d", size = 111271, upload-time = "2026-02-05T13:04:25.589Z" }
sdist = { url = "https://files.pythonhosted.org/packages/80/1b/eed6e7a337e1c5807fd88920c100ff06042abca170a80677cb036629d888/pycaption-2.2.22.tar.gz", hash = "sha256:37680491c4b1867c78ce8b537b0004ec1f790db608b545d934475baf95ee0032", size = 112873, upload-time = "2026-05-04T10:00:28.97Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/88/07/a26c085aa821f90de038b2e744fc9a9bfabb03bdc54ea9bcb410f118c3d4/pycaption-2.2.20-py3-none-any.whl", hash = "sha256:8a5ca8013f7af7a6d908af1741f480e6aae331056b62a4f3140ddd316e0b76a6", size = 124960, upload-time = "2026-02-05T13:04:24.373Z" },
{ url = "https://files.pythonhosted.org/packages/9c/ce/82938777b8efe253be1175647bcc408fd4918faaca1b23c04e8158554288/pycaption-2.2.22-py3-none-any.whl", hash = "sha256:d5f672d05539e46fca0fdecb76f8d23b7c9b1a0f62f91268d4046d0e949f862e", size = 126674, upload-time = "2026-05-04T10:00:27.53Z" },
]
[[package]]
@@ -1647,8 +1656,8 @@ wheels = [
[[package]]
name = "subby"
version = "0.3.27"
source = { git = "https://github.com/vevv/subby.git?rev=1ea6a52028c5bea8177c8abc91716d74e4d097e1#1ea6a52028c5bea8177c8abc91716d74e4d097e1" }
version = "0.3.30"
source = { git = "https://github.com/vevv/subby.git?rev=a057280f31acd3a0ba5c6dc69eaefbb88aea974e#a057280f31acd3a0ba5c6dc69eaefbb88aea974e" }
dependencies = [
{ name = "beautifulsoup4" },
{ name = "click" },
@@ -1766,6 +1775,7 @@ dependencies = [
{ name = "construct" },
{ name = "crccheck" },
{ name = "cryptography" },
{ name = "defusedxml" },
{ name = "filelock" },
{ name = "fonttools" },
{ name = "jsonpickle" },
@@ -1831,6 +1841,7 @@ requires-dist = [
{ name = "construct", specifier = ">=2.8.8,<3" },
{ name = "crccheck", specifier = ">=1.3.0,<2" },
{ name = "cryptography", specifier = ">=45.0.0,<47" },
{ name = "defusedxml", specifier = ">=0.7.1" },
{ name = "filelock", specifier = ">=3.20.3,<4" },
{ name = "fonttools", specifier = ">=4.60.2,<5" },
{ name = "jsonpickle", specifier = ">=3.0.4,<5" },
@@ -1856,7 +1867,7 @@ requires-dist = [
{ name = "rnet", specifier = ">=2.4.2" },
{ name = "ruamel-yaml", specifier = ">=0.18.6,<0.19" },
{ name = "sortedcontainers", specifier = ">=2.4.0,<3" },
{ name = "subby", git = "https://github.com/vevv/subby.git?rev=1ea6a52028c5bea8177c8abc91716d74e4d097e1" },
{ name = "subby", git = "https://github.com/vevv/subby.git?rev=a057280f31acd3a0ba5c6dc69eaefbb88aea974e" },
{ name = "subtitle-filter", specifier = ">=1.4.9,<2" },
{ name = "unidecode", specifier = ">=1.3.8,<2" },
{ name = "urllib3", specifier = ">=2.6.3,<3" },