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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user