41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import base64
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from app.core import secret_box
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize(
|
||
|
|
"encoded_key",
|
||
|
|
[
|
||
|
|
"not-valid-base64!",
|
||
|
|
base64.urlsafe_b64encode(b"short-key").decode("ascii"),
|
||
|
|
],
|
||
|
|
)
|
||
|
|
def test_encrypt_rejects_invalid_existing_secret_key(
|
||
|
|
monkeypatch,
|
||
|
|
tmp_path,
|
||
|
|
encoded_key: str,
|
||
|
|
) -> None:
|
||
|
|
key_file = tmp_path / "settings.key"
|
||
|
|
key_file.write_text(encoded_key, encoding="utf-8")
|
||
|
|
monkeypatch.setattr(secret_box, "SECRET_KEY_FILE", key_file)
|
||
|
|
|
||
|
|
with pytest.raises(ValueError):
|
||
|
|
secret_box.encrypt_secret("probe")
|
||
|
|
|
||
|
|
assert key_file.read_text(encoding="utf-8") == encoded_key
|
||
|
|
|
||
|
|
|
||
|
|
def test_encrypt_replaces_empty_key_file_with_valid_key(monkeypatch, tmp_path) -> None:
|
||
|
|
key_file = tmp_path / "settings.key"
|
||
|
|
key_file.write_text("", encoding="utf-8")
|
||
|
|
monkeypatch.setattr(secret_box, "SECRET_KEY_FILE", key_file)
|
||
|
|
|
||
|
|
encrypted = secret_box.encrypt_secret("probe")
|
||
|
|
|
||
|
|
assert secret_box.decrypt_secret(encrypted) == "probe"
|
||
|
|
assert len(secret_box.read_secret_key()) == secret_box.KEY_BYTES
|