Files
mimic/backend/tests/test_crypto.py
Knacky 9a9c98beab feat(backend): c2 crypto + config CRUD + adapter scaffolding (sprint 8 M1)
- Add Fernet crypto service (MIMIC_ENCRYPTION_KEY env, C2Disabled on absent key)
- Add Alembic migration 0006: c2_config + c2_task tables with cascade FKs
- Add C2Config and C2Task SQLAlchemy models
- Add C2Adapter ABC with dataclasses (C2Health, C2Callback, C2TaskStatus, C2TaskPage)
- Add FakeAdapter (deterministic in-memory, MIMIC_C2_ADAPTER=fake)
- Add MythicAdapter scaffold: test_connection() live, M2+ raise NotImplementedError
- Add decode_response_text() helper for base64/binary Mythic responses
- Add GET/PUT/DELETE/POST-test /api/engagements/<id>/c2-config endpoints
- RBAC: admin+redteam OK, SOC 403; 503 guard when encryption key absent
- Token never returned in API responses; stored Fernet-encrypted only
- 42 new tests (300 total, 258 baseline preserved green)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 19:20:52 +02:00

53 lines
1.5 KiB
Python

"""Tests for the Fernet crypto service."""
from __future__ import annotations
import pytest
from cryptography.fernet import Fernet
from backend.app.services.crypto import C2Disabled, decrypt, encrypt
@pytest.fixture()
def fernet_key(monkeypatch) -> str:
key = Fernet.generate_key().decode()
monkeypatch.setenv("MIMIC_ENCRYPTION_KEY", key)
return key
@pytest.fixture()
def no_key(monkeypatch):
monkeypatch.delenv("MIMIC_ENCRYPTION_KEY", raising=False)
class TestEncryptDecrypt:
def test_round_trip(self, fernet_key):
plaintext = "s3cr3t-api-token"
ciphertext = encrypt(plaintext)
assert ciphertext != plaintext
assert decrypt(ciphertext) == plaintext
def test_different_tokens_for_same_input(self, fernet_key):
# Fernet tokens are non-deterministic (random IV).
t1 = encrypt("same")
t2 = encrypt("same")
assert t1 != t2
assert decrypt(t1) == decrypt(t2) == "same"
def test_decrypt_invalid_ciphertext(self, fernet_key):
with pytest.raises(ValueError):
decrypt("not-valid-fernet-token")
class TestKeyAbsent:
def test_encrypt_raises_c2disabled(self, no_key):
with pytest.raises(C2Disabled):
encrypt("anything")
def test_decrypt_raises_c2disabled(self, no_key):
with pytest.raises(C2Disabled):
decrypt("anything")
def test_c2disabled_message(self, no_key):
with pytest.raises(C2Disabled, match="MIMIC_ENCRYPTION_KEY"):
encrypt("x")