security: rotate bootstrap and clean workspace

This commit is contained in:
2026-03-13 12:14:37 +03:00
parent a79c14af53
commit 52bfbf258c
14 changed files with 219 additions and 169 deletions

View File

@@ -7,12 +7,14 @@ sys.path.append(str(Path(__file__).parent.parent / "src"))
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from cryptography.fernet import Fernet
from src.core.database import Base
from src.models.auth import User, Role, Permission, ADGroupMapping
from src.services.auth_service import AuthService
from src.core.auth.repository import AuthRepository
from src.core.auth.security import verify_password, get_password_hash
from src.scripts.create_admin import create_admin
from src.scripts.init_auth_db import ensure_encryption_key
# Create in-memory SQLite database for testing
SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
@@ -189,3 +191,46 @@ def test_create_admin_is_idempotent_for_existing_user(monkeypatch, db_session):
assert created_user.email is None
assert verify_password("bootstrap-pass", created_user.password_hash)
assert not verify_password("new-password", created_user.password_hash)
def test_ensure_encryption_key_generates_backend_env_file(monkeypatch, tmp_path):
"""Test first-time initialization generates and persists a Fernet key."""
env_file = tmp_path / ".env"
monkeypatch.delenv("ENCRYPTION_KEY", raising=False)
generated_key = ensure_encryption_key(env_file)
assert generated_key
assert env_file.exists()
assert env_file.read_text(encoding="utf-8").strip() == f"ENCRYPTION_KEY={generated_key}"
assert verify_fernet_key(generated_key)
def test_ensure_encryption_key_reuses_existing_env_file_value(monkeypatch, tmp_path):
"""Test persisted key is reused without rewriting file contents."""
env_file = tmp_path / ".env"
existing_key = Fernet.generate_key().decode()
env_file.write_text(f"ENCRYPTION_KEY={existing_key}\nOTHER=value\n", encoding="utf-8")
monkeypatch.delenv("ENCRYPTION_KEY", raising=False)
reused_key = ensure_encryption_key(env_file)
assert reused_key == existing_key
assert env_file.read_text(encoding="utf-8") == f"ENCRYPTION_KEY={existing_key}\nOTHER=value\n"
def test_ensure_encryption_key_prefers_process_environment(monkeypatch, tmp_path):
"""Test explicit process environment has priority over file generation."""
env_file = tmp_path / ".env"
runtime_key = Fernet.generate_key().decode()
monkeypatch.setenv("ENCRYPTION_KEY", runtime_key)
resolved_key = ensure_encryption_key(env_file)
assert resolved_key == runtime_key
assert not env_file.exists()
def verify_fernet_key(value: str) -> bool:
Fernet(value.encode())
return True