Files
ss-tools/backend/tests/api/test_encryption_health_helpers.py

311 lines
12 KiB
Python

# #region Test.Api.EncryptionHealth.Helpers [C:3] [TYPE Module] [SEMANTICS test,api,security,encryption,health]
# @BRIEF Direct unit tests for encryption-health helper functions — fingerprint, decrypt probing, inventories.
# @RELATION BINDS_TO -> [Api.EncryptionHealth.EncryptionHealthRoutes]
# @TEST_EDGE: missing_key -> provider/connection without stored secret -> missing_key status
# @TEST_EDGE: invalid_type -> plaintext value -> not_fernet_token probe result
# @TEST_EDGE: external_fail -> decrypt/DB raises -> broken item or logged warning
import os
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-tests")
os.environ.setdefault("DEV_MODE", "true")
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
_src = str(Path(__file__).resolve().parent.parent.parent / "src")
if _src not in sys.path:
sys.path.insert(0, _src)
from .conftest import ( # noqa: E402
ENCRYPTION_FINGERPRINT_EXPECTED,
FERNET_LIKE_TOKEN,
make_encryption_config_manager,
make_encryption_connection,
make_encryption_pref,
make_encryption_provider,
mock_encryption_auth_session,
)
# ── _key_fingerprint ──
class TestKeyFingerprint:
def test_success_returns_sha256_prefix(self):
manager = MagicMock()
manager.key = b"some-bytes"
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
from src.api.routes.encryption_health import _key_fingerprint
assert _key_fingerprint() == ENCRYPTION_FINGERPRINT_EXPECTED
def test_encryption_manager_unavailable(self):
with patch(
"src.api.routes.encryption_health.get_encryption_manager",
side_effect=RuntimeError("ENCRYPTION_KEY missing"),
):
from src.api.routes.encryption_health import _key_fingerprint
assert _key_fingerprint() == "unavailable"
def test_key_attribute_missing(self):
manager = MagicMock()
del manager.key
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
from src.api.routes.encryption_health import _key_fingerprint
assert _key_fingerprint() == "unavailable"
# ── _try_decrypt ──
class TestTryDecrypt:
def test_plaintext_short_value(self):
from src.api.routes.encryption_health import _try_decrypt
assert _try_decrypt("short-plaintext") == (False, "not_fernet_token")
def test_empty_value(self):
from src.api.routes.encryption_health import _try_decrypt
assert _try_decrypt("") == (False, "not_fernet_token")
def test_decrypt_success(self):
manager = MagicMock()
manager.decrypt.return_value = "decrypted-secret"
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
from src.api.routes.encryption_health import _try_decrypt
assert _try_decrypt(FERNET_LIKE_TOKEN) == (True, None)
manager.decrypt.assert_called_once_with(FERNET_LIKE_TOKEN)
def test_decrypt_failure_returns_short_message(self):
manager = MagicMock()
manager.decrypt.side_effect = ValueError("bad token")
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
from src.api.routes.encryption_health import _try_decrypt
assert _try_decrypt(FERNET_LIKE_TOKEN) == (False, "bad token")
def test_decrypt_failure_message_truncated_to_200(self):
manager = MagicMock()
manager.decrypt.side_effect = ValueError("x" * 250)
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
from src.api.routes.encryption_health import _try_decrypt
ok, err = _try_decrypt(FERNET_LIKE_TOKEN)
assert ok is False
assert len(err) == 200
# ── _sanitize_error ──
class TestSanitizeError:
def test_truncates_long_message(self):
from src.api.routes.encryption_health import _sanitize_error
assert _sanitize_error("a" * 150) == "a" * 100
def test_short_message_unchanged(self):
from src.api.routes.encryption_health import _sanitize_error
assert _sanitize_error("boom") == "boom"
def test_empty_message(self):
from src.api.routes.encryption_health import _sanitize_error
assert _sanitize_error("") == ""
# ── _inventory_llm_providers ──
class TestInventoryLlmProviders:
def _run(self, providers):
service = MagicMock()
service.get_all_providers.return_value = providers
with patch("src.api.routes.encryption_health.LLMProviderService", return_value=service):
from src.api.routes.encryption_health import _inventory_llm_providers
return _inventory_llm_providers(MagicMock())
def test_no_providers(self):
assert self._run([]) == []
def test_provider_without_key_missing(self):
items = self._run([make_encryption_provider(api_key=None)])
assert len(items) == 1
assert items[0]["status"] == "missing_key"
assert items[0]["reason"] == "no_key_stored"
assert items[0]["requires"] == ["api_key"]
assert items[0]["metadata"]["is_active"] is True
def test_provider_healthy(self):
manager = MagicMock()
manager.decrypt.return_value = "key"
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run([make_encryption_provider(api_key=FERNET_LIKE_TOKEN)])
assert items[0]["status"] == "healthy"
assert items[0]["reason"] is None
assert items[0]["requires"] == []
def test_provider_broken_decrypt_error(self):
manager = MagicMock()
manager.decrypt.side_effect = ValueError("invalid token")
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run([make_encryption_provider(api_key=FERNET_LIKE_TOKEN)])
assert items[0]["status"] == "broken"
assert items[0]["reason"] == "invalid token"
assert items[0]["requires"] == ["api_key"]
def test_provider_broken_plaintext(self):
items = self._run([make_encryption_provider(api_key="legacy-plaintext")])
assert items[0]["status"] == "broken"
assert items[0]["reason"] == "not_fernet_token"
def test_provider_broken_empty_error_falls_back(self):
manager = MagicMock()
manager.decrypt.side_effect = ValueError("")
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run([make_encryption_provider(api_key=FERNET_LIKE_TOKEN)])
assert items[0]["status"] == "broken"
assert items[0]["reason"] == "decrypt_failed"
def test_mixed_statuses(self):
manager = MagicMock()
manager.decrypt.side_effect = ["key1", ValueError("bad")]
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run(
[
make_encryption_provider("p1", api_key=FERNET_LIKE_TOKEN),
make_encryption_provider("p2", api_key=None),
make_encryption_provider("p3", api_key=FERNET_LIKE_TOKEN),
]
)
statuses = {it["id"]: it["status"] for it in items}
assert statuses == {"p1": "healthy", "p2": "missing_key", "p3": "broken"}
# ── _inventory_connections ──
class TestInventoryConnections:
def _run(self, connections):
from src.api.routes.encryption_health import _inventory_connections
return _inventory_connections(make_encryption_config_manager(connections))
def test_no_connections(self):
assert self._run([]) == []
def test_connection_without_password_missing(self):
items = self._run([make_encryption_connection(password=None)])
assert len(items) == 1
assert items[0]["status"] == "missing_key"
assert items[0]["reason"] == "no_password_stored"
assert items[0]["requires"] == ["password"]
def test_connection_healthy(self):
manager = MagicMock()
manager.decrypt.return_value = "pw"
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run([make_encryption_connection(password=FERNET_LIKE_TOKEN)])
assert items[0]["status"] == "healthy"
assert items[0]["reason"] is None
assert items[0]["requires"] == []
def test_connection_broken(self):
manager = MagicMock()
manager.decrypt.side_effect = ValueError("key mismatch")
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run([make_encryption_connection(password=FERNET_LIKE_TOKEN)])
assert items[0]["status"] == "broken"
assert items[0]["reason"] == "key mismatch"
assert items[0]["requires"] == ["password"]
def test_mixed_statuses(self):
manager = MagicMock()
manager.decrypt.side_effect = ["pw1", ValueError("bad")]
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run(
[
make_encryption_connection("c1", password=FERNET_LIKE_TOKEN),
make_encryption_connection("c2", password=None),
make_encryption_connection("c3", password=FERNET_LIKE_TOKEN),
]
)
statuses = {it["id"]: it["status"] for it in items}
assert statuses == {"c1": "healthy", "c2": "missing_key", "c3": "broken"}
# ── _inventory_profile_tokens ──
class TestInventoryProfileTokens:
def _run(self, auth_session):
with patch("src.core.database.SessionLocal", return_value=auth_session):
from src.api.routes.encryption_health import _inventory_profile_tokens
return _inventory_profile_tokens()
def test_no_prefs(self):
session = mock_encryption_auth_session([])
assert self._run(session) == []
session.close.assert_called_once()
def test_all_tokens_healthy(self):
manager = MagicMock()
manager.decrypt.return_value = "tok"
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run(
mock_encryption_auth_session(
[make_encryption_pref(FERNET_LIKE_TOKEN), make_encryption_pref(FERNET_LIKE_TOKEN)]
)
)
assert len(items) == 1
assert items[0]["status"] == "healthy"
assert items[0]["reason"] is None
assert items[0]["requires"] == []
assert items[0]["metadata"] == {"total": 2, "broken": 0}
def test_some_tokens_broken(self):
manager = MagicMock()
manager.decrypt.side_effect = [ValueError("bad"), "ok"]
with patch("src.api.routes.encryption_health.get_encryption_manager", return_value=manager):
items = self._run(
mock_encryption_auth_session(
[make_encryption_pref(FERNET_LIKE_TOKEN), make_encryption_pref(FERNET_LIKE_TOKEN)]
)
)
assert items[0]["status"] == "broken"
assert items[0]["reason"] == "1 of 2 cannot decrypt"
assert items[0]["requires"] == ["user_action_profile"]
assert items[0]["metadata"] == {"total": 2, "broken": 1}
def test_query_failure_logs_warning(self):
session = MagicMock()
session.query.side_effect = RuntimeError("db down")
with patch("src.api.routes.encryption_health.logger") as mock_logger:
items = self._run(session)
assert items == []
mock_logger.warning.assert_called_once()
session.close.assert_called_once()
def test_session_creation_failure_logs_warning(self):
with patch("src.core.database.SessionLocal", side_effect=RuntimeError("no engine")), \
patch("src.api.routes.encryption_health.logger") as mock_logger:
from src.api.routes.encryption_health import _inventory_profile_tokens
items = _inventory_profile_tokens()
assert items == []
mock_logger.warning.assert_called_once()
# #endregion Test.Api.EncryptionHealth.Helpers