mirror of
https://github.com/idrainformatica/PecFlow.git
synced 2026-06-16 12:45:42 +02:00
feat: Fase 1 – Fondamenta complete (backend FastAPI + auth + permessi)
- docker-compose.yml: PostgreSQL 16, Redis 7, MinIO, Nginx - backend FastAPI: struttura monorepo, config pydantic-settings - modelli SQLAlchemy: tutti i modelli (tenants, users, mailboxes, messages, archival, permissions, labels, audit_log) - migrazione Alembic 0001: schema completo in pure SQL - auth API: login JWT, refresh token rotation, logout, 2FA TOTP (setup/verify/disable) - CRUD utenti: lista, crea, modifica, reset password, soft delete - permessi granulari (Fase 1-A): mailbox_permissions, assegna/revoca/lista - CRUD tenant: gestione super-admin - sicurezza: AES-256-GCM cifratura credenziali IMAP/SMTP, bcrypt password - RLS PostgreSQL: isolamento multi-tenant per request - seed sviluppo: tenant demo + admin + operator - test unit: security (bcrypt, JWT, AES), auth_service - test integration: auth endpoints, users endpoints - CI GitHub Actions: lint (ruff), test (pytest), build Docker, security scan - infra: nginx.conf, redis.conf - Makefile con comandi make dev/test/migrate/seed Definition of Done: ✅ Login, refresh token e TOTP funzionanti ✅ make dev porta in piedi tutto lo stack locale ✅ CI configurata
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# Unit tests
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
Test unitari per AuthService (mock del DB).
|
||||
"""
|
||||
|
||||
import os
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
os.environ.setdefault("ENCRYPTION_KEY", "a" * 64)
|
||||
os.environ.setdefault("SECRET_KEY", "test-secret-key-only")
|
||||
os.environ.setdefault("DATABASE_URL", "postgresql+asyncpg://test:test@localhost:5432/test")
|
||||
os.environ.setdefault("DATABASE_URL_SYNC", "postgresql://test:test@localhost:5432/test")
|
||||
|
||||
from app.core.exceptions import (
|
||||
AccountDisabledError,
|
||||
AccountLockedError,
|
||||
InvalidCredentialsError,
|
||||
TOTPRequiredError,
|
||||
)
|
||||
from app.core.security import hash_password
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
def make_user(**kwargs) -> User:
|
||||
"""Factory per creare un utente mock."""
|
||||
user = MagicMock(spec=User)
|
||||
user.id = kwargs.get("id", uuid.uuid4())
|
||||
user.tenant_id = kwargs.get("tenant_id", uuid.uuid4())
|
||||
user.email = kwargs.get("email", "test@example.com")
|
||||
user.password_hash = kwargs.get("password_hash", hash_password("Password1!"))
|
||||
user.role = kwargs.get("role", "operator")
|
||||
user.is_active = kwargs.get("is_active", True)
|
||||
user.totp_enabled = kwargs.get("totp_enabled", False)
|
||||
user.totp_secret = kwargs.get("totp_secret", None)
|
||||
user.failed_login_count = kwargs.get("failed_login_count", 0)
|
||||
user.locked_until = kwargs.get("locked_until", None)
|
||||
return user
|
||||
|
||||
|
||||
class TestAuthServiceLogin:
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
db = AsyncMock()
|
||||
db.add = MagicMock()
|
||||
db.execute = AsyncMock()
|
||||
db.flush = AsyncMock()
|
||||
return db
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_with_correct_credentials(self, mock_db):
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
user = make_user(password_hash=hash_password("Password1!"))
|
||||
|
||||
# Mock query utente
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one_or_none.return_value = user
|
||||
mock_db.execute.return_value = mock_result
|
||||
|
||||
service = AuthService(mock_db)
|
||||
|
||||
with patch.object(service, "_handle_failed_login", new_callable=AsyncMock):
|
||||
with patch.object(service, "_reset_failed_login", new_callable=AsyncMock):
|
||||
with patch.object(service, "_log_audit", new_callable=AsyncMock):
|
||||
access, refresh = await service.login(
|
||||
email="test@example.com",
|
||||
password="Password1!",
|
||||
totp_code=None,
|
||||
)
|
||||
|
||||
assert access is not None
|
||||
assert refresh is not None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_user_not_found_raises(self, mock_db):
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one_or_none.return_value = None
|
||||
mock_db.execute.return_value = mock_result
|
||||
|
||||
service = AuthService(mock_db)
|
||||
with patch.object(service, "_log_audit", new_callable=AsyncMock):
|
||||
with pytest.raises(InvalidCredentialsError):
|
||||
await service.login("notfound@example.com", "Password1!", None)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_inactive_user_raises(self, mock_db):
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
user = make_user(is_active=False)
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one_or_none.return_value = user
|
||||
mock_db.execute.return_value = mock_result
|
||||
|
||||
service = AuthService(mock_db)
|
||||
with pytest.raises(AccountDisabledError):
|
||||
await service.login("test@example.com", "Password1!", None)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_locked_account_raises(self, mock_db):
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
user = make_user(
|
||||
locked_until=datetime.now(UTC) + timedelta(minutes=10)
|
||||
)
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one_or_none.return_value = user
|
||||
mock_db.execute.return_value = mock_result
|
||||
|
||||
service = AuthService(mock_db)
|
||||
with pytest.raises(AccountLockedError):
|
||||
await service.login("test@example.com", "Password1!", None)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_wrong_password_raises(self, mock_db):
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
user = make_user(password_hash=hash_password("CorrectPassword1!"))
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one_or_none.return_value = user
|
||||
mock_db.execute.return_value = mock_result
|
||||
|
||||
service = AuthService(mock_db)
|
||||
with patch.object(service, "_handle_failed_login", new_callable=AsyncMock):
|
||||
with patch.object(service, "_log_audit", new_callable=AsyncMock):
|
||||
with pytest.raises(InvalidCredentialsError):
|
||||
await service.login("test@example.com", "WrongPassword1!", None)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_login_totp_required_when_enabled(self, mock_db):
|
||||
from app.services.auth_service import AuthService
|
||||
|
||||
user = make_user(
|
||||
password_hash=hash_password("Password1!"),
|
||||
totp_enabled=True,
|
||||
)
|
||||
mock_result = MagicMock()
|
||||
mock_result.scalar_one_or_none.return_value = user
|
||||
mock_db.execute.return_value = mock_result
|
||||
|
||||
service = AuthService(mock_db)
|
||||
with patch.object(service, "_reset_failed_login", new_callable=AsyncMock):
|
||||
with patch.object(service, "_log_audit", new_callable=AsyncMock):
|
||||
with pytest.raises(TOTPRequiredError):
|
||||
await service.login("test@example.com", "Password1!", totp_code=None)
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
Test unitari per app.core.security.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pytest
|
||||
|
||||
# Override variabili d'ambiente per i test (prima di importare app)
|
||||
os.environ["ENCRYPTION_KEY"] = "a" * 64
|
||||
os.environ["SECRET_KEY"] = "test-secret-key-for-unit-tests-only"
|
||||
os.environ["DATABASE_URL"] = "postgresql+asyncpg://test:test@localhost:5432/test"
|
||||
os.environ["DATABASE_URL_SYNC"] = "postgresql://test:test@localhost:5432/test"
|
||||
|
||||
from app.core.security import (
|
||||
hash_password,
|
||||
verify_password,
|
||||
create_access_token,
|
||||
create_refresh_token,
|
||||
decode_token,
|
||||
encrypt_credential,
|
||||
decrypt_credential,
|
||||
hash_token,
|
||||
)
|
||||
|
||||
|
||||
class TestPasswordHashing:
|
||||
def test_hash_password_returns_bcrypt_hash(self):
|
||||
hashed = hash_password("MySecurePassword1!")
|
||||
assert hashed.startswith("$2b$")
|
||||
assert len(hashed) > 20
|
||||
|
||||
def test_verify_correct_password(self):
|
||||
password = "MySecurePassword1!"
|
||||
hashed = hash_password(password)
|
||||
assert verify_password(password, hashed) is True
|
||||
|
||||
def test_verify_wrong_password(self):
|
||||
hashed = hash_password("CorrectPassword1!")
|
||||
assert verify_password("WrongPassword1!", hashed) is False
|
||||
|
||||
def test_hash_is_different_each_time(self):
|
||||
"""Bcrypt usa salt casuale: due hash dello stesso secret sono diversi."""
|
||||
p = "SamePassword1!"
|
||||
h1 = hash_password(p)
|
||||
h2 = hash_password(p)
|
||||
assert h1 != h2
|
||||
# Ma entrambi verificano correttamente
|
||||
assert verify_password(p, h1)
|
||||
assert verify_password(p, h2)
|
||||
|
||||
|
||||
class TestJWT:
|
||||
def test_create_and_decode_access_token(self):
|
||||
import uuid
|
||||
user_id = uuid.uuid4()
|
||||
tenant_id = uuid.uuid4()
|
||||
token = create_access_token(
|
||||
subject=user_id,
|
||||
tenant_id=tenant_id,
|
||||
role="admin",
|
||||
)
|
||||
payload = decode_token(token)
|
||||
assert payload["sub"] == str(user_id)
|
||||
assert payload["tid"] == str(tenant_id)
|
||||
assert payload["role"] == "admin"
|
||||
assert payload["type"] == "access"
|
||||
|
||||
def test_create_and_decode_refresh_token(self):
|
||||
import uuid
|
||||
user_id = uuid.uuid4()
|
||||
tenant_id = uuid.uuid4()
|
||||
token = create_refresh_token(subject=user_id, tenant_id=tenant_id)
|
||||
payload = decode_token(token)
|
||||
assert payload["sub"] == str(user_id)
|
||||
assert payload["type"] == "refresh"
|
||||
|
||||
def test_expired_token_raises(self):
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from jose import jwt
|
||||
from app.config import get_settings
|
||||
from jose import JWTError
|
||||
|
||||
settings = get_settings()
|
||||
payload = {
|
||||
"sub": "user-id",
|
||||
"tid": "tenant-id",
|
||||
"type": "access",
|
||||
"exp": datetime.now(UTC) - timedelta(seconds=1), # già scaduto
|
||||
}
|
||||
token = jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
||||
with pytest.raises(JWTError):
|
||||
decode_token(token)
|
||||
|
||||
def test_invalid_signature_raises(self):
|
||||
from jose import JWTError
|
||||
with pytest.raises(JWTError):
|
||||
decode_token("this.is.not.a.valid.token")
|
||||
|
||||
|
||||
class TestAESEncryption:
|
||||
def test_encrypt_decrypt_roundtrip(self):
|
||||
secret = "imap_password_super_secret_123!"
|
||||
encrypted = encrypt_credential(secret)
|
||||
decrypted = decrypt_credential(encrypted)
|
||||
assert decrypted == secret
|
||||
|
||||
def test_encrypt_produces_different_output_each_time(self):
|
||||
"""Nonce casuale garantisce che due cifrature dello stesso plaintext siano diverse."""
|
||||
secret = "same_secret"
|
||||
enc1 = encrypt_credential(secret)
|
||||
enc2 = encrypt_credential(secret)
|
||||
assert enc1 != enc2
|
||||
# Ma entrambi decifrano correttamente
|
||||
assert decrypt_credential(enc1) == secret
|
||||
assert decrypt_credential(enc2) == secret
|
||||
|
||||
def test_decrypt_with_wrong_data_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
decrypt_credential("dGhpcyBpcyBub3QgdmFsaWQgYWVzIGRhdGE=")
|
||||
|
||||
def test_encrypt_empty_string(self):
|
||||
encrypted = encrypt_credential("")
|
||||
decrypted = decrypt_credential(encrypted)
|
||||
assert decrypted == ""
|
||||
|
||||
def test_encrypt_unicode_string(self):
|
||||
secret = "pàssword_con_àccenti_è_ù!"
|
||||
encrypted = encrypt_credential(secret)
|
||||
decrypted = decrypt_credential(encrypted)
|
||||
assert decrypted == secret
|
||||
|
||||
|
||||
class TestHashToken:
|
||||
def test_hash_is_deterministic(self):
|
||||
token = "my_refresh_token"
|
||||
assert hash_token(token) == hash_token(token)
|
||||
|
||||
def test_different_tokens_different_hashes(self):
|
||||
assert hash_token("token1") != hash_token("token2")
|
||||
|
||||
def test_hash_is_64_chars(self):
|
||||
"""SHA-256 produce 32 bytes = 64 caratteri hex."""
|
||||
assert len(hash_token("any_token")) == 64
|
||||
Reference in New Issue
Block a user