forked from kenzuya/unshackle
refactor(core): move login state to core.login and load key vaults through one factory
This commit is contained in:
@@ -33,11 +33,11 @@ def login_calls(monkeypatch, tmp_path):
|
||||
|
||||
return call
|
||||
|
||||
dl = search_command.dl
|
||||
monkeypatch.setattr(dl, "get_cookie_jar", record("get_cookie_jar", None))
|
||||
monkeypatch.setattr(dl, "get_credentials", record("get_credentials", None))
|
||||
monkeypatch.setattr(dl, "get_cookie_path", record("get_cookie_path", tmp_path / "cookies.txt"))
|
||||
monkeypatch.setattr(dl, "save_cookies", record("save_cookies", None))
|
||||
login = search_command.login
|
||||
monkeypatch.setattr(login, "get_cookie_jar", record("get_cookie_jar", None))
|
||||
monkeypatch.setattr(login, "get_credentials", record("get_credentials", None))
|
||||
monkeypatch.setattr(login, "get_cookie_path", record("get_cookie_path", tmp_path / "cookies.txt"))
|
||||
monkeypatch.setattr(login, "save_cookies", record("save_cookies", None))
|
||||
return calls
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""load_config_vaults: one vault factory for dl, the server, the health probe and kv."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core import vaults as vaults_module
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.vaults import load_config_vaults
|
||||
|
||||
|
||||
class FakeVault:
|
||||
def __init__(self, name: str, **kwargs: Any) -> None:
|
||||
self.name = name
|
||||
self.kwargs = kwargs
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_type(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setitem(vaults_module.MODULES, "API", FakeVault)
|
||||
|
||||
|
||||
def sqlite(tmp_path: Path) -> dict[str, Any]:
|
||||
return {"type": "SQLite", "name": "local", "path": tmp_path / "keys.db"}
|
||||
|
||||
|
||||
def test_config_key_vaults_load_by_default(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config, "key_vaults", [sqlite(tmp_path), {"type": "API", "name": "remote", "uri": "u"}])
|
||||
|
||||
vaults, failed = load_config_vaults("EXAMPLE")
|
||||
|
||||
assert [v.name for v in vaults] == ["local", "remote"]
|
||||
assert vaults.service == "EXAMPLE"
|
||||
assert failed == {}
|
||||
|
||||
|
||||
def test_a_vault_that_fails_is_left_out_and_named_with_its_error() -> None:
|
||||
vaults, failed = load_config_vaults("EXAMPLE", [{"type": "Missing", "name": "gone"}, {"type": "API", "name": "ok"}])
|
||||
|
||||
assert [v.name for v in vaults] == ["ok"]
|
||||
assert list(failed) == ["gone"]
|
||||
assert isinstance(failed["gone"], ValueError)
|
||||
|
||||
|
||||
def test_an_entry_without_a_type_fails_like_any_other() -> None:
|
||||
vaults, failed = load_config_vaults("EXAMPLE", [{"name": "untyped"}, {"type": "API", "name": "ok"}])
|
||||
|
||||
assert [v.name for v in vaults] == ["ok"]
|
||||
assert list(failed) == ["untyped"]
|
||||
|
||||
|
||||
def test_a_critical_vault_that_fails_raises() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
load_config_vaults("EXAMPLE", [{"type": "Missing", "name": "gone"}], critical={"missing"})
|
||||
|
||||
|
||||
def test_critical_applies_only_to_the_types_it_accepts(tmp_path: Path) -> None:
|
||||
configs = [sqlite(tmp_path), {"type": "Missing", "name": "gone"}]
|
||||
|
||||
vaults, failed = load_config_vaults("EXAMPLE", configs, critical={"sqlite"})
|
||||
|
||||
assert [v.name for v in vaults] == ["local"]
|
||||
assert list(failed) == ["gone"]
|
||||
|
||||
|
||||
def test_the_caller_config_is_not_changed(tmp_path: Path) -> None:
|
||||
configs = [sqlite(tmp_path)]
|
||||
|
||||
load_config_vaults("EXAMPLE", configs)
|
||||
|
||||
assert configs[0]["type"] == "SQLite"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("own_token", "global_key", "expected"),
|
||||
[(None, "global", "global"), ("own", "global", "own"), (None, "", None)],
|
||||
)
|
||||
def test_a_decrypt_labs_vault_takes_the_global_key_only_without_its_own(
|
||||
monkeypatch: pytest.MonkeyPatch, own_token: Any, global_key: str, expected: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(config, "decrypt_labs_api_key", global_key)
|
||||
cfg = {"type": "API", "name": "decrypt_labs_vault", **({"token": own_token} if own_token else {})}
|
||||
|
||||
vaults, _ = load_config_vaults("EXAMPLE", [cfg])
|
||||
|
||||
assert vaults.vaults[0].kwargs.get("token") == expected
|
||||
|
||||
|
||||
def test_only_a_decrypt_labs_vault_takes_the_global_key(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(config, "decrypt_labs_api_key", "global")
|
||||
|
||||
vaults, _ = load_config_vaults("EXAMPLE", [{"type": "API", "name": "other"}])
|
||||
|
||||
assert "token" not in vaults.vaults[0].kwargs
|
||||
|
||||
|
||||
def test_server_vaults_read_the_global_decrypt_labs_key(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from unshackle.core.api import handlers
|
||||
|
||||
monkeypatch.setattr(config, "decrypt_labs_api_key", "global")
|
||||
monkeypatch.setattr(config, "key_vaults", [{"type": "API", "name": "decrypt_labs"}, {"type": "Missing"}])
|
||||
|
||||
vaults = handlers.load_server_vaults("EXAMPLE")
|
||||
|
||||
assert [v.kwargs.get("token") for v in vaults] == ["global"]
|
||||
|
||||
|
||||
def test_the_health_probe_reports_the_load_error_without_logging_it(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
from unshackle.core.api import handlers
|
||||
|
||||
class Broken:
|
||||
def __init__(self, name: str, **kwargs: Any) -> None:
|
||||
raise ConnectionError("cannot reach the vault")
|
||||
|
||||
monkeypatch.setitem(vaults_module.MODULES, "Broken", Broken)
|
||||
monkeypatch.setattr(config, "key_vaults", [{"type": "Broken", "name": "down"}])
|
||||
|
||||
with caplog.at_level("ERROR"):
|
||||
checks = {c["id"]: c for c in handlers.run_health_checks()}
|
||||
|
||||
assert checks["vault:down"]["status"] == "fail"
|
||||
assert checks["vault:down"]["detail"] == "ConnectionError: cannot reach the vault"
|
||||
assert not caplog.records
|
||||
|
||||
|
||||
def test_kv_names_the_vault_that_failed(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
import click
|
||||
|
||||
from unshackle.commands.kv import load_vaults
|
||||
|
||||
monkeypatch.setattr(config, "key_vaults", [{"type": "Missing", "name": "gone"}])
|
||||
|
||||
with pytest.raises(click.ClickException, match=r"Failed to load vault \(gone\)"):
|
||||
load_vaults(["gone"])
|
||||
@@ -1,11 +1,11 @@
|
||||
"""Cookie files that use spaces instead of tabs must still load."""
|
||||
"""Cookie files load the way every caller expects: spaces or tabs, and the user's file never rewritten."""
|
||||
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core import login
|
||||
|
||||
HEADER = "# Netscape HTTP Cookie File\n"
|
||||
|
||||
@@ -18,7 +18,7 @@ def test_space_separated_cookie_file(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + ".example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_tab_separated_value_keeps_spaces(tmp_path: Path) -> None:
|
||||
@@ -27,21 +27,21 @@ def test_tab_separated_value_keeps_spaces(tmp_path: Path) -> None:
|
||||
HEADER + "\t".join([".example.com", "TRUE", "/", "TRUE", "1234567890", "sid", "a b c"]) + "\n", "utf8"
|
||||
)
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "a b c"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "a b c"}
|
||||
|
||||
|
||||
def test_space_separated_empty_value(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + ".example.com TRUE / TRUE 1234567890 sid \n", "utf8")
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": ""}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": ""}
|
||||
|
||||
|
||||
def test_space_separated_httponly(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + "#HttpOnly_.example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_mixed_separators_in_one_file(tmp_path: Path) -> None:
|
||||
@@ -53,7 +53,7 @@ def test_mixed_separators_in_one_file(tmp_path: Path) -> None:
|
||||
"utf8",
|
||||
)
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"tabbed": "1", "spaced": "2"}
|
||||
assert _names(login.load_cookie_file(file)) == {"tabbed": "1", "spaced": "2"}
|
||||
|
||||
|
||||
def test_malformed_row_is_reported(tmp_path: Path) -> None:
|
||||
@@ -61,21 +61,21 @@ def test_malformed_row_is_reported(tmp_path: Path) -> None:
|
||||
file.write_text(HEADER + ".a.com\tTRUE\t/\tTRUE\t1\tsid\tv\nnot a cookie\n", "utf8")
|
||||
|
||||
with pytest.raises(ValueError, match="line 3"):
|
||||
dl.load_cookie_file(file)
|
||||
login.load_cookie_file(file)
|
||||
|
||||
|
||||
def test_missing_header_is_added(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(".example.com\tTRUE\t/\tTRUE\t1234567890\tsid\tabc123\n", "utf8")
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_utf8_bom_is_ignored(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_bytes(b"\xef\xbb\xbf" + (HEADER + ".example.com\tTRUE\t/\tTRUE\t1234567890\tsid\tabc123\n").encode())
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_json_export_gives_clear_error(tmp_path: Path) -> None:
|
||||
@@ -83,21 +83,21 @@ def test_json_export_gives_clear_error(tmp_path: Path) -> None:
|
||||
file.write_text('[{"domain": ".example.com", "name": "sid", "value": "abc123"}]\n', "utf8")
|
||||
|
||||
with pytest.raises(ValueError, match="JSON export"):
|
||||
dl.load_cookie_file(file)
|
||||
login.load_cookie_file(file)
|
||||
|
||||
|
||||
def test_leading_blank_line_is_not_json(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text("\n" + HEADER + ".example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_dot_flag_mismatch_does_not_abort_file(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + "example.com\tTRUE\t/\tTRUE\t1\tsid\tv\n", "utf8")
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "v"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "v"}
|
||||
|
||||
|
||||
def test_the_users_file_is_never_rewritten(tmp_path: Path) -> None:
|
||||
@@ -105,7 +105,7 @@ def test_the_users_file_is_never_rewritten(tmp_path: Path) -> None:
|
||||
original = ".example.com TRUE / TRUE 1234567890 sid abc123\n"
|
||||
file.write_text(original, "utf8")
|
||||
|
||||
dl.load_cookie_file(file)
|
||||
login.load_cookie_file(file)
|
||||
|
||||
assert file.read_text("utf8") == original
|
||||
|
||||
@@ -114,9 +114,9 @@ def test_save_cookies_onto_an_unrepaired_file(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(".example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
dl.save_cookies(file, CookieJar())
|
||||
login.save_cookies(file, CookieJar())
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
|
||||
|
||||
def test_tabbed_row_is_never_resplit_on_spaces(tmp_path: Path) -> None:
|
||||
@@ -124,7 +124,7 @@ def test_tabbed_row_is_never_resplit_on_spaces(tmp_path: Path) -> None:
|
||||
file.write_text(HEADER + ".a.com\tTRUE\t/\tFALSE\thello world\n", "utf8")
|
||||
|
||||
with pytest.raises(ValueError, match="not a Netscape cookie row"):
|
||||
dl.load_cookie_file(file)
|
||||
login.load_cookie_file(file)
|
||||
|
||||
|
||||
def test_file_without_cookies_is_reported(tmp_path: Path) -> None:
|
||||
@@ -132,14 +132,14 @@ def test_file_without_cookies_is_reported(tmp_path: Path) -> None:
|
||||
file.write_text(HEADER + "# nothing else here\n", "utf8")
|
||||
|
||||
with pytest.raises(ValueError, match="holds no cookies"):
|
||||
dl.load_cookie_file(file)
|
||||
login.load_cookie_file(file)
|
||||
|
||||
|
||||
def test_round_trip_keeps_httponly_and_blank_expiry(tmp_path: Path) -> None:
|
||||
file = tmp_path / "cookies.txt"
|
||||
file.write_text(HEADER + "#HttpOnly_.example.com TRUE / TRUE 1234567890 sid abc123\n", "utf8")
|
||||
|
||||
dl.save_cookies(file, CookieJar())
|
||||
login.save_cookies(file, CookieJar())
|
||||
|
||||
assert _names(dl.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert _names(login.load_cookie_file(file)) == {"sid": "abc123"}
|
||||
assert "#HttpOnly_" in file.read_text("utf8")
|
||||
@@ -243,7 +243,7 @@ def test_clear_by_name_drops_a_server_set_cookie(server: str) -> None:
|
||||
def test_clear_before_the_client_exists_empties_the_jar_and_sends_nothing(server: str) -> None:
|
||||
"""``clear()`` on a session that has made no request must empty every cookie view.
|
||||
|
||||
``dl.save_cookies`` writes ``cookies.jar`` back to the cookie file and only ever merges,
|
||||
``login.save_cookies`` writes ``cookies.jar`` back to the cookie file and only ever merges,
|
||||
so a cleared cookie left in the jar returns to disk.
|
||||
"""
|
||||
session = RnetSession()
|
||||
|
||||
@@ -186,8 +186,8 @@ def test_setup_list_service_threads_request(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||
monkeypatch.setattr(handlers, "instantiate_service", lambda *args: FakeService())
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None))
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_credentials", staticmethod(lambda service, profile: None))
|
||||
monkeypatch.setattr("unshackle.core.login.get_cookie_jar", lambda service, profile: None)
|
||||
monkeypatch.setattr("unshackle.core.login.get_credentials", lambda service, profile: None)
|
||||
|
||||
req = request("plainkey")
|
||||
handlers.setup_list_service({}, "EXAMPLE", None, "some-title", req)
|
||||
@@ -204,8 +204,8 @@ def test_search_reports_failed_proxy_check_as_invalid_proxy(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: None)
|
||||
monkeypatch.setattr(handlers, "instantiate_service", failed_check)
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None))
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_credentials", staticmethod(lambda service, profile: None))
|
||||
monkeypatch.setattr("unshackle.core.login.get_cookie_jar", lambda service, profile: None)
|
||||
monkeypatch.setattr("unshackle.core.login.get_credentials", lambda service, profile: None)
|
||||
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.run_service_search({}, "EXAMPLE", "query", request("plainkey"))
|
||||
|
||||
@@ -64,8 +64,8 @@ def seen(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: None)
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda service: module))
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None))
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_credentials", staticmethod(lambda service, profile: None))
|
||||
monkeypatch.setattr("unshackle.core.login.get_cookie_jar", lambda service, profile: None)
|
||||
monkeypatch.setattr("unshackle.core.login.get_credentials", lambda service, profile: None)
|
||||
return _CacheService.seen
|
||||
|
||||
|
||||
|
||||
+7
-144
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
@@ -16,8 +15,6 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from copy import deepcopy
|
||||
from datetime import date, timedelta
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar, MozillaCookieJar
|
||||
from io import StringIO
|
||||
from itertools import groupby
|
||||
from operator import attrgetter
|
||||
from pathlib import Path
|
||||
@@ -36,7 +33,7 @@ from rich.rule import Rule
|
||||
from rich.spinner import Spinner
|
||||
from rich.table import Table
|
||||
|
||||
from unshackle.core import __version__, binaries, providers
|
||||
from unshackle.core import __version__, binaries, login, providers
|
||||
from unshackle.core.cdm.choice import choose_cdm
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm
|
||||
from unshackle.core.config import cdm_entry_names_device, config, load_yaml, resolve_cdm_name, resolve_decryption
|
||||
@@ -49,7 +46,6 @@ from unshackle.core.constants import (
|
||||
AnyTrack,
|
||||
context_settings,
|
||||
)
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.dl_options import DL_OPTION_ALIASES
|
||||
from unshackle.core.downloaders import (
|
||||
default_max_workers,
|
||||
@@ -135,7 +131,7 @@ from unshackle.core.utils.post_scripts import NO_POST_SCRIPTS, build_context, di
|
||||
from unshackle.core.utils.redact import mask_proxy
|
||||
from unshackle.core.utils.selector import select_multiple
|
||||
from unshackle.core.utils.subprocess import ffprobe
|
||||
from unshackle.core.vaults import Vaults
|
||||
from unshackle.core.vaults import Vaults, load_config_vaults
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pysubs2
|
||||
@@ -1509,40 +1505,8 @@ class dl:
|
||||
)
|
||||
else:
|
||||
with console.status("Loading Key Vaults...", spinner="dots"):
|
||||
self.vaults = Vaults(self.vault_service)
|
||||
self.vaults, failed_vaults = load_config_vaults(self.vault_service, critical={"sqlite"})
|
||||
total_vaults = len(config.key_vaults)
|
||||
failed_vaults = []
|
||||
|
||||
for vault in config.key_vaults:
|
||||
vault_type = vault["type"]
|
||||
vault_name = vault.get("name", vault_type)
|
||||
vault_copy = vault.copy()
|
||||
del vault_copy["type"]
|
||||
|
||||
if vault_type.lower() == "api" and "decrypt_labs" in vault_name.lower():
|
||||
if "token" not in vault_copy or not vault_copy["token"]:
|
||||
if config.decrypt_labs_api_key:
|
||||
vault_copy["token"] = config.decrypt_labs_api_key
|
||||
else:
|
||||
self.log.warning(
|
||||
f"No token provided for DecryptLabs vault '{vault_name}' and no global "
|
||||
"decrypt_labs_api_key configured"
|
||||
)
|
||||
|
||||
if vault_type.lower() == "sqlite":
|
||||
try:
|
||||
self.vaults.load_critical(vault_type, **vault_copy)
|
||||
self.log.debug(f"Successfully loaded vault: {vault_name} ({vault_type})")
|
||||
except Exception as e:
|
||||
self.log.error(f"vault failure: {vault_name} ({vault_type}) - {e}")
|
||||
raise
|
||||
else:
|
||||
# Other vaults (MySQL, HTTP, API) - soft fail
|
||||
if not self.vaults.load(vault_type, **vault_copy):
|
||||
failed_vaults.append(vault_name)
|
||||
self.log.debug(f"Failed to load vault: {vault_name} ({vault_type})")
|
||||
else:
|
||||
self.log.debug(f"Successfully loaded vault: {vault_name} ({vault_type})")
|
||||
|
||||
loaded_count = len(self.vaults)
|
||||
if failed_vaults:
|
||||
@@ -1968,8 +1932,8 @@ class dl:
|
||||
spinner="dots",
|
||||
):
|
||||
try:
|
||||
cookies = self.get_cookie_jar(self.service, self.profile)
|
||||
credential = self.get_credentials(self.service, self.profile)
|
||||
cookies = login.get_cookie_jar(self.service, self.profile)
|
||||
credential = login.get_credentials(self.service, self.profile)
|
||||
service.authenticate(cookies, credential)
|
||||
if cookies or credential:
|
||||
self.log.info("Authenticated with Service")
|
||||
@@ -3394,9 +3358,9 @@ class dl:
|
||||
progress_sink({"output_files": [str(p) for p in self.completed_files]})
|
||||
|
||||
if not hasattr(service, "close"):
|
||||
cookie_file = self.get_cookie_path(self.service, self.profile)
|
||||
cookie_file = login.get_cookie_path(self.service, self.profile)
|
||||
if cookie_file:
|
||||
self.save_cookies(cookie_file, service.session.cookies)
|
||||
login.save_cookies(cookie_file, service.session.cookies)
|
||||
|
||||
self.keys.wait_vault_writes()
|
||||
if hasattr(service, "close"):
|
||||
@@ -3966,107 +3930,6 @@ class dl:
|
||||
cdm = self.get_cdm(self.service, self.profile, drm=system)
|
||||
return cdm
|
||||
|
||||
@staticmethod
|
||||
def get_cookie_path(service: str, profile: Optional[str]) -> Optional[Path]:
|
||||
"""Get Service Cookie File Path for Profile."""
|
||||
direct_cookie_file = config.directories.cookies / f"{service}.txt"
|
||||
profile_cookie_file = config.directories.cookies / service / f"{profile}.txt"
|
||||
default_cookie_file = config.directories.cookies / service / "default.txt"
|
||||
|
||||
if direct_cookie_file.exists():
|
||||
return direct_cookie_file
|
||||
elif profile_cookie_file.exists():
|
||||
return profile_cookie_file
|
||||
elif default_cookie_file.exists():
|
||||
return default_cookie_file
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def get_cookie_jar(service: str, profile: Optional[str]) -> Optional[CookieJar]:
|
||||
"""
|
||||
Get Service Cookies for Profile.
|
||||
|
||||
If the config has firefox_cookies for the service, cookies come from Firefox first. If that extraction
|
||||
raises or returns nothing, unshackle uses the profile's cookie file instead and does not log the failure.
|
||||
"""
|
||||
ff_settings = getattr(config, "firefox_cookies", {}).get(service)
|
||||
if ff_settings:
|
||||
try:
|
||||
from unshackle.core.utils.firefox_cookie_extractor import get_firefox_cookies
|
||||
|
||||
extracted_jar = get_firefox_cookies(ff_settings)
|
||||
if extracted_jar:
|
||||
return extracted_jar
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cookie_file = dl.get_cookie_path(service, profile)
|
||||
if cookie_file:
|
||||
return dl.load_cookie_file(cookie_file)
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def load_cookie_file(cookie_file: Path) -> MozillaCookieJar:
|
||||
"""Load a Netscape cookie file with every expiry blanked, so no layer drops an expired cookie."""
|
||||
cookie_jar = dl.parse_cookie_text(cookie_file.read_text("utf-8-sig"), str(cookie_file))
|
||||
cookie_jar.filename = str(cookie_file)
|
||||
return cookie_jar
|
||||
|
||||
@staticmethod
|
||||
def parse_cookie_text(text: str, source: str) -> MozillaCookieJar:
|
||||
"""Parse Netscape cookie text the way :meth:`load_cookie_file` does; ``source`` names it in errors."""
|
||||
cookie_jar = MozillaCookieJar()
|
||||
cookie_data = html.unescape(text).splitlines(keepends=False)
|
||||
head = next((line.lstrip() for line in cookie_data if line.strip()), "")
|
||||
if head[:1] in ("[", "{"):
|
||||
raise ValueError(f"{source} is a JSON export; export it again in Netscape format")
|
||||
for i, line in enumerate(cookie_data):
|
||||
body = line.lstrip()
|
||||
prefix = "#HttpOnly_" if body.startswith("#HttpOnly_") else ""
|
||||
body = body[len(prefix) :]
|
||||
if not body or body.startswith("#"):
|
||||
continue
|
||||
line_data = body.split("\t") if "\t" in body else body.split(None, 6)
|
||||
if len(line_data) == 6:
|
||||
line_data.append("")
|
||||
if len(line_data) != 7:
|
||||
raise ValueError(f"{source} line {i + 1} is not a Netscape cookie row: {line!r}")
|
||||
line_data[4] = ""
|
||||
line_data[1] = str(line_data[0].startswith(".")).upper()
|
||||
cookie_data[i] = prefix + "\t".join(line_data)
|
||||
cookie_data.insert(0, "# Netscape HTTP Cookie File")
|
||||
cookie_jar._really_load(StringIO("\n".join(cookie_data)), source, True, True) # type: ignore[attr-defined]
|
||||
if not len(cookie_jar):
|
||||
raise ValueError(f"{source} holds no cookies; export it again in Netscape format")
|
||||
return cookie_jar
|
||||
|
||||
@staticmethod
|
||||
def save_cookies(path: Path, cookies: CookieJar) -> None:
|
||||
if hasattr(cookies, "jar"):
|
||||
cookies = cookies.jar
|
||||
|
||||
cookie_jar = dl.load_cookie_file(path) if path.exists() else MozillaCookieJar(path)
|
||||
for cookie in cookies:
|
||||
if not cookie.name or not cookie.domain:
|
||||
continue
|
||||
cookie_jar.set_cookie(cookie)
|
||||
cookie_jar.save(ignore_discard=True, ignore_expires=True)
|
||||
|
||||
@staticmethod
|
||||
def get_credentials(service: str, profile: Optional[str]) -> Optional[Credential]:
|
||||
"""Get Service Credentials for Profile."""
|
||||
credentials = config.credentials.get(service)
|
||||
if credentials:
|
||||
if isinstance(credentials, dict):
|
||||
if profile:
|
||||
credentials = credentials.get(profile) or credentials.get("default")
|
||||
else:
|
||||
credentials = credentials.get("default")
|
||||
if credentials:
|
||||
return Credential.from_config(credentials)
|
||||
return None
|
||||
|
||||
def cdm_from_service_entry(self) -> bool:
|
||||
"""Whether the service's own ``cdm`` entry named the loaded device, not ``--cdm`` or the ``default`` entry."""
|
||||
return (
|
||||
|
||||
@@ -24,12 +24,12 @@ from unshackle.core.console import GradientPulseBarColumn, console
|
||||
from unshackle.core.constants import context_settings
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.vault import Vault, is_null_key
|
||||
from unshackle.core.vaults import Vaults
|
||||
from unshackle.core.vaults import Vaults, load_config_vaults
|
||||
|
||||
|
||||
def load_vaults(vault_names: list[str]) -> Vaults:
|
||||
"""Load and validate vaults by config name, or by the path of an SQLite vault file."""
|
||||
vaults = Vaults()
|
||||
configs = []
|
||||
for vault_name in vault_names:
|
||||
vault_config = next((x for x in config.key_vaults if x["name"] == vault_name), None)
|
||||
if not vault_config:
|
||||
@@ -37,14 +37,11 @@ def load_vaults(vault_names: list[str]) -> Vaults:
|
||||
if not path.is_file():
|
||||
raise click.ClickException(f"Vault ({vault_name}) is not defined in the config or an existing file.")
|
||||
vault_config = {"type": "SQLite", "name": path.stem, "path": path}
|
||||
configs.append(vault_config)
|
||||
|
||||
vault_type = vault_config["type"]
|
||||
vault_args = vault_config.copy()
|
||||
del vault_args["type"]
|
||||
|
||||
if not vaults.load(vault_type, **vault_args):
|
||||
raise click.ClickException(f"Failed to load vault ({vault_name}).")
|
||||
|
||||
vaults, failed = load_config_vaults(configs=configs)
|
||||
if failed:
|
||||
raise click.ClickException(f"Failed to load vault ({next(iter(failed))}).")
|
||||
return vaults
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from rich.padding import Padding
|
||||
from rich.rule import Rule
|
||||
from rich.tree import Tree
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core import login
|
||||
from unshackle.core.config import config, load_yaml
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.constants import context_settings
|
||||
@@ -140,8 +140,8 @@ def result(service: Service, profile: Optional[str] = None, remote: bool = False
|
||||
|
||||
if not remote and not service.ANONYMOUS_SEARCH:
|
||||
with console.status("Authenticating with Service...", spinner="dots"):
|
||||
cookies = dl.get_cookie_jar(service_tag, profile)
|
||||
credential = dl.get_credentials(service_tag, profile)
|
||||
cookies = login.get_cookie_jar(service_tag, profile)
|
||||
credential = login.get_credentials(service_tag, profile)
|
||||
service.authenticate(cookies, credential)
|
||||
if cookies or credential:
|
||||
log.info("Authenticated with Service")
|
||||
@@ -159,9 +159,9 @@ def result(service: Service, profile: Optional[str] = None, remote: bool = False
|
||||
result_text += f"\n[bright_black]id: {result.id}[/]"
|
||||
search_results.add(result_text + "\n")
|
||||
|
||||
cookie_file = None if remote or service.ANONYMOUS_SEARCH else dl.get_cookie_path(service_tag, profile)
|
||||
cookie_file = None if remote or service.ANONYMOUS_SEARCH else login.get_cookie_path(service_tag, profile)
|
||||
if cookie_file:
|
||||
dl.save_cookies(cookie_file, service.session.cookies)
|
||||
login.save_cookies(cookie_file, service.session.cookies)
|
||||
|
||||
console.print(Padding(Rule(f"[rule.text]{len(search_results.children)} Search Results"), (1, 2)))
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ from urllib.parse import urlsplit
|
||||
import click
|
||||
from aiohttp import web
|
||||
|
||||
from unshackle.core import login
|
||||
from unshackle.core.api.compression import safe_inflate
|
||||
from unshackle.core.api.errors import APIError, categorize_exception, handle_api_exception
|
||||
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
|
||||
@@ -224,13 +225,12 @@ def server_login_material(
|
||||
which the operator's own UI drives, uses its own profiles; a ``--remote-only`` server uses only
|
||||
what the client sent, the same rule as a remote session.
|
||||
"""
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.api.stats import stats
|
||||
|
||||
if account:
|
||||
return server_account_cookies(normalized_service, profile), dl.get_credentials(normalized_service, profile)
|
||||
return server_account_cookies(normalized_service, profile), login.get_credentials(normalized_service, profile)
|
||||
if stats.mode != "remote_only":
|
||||
return dl.get_cookie_jar(normalized_service, profile), dl.get_credentials(normalized_service, profile)
|
||||
return login.get_cookie_jar(normalized_service, profile), login.get_credentials(normalized_service, profile)
|
||||
return load_client_cookies(data.get("cookies")), client_credential(data)
|
||||
|
||||
|
||||
@@ -1244,12 +1244,10 @@ def _regions(value: Any) -> set[str]:
|
||||
|
||||
def server_account_cookies(service: str, profile: Optional[str]) -> Any:
|
||||
"""Cookies for a server account: the profile's own file only, so a bare ``cookies/{service}.txt`` cannot shadow it."""
|
||||
from unshackle.commands.dl import dl
|
||||
|
||||
if profile is None:
|
||||
return dl.get_cookie_jar(service, None)
|
||||
return login.get_cookie_jar(service, None)
|
||||
path = config.directories.cookies / service / f"{profile}.txt"
|
||||
return dl.load_cookie_file(path) if path.exists() else None
|
||||
return login.load_cookie_file(path) if path.exists() else None
|
||||
|
||||
|
||||
def load_client_cookies(cookie_text: Any) -> Optional[CookieJar]:
|
||||
@@ -1259,14 +1257,12 @@ def load_client_cookies(cookie_text: Any) -> Optional[CookieJar]:
|
||||
the way local ``dl`` parses a cookie file, so a file that works locally also works
|
||||
over ``--remote``.
|
||||
"""
|
||||
from unshackle.commands.dl import dl
|
||||
|
||||
if not cookie_text or not isinstance(cookie_text, str):
|
||||
return None
|
||||
|
||||
try:
|
||||
cookie_str = safe_inflate(base64.b64decode(cookie_text)).decode("utf-8-sig")
|
||||
return dl.parse_cookie_text(cookie_str, "client cookies")
|
||||
return login.parse_cookie_text(cookie_str, "client cookies")
|
||||
except (ValueError, zlib.error, OSError) as e:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"cookies is not a compressed Netscape cookie file: {e}")
|
||||
|
||||
@@ -2755,11 +2751,11 @@ def run_health_checks(checks: Optional[List[Dict[str, Any]]] = None) -> List[Dic
|
||||
name = vault_config.get("name") or vault_config.get("type", "vault")
|
||||
|
||||
def vault_probe(vault_config: Any = vault_config) -> tuple[str, str]:
|
||||
from unshackle.core.vaults import Vaults
|
||||
from unshackle.core.vaults import load_config_vaults
|
||||
|
||||
cfg = dict(vault_config)
|
||||
vaults = Vaults(probe_service)
|
||||
vaults.load_critical(cfg.pop("type"), **cfg)
|
||||
vaults, failed = load_config_vaults(probe_service, [vault_config])
|
||||
if failed:
|
||||
raise next(iter(failed.values()))
|
||||
vault = vaults.vaults[0]
|
||||
try:
|
||||
vault.get_key(HEALTH_PROBE_KID, probe_service)
|
||||
@@ -3389,7 +3385,6 @@ def create_service_instance(
|
||||
client that sends nothing authenticates with nothing, because the server never lends its
|
||||
own accounts.
|
||||
"""
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.tracks import Video
|
||||
|
||||
server_config = service_config = key_service_yaml(normalized_service, user_config)
|
||||
@@ -3433,7 +3428,7 @@ def create_service_instance(
|
||||
|
||||
if server_account:
|
||||
cookies = server_account_cookies(normalized_service, profile)
|
||||
credential = dl.get_credentials(normalized_service, profile)
|
||||
credential = login.get_credentials(normalized_service, profile)
|
||||
else:
|
||||
credential = client_credential(data)
|
||||
cookies = load_client_cookies(data.get("cookies"))
|
||||
@@ -4454,21 +4449,11 @@ def pick_server_pssh(track: Any, candidates: List[str]) -> Optional[tuple[str, s
|
||||
|
||||
|
||||
def load_server_vaults(service_name: str) -> Any:
|
||||
"""Load server vaults from config.key_vaults."""
|
||||
from unshackle.core.config import config as app_config
|
||||
"""Load server vaults from config.key_vaults; a vault that fails to load is left out."""
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.vaults import Vaults
|
||||
from unshackle.core.vaults import load_config_vaults
|
||||
|
||||
vaults = Vaults(Services.get_vault_tag(service_name))
|
||||
for vault_config in app_config.key_vaults:
|
||||
cfg = vault_config.copy()
|
||||
vault_type = cfg.pop("type", None)
|
||||
if vault_type:
|
||||
try:
|
||||
vaults.load(vault_type, **cfg)
|
||||
except (Exception, SystemExit) as e:
|
||||
log.warning(f"Could not load vault '{vault_type}': {e}")
|
||||
return vaults
|
||||
return load_config_vaults(Services.get_vault_tag(service_name))[0]
|
||||
|
||||
|
||||
def once(shared: Dict[Any, Any], key: Any, make: Callable[[], Any]) -> Any:
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Login state for a service: its cookie file, cookie jar and credentials, read from the config."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
from http.cookiejar import CookieJar, MozillaCookieJar
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.credential import Credential
|
||||
|
||||
|
||||
def get_cookie_path(service: str, profile: Optional[str]) -> Optional[Path]:
|
||||
"""Get Service Cookie File Path for Profile."""
|
||||
direct_cookie_file = config.directories.cookies / f"{service}.txt"
|
||||
profile_cookie_file = config.directories.cookies / service / f"{profile}.txt"
|
||||
default_cookie_file = config.directories.cookies / service / "default.txt"
|
||||
|
||||
if direct_cookie_file.exists():
|
||||
return direct_cookie_file
|
||||
elif profile_cookie_file.exists():
|
||||
return profile_cookie_file
|
||||
elif default_cookie_file.exists():
|
||||
return default_cookie_file
|
||||
return None
|
||||
|
||||
|
||||
def get_cookie_jar(service: str, profile: Optional[str]) -> Optional[CookieJar]:
|
||||
"""
|
||||
Get Service Cookies for Profile.
|
||||
|
||||
If the config has firefox_cookies for the service, cookies come from Firefox first. If that extraction
|
||||
raises or returns nothing, unshackle uses the profile's cookie file instead and does not log the failure.
|
||||
"""
|
||||
ff_settings = getattr(config, "firefox_cookies", {}).get(service)
|
||||
if ff_settings:
|
||||
try:
|
||||
from unshackle.core.utils.firefox_cookie_extractor import get_firefox_cookies
|
||||
|
||||
extracted_jar = get_firefox_cookies(ff_settings)
|
||||
if extracted_jar:
|
||||
return extracted_jar
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cookie_file = get_cookie_path(service, profile)
|
||||
if cookie_file:
|
||||
return load_cookie_file(cookie_file)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def load_cookie_file(cookie_file: Path) -> MozillaCookieJar:
|
||||
"""Load a Netscape cookie file with every expiry blanked, so no layer drops an expired cookie."""
|
||||
cookie_jar = parse_cookie_text(cookie_file.read_text("utf-8-sig"), str(cookie_file))
|
||||
cookie_jar.filename = str(cookie_file)
|
||||
return cookie_jar
|
||||
|
||||
|
||||
def parse_cookie_text(text: str, source: str) -> MozillaCookieJar:
|
||||
"""Parse Netscape cookie text the way :func:`load_cookie_file` does; ``source`` names it in errors."""
|
||||
cookie_jar = MozillaCookieJar()
|
||||
cookie_data = html.unescape(text).splitlines(keepends=False)
|
||||
head = next((line.lstrip() for line in cookie_data if line.strip()), "")
|
||||
if head[:1] in ("[", "{"):
|
||||
raise ValueError(f"{source} is a JSON export; export it again in Netscape format")
|
||||
for i, line in enumerate(cookie_data):
|
||||
body = line.lstrip()
|
||||
prefix = "#HttpOnly_" if body.startswith("#HttpOnly_") else ""
|
||||
body = body[len(prefix) :]
|
||||
if not body or body.startswith("#"):
|
||||
continue
|
||||
line_data = body.split("\t") if "\t" in body else body.split(None, 6)
|
||||
if len(line_data) == 6:
|
||||
line_data.append("")
|
||||
if len(line_data) != 7:
|
||||
raise ValueError(f"{source} line {i + 1} is not a Netscape cookie row: {line!r}")
|
||||
line_data[4] = ""
|
||||
line_data[1] = str(line_data[0].startswith(".")).upper()
|
||||
cookie_data[i] = prefix + "\t".join(line_data)
|
||||
cookie_data.insert(0, "# Netscape HTTP Cookie File")
|
||||
cookie_jar._really_load(StringIO("\n".join(cookie_data)), source, True, True) # type: ignore[attr-defined]
|
||||
if not len(cookie_jar):
|
||||
raise ValueError(f"{source} holds no cookies; export it again in Netscape format")
|
||||
return cookie_jar
|
||||
|
||||
|
||||
def save_cookies(path: Path, cookies: CookieJar) -> None:
|
||||
if hasattr(cookies, "jar"):
|
||||
cookies = cookies.jar
|
||||
|
||||
cookie_jar = load_cookie_file(path) if path.exists() else MozillaCookieJar(path)
|
||||
for cookie in cookies:
|
||||
if not cookie.name or not cookie.domain:
|
||||
continue
|
||||
cookie_jar.set_cookie(cookie)
|
||||
cookie_jar.save(ignore_discard=True, ignore_expires=True)
|
||||
|
||||
|
||||
def get_credentials(service: str, profile: Optional[str]) -> Optional[Credential]:
|
||||
"""Get Service Credentials for Profile."""
|
||||
credentials = config.credentials.get(service)
|
||||
if credentials:
|
||||
if isinstance(credentials, dict):
|
||||
if profile:
|
||||
credentials = credentials.get(profile) or credentials.get("default")
|
||||
else:
|
||||
credentials = credentials.get("default")
|
||||
if credentials:
|
||||
return Credential.from_config(credentials)
|
||||
return None
|
||||
@@ -45,6 +45,7 @@ from rich.padding import Padding
|
||||
from rich.rule import Rule
|
||||
from rich.spinner import Spinner
|
||||
|
||||
from unshackle.core import login
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.console import SyncLive, console
|
||||
from unshackle.core.constants import AnyTrack
|
||||
@@ -632,9 +633,7 @@ def make_remote_service(
|
||||
|
||||
|
||||
def load_credentials_for_transport(service_tag: str, profile: Optional[str]) -> Optional[Dict[str, str]]:
|
||||
from unshackle.commands.dl import dl
|
||||
|
||||
credential = dl.get_credentials(service_tag, profile)
|
||||
credential = login.get_credentials(service_tag, profile)
|
||||
if credential:
|
||||
result: Dict[str, str] = {"username": credential.username, "password": credential.password}
|
||||
if credential.extra:
|
||||
@@ -646,9 +645,7 @@ def load_credentials_for_transport(service_tag: str, profile: Optional[str]) ->
|
||||
def load_cookies_for_transport(service_tag: str, profile: Optional[str]) -> Optional[str]:
|
||||
import zlib
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
|
||||
cookie_path = dl.get_cookie_path(service_tag, profile)
|
||||
cookie_path = login.get_cookie_path(service_tag, profile)
|
||||
if cookie_path and cookie_path.exists():
|
||||
return base64.b64encode(zlib.compress(cookie_path.read_bytes())).decode("ascii")
|
||||
return None
|
||||
@@ -789,9 +786,7 @@ def cache_key_filter(service_tag: str, profile: Optional[str]) -> Callable[[str]
|
||||
because a service may embed the credential digest or profile name in a directory name
|
||||
as well as in the basename. A profile with no credentials entry uses the default one.
|
||||
"""
|
||||
from unshackle.commands.dl import dl
|
||||
|
||||
credential = dl.get_credentials(service_tag, profile)
|
||||
credential = login.get_credentials(service_tag, profile)
|
||||
allowed = credential_cache_digests(credential) if credential else set()
|
||||
active = profile or "default"
|
||||
profiles = config.credentials.get(service_tag)
|
||||
|
||||
@@ -418,7 +418,7 @@ class RnetCookieAdapter(MutableMapping):
|
||||
def jar(self) -> CookieJar:
|
||||
"""Return a CookieJar of the cookies that arrived as a CookieJar (requests compat).
|
||||
|
||||
``save_cookies`` in dl.py uses this to write cookies back to disk, so it carries a value
|
||||
``login.save_cookies`` uses this to write cookies back to disk, so it carries a value
|
||||
the server rotated for one of those cookies but not the cookies set by name.
|
||||
"""
|
||||
jar = CookieJar()
|
||||
|
||||
+40
-20
@@ -3,7 +3,7 @@ import logging
|
||||
import time
|
||||
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
|
||||
from functools import partial
|
||||
from typing import Any, Iterator, Optional, Union
|
||||
from typing import Any, Collection, Iterable, Iterator, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.config import config
|
||||
@@ -38,30 +38,15 @@ class Vaults:
|
||||
def __len__(self) -> int:
|
||||
return len(self.vaults)
|
||||
|
||||
def load(self, type_: str, **kwargs: Any) -> bool:
|
||||
"""Load a Vault into the vaults list. Returns True if successful, False otherwise."""
|
||||
def load(self, type_: str, **kwargs: Any) -> None:
|
||||
"""Load a Vault into the vaults list, or raise when it cannot be built."""
|
||||
module = MODULES.get(type_)
|
||||
if not module:
|
||||
raise ValueError(f"Unable to find vault command by the name '{type_}'.")
|
||||
# only pass the global default to vaults that declare a timeout param (per-vault config still wins)
|
||||
if "timeout" not in kwargs and "timeout" in inspect.signature(module).parameters:
|
||||
kwargs["timeout"] = config.vault_timeout
|
||||
try:
|
||||
vault = module(**kwargs)
|
||||
self.vaults.append(vault)
|
||||
return True
|
||||
# one bad vault config must not stop the others from loading
|
||||
except Exception as e:
|
||||
log.debug(f"Vault '{type_}' failed to load: {e!r}")
|
||||
return False
|
||||
|
||||
def load_critical(self, type_: str, **kwargs: Any) -> None:
|
||||
"""Load a critical Vault that must succeed or raise an exception."""
|
||||
module = MODULES.get(type_)
|
||||
if not module:
|
||||
raise ValueError(f"Unable to find vault command by the name '{type_}'.")
|
||||
vault = module(**kwargs)
|
||||
self.vaults.append(vault)
|
||||
self.vaults.append(module(**kwargs))
|
||||
|
||||
def get_key(self, kid: Union[UUID, str]) -> tuple[Optional[str], Optional[Vault]]:
|
||||
"""Get Key from the first Vault it can by KID (Key ID) and Service.
|
||||
@@ -274,4 +259,39 @@ class Vaults:
|
||||
log.warning(f"Skipping Vault '{vault.name}' for the rest of this run")
|
||||
|
||||
|
||||
__all__ = ("Vaults",)
|
||||
__all__ = ("Vaults", "load_config_vaults")
|
||||
|
||||
|
||||
def load_config_vaults(
|
||||
service: Optional[str] = None,
|
||||
configs: Optional[Iterable[dict[str, Any]]] = None,
|
||||
critical: Collection[str] = (),
|
||||
) -> tuple[Vaults, dict[str, BaseException]]:
|
||||
"""Load vault configs (the config's ``key_vaults`` by default) into one Vaults for a service.
|
||||
|
||||
A vault whose lower-case type is in ``critical`` raises when it fails to load; any other vault
|
||||
that fails is left out and returned by name with its error. A DecryptLabs API vault with no
|
||||
token of its own takes the global ``decrypt_labs_api_key``.
|
||||
"""
|
||||
vaults = Vaults(service)
|
||||
failed: dict[str, BaseException] = {}
|
||||
for vault_config in config.key_vaults if configs is None else configs:
|
||||
cfg = dict(vault_config)
|
||||
type_ = str(cfg.pop("type", ""))
|
||||
name = str(cfg.get("name") or type_)
|
||||
if type_.lower() == "api" and "decrypt_labs" in name.lower() and not cfg.get("token"):
|
||||
if config.decrypt_labs_api_key:
|
||||
cfg["token"] = config.decrypt_labs_api_key
|
||||
else:
|
||||
log.warning(f"No token for DecryptLabs vault '{name}' and no global decrypt_labs_api_key")
|
||||
try:
|
||||
vaults.load(type_, **cfg)
|
||||
except (Exception, SystemExit) as e:
|
||||
if type_.lower() in critical:
|
||||
log.error(f"vault failure: {name} ({type_}) - {e}")
|
||||
raise
|
||||
failed[name] = e
|
||||
log.debug(f"Failed to load vault: {name} ({type_}): {e!r}")
|
||||
else:
|
||||
log.debug(f"Successfully loaded vault: {name} ({type_})")
|
||||
return vaults, failed
|
||||
|
||||
Reference in New Issue
Block a user