48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
|
|
import pytest
|
|
from cryptography.fernet import Fernet
|
|
|
|
_scripts = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
|
|
if _scripts not in sys.path:
|
|
sys.path.insert(0, _scripts)
|
|
|
|
from service.crypto import CredentialDecryptError, decrypt_secret, encrypt_secret # noqa: E402
|
|
from service.master_key import ENV_MASTER_KEY # noqa: E402
|
|
|
|
|
|
@pytest.fixture()
|
|
def crypto_env(monkeypatch):
|
|
tmp = tempfile.mkdtemp(prefix="crypto_test_")
|
|
data_root = os.path.join(tmp, "claw-data")
|
|
os.makedirs(data_root, exist_ok=True)
|
|
monkeypatch.setenv("JIANGCHANG_DATA_ROOT", data_root)
|
|
monkeypatch.setenv("JIANGCHANG_USER_ID", "c_uid")
|
|
key = Fernet.generate_key()
|
|
monkeypatch.setenv(ENV_MASTER_KEY, key.decode("ascii"))
|
|
yield key
|
|
|
|
|
|
def test_encrypt_decrypt_roundtrip(crypto_env):
|
|
pt = "my-password-123"
|
|
ct = encrypt_secret(pt)
|
|
assert decrypt_secret(ct) == pt
|
|
|
|
|
|
def test_decrypt_invalid_token(crypto_env):
|
|
with pytest.raises(CredentialDecryptError) as ei:
|
|
decrypt_secret("AAAA-invalid-token-AAAA")
|
|
assert ei.value.code == "ERR_CREDENTIAL_DECRYPT_FAILED"
|
|
|
|
|
|
def test_decrypt_wrong_master_key(monkeypatch, crypto_env):
|
|
pt = "secret-value"
|
|
ct = encrypt_secret(pt)
|
|
other = Fernet.generate_key().decode("ascii")
|
|
monkeypatch.setenv(ENV_MASTER_KEY, other)
|
|
with pytest.raises(CredentialDecryptError):
|
|
decrypt_secret(ct)
|