From fbe40107be2d5fc410a66d35f3abddbe57fdba8d Mon Sep 17 00:00:00 2001 From: Ivan Golikov Date: Fri, 3 Jan 2025 15:28:15 +0100 Subject: [PATCH] Tests for encryption --- tests/conftest.py | 7 +++++++ tests/unit/__init__.py | 0 tests/unit/test_utils.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/test_utils.py diff --git a/tests/conftest.py b/tests/conftest.py index 87da6ad..b7e212f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,10 +1,12 @@ from collections.abc import AsyncGenerator +from cryptography.fernet import Fernet import pytest from fastapi.testclient import TestClient from pydantic_settings import SettingsConfigDict from redis import asyncio as aioredis +from pssecret_server.fernet import get_fernet from pssecret_server.main import app from pssecret_server.settings import Settings, get_settings @@ -29,6 +31,11 @@ def get_test_settings() -> Settings: return TestSettings() +@pytest.fixture +def fernet(settings: Settings) -> Fernet: + return get_fernet(settings) + + @pytest.fixture(scope="session") def client() -> TestClient: client_ = TestClient(app) diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py new file mode 100644 index 0000000..35cc82f --- /dev/null +++ b/tests/unit/test_utils.py @@ -0,0 +1,29 @@ +from cryptography.fernet import Fernet, InvalidToken +import pytest +from pssecret_server.utils import encrypt_secret, decrypt_secret +from ..factories import SecretFactory + + +def test_encrypte_secret_ok(fernet: Fernet): + secret = SecretFactory().build() + encrypted_secret = encrypt_secret(secret, fernet) + + assert secret.data != encrypted_secret.data + + +def test_secret_is_decryptable_by_correct_key(fernet: Fernet): + secret = SecretFactory().build() + encrypted_secret = encrypt_secret(secret, fernet) + decrypted_secret = decrypt_secret(encrypted_secret.data.encode(), fernet) + + assert decrypted_secret.decode() == secret.data + + +def test_secret_is_not_decryptable_by_random_key(fernet: Fernet): + secret = SecretFactory().build() + encrypted_secret = encrypt_secret(secret, fernet) + + random_fernet = Fernet(Fernet.generate_key()) + + with pytest.raises(InvalidToken): + decrypt_secret(encrypted_secret.data.encode(), random_fernet)