Files
unshackle/tests/test_client_session_auth.py
T

299 lines
11 KiB
Python

from types import SimpleNamespace
import pytest
import requests
from tests.remote.sessions import hold_session, session_entry
from unshackle.core.api import server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data
from unshackle.core.wire import apply_session_cookies
def _session(client_auth):
cookie = SimpleNamespace(name="sid", value="secret", domain=".example.com", path="/")
svc = SimpleNamespace(headers={"Authorization": "Bearer x", "User-Agent": "ua"}, cookies=[cookie])
return session_entry(service_instance=SimpleNamespace(session=svc), client_auth=client_auth)
def test_client_login_keeps_auth():
headers, cookies = client_session_auth(_session(True))
assert headers == {"Authorization": "Bearer x", "User-Agent": "ua"}
assert cookies == [{"name": "sid", "value": "secret", "domain": ".example.com", "path": "/", "secure": False}]
assert scrub_track_data({"token": "t", "hls": {}}, _session(True)) == {"token": "t", "hls": {}}
def test_client_cookies_keep_their_domain():
session = requests.Session()
_, cookies = client_session_auth(_session(True))
apply_session_cookies(session, {"session_cookie_jar": cookies})
assert session.cookies.get("sid", domain=".example.com") == "secret"
cdn = session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4"))
assert "Cookie" not in cdn.headers
own = session.prepare_request(requests.Request("GET", "https://www.example.com/api"))
assert own.headers["Cookie"] == "sid=secret"
def test_client_takes_old_server_cookies_without_domain():
session = requests.Session()
apply_session_cookies(session, {"session_cookies": {"sid": "secret"}})
assert session.cookies.get("sid") == "secret"
def test_client_keeps_secure_cookies_off_http():
session = requests.Session()
jar = [{"name": "sid", "value": "s", "domain": ".example.com", "path": "/", "secure": True}]
apply_session_cookies(session, {"session_cookie_jar": jar})
plain = session.prepare_request(requests.Request("GET", "http://cdn.example.com/seg.mp4"))
assert "Cookie" not in plain.headers
tls = session.prepare_request(requests.Request("GET", "https://cdn.example.com/seg.mp4"))
assert tls.headers["Cookie"] == "sid=s"
def test_client_skips_malformed_server_cookies():
session = requests.Session()
jar = [{"value": "v"}, "str", {"name": "n", "value": 1}, {"name": "ok", "value": "v", "domain": ".example.com"}]
apply_session_cookies(session, {"session_cookie_jar": jar})
assert [c.name for c in session.cookies] == ["ok"]
session = requests.Session()
apply_session_cookies(session, {"session_cookie_jar": 5, "session_cookies": ["x"]})
assert not session.cookies
def test_rnet_session_sends_client_and_set_cookies():
from unshackle.core.session import RnetSession
svc = RnetSession()
svc.cookies.set("sid", "stale", domain=".example.com")
svc.cookies.set("cdn", "c", domain="cdn.other.net")
svc.export_origin_cookies = lambda: {"https://www.example.com": "sid=live; cf=1"}
_, cookies = client_session_auth(session_entry(service_instance=SimpleNamespace(session=svc), client_auth=True))
assert {(c["name"], c["value"], c["domain"]) for c in cookies} == {
("sid", "live", "www.example.com"),
("cf", "1", "www.example.com"),
("cdn", "c", "cdn.other.net"),
}
def call_session_handler(handler, body, service, **entry_fields):
"""The JSON body that a session route handler answers for a remote session with these fields."""
import asyncio
import json
from unshackle.core.api import session_store as store_mod
async def run():
store = store_mod.get_session_store()
entry = await store.create(service_tag="EXAMPLE", service_instance=service, session_id="s", owner_key=None)
entry.presence.attached()
for name, value in entry_fields.items():
setattr(entry, name, value)
try:
return json.loads((await handler(body, "s")).body)
finally:
await store.delete("s")
return asyncio.run(run())
class StubService:
LICENSE_FIRST = False
def __init__(self, tracks=(), cookies=()):
self.session = SimpleNamespace(headers={}, cookies=list(cookies))
self.tracks = list(tracks)
def get_tracks(self, title):
from unshackle.core.tracks import Tracks
return Tracks(self.tracks)
def get_chapters(self, title):
raise NotImplementedError
def decrypts_samples(self, track):
return False
def fairplay_bridge(self):
return None
def stub_video():
from unshackle.core.tracks import Video
return Video(url="https://cdn.example.com/v.mp4", language="en", codec=Video.Codec.AVC, id_="v1")
def test_tracks_response_carries_the_cookie_jar():
from unshackle.core.api.handlers import session_tracks_handler
cookie = SimpleNamespace(name="sid", value="secret", domain=".example.com", path="/", secure=True)
body = call_session_handler(
session_tracks_handler,
{"title_id": "t1"},
StubService(cookies=[cookie]),
title_map={"t1": "Example Title"},
client_auth=True,
)
assert body["session_cookies"] == {"sid": "secret"}
assert body["session_cookie_jar"] == [
{"name": "sid", "value": "secret", "domain": ".example.com", "path": "/", "secure": True}
]
def test_tracks_reply_scrubs_track_data_on_a_server_login():
from unshackle.core.api.handlers import session_tracks_handler
track = stub_video()
track.data.update(api_token="secret", keep=1)
body = call_session_handler(
session_tracks_handler,
{"title_id": "t1"},
StubService(tracks=[track]),
title_map={"t1": "Example Title"},
client_auth=False,
)
assert body["video"][0]["data"] == {"keep": 1}
def test_segments_data_drops_the_parser_keys():
from unshackle.core.api.handlers import session_segments_handler
track = stub_video()
track.data.update(dash={"representation": object()}, hls={"playlist": object()}, service_value={"a": 1})
body = call_session_handler(
session_segments_handler, {"track_ids": ["v1"]}, StubService(), tracks={"v1": track}, client_auth=True
)
assert body["tracks"]["v1"]["data"] == {"service_value": {"a": 1}}
def test_remote_get_tracks_scopes_server_cookies():
import logging
from unshackle.core.remote_service import RemoteService
jar = [{"name": "sid", "value": "secret", "domain": ".example.com", "path": "/"}]
service = object.__new__(RemoteService)
service.__dict__.update(
_tracks_by_title={},
_chapters_by_title={},
_title_alias={},
_sample_decrypt_tracks=set(),
_server_cdm_request=None,
session=requests.Session(),
service_tag="EXAMPLE",
log=logging.getLogger("test"),
client=SimpleNamespace(post=lambda path, body: {"session_cookie_jar": jar}, probe=lambda endpoint: {}),
)
hold_session(service)
service.get_tracks(SimpleNamespace(id="t1"))
cdn = service.session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4"))
assert "Cookie" not in cdn.headers
assert service.session.cookies.get("sid", domain=".example.com") == "secret"
def test_server_account_rejects_client_proxy_uri(monkeypatch):
monkeypatch.setattr("unshackle.core.api.handlers.server_account_for", lambda request, service: True)
with pytest.raises(APIError):
resolve_handler_proxy({"proxy": "http://attacker:8080"}, "svc", None)
def test_profile_rejects_paths():
from unshackle.core.api.handlers import client_profile
assert client_profile({"profile": "main-1.b"}) == "main-1.b"
assert client_profile({}) is None
for bad in ("../x", "a/b", "..", "a\\b", "x" * 65):
with pytest.raises(APIError):
client_profile({"profile": bad})
def test_client_pssh_must_match_track(monkeypatch):
import uuid
kid, other = uuid.uuid4(), uuid.uuid4()
monkeypatch.setattr(server_keys, "pssh_kids", lambda pssh, drm_type: {other} if pssh == "OTHER" else {kid})
track = SimpleNamespace(id="t1", drm=[SimpleNamespace(kids=[kid])])
server_keys.require_track_pssh(track, "MINE", "widevine")
with pytest.raises(APIError):
server_keys.require_track_pssh(track, "OTHER", "widevine")
with pytest.raises(APIError):
server_keys.require_track_pssh(SimpleNamespace(id="t2", drm=[]), "MINE", "widevine")
def test_output_dir_stays_under_downloads(tmp_path, monkeypatch):
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 refusal({"output_dir": "../../etc"})
data = {"output_dir": "shows/x"}
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):
from unshackle.core.api import download_manager as dm
monkeypatch.setattr(dm, "history_path", lambda: tmp_path / "h.jsonl")
(tmp_path / "h.jsonl").write_text(
f'{{"job_id": "a", "owner": "{dm.owner_id("k1")}", "service": "X"}}\n'
f'{{"job_id": "b", "owner": "{dm.owner_id("k2")}", "service": "X"}}\n'
)
assert [e["job_id"] for e in dm.read_job_history(owner=dm.owner_id("k1"))] == ["a"]
assert not dm.delete_job_history("b", owner=dm.owner_id("k1"))
assert dm.delete_job_history("b", owner=dm.owner_id("k2"))
def test_log_capture_ignores_other_threads():
import logging
import threading
from unshackle.core.api.session_log import SessionLogBuffer, capture_service_logs
buf = SessionLogBuffer()
logger = logging.getLogger("SvcBleed")
with capture_service_logs("SvcBleed", buf):
logger.info("mine")
t = threading.Thread(target=lambda: logger.info("theirs"))
t.start()
t.join()
assert [r["message"] for r in buf.since(0)] == ["mine"]
def test_dashboard_logs_redact_path():
from pathlib import Path
from unshackle.core.utils.redact import redact_path
# A path under the real home dir must lose the home prefix, whatever the machine's user is.
secret = str(Path.home() / "secret" / "svc.py")
out = redact_path(f'Traceback: File "{secret}", line 5')
assert str(Path.home()) not in out
assert "svc.py" in out
def test_server_login_strips_nested_and_unlisted_secrets():
headers, _ = client_session_auth(
session_entry(
service_instance=SimpleNamespace(
session=SimpleNamespace(headers={"X-Api-Key": "k", "Accept": "*"}, cookies=[])
),
client_auth=False,
)
)
assert headers == {"Accept": "*"}
data = {"license": {"auth_token": "t", "url": "u"}, "items": [{"password": "p", "id": 1}]}
assert scrub_track_data(data, _session(False)) == {"license": {"url": "u"}, "items": [{"id": 1}]}
def test_download_rejects_path_profile_and_bad_output_dir(tmp_path, monkeypatch):
from tests.admission import refusal
from unshackle.core.api.handlers import config
monkeypatch.setattr(config.directories, "downloads", tmp_path)
assert refusal({"profile": "../x"})
assert refusal({"profile": "ok"}) is None
assert refusal({"output_dir": "a\x00b"})