From daa9caa02b2985b001e645f1a0965f0693ef2c59 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Sat, 28 Nov 2026 14:32:31 -0700 Subject: [PATCH] fix(api): check serve and service dl defaults at job admission --- docs/dev/rest-api/endpoints.md | 2 ++ docs/reference/configuration/download.md | 4 ++- tests/remote/unit/test_job_admission.py | 44 ++++++++++++++++++++++++ unshackle/core/api/job_admission.py | 38 +++++++++++++++----- unshackle/core/utils/service_params.py | 3 ++ 5 files changed, 81 insertions(+), 10 deletions(-) diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 94e07fed..3f3dae80 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -538,6 +538,8 @@ profile, never a service's own `--profile` option. On the server, unshackle merges the effective parameters in this order: defaults → `serve:` config overrides → service-specific defaults → your request body. + The server checks each `serve:` and `services..dl` value that a job uses with the rules of a request body. A bad value refuses the job with `400 INVALID_PARAMETERS`, and the message starts with the config block, for example `serve: workers must be a positive integer`. A value that your request body replaces is not checked. + | Status | Error code | Meaning | | --- | --- | --- | | `202` | - | Job queued. | diff --git a/docs/reference/configuration/download.md b/docs/reference/configuration/download.md index 3369a84a..de3fda5e 100644 --- a/docs/reference/configuration/download.md +++ b/docs/reference/configuration/download.md @@ -105,7 +105,9 @@ dl: The [`serve`](services.md#serve) block accepts most of the same `dl` option keys at its top level to set server-wide download defaults for every request it handles. The API ignores the config keys it does not know there, `speed_limit` for example. `serve` has its own - `global_speed_limit`. + `global_speed_limit`. A `serve` or `services..dl` value that the API refuses in a + request body, `workers: 0` for example, makes each job that uses it fail at submit with + `400 INVALID_PARAMETERS`. ## `continue_downloads` diff --git a/tests/remote/unit/test_job_admission.py b/tests/remote/unit/test_job_admission.py index 9d1499a6..c7561910 100644 --- a/tests/remote/unit/test_job_admission.py +++ b/tests/remote/unit/test_job_admission.py @@ -84,6 +84,50 @@ def test_a_serve_default_that_dl_refuses_with_the_request_is_refused_at_create(s assert "--include-sample" in ei.value.message +@pytest.mark.parametrize( + ("serve", "services", "body", "prefix"), + [ + ({"workers": 0}, {}, {}, "serve: workers"), + ({}, {"EXAMPLE": {"dl": {"imdb_id": "nope"}}}, {}, "services.EXAMPLE.dl: imdb_id"), + ({"no_subs": "maybe"}, {}, {}, "serve: Invalid no_subs"), + ({"wanted": "zz"}, {}, {}, "serve: Invalid wanted"), + ({"all_drm": True}, {}, {"cdm": "dev"}, "all_drm needs a CDM"), + ], +) +def test_a_bad_config_default_is_refused_at_admission(server, monkeypatch, serve, services, body, prefix): + monkeypatch.setattr(handlers.config, "serve", serve) + monkeypatch.setattr(handlers.config, "services", services) + with pytest.raises(APIError) as ei: + admit(body) + assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS + assert ei.value.message.startswith(prefix) + + +def test_a_bad_config_default_that_a_later_layer_replaces_is_not_read(server, monkeypatch): + monkeypatch.setattr(handlers.config, "serve", {"workers": 0, "imdb_id": "nope"}) + monkeypatch.setattr(handlers.config, "services", {"EXAMPLE": {"dl": {"workers": 4, "tmdb_id": -3}}}) + params = admit({"imdb_id": "tt1", "tmdb_id": None}).params + assert (params["workers"], params["imdb_id"]) == (4, "tt1") + + +def test_a_relayed_job_does_not_read_the_local_service_defaults(server, monkeypatch): + async def relay(data, request): + return "box", {"tag": "EXAMPLE"}, {**data, "service": "EXAMPLE"} + + monkeypatch.setattr(handlers, "relay_target", relay) + monkeypatch.setattr(handlers.config, "services", {"EXAMPLE": {"dl": {"workers": 0}}}) + assert admit({"remote": "box"}).params["workers"] is None + + +def test_config_defaults_in_their_cli_form_pass_and_are_stored_raw(server, monkeypatch): + serve = {"lang": "en", "a_lang": "orig,-es", "latest_episodes": "3", "output_dir": "/elsewhere", "profile": "my p"} + monkeypatch.setattr(handlers.config, "serve", serve) + monkeypatch.setattr(handlers.config, "services", {"EXAMPLE": {"dl": {"quality": "1080p", "no_subs": "yes"}}}) + params = admit({}).params + assert {k: params[k] for k in serve} == serve + assert (params["quality"], params["no_subs"]) == ("1080p", "yes") + + def test_a_relayed_retry_resubmits_only_what_the_client_sent(server, monkeypatch): async def relay(data, request): return "box", {"tag": "EXAMPLE"}, {**data, "service": "EXAMPLE"} diff --git a/unshackle/core/api/job_admission.py b/unshackle/core/api/job_admission.py index b4ae7619..8f97234e 100644 --- a/unshackle/core/api/job_admission.py +++ b/unshackle/core/api/job_admission.py @@ -13,9 +13,9 @@ from unshackle.core.api import handlers from unshackle.core.api.download_manager import plan_keys, stamped_keys from unshackle.core.api.errors import APIError from unshackle.core.config import config -from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_API_NAMES +from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_ALIASES, DL_OPTION_API_NAMES from unshackle.core.remote_protocol import APIErrorCode -from unshackle.core.run_plan import PlanError, api_plan +from unshackle.core.run_plan import PlanError, api_plan, cast_plan from unshackle.core.services import ROUTING_PARAMS, Services from unshackle.core.utils.collections import as_list, ci_get @@ -81,10 +81,13 @@ def job_spec(data: dict[str, Any], server: str | None, request: web.Request | No sent = {k: v for k, v in data.items() if k not in ENVELOPE_KEYS} serve_defaults = {k: v for k, v in (config.serve or {}).items() if k in DEFAULT_DOWNLOAD_PARAMS and v is not None} # A relayed job gets no local service overrides, so none of its keys may count as defaults. + service_defaults = {} if server else service_dl_defaults(service) + check_defaults("serve", serve_defaults, {**service_defaults, **sent}, data) + check_defaults(f"services.{service}.dl", service_defaults, sent, data) params = { **DEFAULT_DOWNLOAD_PARAMS, **serve_defaults, - **({} if server else service_dl_defaults(service)), + **service_defaults, **sent, "client_keys": sorted(sent), } @@ -148,11 +151,6 @@ def check_parameters(data: dict[str, Any]) -> dict[str, Any]: raise invalid("output_dir must be a path under the server's downloads directory.", data) checked["output_dir"] = str(target) - if data.get("all_drm") and data.get("cdm"): - raise invalid( - "all_drm needs a CDM for each DRM system, so it cannot be used with cdm, which selects one device.", data - ) - for name in POSITIVE_INT_KEYS: value = data.get(name) if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value <= 0): @@ -184,10 +182,32 @@ def check_parameters(data: dict[str, Any]) -> dict[str, Any]: return checked +def check_defaults(source: str, defaults: dict[str, Any], overrides: dict[str, Any], data: dict[str, Any]) -> None: + """INVALID_PARAMETERS, prefixed with the config block ``source``, for a default that a request body could not send. + + Only the defaults that ``overrides`` does not replace are read, as click reads a default only for an option not + given. They are read as dl casts them, so a value in the CLI form of the config (``lang: en``) passes. The + operator's ``output_dir`` and ``profile`` are not held to the client rules. + """ + used = {k: v for k, v in defaults.items() if k not in overrides and k not in ("output_dir", "profile")} + if not used: + return + try: + cast = cast_plan(used, ()).params + check_parameters({k: cast[DL_OPTION_ALIASES.get(k, k)] for k in used}) + except (PlanError, APIError) as e: + raise invalid(f"{source}: {e.message}", data) from None + + def check_plan(params: dict[str, Any]) -> None: - """INVALID_PARAMETERS when dl would refuse the job's merged parameters, as the worker plans them.""" + """INVALID_PARAMETERS when dl would refuse the job's merged parameters, as the worker plans them, or when they + pair ``all_drm`` with a ``cdm``.""" from unshackle.commands.dl import subtitle_look + if params.get("all_drm") and params.get("cdm"): + raise invalid( + "all_drm needs a CDM for each DRM system, so it cannot be used with cdm, which selects one device.", params + ) try: plan = api_plan(params, plan_keys(params)).params except PlanError as e: diff --git a/unshackle/core/utils/service_params.py b/unshackle/core/utils/service_params.py index eb6958e3..80c9405a 100644 --- a/unshackle/core/utils/service_params.py +++ b/unshackle/core/utils/service_params.py @@ -46,6 +46,9 @@ def cast_service_options(params: Iterable[click.Parameter], ctx: Any, options: d raise click.BadParameter("expected a number, not a boolean", ctx=ctx, param=param) try: cast[k] = param.type_cast_value(ctx, v) + except click.BadParameter as e: + e.param = e.param or param + raise except (TypeError, ValueError, AttributeError, OverflowError) as e: raise click.BadParameter(f"not a valid {param.type.name} value", ctx=ctx, param=param) from e return cast