mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
refactor(api): admit download job create and retry through one job_admission step
This commit is contained in:
@@ -707,10 +707,10 @@ Remove every terminal (completed/failed/cancelled) job from the manager. No requ
|
||||
|
||||
### `POST /api/download/jobs/{job_id}/retry`
|
||||
|
||||
Enqueue a **new** job that reuses a terminal job's service, title, and parameters. The service allowlist and parameter gates are re-checked. Returns `202` with the new job's ID.
|
||||
Enqueue a **new** job from the request that made a terminal job. The request goes through the same checks as a new submission: the service allowlist, the parameter checks and the download gates. A parameter that the request did not send takes the server default of the time of the retry. Returns `202` with the new job's ID.
|
||||
|
||||
!!! warning "Retry reuses the original, unredacted parameters"
|
||||
A retry replays the finished job's stored parameters exactly as the original client submitted them, including any secrets such as `credential`/`credentials`. It does not use the redacted `parameters` view that `GET /api/download/jobs` and `GET /api/history` give. This is deliberate: it lets a retried job reproduce a credentialed download that the redacted job record alone never could. The API masks those credentials everywhere else. But anyone who can retry a job can operate it again with the original credentials.
|
||||
A retry sends again the parameters that the original client submitted, including any secrets such as `credential`/`credentials`. It does not use the redacted `parameters` view that `GET /api/download/jobs` and `GET /api/history` give. This is deliberate: it lets a retried job reproduce a credentialed download that the redacted job record alone never could. The API masks those credentials everywhere else. But anyone who can retry a job can operate it again with the original credentials.
|
||||
|
||||
=== "Response `202`"
|
||||
|
||||
@@ -728,6 +728,7 @@ Enqueue a **new** job that reuses a terminal job's service, title, and parameter
|
||||
| `404` | `JOB_NOT_FOUND` | No such job. |
|
||||
| `409` | `CONFLICT` | Job is not in a terminal state. |
|
||||
| `400` | `INVALID_SERVICE` | Service is no longer allowed. |
|
||||
| `400` | `INVALID_PARAMETERS` | A parameter no longer passes the checks, for example an `output_dir` outside a moved downloads directory. |
|
||||
| `403` | `FORBIDDEN` | A gated parameter is no longer permitted. |
|
||||
| `403` | `SERVER_CDM_CAPPED` | The job is no longer inside the `server_cdm_max_height` of the API key. |
|
||||
|
||||
|
||||
@@ -265,9 +265,13 @@ ID with `202`.
|
||||
- You can retry only terminal jobs. A retry of a `queued` or `downloading` job returns
|
||||
`409` with error code `CONFLICT`.
|
||||
- A missing job returns `404` (`JOB_NOT_FOUND`).
|
||||
- The server examines the service allowlist and any download gates again for the new
|
||||
job, exactly as for the original submission. Thus the server can reject a retry with
|
||||
`INVALID_SERVICE` or `FORBIDDEN` if permissions changed.
|
||||
- The server sends the original request through the same checks as a new submission:
|
||||
the service allowlist, the parameter checks and the download gates. A retry that no
|
||||
longer passes gets the same error as a new submission, for example
|
||||
`INVALID_SERVICE`, `INVALID_PARAMETERS` or `FORBIDDEN` after a config change.
|
||||
- Each parameter that the original request did not send takes the server default of
|
||||
the time of the retry, from `serve:` and `services.<TAG>.dl`. A job for a
|
||||
`remote` server takes no local service defaults.
|
||||
|
||||
```json title="202 Accepted, a fresh job"
|
||||
{
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Test helper for the parameter check of download job admission."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.job_admission import check_parameters, check_plan
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
|
||||
def refusal(data: dict[str, Any]) -> str | None:
|
||||
"""The message of the INVALID_PARAMETERS refusal that the parameter and plan checks give ``data``, else None."""
|
||||
try:
|
||||
check_plan(check_parameters(data))
|
||||
except APIError as e:
|
||||
assert e.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||
return e.message
|
||||
return None
|
||||
@@ -14,9 +14,10 @@ from pyplayready.system.pssh import PSSH as PR_PSSH
|
||||
from pywidevine.cdm import Cdm as WidevineCdm
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
from tests.admission import refusal
|
||||
from tests.core.key_resolver import NoVaults, key_table, resolver
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api.handlers import load_full_cdm, resolve_server_cdm, validate_download_parameters
|
||||
from unshackle.core.api.handlers import load_full_cdm, resolve_server_cdm
|
||||
from unshackle.core.cdm.detect import is_widevine_cdm
|
||||
from unshackle.core.drm import PlayReady, Widevine
|
||||
from unshackle.core.manifests import HLS
|
||||
@@ -208,9 +209,9 @@ def test_the_other_drm_system_can_return_a_different_set_of_kids() -> None:
|
||||
|
||||
|
||||
def test_the_api_refuses_all_drm_with_one_device() -> None:
|
||||
assert "cdm" in (validate_download_parameters({"all_drm": True, "cdm": "device"}) or "")
|
||||
assert validate_download_parameters({"all_drm": True, "cdm_only": True}) is None
|
||||
assert validate_download_parameters({"all_drm": True, "cdm_only": False}) is None
|
||||
assert "cdm" in (refusal({"all_drm": True, "cdm": "device"}) or "")
|
||||
assert refusal({"all_drm": True, "cdm_only": True}) is None
|
||||
assert refusal({"all_drm": True, "cdm_only": False}) is None
|
||||
|
||||
|
||||
def test_a_content_key_in_a_vault_stops_the_challenge_of_each_drm_system() -> None:
|
||||
|
||||
@@ -18,10 +18,10 @@ from typing import Any
|
||||
import pytest
|
||||
|
||||
import unshackle.commands.dl as dl_module
|
||||
from tests.admission import refusal
|
||||
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
|
||||
from unshackle.core import mux_step
|
||||
from unshackle.core.api import download_manager, handlers, key_policy
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.mux_step import hybrid_plan, hybrid_source_tracks, hybrid_step_error, missing_hybrid_error
|
||||
from unshackle.core.service import Service, TrackRequest
|
||||
@@ -784,8 +784,8 @@ def test_the_hybrid_step_gets_the_base_alone_when_there_is_no_dv(tmp_path: Path)
|
||||
def test_the_api_takes_generate_dv_with_any_range_as_dl_does(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr("unshackle.core.binaries.DoviTool", Path("dovi_tool"))
|
||||
for data in ({}, {"range": ["SDR"]}, {"range": ["DV"]}, {"range": ["HYBRID"]}, {"range": ["HDR10"]}):
|
||||
assert validate_download_parameters({"generate_dv": True, **data}) is None
|
||||
assert "boolean" in (validate_download_parameters({"generate_dv": "yes", "range": ["HYBRID"]}) or "")
|
||||
assert refusal({"generate_dv": True, **data}) is None
|
||||
assert "boolean" in (refusal({"generate_dv": "yes", "range": ["HYBRID"]}) or "")
|
||||
|
||||
|
||||
class _Captured(Exception):
|
||||
|
||||
@@ -4,8 +4,8 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.admission import refusal
|
||||
from unshackle.commands.dl import latest_episode_keys
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.titles import Movie, Movies, Series
|
||||
from unshackle.core.titles.episode import Episode
|
||||
|
||||
@@ -52,8 +52,8 @@ def test_titles_that_are_not_a_series_are_left_alone() -> None:
|
||||
|
||||
@pytest.mark.parametrize("value", [0, -1, True, "3", 1.5])
|
||||
def test_a_non_positive_or_non_integer_count_is_refused(value: object) -> None:
|
||||
assert validate_download_parameters({"latest_episodes": value}) == "latest_episodes must be a positive integer"
|
||||
assert refusal({"latest_episodes": value}) == "latest_episodes must be a positive integer"
|
||||
|
||||
|
||||
def test_a_positive_count_is_accepted() -> None:
|
||||
assert validate_download_parameters({"latest_episodes": 3}) is None
|
||||
assert refusal({"latest_episodes": 3}) is None
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from tests.admission import refusal
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.run_plan import PlanError, validate_metadata_ids
|
||||
|
||||
@@ -90,18 +90,18 @@ def test_one_kind_keeping_the_provider_is_enough(monkeypatch: pytest.MonkeyPatch
|
||||
],
|
||||
)
|
||||
def test_api_refuses_two_ids(payload: dict) -> None:
|
||||
err = validate_download_parameters(payload)
|
||||
err = refusal(payload)
|
||||
assert err and "cannot be used together" in err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [{"tmdb_id": 27205}, {"imdb_id": "tt1375666"}, {"tvdb_id": 73871}, {}])
|
||||
def test_api_accepts_one_id(payload: dict, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
with_keys(monkeypatch, tmdb_api_key="k", tvdb_api_key="k")
|
||||
assert validate_download_parameters(payload) is None
|
||||
assert refusal(payload) is None
|
||||
|
||||
|
||||
def test_api_still_reports_a_malformed_id_first() -> None:
|
||||
err = validate_download_parameters({"tmdb_id": "12345", "imdb_id": "tt1"})
|
||||
err = refusal({"tmdb_id": "12345", "imdb_id": "tt1"})
|
||||
assert err and "positive integer" in err
|
||||
|
||||
|
||||
@@ -133,21 +133,21 @@ def test_a_malformed_anilist_value_is_refused(monkeypatch: pytest.MonkeyPatch, v
|
||||
|
||||
@pytest.mark.parametrize("payload", [{"anilist_id": 21}, {"anilist_id": "mal:21"}, {"anilist_id": "21"}])
|
||||
def test_api_accepts_an_anilist_id(payload: dict) -> None:
|
||||
assert validate_download_parameters(payload) is None
|
||||
assert refusal(payload) is None
|
||||
|
||||
|
||||
def test_api_accepts_anilist_alongside_one_western_id() -> None:
|
||||
assert validate_download_parameters({"imdb_id": "tt1375666", "anilist_id": 21}) is None
|
||||
assert refusal({"imdb_id": "tt1375666", "anilist_id": 21}) is None
|
||||
|
||||
|
||||
def test_api_still_refuses_two_western_ids_with_anilist() -> None:
|
||||
err = validate_download_parameters({"tmdb_id": 27205, "imdb_id": "tt1375666", "anilist_id": 21})
|
||||
err = refusal({"tmdb_id": 27205, "imdb_id": "tt1375666", "anilist_id": 21})
|
||||
assert err and "cannot be used together" in err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [0, -3, True, "mal:", "tt1375666", "anilist:21", 1.5])
|
||||
def test_api_refuses_a_malformed_anilist_id(value: object) -> None:
|
||||
err = validate_download_parameters({"anilist_id": value})
|
||||
err = refusal({"anilist_id": value})
|
||||
assert err and "anilist" in err
|
||||
|
||||
|
||||
@@ -162,17 +162,15 @@ def test_a_non_positive_or_non_decimal_anilist_value_is_refused(monkeypatch: pyt
|
||||
@pytest.mark.parametrize("payload", [{"anilist_id": "MAL:21"}, {"anilist_id": "007"}, {"anilist_id": " 21 "}])
|
||||
def test_api_accepts_what_the_cli_accepts(payload: dict) -> None:
|
||||
"""Both surfaces share parse_anilist_ref, so their accept sets cannot drift."""
|
||||
assert validate_download_parameters(payload) is None
|
||||
assert refusal(payload) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["0", "mal:0", "²"])
|
||||
def test_api_refuses_what_the_cli_refuses(value: str) -> None:
|
||||
err = validate_download_parameters({"anilist_id": value})
|
||||
err = refusal({"anilist_id": value})
|
||||
assert err and "anilist" in err
|
||||
|
||||
|
||||
def test_api_refuses_an_id_no_configured_provider_can_find(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
with_keys(monkeypatch)
|
||||
assert validate_download_parameters({"tmdb_id": 27205}) == (
|
||||
"--tmdb needs the tmdb provider: set tmdb_api_key in your config"
|
||||
)
|
||||
assert refusal({"tmdb_id": 27205}) == "--tmdb needs the tmdb provider: set tmdb_api_key in your config"
|
||||
|
||||
@@ -10,9 +10,9 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.admission import refusal
|
||||
from tests.lang_selection import test_kind_only_selection as harness
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.utilities import kind_only_conflict
|
||||
|
||||
KEYS = ["audio_description_only", "forced_subs_only"]
|
||||
@@ -56,18 +56,18 @@ def test_kind_only_conflict(params, expected):
|
||||
|
||||
|
||||
def test_api_rejects_a_conflict():
|
||||
assert validate_download_parameters({**BASE, "audio_description_only": True, "no_audio": True}) == (
|
||||
assert refusal({**BASE, "audio_description_only": True, "no_audio": True}) == (
|
||||
"--audio-description-only cannot be used with --no-audio: --no-audio drops the tracks that "
|
||||
"--audio-description-only selects."
|
||||
)
|
||||
assert validate_download_parameters({**BASE, "audio_description_only": True, "audio_only": True}) is None
|
||||
assert refusal({**BASE, "audio_description_only": True, "audio_only": True}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", [*KEYS, "audio_description", "audio_only"])
|
||||
def test_api_rejects_a_non_boolean_flag(key):
|
||||
# the string "false" is truthy in dl.result, so it would turn the flag on
|
||||
assert validate_download_parameters({**BASE, key: "false"}) == f"{key} must be a boolean"
|
||||
assert validate_download_parameters({**BASE, key: None}) is None
|
||||
assert refusal({**BASE, key: "false"}) == f"{key} must be a boolean"
|
||||
assert refusal({**BASE, key: None}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flags", [{"forced_subs_only": True}, {"forced_s_lang": ["en"]}, {"forced_s_lang": ["-en"]}])
|
||||
|
||||
@@ -93,11 +93,11 @@ def test_api_passes_the_flags_through(key):
|
||||
|
||||
|
||||
def test_api_accepts_the_require_flags():
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from tests.admission import refusal
|
||||
|
||||
# unlike require_subs, these carry no conflict with a language selection
|
||||
assert (
|
||||
validate_download_parameters(
|
||||
refusal(
|
||||
{"service": "EXAMPLE", "title": "x", "require_audio": ["en"], "require_video": ["en"], "lang": ["en", "fr"]}
|
||||
)
|
||||
is None
|
||||
@@ -121,22 +121,17 @@ def test_api_reaches_dl_result(key, default):
|
||||
@pytest.mark.parametrize("key", ["require_audio", "require_video"])
|
||||
def test_api_rejects_a_non_array_require_value(key, value):
|
||||
# a JSON string iterates character by character and blows up in langcodes, so it must 400 first
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from tests.admission import refusal
|
||||
|
||||
error = validate_download_parameters({"service": "EXAMPLE", "title": "x", key: value})
|
||||
error = refusal({"service": "EXAMPLE", "title": "x", key: value})
|
||||
assert error == f"{key} must be an array of language strings"
|
||||
|
||||
|
||||
def test_require_subs_no_longer_conflicts_with_s_lang():
|
||||
# gate and selection are separate concerns: -sl decides what to keep, --require-subs only gates
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from tests.admission import refusal
|
||||
|
||||
assert (
|
||||
validate_download_parameters(
|
||||
{"service": "EXAMPLE", "title": "x", "s_lang": ["en", "ko", "ja"], "require_subs": ["en"]}
|
||||
)
|
||||
is None
|
||||
)
|
||||
assert refusal({"service": "EXAMPLE", "title": "x", "s_lang": ["en", "ko", "ja"], "require_subs": ["en"]}) is None
|
||||
|
||||
|
||||
def test_exact_lang_turns_off_the_bare_tag_fallback():
|
||||
|
||||
@@ -7,9 +7,9 @@ import click
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from tests.admission import refusal
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api import routes
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.dl_options import (
|
||||
DEFAULT_DOWNLOAD_PARAMS,
|
||||
DL_OPTION_ALIASES,
|
||||
@@ -164,7 +164,7 @@ def test_no_forwarded_option_has_an_alias():
|
||||
@pytest.mark.parametrize("value", ["en", "en,fr", [1], {"x": "en"}])
|
||||
def test_api_rejects_a_non_array_language_value(key, value):
|
||||
"""A string would reach dl.result and split into one-character language codes."""
|
||||
assert validate_download_parameters({key: value}) == f"{key} must be an array of language strings"
|
||||
assert refusal({key: value}) == f"{key} must be an array of language strings"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -176,7 +176,7 @@ def test_api_rejects_a_non_array_language_value(key, value):
|
||||
],
|
||||
)
|
||||
def test_api_refuses_a_value_the_dl_option_cannot_take(data, error):
|
||||
assert (validate_download_parameters(data) or "").startswith(error)
|
||||
assert (refusal(data) or "").startswith(error)
|
||||
|
||||
|
||||
def test_no_dl_option_needs_a_parse_step_the_cast_skips():
|
||||
@@ -196,7 +196,7 @@ def test_a_boolean_is_not_a_number(key):
|
||||
|
||||
@pytest.mark.parametrize("value", [[1], [None], {"a": 1}])
|
||||
def test_a_non_string_range_is_a_validation_error(value):
|
||||
assert (validate_download_parameters({"range": value}) or "").startswith("Invalid range")
|
||||
assert (refusal({"range": value}) or "").startswith("Invalid range")
|
||||
|
||||
|
||||
def test_the_worker_keeps_the_code_of_an_api_error(tmp_path, monkeypatch):
|
||||
|
||||
@@ -9,8 +9,8 @@ import click
|
||||
import pytest
|
||||
|
||||
import unshackle.commands.dl as dl_module
|
||||
from tests.admission import refusal
|
||||
from unshackle.core.api import download_manager, handlers, key_policy
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.services import Services
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
@@ -22,7 +22,7 @@ class _Captured(Exception):
|
||||
|
||||
@pytest.mark.parametrize("quality", ["1080p", ["1080"], [1080, 720], "1080,720"])
|
||||
def test_the_api_accepts_the_quality_forms_the_cli_accepts(quality: Any) -> None:
|
||||
assert validate_download_parameters({"quality": quality}) is None
|
||||
assert refusal({"quality": quality}) is None
|
||||
|
||||
|
||||
def test_a_rest_job_converts_quality_and_passes_cdm_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
@@ -8,7 +8,7 @@ import click
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import download_manager as dm
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, job_admission
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
@@ -35,7 +35,7 @@ def env(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: "EXAMPLE1")
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace())
|
||||
monkeypatch.setattr(dm, "get_download_manager", lambda: manager)
|
||||
monkeypatch.setattr(handlers, "enforce_download_gates", lambda params, request: gate_input.update(params))
|
||||
monkeypatch.setattr(job_admission, "enforce_download_gates", lambda params, request: gate_input.update(params))
|
||||
monkeypatch.setattr(handlers, "caller_key", lambda request: None)
|
||||
monkeypatch.setattr(handlers.config, "serve", {}, raising=False)
|
||||
monkeypatch.setattr(handlers.config, "services", {}, raising=False)
|
||||
@@ -94,9 +94,10 @@ def test_relayed_job_skips_service_dl(env, monkeypatch):
|
||||
|
||||
monkeypatch.setattr(handlers, "relay_target", relay)
|
||||
baseline_workers = DEFAULT_DOWNLOAD_PARAMS["workers"]
|
||||
params = env(dl={"workers": 7})
|
||||
params = env(body={"remote": "box"}, dl={"workers": 7})
|
||||
assert params["workers"] == baseline_workers
|
||||
assert set(params["client_keys"]) >= set(DEFAULT_DOWNLOAD_PARAMS)
|
||||
assert params["client_keys"] == ["remote"]
|
||||
assert dm.client_sent_keys(params) is None
|
||||
|
||||
|
||||
def test_client_sent_keys_uses_the_stamp():
|
||||
|
||||
@@ -9,6 +9,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from tests.admission import refusal
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.download_manager import (
|
||||
DownloadJob,
|
||||
@@ -167,11 +168,11 @@ async def test_credential_allowed_when_enabled(stub_handler):
|
||||
def test_range_validation_accepts_hdr10p_and_alias(monkeypatch):
|
||||
monkeypatch.setattr("unshackle.core.binaries.DoviTool", Path("dovi_tool"))
|
||||
# canonical "HDR10P" and back-compat "HDR10+" both pass; mixed casing too
|
||||
assert handlers.validate_download_parameters({"range": ["HDR10P", "DV", "SDR"]}) is None
|
||||
assert handlers.validate_download_parameters({"range": ["hdr10+"]}) is None
|
||||
assert handlers.validate_download_parameters({"range": "HYBRID"}) is None
|
||||
assert refusal({"range": ["HDR10P", "DV", "SDR"]}) is None
|
||||
assert refusal({"range": ["hdr10+"]}) is None
|
||||
assert refusal({"range": "HYBRID"}) is None
|
||||
|
||||
|
||||
def test_range_validation_rejects_unknown_and_lists_hdr10p():
|
||||
err = handlers.validate_download_parameters({"range": ["HDR99"]})
|
||||
err = refusal({"range": ["HDR99"]})
|
||||
assert err and "hdr10p" in err.lower() and "HDR99" in err
|
||||
|
||||
@@ -5,7 +5,7 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api import handlers, job_admission, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.utils import ip_info
|
||||
@@ -213,38 +213,38 @@ class TestDownloadGates:
|
||||
|
||||
def test_country_code_rejected_when_denied(self, monkeypatch):
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE", "proxy": "us"}, request("plainkey"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "us"}, request("plainkey"))
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
|
||||
def test_provider_country_rejected_when_denied(self, monkeypatch):
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE", "proxy": "nordvpn:us"}, request("plainkey"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "nordvpn:us"}, request("plainkey"))
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
|
||||
def test_full_uri_passes_when_denied(self):
|
||||
handlers.enforce_download_gates(
|
||||
job_admission.enforce_download_gates(
|
||||
{"service": "EXAMPLE", "proxy": "socks5://user:pass@host:1080"}, request("plainkey")
|
||||
)
|
||||
|
||||
def test_no_proxy_param_passes_when_denied(self):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE"}, request("plainkey"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE"}, request("plainkey"))
|
||||
|
||||
def test_country_code_passes_when_opted_in(self, monkeypatch):
|
||||
# The gate must not even try to resolve for an opted-in key: dl resolves at run time,
|
||||
# exactly as before the gate existed.
|
||||
monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda **_: pytest.fail("providers loaded"))
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE", "proxy": "us"}, request("proxykey"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "us"}, request("proxykey"))
|
||||
|
||||
def test_region_mismatch_rejected_at_submit(self, monkeypatch):
|
||||
"""A queued job reaches the same region verdict, at submission."""
|
||||
patch_server_region(monkeypatch, "IN")
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE", "client_region": "gb"}, request("plainkey"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE", "client_region": "gb"}, request("plainkey"))
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
|
||||
def test_download_proxy_on_local_network_refused(self):
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.enforce_download_gates(
|
||||
job_admission.enforce_download_gates(
|
||||
{"service": "EXAMPLE", "proxy_download": "http://127.0.0.1:9"}, request("plainkey")
|
||||
)
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
@@ -275,7 +275,7 @@ class TestDownloadEnforcement:
|
||||
|
||||
monkeypatch.setattr(dm, "get_download_manager", lambda: FakeManager())
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: "EXAMPLE")
|
||||
monkeypatch.setattr(handlers, "enforce_download_gates", lambda params, request=None: None)
|
||||
monkeypatch.setattr(job_admission, "enforce_download_gates", lambda params, request=None: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace())
|
||||
|
||||
def run(body, req):
|
||||
|
||||
@@ -8,13 +8,13 @@ import pytest
|
||||
import requests
|
||||
from langcodes import Language
|
||||
|
||||
from tests.admission import refusal
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.handlers import (
|
||||
drm_preference_name,
|
||||
listed_titles,
|
||||
sanitize_log,
|
||||
search_handler,
|
||||
validate_download_parameters,
|
||||
validate_service,
|
||||
)
|
||||
from unshackle.core.config import config
|
||||
@@ -288,7 +288,7 @@ def test_validate_service_unknown_returns_none() -> None:
|
||||
|
||||
|
||||
def test_validate_download_params_accepts_defaults() -> None:
|
||||
assert validate_download_parameters({}) is None
|
||||
assert refusal({}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -304,7 +304,7 @@ def test_validate_download_params_accepts_defaults() -> None:
|
||||
({"vbitrate": 5000, "vbitrate_range": "1-2"}, "--vbitrate and --vbitrate-range"),
|
||||
({"abitrate": 128, "abitrate_range": "96-256"}, "--abitrate and --abitrate-range"),
|
||||
({"abitrate_range": "1-2-3"}, "MIN-MAX"),
|
||||
({"quality": "4k"}, "Invalid quality"),
|
||||
({"quality": "4k"}, "quality: "),
|
||||
({"quality": [0]}, "above 0"),
|
||||
({"channels": -3}, "channels"),
|
||||
({"workers": 0}, "workers"),
|
||||
@@ -318,7 +318,7 @@ def test_validate_download_params_accepts_defaults() -> None:
|
||||
],
|
||||
)
|
||||
def test_validate_download_params_errors(data: dict, fragment) -> None:
|
||||
result = validate_download_parameters(data)
|
||||
result = refusal(data)
|
||||
if fragment is None:
|
||||
assert result is None
|
||||
else:
|
||||
@@ -328,7 +328,7 @@ def test_validate_download_params_errors(data: dict, fragment) -> None:
|
||||
|
||||
def test_validate_download_params_accepts_valid_values() -> None:
|
||||
assert (
|
||||
validate_download_parameters(
|
||||
refusal(
|
||||
{
|
||||
"vcodec": "H264,H265",
|
||||
"acodec": ["AAC", "EAC3"],
|
||||
@@ -347,7 +347,7 @@ def test_validate_download_params_accepts_valid_values() -> None:
|
||||
|
||||
@pytest.mark.parametrize("vrange", ["6000-7000", "7000-6000", " 6000 - 7000 "])
|
||||
def test_validate_download_params_accepts_valid_bitrate_ranges(vrange: str) -> None:
|
||||
assert validate_download_parameters({"vbitrate_range": vrange, "abitrate_range": "96-192"}) is None
|
||||
assert refusal({"vbitrate_range": vrange, "abitrate_range": "96-192"}) is None
|
||||
|
||||
|
||||
async def test_search_missing_service_raises_invalid_input() -> None:
|
||||
@@ -368,7 +368,7 @@ async def test_search_unknown_service_raises_invalid_service() -> None:
|
||||
|
||||
|
||||
def test_resolve_vcodec_rejects_junk_as_invalid_input() -> None:
|
||||
"""Session routes skip validate_download_parameters, so a bad codec must be a 400, not a 500."""
|
||||
"""Session routes skip the download job admission, so a bad codec must be a 400, not a 500."""
|
||||
from unshackle.core.api.handlers import resolve_vcodec
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.tracks import Video
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Download job admission: one checked, merged and allowed job spec for a create and for a retry."""
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers, job_admission
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(monkeypatch, tmp_path):
|
||||
"""A server with the EXAMPLE service installed and no serve or service config."""
|
||||
monkeypatch.setattr(handlers.config, "serve", {}, raising=False)
|
||||
monkeypatch.setattr(handlers.config, "services", {}, raising=False)
|
||||
monkeypatch.setattr(handlers.config.directories, "downloads", tmp_path)
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "EXAMPLE")
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
|
||||
return tmp_path
|
||||
|
||||
|
||||
def admit(body):
|
||||
return asyncio.run(job_admission.admit_job({"service": "example", "title_id": "t1", **body}))
|
||||
|
||||
|
||||
def test_a_retry_admits_the_same_job_as_its_create(server):
|
||||
spec = admit({"workers": 4, "output_dir": "shows", "lang": ["en"]})
|
||||
again = admit(job_admission.resubmission(spec.service, spec.title_id, spec.params))
|
||||
assert again == spec
|
||||
assert spec.params["client_keys"] == ["lang", "output_dir", "workers"]
|
||||
assert spec.params["output_dir"] == str((server / "shows").resolve())
|
||||
|
||||
|
||||
def test_a_retry_takes_the_server_defaults_of_today(server, monkeypatch):
|
||||
spec = admit({"lang": ["en"]})
|
||||
monkeypatch.setattr(handlers.config, "serve", {"workers": 9})
|
||||
again = admit(job_admission.resubmission(spec.service, spec.title_id, spec.params))
|
||||
assert again.params["workers"] == 9
|
||||
assert again.params["lang"] == ["en"]
|
||||
|
||||
|
||||
def test_a_retry_whose_parameters_no_longer_pass_gets_the_refusal_of_a_create(server, monkeypatch, tmp_path_factory):
|
||||
spec = admit({"output_dir": "shows"})
|
||||
monkeypatch.setattr(handlers.config.directories, "downloads", tmp_path_factory.mktemp("moved"))
|
||||
with pytest.raises(APIError) as retried:
|
||||
admit(job_admission.resubmission(spec.service, spec.title_id, spec.params))
|
||||
with pytest.raises(APIError) as created:
|
||||
admit({"output_dir": spec.params["output_dir"]})
|
||||
assert retried.value.error_code is created.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||
assert retried.value.message == created.value.message
|
||||
|
||||
|
||||
def test_a_job_without_a_client_keys_stamp_resubmits_every_parameter_but_the_server_stamps():
|
||||
body = job_admission.resubmission("EXAMPLE", "t1", {"workers": 2, "server_proxy": True})
|
||||
assert body == {"workers": 2, "service": "EXAMPLE", "title_id": "t1"}
|
||||
|
||||
|
||||
def test_the_server_proxy_stamp_comes_from_the_key_policy(server):
|
||||
assert admit({"server_proxy": True}).params["server_proxy"] is False
|
||||
|
||||
|
||||
def test_the_parameter_check_leaves_the_request_body_as_it_is(server):
|
||||
body = {"output_dir": "shows"}
|
||||
assert job_admission.check_parameters(body)["output_dir"] == str((server / "shows").resolve())
|
||||
assert body == {"output_dir": "shows"}
|
||||
|
||||
|
||||
def test_a_profile_that_names_a_path_is_invalid_parameters(server):
|
||||
with pytest.raises(APIError) as ei:
|
||||
admit({"profile": "../x"})
|
||||
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||
assert ei.value.details == {"service": "EXAMPLE", "title_id": "t1"}
|
||||
|
||||
|
||||
def test_a_serve_default_that_dl_refuses_with_the_request_is_refused_at_create(server, monkeypatch):
|
||||
monkeypatch.setattr(handlers.config, "serve", {"sample": "120-180"})
|
||||
with pytest.raises(APIError) as ei:
|
||||
admit({"include_sample": True})
|
||||
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||
assert "--include-sample" in ei.value.message
|
||||
|
||||
|
||||
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"}
|
||||
|
||||
monkeypatch.setattr(handlers, "relay_target", relay)
|
||||
monkeypatch.setattr(handlers.config, "serve", {"lang": "en", "workers": 8})
|
||||
spec = admit({"remote": "box", "quality": [1080]})
|
||||
assert spec.params["client_keys"] == ["quality", "remote"]
|
||||
monkeypatch.setattr(handlers.config, "serve", {"lang": "en", "workers": 2})
|
||||
again = admit(job_admission.resubmission(spec.service, spec.title_id, spec.params))
|
||||
assert again.params["workers"] == 2
|
||||
|
||||
|
||||
def test_a_retry_refused_by_admission_queues_no_job(server, monkeypatch):
|
||||
from datetime import datetime
|
||||
|
||||
from unshackle.core.api import download_manager as dm
|
||||
|
||||
spec = admit({"output_dir": "shows"})
|
||||
job = SimpleNamespace(
|
||||
service=spec.service, title_id=spec.title_id, parameters=spec.params, status=dm.JobStatus.FAILED
|
||||
)
|
||||
created = []
|
||||
|
||||
async def start_workers():
|
||||
return None
|
||||
|
||||
manager = SimpleNamespace(
|
||||
get_job=lambda job_id: job,
|
||||
start_workers=start_workers,
|
||||
create_job=lambda *a, **k: (
|
||||
created.append(k) or SimpleNamespace(job_id="j", status=dm.JobStatus.QUEUED, created_time=datetime.now())
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(dm, "get_download_manager", lambda: manager)
|
||||
monkeypatch.setattr(handlers, "owns_job", lambda job, request: True)
|
||||
monkeypatch.setattr(handlers.config.directories, "downloads", server / "moved")
|
||||
with pytest.raises(APIError) as ei:
|
||||
asyncio.run(handlers.retry_download_job_handler("j0"))
|
||||
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||
assert created == []
|
||||
@@ -8,7 +8,7 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api import handlers, job_admission, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.api.session_store import get_session_store
|
||||
@@ -87,7 +87,7 @@ def test_a_job_is_refused_for_a_key_with_its_own_identity(server, monkeypatch):
|
||||
handlers, "request_policy", lambda request: KeyPolicy({"server_cdm": True, "cdm": {"EXAMPLE": "own"}})
|
||||
)
|
||||
with pytest.raises(APIError, match="its own"):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE"})
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -5,7 +5,7 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import handlers, job_admission
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
@@ -37,9 +37,9 @@ def request(key):
|
||||
|
||||
|
||||
def test_download_gate_uses_job_service(serve_users):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1"}, request("tier2key"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE1"}, request("tier2key"))
|
||||
with pytest.raises(APIError):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE2"}, request("tier2key"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE2"}, request("tier2key"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("service", "allowed"), [("EXAMPLE1", True), ("EXAMPLE2", False)])
|
||||
@@ -61,6 +61,7 @@ async def test_retry_gate_uses_job_service(serve_users, monkeypatch, service, al
|
||||
monkeypatch.setattr(dm, "get_download_manager", lambda: manager)
|
||||
monkeypatch.setattr(handlers, "owns_job", lambda job, request: True)
|
||||
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
|
||||
|
||||
if allowed:
|
||||
response = await handlers.retry_download_job_handler("job1", request("tier2key"))
|
||||
@@ -75,12 +76,12 @@ async def test_retry_gate_uses_job_service(serve_users, monkeypatch, service, al
|
||||
def test_download_gate_follows_entitlement(serve_users, key, allowed):
|
||||
# A download job licenses with the server CDM, so submission obeys the same gate.
|
||||
if allowed:
|
||||
handlers.enforce_download_gates({}, request(key))
|
||||
job_admission.enforce_download_gates({}, request(key))
|
||||
else:
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.enforce_download_gates({}, request(key))
|
||||
job_admission.enforce_download_gates({}, request(key))
|
||||
assert ei.value.error_code == APIErrorCode.FORBIDDEN
|
||||
|
||||
|
||||
def test_download_gate_without_request(serve_users):
|
||||
handlers.enforce_download_gates({})
|
||||
job_admission.enforce_download_gates({})
|
||||
|
||||
@@ -17,7 +17,7 @@ from tests.remote.key_source import CAPPED, PR_DEVICE, MemoryKeySource, one_titl
|
||||
from tests.remote.sessions import session_entry
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core import remote_channel
|
||||
from unshackle.core.api import handlers, key_policy
|
||||
from unshackle.core.api import handlers, job_admission, key_policy
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.key_policy import KeyPolicy
|
||||
from unshackle.core.config import cdm_entry_names_device
|
||||
@@ -171,10 +171,10 @@ def test_a_vault_miss_raises_the_refusal_before_the_device_loads(widevine_env, m
|
||||
def test_download_jobs_stay_inside_the_cap(quality, allowed):
|
||||
params = {"service": "EXAMPLE1", "quality": quality}
|
||||
if allowed:
|
||||
handlers.enforce_download_gates(params, request("flat"))
|
||||
job_admission.enforce_download_gates(params, request("flat"))
|
||||
else:
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.enforce_download_gates(params, request("flat"))
|
||||
job_admission.enforce_download_gates(params, request("flat"))
|
||||
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
|
||||
|
||||
|
||||
@@ -251,13 +251,13 @@ def test_an_ultrawide_track_is_measured_as_the_smallest_quality_that_selects_it(
|
||||
@pytest.mark.parametrize("quality", [[-1], [0], [1080, 0]])
|
||||
def test_a_height_of_zero_or_less_is_invalid_input(quality):
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1", "quality": quality}, request("flat"))
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE1", "quality": quality}, request("flat"))
|
||||
assert ei.value.error_code is APIErrorCode.INVALID_INPUT
|
||||
|
||||
|
||||
def test_a_capped_download_job_cannot_set_best_available():
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.enforce_download_gates(
|
||||
job_admission.enforce_download_gates(
|
||||
{"service": "EXAMPLE1", "quality": [1080], "best_available": True}, request("flat")
|
||||
)
|
||||
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
|
||||
@@ -266,23 +266,31 @@ def test_a_capped_download_job_cannot_set_best_available():
|
||||
def test_the_download_gate_reads_the_serve_dl_defaults(monkeypatch):
|
||||
serve = {"users": USERS, "quality": [1080], "best_available": True}
|
||||
monkeypatch.setattr(handlers.config, "serve", serve, raising=False)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace())
|
||||
|
||||
def admit(**body):
|
||||
return job_admission.job_spec({"service": "EXAMPLE1", "title_id": "t1", **body}, None, request("flat"))
|
||||
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1"}, request("flat"))
|
||||
admit()
|
||||
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
|
||||
assert admit(best_available=False).params["quality"] == [1080]
|
||||
|
||||
serve["best_available"] = False
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1"}, request("flat"))
|
||||
# the job's own value wins over the serve default
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1", "best_available": False}, request("flat"))
|
||||
admit()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hdr_range", ["HYBRID", ["SDR", "hybrid"], [Video.Range.HYBRID]])
|
||||
def test_a_capped_download_job_cannot_ask_for_hybrid(hdr_range):
|
||||
"""HYBRID always keeps the lowest DV track, whatever the quality."""
|
||||
with pytest.raises(APIError) as ei:
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1", "quality": [1080], "range": hdr_range}, request("flat"))
|
||||
job_admission.enforce_download_gates(
|
||||
{"service": "EXAMPLE1", "quality": [1080], "range": hdr_range}, request("flat")
|
||||
)
|
||||
assert ei.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE1", "quality": [1080], "range": ["HDR10"]}, request("flat"))
|
||||
job_admission.enforce_download_gates(
|
||||
{"service": "EXAMPLE1", "quality": [1080], "range": ["HDR10"]}, request("flat")
|
||||
)
|
||||
|
||||
|
||||
def test_a_service_click_default_stays_out_of_the_download_gate(monkeypatch):
|
||||
|
||||
@@ -504,11 +504,11 @@ def test_a_connection_that_stops_reading_is_dropped() -> None:
|
||||
|
||||
|
||||
def test_a_download_job_refuses_a_tunnel_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api import job_admission
|
||||
from unshackle.core.api.errors import APIError
|
||||
|
||||
with pytest.raises(APIError, match="tunnel"):
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE", "proxy": "tunnel:abc"}, None)
|
||||
job_admission.enforce_download_gates({"service": "EXAMPLE", "proxy": "tunnel:t1"}, None)
|
||||
|
||||
|
||||
@responses.activate
|
||||
|
||||
@@ -177,13 +177,15 @@ def test_client_pssh_must_match_track(monkeypatch):
|
||||
|
||||
|
||||
def test_output_dir_stays_under_downloads(tmp_path, monkeypatch):
|
||||
from unshackle.core.api.handlers import config, validate_download_parameters
|
||||
from tests.admission import refusal
|
||||
from unshackle.core.api.handlers import config
|
||||
from unshackle.core.api.job_admission import check_parameters
|
||||
|
||||
monkeypatch.setattr(config.directories, "downloads", tmp_path)
|
||||
assert validate_download_parameters({"output_dir": "../../etc"})
|
||||
assert refusal({"output_dir": "../../etc"})
|
||||
data = {"output_dir": "shows/x"}
|
||||
assert validate_download_parameters(data) is None
|
||||
assert data["output_dir"] == str((tmp_path / "shows/x").resolve())
|
||||
assert check_parameters(data)["output_dir"] == str((tmp_path / "shows/x").resolve())
|
||||
assert data == {"output_dir": "shows/x"}
|
||||
|
||||
|
||||
def test_history_scoped_by_owner(tmp_path, monkeypatch):
|
||||
@@ -252,12 +254,13 @@ def test_track_own_pssh_passes_without_kids(monkeypatch):
|
||||
|
||||
|
||||
def test_download_rejects_path_profile_and_bad_output_dir(tmp_path, monkeypatch):
|
||||
from unshackle.core.api.handlers import config, validate_download_parameters
|
||||
from tests.admission import refusal
|
||||
from unshackle.core.api.handlers import config
|
||||
|
||||
monkeypatch.setattr(config.directories, "downloads", tmp_path)
|
||||
assert validate_download_parameters({"profile": "../x"})
|
||||
assert validate_download_parameters({"profile": "ok"}) is None
|
||||
assert validate_download_parameters({"output_dir": "a\x00b"})
|
||||
assert refusal({"profile": "../x"})
|
||||
assert refusal({"profile": "ok"}) is None
|
||||
assert refusal({"output_dir": "a\x00b"})
|
||||
|
||||
|
||||
def test_safe_inflate_rejects_non_str_via_isinstance():
|
||||
|
||||
@@ -15,7 +15,7 @@ import click
|
||||
import pytest
|
||||
from requests import Session
|
||||
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from tests.admission import refusal
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.manifests.dash import DASH
|
||||
from unshackle.core.placement import sample_name
|
||||
@@ -287,16 +287,16 @@ def test_sample_range_reads_a_window() -> None:
|
||||
|
||||
@pytest.mark.parametrize("sample", [True, "60-120", [60, 120]])
|
||||
def test_the_api_accepts_a_sample_window(sample: object) -> None:
|
||||
assert validate_download_parameters({"sample": sample}) is None
|
||||
assert refusal({"sample": sample}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sample", ["abc", "120-60", [1, 2, 3], ["a", "b"], 5, {"start": 1}])
|
||||
def test_the_api_refuses_a_bad_sample_window(sample: object) -> None:
|
||||
assert "sample" in (validate_download_parameters({"sample": sample}) or "")
|
||||
assert "sample" in (refusal({"sample": sample}) or "")
|
||||
|
||||
|
||||
def test_the_api_refuses_sample_with_include_sample() -> None:
|
||||
assert "--include-sample" in (validate_download_parameters({"sample": True, "include_sample": True}) or "")
|
||||
assert "--include-sample" in (refusal({"sample": True, "include_sample": True}) or "")
|
||||
|
||||
|
||||
def test_sample_name_uses_the_separator_of_the_template(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
@@ -5,9 +5,9 @@ from __future__ import annotations
|
||||
import pysubs2
|
||||
import pytest
|
||||
|
||||
from tests.admission import refusal
|
||||
from unshackle.commands.dl import dl, set_subtitle_look, subtitle_look
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.api.handlers import validate_download_parameters
|
||||
from unshackle.core.tracks import subtitle_convert as sc
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
@@ -221,11 +221,11 @@ def test_a_font_from_config_is_ignored_with_another_format():
|
||||
],
|
||||
)
|
||||
def test_the_api_refuses_a_sub_font_it_cannot_use(data, error):
|
||||
assert (validate_download_parameters(data) or "").startswith(error)
|
||||
assert (refusal(data) or "").startswith(error)
|
||||
|
||||
|
||||
def test_the_api_takes_a_sub_font_with_ass():
|
||||
assert validate_download_parameters({"sub_font": "My Font", "sub_format": "ASS"}) is None
|
||||
assert refusal({"sub_font": "My Font", "sub_format": "ASS"}) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -361,9 +361,24 @@ def delete_job_history(job_id: str, allowed: set | None = None, owner: str | Non
|
||||
return True
|
||||
|
||||
|
||||
def client_sent_keys(params: dict[str, Any]) -> set[str]:
|
||||
"""Pop the server's ``client_keys`` stamp; a job without one counts every parameter as client-sent."""
|
||||
return set(params.pop("client_keys", params))
|
||||
def stamped_keys(params: dict[str, Any]) -> set[str]:
|
||||
"""The parameters the client sent, from the server's ``client_keys`` stamp; every parameter without one."""
|
||||
return set(params.get("client_keys", params))
|
||||
|
||||
|
||||
def plan_keys(params: dict[str, Any]) -> set[str] | None:
|
||||
"""The parameters a job's dl plan counts as typed: :func:`stamped_keys`, or None (every one) for a relayed job.
|
||||
|
||||
The remote server's own defaults must never replace the values this server merged for a relayed job.
|
||||
"""
|
||||
return None if params.get("remote") else stamped_keys(params)
|
||||
|
||||
|
||||
def client_sent_keys(params: dict[str, Any]) -> set[str] | None:
|
||||
"""Pop the ``client_keys`` stamp and give the :func:`plan_keys` it held."""
|
||||
keys = plan_keys(params)
|
||||
params.pop("client_keys", None)
|
||||
return keys
|
||||
|
||||
|
||||
def perform_download(
|
||||
|
||||
+15
-303
@@ -41,7 +41,6 @@ from unshackle.core.cdm.loader import device_system
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.dl_options import (
|
||||
DEFAULT_DOWNLOAD_PARAMS,
|
||||
DL_OPTION_API_NAMES,
|
||||
forwarded_dl_params,
|
||||
)
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
|
||||
@@ -69,7 +68,6 @@ from unshackle.core.remote_protocol import (
|
||||
TracksReply,
|
||||
TracksRequest,
|
||||
)
|
||||
from unshackle.core.run_plan import PlanError, api_plan
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.session import RnetSession, utf8_text
|
||||
from unshackle.core.titles import Episode, Song
|
||||
@@ -86,7 +84,6 @@ from unshackle.core.tunnel import (
|
||||
)
|
||||
from unshackle.core.utilities import declared_kwargs
|
||||
from unshackle.core.utils.click_types import QUALITY_LIST, SEASON_RANGE, VIDEO_CODEC_LIST, ContextData
|
||||
from unshackle.core.utils.collections import ci_get
|
||||
from unshackle.core.utils.hdr10plus import probed_tracks
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
|
||||
from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
|
||||
@@ -1535,7 +1532,7 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None
|
||||
def resolve_vcodec(value: Any) -> list | None:
|
||||
"""Map a client's vcodec field to codec enums.
|
||||
|
||||
Session routes do not run validate_download_parameters, so this must answer junk with a 400
|
||||
Session routes do not run the download job admission, so this must answer junk with a 400
|
||||
instead of letting click's UsageError surface as a 500.
|
||||
"""
|
||||
if not value:
|
||||
@@ -1555,302 +1552,24 @@ def wanted_refusal(wanted: Any) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def validate_download_parameters(data: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
Validate download parameters and return error message if invalid.
|
||||
|
||||
Returns:
|
||||
None if valid, error message string if invalid
|
||||
"""
|
||||
for banned in ("postscript", "post_script", "post_scripts"):
|
||||
if data.get(banned):
|
||||
return f"'{banned}' is not accepted over the API, only from unshackle.yaml"
|
||||
|
||||
# The worker reads cookies/{service}/{profile}.txt, so a profile must not be able to name a path.
|
||||
try:
|
||||
client_profile(data)
|
||||
except APIError as e:
|
||||
return e.message
|
||||
|
||||
# The serve user would create and write any directory a client names; keep it under downloads.
|
||||
if data.get("output_dir"):
|
||||
root = config.directories.downloads.resolve()
|
||||
raw = str(data["output_dir"])
|
||||
if "\x00" in raw:
|
||||
return "output_dir is not a usable path."
|
||||
try:
|
||||
target = (root / raw).resolve()
|
||||
except (OSError, ValueError):
|
||||
return "output_dir is not a usable path."
|
||||
if not target.is_relative_to(root):
|
||||
return "output_dir must be a path under the server's downloads directory."
|
||||
data["output_dir"] = str(target)
|
||||
|
||||
if data.get("all_drm") and data.get("cdm"):
|
||||
return "all_drm needs a CDM for each DRM system, so it cannot be used with cdm, which selects one device."
|
||||
|
||||
if "vbitrate" in data and data["vbitrate"] is not None:
|
||||
if not isinstance(data["vbitrate"], int) or data["vbitrate"] <= 0:
|
||||
return "vbitrate must be a positive integer"
|
||||
|
||||
if "abitrate" in data and data["abitrate"] is not None:
|
||||
if not isinstance(data["abitrate"], int) or data["abitrate"] <= 0:
|
||||
return "abitrate must be a positive integer"
|
||||
|
||||
if data.get("quality") is not None:
|
||||
try:
|
||||
heights = QUALITY_LIST.convert(data["quality"])
|
||||
except click.BadParameter as e:
|
||||
return f"Invalid quality: {e.message}"
|
||||
if any(height <= 0 for height in heights):
|
||||
return "quality heights must be above 0"
|
||||
|
||||
if "channels" in data and data["channels"] is not None:
|
||||
if not isinstance(data["channels"], (int, float)) or data["channels"] <= 0:
|
||||
return "channels must be a positive number"
|
||||
|
||||
if "workers" in data and data["workers"] is not None:
|
||||
if not isinstance(data["workers"], int) or data["workers"] <= 0:
|
||||
return "workers must be a positive integer"
|
||||
|
||||
if "download_processes" in data and data["download_processes"] is not None:
|
||||
if not isinstance(data["download_processes"], int) or data["download_processes"] <= 0:
|
||||
return "download_processes must be a positive integer"
|
||||
|
||||
if "downloads" in data and data["downloads"] is not None:
|
||||
if not isinstance(data["downloads"], int) or data["downloads"] <= 0:
|
||||
return "downloads must be a positive integer"
|
||||
|
||||
for name in ("tmdb_id", "tvdb_id", "latest_episodes"):
|
||||
if data.get(name) is not None:
|
||||
value = data[name]
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
return f"{name} must be a positive integer"
|
||||
|
||||
if data.get("imdb_id") is not None:
|
||||
if not isinstance(data["imdb_id"], str) or not re.fullmatch(r"tt\d+", data["imdb_id"]):
|
||||
return "imdb_id must be an IMDB ID like 'tt1375666'"
|
||||
|
||||
for key, default in DEFAULT_DOWNLOAD_PARAMS.items():
|
||||
if isinstance(default, bool) and data.get(key) is not None and not isinstance(data[key], bool):
|
||||
return f"{key} must be a boolean"
|
||||
|
||||
for key in (
|
||||
"lang",
|
||||
"v_lang",
|
||||
"a_lang",
|
||||
"s_lang",
|
||||
"forced_s_lang",
|
||||
"require_audio",
|
||||
"require_video",
|
||||
"require_subs",
|
||||
):
|
||||
value = data.get(key)
|
||||
if value is not None and (not isinstance(value, list) or not all(isinstance(v, str) for v in value)):
|
||||
return f"{key} must be an array of language strings"
|
||||
|
||||
from unshackle.commands.dl import subtitle_look
|
||||
|
||||
try:
|
||||
params = api_plan(data).params
|
||||
except PlanError as e:
|
||||
return e.message
|
||||
|
||||
if params.get("sub_font"):
|
||||
try:
|
||||
subtitle_look(params.get("sub_format"), params["sub_font"], None)
|
||||
except ValueError as e:
|
||||
return f"Invalid sub_font: {e}"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def enforce_download_gates(params: dict[str, Any], request: web.Request | None = None) -> None:
|
||||
"""Enforce serve-config gates on per-job cdm overrides and client-supplied credentials.
|
||||
|
||||
A per-request `cdm` selects a server-side device, so this function gates it here rather than
|
||||
honour it blindly. `serve.cdm_overrides` opts in: a list permits only those device names, or `true`
|
||||
permits any (for a single trusted client). Unset/false rejects every override.
|
||||
A per-request `credential` (or `credentials` map) authenticates the job with client-supplied
|
||||
secrets instead of the server-side credentials. Gate it behind `serve.allow_job_credentials`
|
||||
(default off) so a default deployment stays locked to its own credentials. This mirrors the
|
||||
CDM gate. A download job licenses DRM in-process with the server's own CDM, so an API key without
|
||||
``server_cdm`` cannot submit or retry jobs. A job can also spend the server's proxy providers,
|
||||
through an explicit ``proxy`` country code or through the geofence auto-proxy, so the
|
||||
``server_proxy`` policy from :func:`resolve_handler_proxy` applies here too: without the opt-in
|
||||
the job must carry a full proxy URI or no proxy at all. Under a ``server_cdm_max_height`` the job
|
||||
must set a quality at or under it, no ``best_available`` and no HYBRID range, as a job has no client device
|
||||
to fall back to. Pass the job's merged parameters, so the gate sees the values the job runs with.
|
||||
"""
|
||||
policy = request_policy(request)
|
||||
if not policy.allows("server_cdm", params.get("service")):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"Download jobs license with the server CDM, which is not enabled for this API key on this service",
|
||||
)
|
||||
service = params.get("service")
|
||||
if service and policy.owns_identity(service):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"Download jobs run on the server's own device config, and this API key has its own for this service",
|
||||
)
|
||||
cap = policy.max_height(params.get("service"))
|
||||
if cap is not None:
|
||||
serve_defaults = config.serve or {}
|
||||
|
||||
def effective(key: str) -> Any:
|
||||
"""The job's own value for this parameter, or the ``serve:`` dl default that the job falls back to."""
|
||||
return params[key] if key in params else serve_defaults.get(key)
|
||||
|
||||
capped = f"Download jobs license with the server CDM, up to {cap}p for this API key"
|
||||
wanted = requested_height(effective("quality"))
|
||||
if wanted is None or wanted > cap:
|
||||
raise capped_error(f"{capped}: pass a quality", cap)
|
||||
if effective("best_available"):
|
||||
raise capped_error(f"{capped}: drop best_available", cap)
|
||||
ranges = effective("range") or []
|
||||
ranges = [ranges] if isinstance(ranges, str) else ranges
|
||||
if any(str(getattr(r, "value", r)).upper() == "HYBRID" for r in ranges):
|
||||
raise capped_error(f"{capped}: drop HYBRID", cap)
|
||||
|
||||
if params.get("proxy_download") is not None and not isinstance(params["proxy_download"], str):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "proxy_download must be a string.")
|
||||
|
||||
if any(str(params.get(key) or "").startswith("tunnel:") for key in ("proxy", "proxy_download")):
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PROXY,
|
||||
"A download job cannot use a tunnel: proxy, because a tunnel belongs to one --remote client run.",
|
||||
)
|
||||
|
||||
if not policy.allows("server_proxy"):
|
||||
resolve_handler_proxy(params, params.get("service") or "", request)
|
||||
if params.get("proxy_download"):
|
||||
# the download proxy is gated like the main one: a full URI or nothing, never a server provider
|
||||
resolve_handler_proxy(
|
||||
{**params, "proxy": params["proxy_download"], "client_region": None},
|
||||
params.get("service") or "",
|
||||
request,
|
||||
)
|
||||
|
||||
requested_cdm = params.get("cdm")
|
||||
if requested_cdm:
|
||||
allowed = (config.serve or {}).get("cdm_overrides")
|
||||
permitted = allowed is True or (isinstance(allowed, (list, tuple, set)) and requested_cdm in allowed)
|
||||
if not permitted:
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"The requested CDM is not permitted for API downloads.",
|
||||
details={"cdm": requested_cdm},
|
||||
)
|
||||
|
||||
if params.get("credential") or params.get("credentials"):
|
||||
if not (config.serve or {}).get("allow_job_credentials"):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"Per-request credentials are not permitted for API downloads.",
|
||||
)
|
||||
|
||||
|
||||
def service_dl_defaults(service: str) -> dict[str, Any]:
|
||||
"""The ``services.<TAG>.dl`` values that name an API download parameter, keyed as the API names them."""
|
||||
from unshackle.core.services import ROUTING_PARAMS
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
for key, value in ((ci_get(config.services, service) or {}).get("dl") or {}).items():
|
||||
key = DL_OPTION_API_NAMES.get(key, key)
|
||||
if value is None or key in ROUTING_PARAMS:
|
||||
continue
|
||||
if key not in DEFAULT_DOWNLOAD_PARAMS:
|
||||
log.debug("Ignoring services.%s.dl key %r: not an API download parameter", service, key)
|
||||
continue
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
async def enqueue_job(
|
||||
service: str, title_id: str, params: dict[str, Any], request: web.Request | None, gate_service: str
|
||||
) -> web.Response:
|
||||
"""Check the download gates for ``gate_service``, then queue a job with ``params`` and answer 202.
|
||||
|
||||
``server_proxy`` is always stamped here, so a client-sent value cannot grant the server's proxy providers.
|
||||
"""
|
||||
async def enqueue_job(body: dict[str, Any], request: web.Request | None) -> web.Response:
|
||||
"""Admit the job that the request ``body`` asks for, queue it and answer 202."""
|
||||
from unshackle.core.api.download_manager import get_download_manager
|
||||
from unshackle.core.api.job_admission import admit_job
|
||||
|
||||
await asyncio.to_thread(enforce_download_gates, {**params, "service": gate_service}, request)
|
||||
spec = await admit_job(body, request)
|
||||
manager = get_download_manager()
|
||||
await manager.start_workers()
|
||||
job = manager.create_job(
|
||||
service,
|
||||
title_id,
|
||||
owner_key=caller_key(request),
|
||||
**{**params, "server_proxy": request_policy(request).allows("server_proxy")},
|
||||
)
|
||||
job = manager.create_job(spec.service, spec.title_id, owner_key=caller_key(request), **spec.params)
|
||||
return web.json_response(
|
||||
{"job_id": job.job_id, "status": job.status.value, "created_time": job.created_time.isoformat()}, status=202
|
||||
)
|
||||
|
||||
|
||||
async def download_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
|
||||
"""Answer the download request: make a download job and add it to the queue."""
|
||||
|
||||
require_fields(data, "service", "title_id")
|
||||
service_tag = data["service"]
|
||||
title_id = data["title_id"]
|
||||
if not isinstance(title_id, str):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "title_id must be a string", details={"title_id": title_id})
|
||||
if refusal := wanted_refusal(data.get("wanted")):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, refusal, details={"wanted": data.get("wanted")})
|
||||
|
||||
server, info, data = await relay_target(data, request)
|
||||
normalized_service = info["tag"] if info else validate_service(service_tag, request)
|
||||
if not normalized_service:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_SERVICE,
|
||||
f"Invalid or unavailable service: {service_tag}",
|
||||
details={"service": service_tag},
|
||||
)
|
||||
|
||||
validation_error = await asyncio.to_thread(validate_download_parameters, data)
|
||||
if validation_error:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS,
|
||||
validation_error,
|
||||
details={"service": normalized_service, "title_id": title_id},
|
||||
)
|
||||
|
||||
"""Answer the download request: admit the job and add it to the queue."""
|
||||
try:
|
||||
service_module = None if server else Services.load(normalized_service)
|
||||
service_params: dict[str, Any] | None = None
|
||||
|
||||
# Service options travel nested, so a flat key the worker reads stays a dl value; click fills the defaults
|
||||
# when the worker builds the service. A remote service applies its own on the remote server.
|
||||
cli_params = getattr(getattr(service_module, "cli", None), "params", None)
|
||||
if cli_params is not None:
|
||||
sent = service_options(data, {param.name for param in cli_params}, DL_TRANSPORT_KEYS)
|
||||
cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent)
|
||||
service_params = sent
|
||||
|
||||
filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id", "owner_key"]}
|
||||
# Overlay any dl-relevant keys from `serve:` config (e.g. downloads, workers) so the API
|
||||
# respects server-side defaults without each client having to send them.
|
||||
serve_overrides = {
|
||||
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_dl = {} if server else service_dl_defaults(normalized_service)
|
||||
params_with_defaults = {
|
||||
**DEFAULT_DOWNLOAD_PARAMS,
|
||||
**serve_overrides,
|
||||
**service_dl,
|
||||
**filtered_params,
|
||||
}
|
||||
if service_params is not None:
|
||||
params_with_defaults["service_params"] = service_params
|
||||
params_with_defaults["client_keys"] = sorted(
|
||||
[*params_with_defaults, "server_proxy"] if server else filtered_params
|
||||
)
|
||||
return await enqueue_job(normalized_service, title_id, params_with_defaults, request, gate_service=service_tag)
|
||||
|
||||
return await enqueue_job(data, request)
|
||||
except APIError:
|
||||
raise
|
||||
except (Exception, SystemExit) as e:
|
||||
@@ -1858,7 +1577,11 @@ async def download_handler(data: dict[str, Any], request: web.Request | None = N
|
||||
debug_mode = request.app.get("debug_api", False) if request else False
|
||||
return handle_api_exception(
|
||||
e,
|
||||
context={"operation": "create_download_job", "service": normalized_service, "title_id": title_id},
|
||||
context={
|
||||
"operation": "create_download_job",
|
||||
"service": data.get("service"),
|
||||
"title_id": data.get("title_id"),
|
||||
},
|
||||
debug_mode=debug_mode,
|
||||
)
|
||||
|
||||
@@ -2562,6 +2285,7 @@ async def clear_finished_download_jobs_handler(request: web.Request | None = Non
|
||||
async def retry_download_job_handler(job_id: str, request: web.Request | None = None) -> web.Response:
|
||||
"""Answer the retry download job request: enqueue a new job with the original's parameters."""
|
||||
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
|
||||
from unshackle.core.api.job_admission import resubmission
|
||||
|
||||
try:
|
||||
manager = get_download_manager()
|
||||
@@ -2581,19 +2305,7 @@ async def retry_download_job_handler(job_id: str, request: web.Request | None =
|
||||
details={"job_id": job_id, "status": job.status.value},
|
||||
)
|
||||
|
||||
# Re-apply creation-time gates so retry cannot bypass the caller's service allowlist
|
||||
# or currently-disabled cdm_overrides / allow_job_credentials config. A remote job is checked
|
||||
# against its remote server, which must still be configured and offer the service.
|
||||
if job.parameters.get("remote"):
|
||||
await asyncio.to_thread(remote_server, {**job.parameters, "service": job.service}, request)
|
||||
elif not validate_service(job.service, request):
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_SERVICE,
|
||||
f"Invalid or unavailable service: {job.service}",
|
||||
details={"service": job.service},
|
||||
)
|
||||
# Reuse the raw in-memory parameters; redaction only ever applies to serialized copies.
|
||||
return await enqueue_job(job.service, job.title_id, job.parameters, request, gate_service=job.service)
|
||||
return await enqueue_job(resubmission(job.service, job.title_id, job.parameters), request)
|
||||
|
||||
except APIError:
|
||||
raise
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Download job admission: one checked, merged and allowed job from a request body, or one refusal."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
from aiohttp import web
|
||||
|
||||
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.remote_protocol import APIErrorCode
|
||||
from unshackle.core.run_plan import PlanError, api_plan
|
||||
from unshackle.core.services import ROUTING_PARAMS, Services
|
||||
from unshackle.core.utils.collections import as_list, ci_get
|
||||
from unshackle.core.utils.service_params import service_options
|
||||
|
||||
ENVELOPE_KEYS = ("service", "title_id", "owner_key")
|
||||
log = logging.getLogger("api")
|
||||
SERVER_STAMPS = ("client_keys", "server_proxy")
|
||||
LANGUAGE_LIST_KEYS = (
|
||||
"lang",
|
||||
"v_lang",
|
||||
"a_lang",
|
||||
"s_lang",
|
||||
"forced_s_lang",
|
||||
"require_audio",
|
||||
"require_video",
|
||||
"require_subs",
|
||||
)
|
||||
POSITIVE_INT_KEYS = (
|
||||
"vbitrate",
|
||||
"abitrate",
|
||||
"workers",
|
||||
"download_processes",
|
||||
"downloads",
|
||||
"tmdb_id",
|
||||
"tvdb_id",
|
||||
"latest_episodes",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JobSpec:
|
||||
"""A download job that passed admission: its service tag, its title and the merged parameters it runs with."""
|
||||
|
||||
service: str
|
||||
title_id: str
|
||||
params: dict[str, Any]
|
||||
|
||||
|
||||
async def admit_job(data: dict[str, Any], request: web.Request | None = None) -> JobSpec:
|
||||
"""The job that the request body ``data`` asks for, checked, merged with the server defaults and allowed for the
|
||||
caller's API key. Raises one APIError for the first refusal. A create and a retry both come here."""
|
||||
handlers.require_fields(data, "service", "title_id")
|
||||
if not isinstance(data["title_id"], str):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "title_id must be a string", details={"title_id": data["title_id"]})
|
||||
if refusal := handlers.wanted_refusal(data.get("wanted")):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, refusal, details={"wanted": data.get("wanted")})
|
||||
|
||||
server, info, data = await handlers.relay_target(data, request)
|
||||
service = info["tag"] if info else handlers.validate_service(data["service"], request)
|
||||
if not service:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_SERVICE,
|
||||
f"Invalid or unavailable service: {data['service']}",
|
||||
details={"service": data["service"]},
|
||||
)
|
||||
return await asyncio.to_thread(job_spec, {**data, "service": service}, server, request)
|
||||
|
||||
|
||||
def job_spec(data: dict[str, Any], server: str | None, request: web.Request | None) -> JobSpec:
|
||||
"""The blocking part of :func:`admit_job`, for a request with a resolved service tag; ``server`` names the
|
||||
remote server of a relayed job. The server stamps ``server_proxy``, so a client value cannot grant it."""
|
||||
data = check_parameters(data)
|
||||
service = data["service"]
|
||||
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.
|
||||
params = {
|
||||
**DEFAULT_DOWNLOAD_PARAMS,
|
||||
**serve_defaults,
|
||||
**({} if server else service_dl_defaults(service)),
|
||||
**sent,
|
||||
"client_keys": sorted(sent),
|
||||
}
|
||||
merged = {**params, "service": service, "title_id": data["title_id"]}
|
||||
check_plan(merged)
|
||||
enforce_download_gates(merged, request)
|
||||
|
||||
# Service options travel nested, so a flat key the worker reads stays a dl value; click fills the defaults
|
||||
# when the worker builds the service. A remote service applies its own on the remote server.
|
||||
cli_params = None if server else getattr(getattr(Services.load(service), "cli", None), "params", None)
|
||||
if cli_params is not None:
|
||||
options = service_options(data, {param.name for param in cli_params}, handlers.DL_TRANSPORT_KEYS)
|
||||
handlers.cast_or_refuse(cli_params, click.Context(click.Command(service)), options)
|
||||
params["service_params"] = options
|
||||
params["server_proxy"] = handlers.request_policy(request).allows("server_proxy")
|
||||
return JobSpec(service, data["title_id"], params)
|
||||
|
||||
|
||||
def resubmission(service: str, title_id: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||
"""The request body that made a job with these stored values, so a retry passes the admission a create passes."""
|
||||
body = {k: params[k] for k in stamped_keys(params) if k in params and k not in SERVER_STAMPS}
|
||||
return {**body, "service": service, "title_id": title_id}
|
||||
|
||||
|
||||
def invalid(message: str, data: dict[str, Any]) -> APIError:
|
||||
"""The INVALID_PARAMETERS refusal of a job request."""
|
||||
return APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS,
|
||||
message,
|
||||
details={"service": data.get("service"), "title_id": data.get("title_id")},
|
||||
)
|
||||
|
||||
|
||||
def check_parameters(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""``data`` with ``output_dir`` resolved under the downloads directory, or INVALID_PARAMETERS for the first value
|
||||
that the API does not take. ``data`` stays as it is."""
|
||||
|
||||
for banned in ("postscript", "post_script", "post_scripts"):
|
||||
if data.get(banned):
|
||||
raise invalid(f"'{banned}' is not accepted over the API, only from unshackle.yaml", data)
|
||||
|
||||
# The worker reads cookies/{service}/{profile}.txt, so a profile must not be able to name a path.
|
||||
try:
|
||||
handlers.client_profile(data)
|
||||
except APIError as e:
|
||||
raise invalid(e.message, data) from None
|
||||
|
||||
checked = dict(data)
|
||||
# The serve user would create and write any directory a client names; keep it under downloads.
|
||||
if data.get("output_dir"):
|
||||
root = config.directories.downloads.resolve()
|
||||
raw = str(data["output_dir"])
|
||||
if "\x00" in raw:
|
||||
raise invalid("output_dir is not a usable path.", data)
|
||||
try:
|
||||
target = (root / raw).resolve()
|
||||
except (OSError, ValueError):
|
||||
raise invalid("output_dir is not a usable path.", data) from None
|
||||
if not target.is_relative_to(root):
|
||||
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):
|
||||
raise invalid(f"{name} must be a positive integer", data)
|
||||
|
||||
if data.get("quality") is not None:
|
||||
try:
|
||||
handlers.requested_heights(data["quality"])
|
||||
except APIError as e:
|
||||
raise invalid(e.message, data) from None
|
||||
|
||||
channels = data.get("channels")
|
||||
if channels is not None and (not isinstance(channels, (int, float)) or channels <= 0):
|
||||
raise invalid("channels must be a positive number", data)
|
||||
|
||||
imdb_id = data.get("imdb_id")
|
||||
if imdb_id is not None and (not isinstance(imdb_id, str) or not re.fullmatch(r"tt\d+", imdb_id)):
|
||||
raise invalid("imdb_id must be an IMDB ID like 'tt1375666'", data)
|
||||
|
||||
for key, default in DEFAULT_DOWNLOAD_PARAMS.items():
|
||||
if isinstance(default, bool) and data.get(key) is not None and not isinstance(data[key], bool):
|
||||
raise invalid(f"{key} must be a boolean", data)
|
||||
|
||||
for key in LANGUAGE_LIST_KEYS:
|
||||
value = data.get(key)
|
||||
if value is not None and (not isinstance(value, list) or not all(isinstance(v, str) for v in value)):
|
||||
raise invalid(f"{key} must be an array of language strings", data)
|
||||
|
||||
return checked
|
||||
|
||||
|
||||
def check_plan(params: dict[str, Any]) -> None:
|
||||
"""INVALID_PARAMETERS when dl would refuse the job's merged parameters, as the worker plans them."""
|
||||
from unshackle.commands.dl import subtitle_look
|
||||
|
||||
try:
|
||||
plan = api_plan(params, plan_keys(params)).params
|
||||
except PlanError as e:
|
||||
raise invalid(e.message, params) from None
|
||||
if plan.get("sub_font"):
|
||||
try:
|
||||
subtitle_look(plan.get("sub_format"), plan["sub_font"], None)
|
||||
except ValueError as e:
|
||||
raise invalid(f"Invalid sub_font: {e}", params) from None
|
||||
|
||||
|
||||
def enforce_download_gates(params: dict[str, Any], request: web.Request | None = None) -> None:
|
||||
"""Refuse a job that the caller's API key or the ``serve`` config does not allow, from its merged parameters.
|
||||
|
||||
A download job licenses with the server CDM, so the API key needs ``server_cdm`` for the service, and an API
|
||||
key with its own device config for the service gets a refusal. Under ``server_cdm_max_height`` the job must set a quality at or
|
||||
under the cap, no ``best_available`` and no HYBRID range. Without ``server_proxy`` a proxy must be a full URI or
|
||||
nothing, as in :func:`resolve_handler_proxy`. A ``cdm`` override needs ``serve.cdm_overrides`` (a device list,
|
||||
or ``true`` for any), and a ``credential`` needs ``serve.allow_job_credentials``.
|
||||
"""
|
||||
service = params.get("service")
|
||||
policy = handlers.request_policy(request)
|
||||
if not policy.allows("server_cdm", service):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"Download jobs license with the server CDM, which is not enabled for this API key on this service",
|
||||
)
|
||||
if service and policy.owns_identity(service):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"Download jobs run on the server's own device config, and this API key has its own for this service",
|
||||
)
|
||||
cap = policy.max_height(service)
|
||||
if cap is not None:
|
||||
capped = f"Download jobs license with the server CDM, up to {cap}p for this API key"
|
||||
wanted = handlers.requested_height(params.get("quality"))
|
||||
if wanted is None or wanted > cap:
|
||||
raise handlers.capped_error(f"{capped}: pass a quality", cap)
|
||||
if params.get("best_available"):
|
||||
raise handlers.capped_error(f"{capped}: drop best_available", cap)
|
||||
if any(str(getattr(r, "value", r)).upper() == "HYBRID" for r in as_list(params.get("range") or [])):
|
||||
raise handlers.capped_error(f"{capped}: drop HYBRID", cap)
|
||||
|
||||
if params.get("proxy_download") is not None and not isinstance(params["proxy_download"], str):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "proxy_download must be a string.")
|
||||
|
||||
if any(str(params.get(key) or "").startswith("tunnel:") for key in ("proxy", "proxy_download")):
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PROXY,
|
||||
"A download job cannot use a tunnel: proxy, because a tunnel belongs to one --remote client run.",
|
||||
)
|
||||
|
||||
if not policy.allows("server_proxy"):
|
||||
handlers.resolve_handler_proxy(params, service or "", request)
|
||||
if params.get("proxy_download"):
|
||||
# the download proxy is gated like the main one: a full URI or nothing, never a server provider
|
||||
handlers.resolve_handler_proxy(
|
||||
{**params, "proxy": params["proxy_download"], "client_region": None}, service or "", request
|
||||
)
|
||||
|
||||
requested_cdm = params.get("cdm")
|
||||
if requested_cdm:
|
||||
allowed = (config.serve or {}).get("cdm_overrides")
|
||||
permitted = allowed is True or (isinstance(allowed, (list, tuple, set)) and requested_cdm in allowed)
|
||||
if not permitted:
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN,
|
||||
"The requested CDM is not permitted for API downloads.",
|
||||
details={"cdm": requested_cdm},
|
||||
)
|
||||
|
||||
if (params.get("credential") or params.get("credentials")) and not (config.serve or {}).get(
|
||||
"allow_job_credentials"
|
||||
):
|
||||
raise APIError(APIErrorCode.FORBIDDEN, "Per-request credentials are not permitted for API downloads.")
|
||||
|
||||
|
||||
def service_dl_defaults(service: str) -> dict[str, Any]:
|
||||
"""The ``services.<TAG>.dl`` values that name an API download parameter, keyed as the API names them."""
|
||||
result: dict[str, Any] = {}
|
||||
for key, value in ((ci_get(config.services, service) or {}).get("dl") or {}).items():
|
||||
key = DL_OPTION_API_NAMES.get(key, key)
|
||||
if value is None or key in ROUTING_PARAMS:
|
||||
continue
|
||||
if key not in DEFAULT_DOWNLOAD_PARAMS:
|
||||
log.debug("Ignoring services.%s.dl key %r: not an API download parameter", service, key)
|
||||
continue
|
||||
result[key] = value
|
||||
return result
|
||||
@@ -1493,7 +1493,7 @@ async def retry_download_job(request: web.Request) -> web.Response:
|
||||
Retry download job.
|
||||
---
|
||||
summary: Retry download job
|
||||
description: Enqueue a new job reusing a completed, failed, or cancelled job's service, title, and parameters
|
||||
description: Enqueue a new job from the request that made a completed, failed, or cancelled job, checked as a new submission
|
||||
parameters:
|
||||
- name: job_id
|
||||
in: path
|
||||
@@ -1514,6 +1514,10 @@ async def retry_download_job(request: web.Request) -> web.Response:
|
||||
type: string
|
||||
created_time:
|
||||
type: string
|
||||
'400':
|
||||
description: The service or a parameter no longer passes the checks of a new submission
|
||||
'403':
|
||||
description: The API key may no longer run this job
|
||||
'404':
|
||||
description: Job not found
|
||||
'409':
|
||||
|
||||
Reference in New Issue
Block a user