fix(title-cache): key a cookie-only login by its cookie file path

This commit is contained in:
imSp4rky
2026-12-02 15:24:00 -07:00
parent 3868928d98
commit 2c305c475f
5 changed files with 79 additions and 6 deletions
+4 -2
View File
@@ -650,14 +650,16 @@ prepared, all derived from the Click context (`ctx`) that `dl` passes in.
everywhere. (unshackle also ships an rnet-based TLS-fingerprinting HTTP session that the
newer `session()` factory uses and that the `network` config key configures.)
- **`self.credential`**: the active `Credential` (`username:password[:extra]`), populated
by `authenticate`. unshackle uses its `sha1` as the account hash for cache keys.
by `authenticate`. unshackle uses its `sha1` as the account hash for cache keys. A login
with cookies only uses a hash of the path of its cookie file.
- **`self.cache`**: a generic `Cacher`: JSON key/value storage under the service's cache
dir, with CRC32 integrity checks, versioning, and optional expiry (auto-derived from a
JWT `exp` claim when present). Good for auth tokens and API responses.
- **`self.title_cache`**: a `TitleCacher` that wraps `get_titles` results, keyed by title
ID, region, and account hash. It serves fresh data within `title_cache_time`, falls back
to stale data within `title_cache_max_retention` when an API call fails, and `--no-cache`
bypasses it.
bypasses it. If you put the cookies of a different account into the same cookie file, use
`--reset-cache` once.
- **`self.track_request`**: the `TrackRequest` describing what the user asked for
(codecs, ranges, best-available), for use inside `get_tracks`.
+65
View File
@@ -15,6 +15,8 @@ from tests.lang_selection import test_kind_only_selection as harness
from tests.lang_selection.test_kind_only_selection import FakeService
from tests.remote.key_source import MemoryKeySource, remote_keys
from unshackle.commands import dl as dl_module
from unshackle.core.config import config
from unshackle.core.credential import Credential
from unshackle.core.drm import BlowfishStripe, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.import_service import ImportService
@@ -80,6 +82,69 @@ def test_a_remote_session_and_an_import_have_no_title_cache(tmp_path: Path) -> N
assert an_import(tmp_path).cache_identity() == CacheIdentity(None, "movie-1", None, None)
COOKIE_LINE = ".example.com\tTRUE\t/\tFALSE\t0\tsession\t{}\n"
class CookieOnlyService(FakeService):
"""A cookie login whose authenticate does not hand the jar to the base class; it records its cache identity."""
identity: CacheIdentity | None = None
def get_titles_cached(self, title_id: str | None = None) -> Any:
self.identity = self.cache_identity()
raise SystemExit(0)
def dl_login(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
profile: str,
value: str | None = "one",
) -> CacheIdentity:
"""The cache identity of a cookie-only service after dl logs it in with the cookie file of ``profile``."""
monkeypatch.setattr(config.directories, "cookies", tmp_path)
if value is not None:
cookie_file = tmp_path / "FAKE" / f"{profile}.txt"
cookie_file.parent.mkdir(exist_ok=True)
cookie_file.write_text("# Netscape HTTP Cookie File\n" + COOKIE_LINE.format(value))
monkeypatch.setattr(harness.Harness, "profile", profile, raising=False)
svc = CookieOnlyService({})
assert harness.run(monkeypatch, caplog, {}, service=svc) == 0
assert svc.identity is not None
return svc.identity
def test_two_cookie_profiles_have_their_own_title_cache_account(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
alpha = dl_login(tmp_path, monkeypatch, caplog, "alpha")
beta = dl_login(tmp_path, monkeypatch, caplog, "beta")
assert alpha.account_hash is not None
assert alpha.account_hash != beta.account_hash
def test_rotated_cookies_keep_the_title_cache_account(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
before = dl_login(tmp_path, monkeypatch, caplog, "alpha", "one")
after = dl_login(tmp_path, monkeypatch, caplog, "alpha", "two")
assert before.account_hash is not None
assert before == after
def test_a_login_with_no_cookies_and_no_credential_has_no_account(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
assert dl_login(tmp_path, monkeypatch, caplog, "alpha", None).account_hash is None
def test_a_credential_login_keeps_its_account_hash() -> None:
credential = Credential("user", "pass")
svc = service(credential=credential, cookie_file="/cookies/EXAMPLE/alpha.txt")
assert svc.cache_identity().account_hash == credential.sha1
def test_only_a_service_saves_its_login_cookies(tmp_path: Path) -> None:
session = requests.Session()
assert service(session=session).login_cookies is session.cookies
+1
View File
@@ -1736,6 +1736,7 @@ class dl:
cookies = login.get_cookie_jar(self.service, self.profile)
credential = login.get_credentials(self.service, self.profile)
service.authenticate(cookies, credential)
service.cookie_file = getattr(cookies, "filename", None)
if cookies or credential:
self.log.info("Authenticated with Service")
log_event(
+6 -3
View File
@@ -241,18 +241,21 @@ class TitleCacher:
self.log.debug(f"Cached {provider_name} data for {title_id}")
def get_account_hash(credential: Credential | None) -> str | None:
def get_account_hash(credential: Credential | None, cookie_file: str | None = None) -> str | None:
"""
Make a hash for account identification.
A cookie-only login hashes the path of its cookie file, not the cookies, as the cookies change on each save.
Args:
credential: Credential object
cookie_file: Path of the cookie file of the login
Returns:
SHA1 hash of the credential or None
SHA1 hash of the credential, else of the cookie file path, or None
"""
if not credential:
return None
return hashlib.sha1(cookie_file.encode()).hexdigest() if cookie_file else None
if hasattr(credential, "sha1"):
return credential.sha1
+3 -1
View File
@@ -111,6 +111,7 @@ class TitleSource(metaclass=ABCMeta):
log: logging.Logger
session: requests.Session
credential: Credential | None = None
cookie_file: str | None = None
current_region: str | None = None
title_cache: TitleCacher | None = None
@@ -140,7 +141,8 @@ class TitleSource(metaclass=ABCMeta):
title_id = self.title_id
else:
title_id = None
return CacheIdentity(self.title_cache, title_id, self.current_region, get_account_hash(self.credential))
account = get_account_hash(self.credential, self.cookie_file)
return CacheIdentity(self.title_cache, title_id, self.current_region, account)
@abstractmethod
def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None: