T01: core infrastructure + auth + multi-tenant + RLS

- 10 models: tenants, users, user_tenants, roles, sessions, audit_log, deletion_log, notifications, password_reset_tokens, api_tokens
- Session-based auth (Redis + PostgreSQL audit trail)
- Multi-tenant with ORM-level filtering + PostgreSQL RLS (set_config)
- RBAC with roles/permissions + field-level permissions
- CSRF protection via Origin header validation
- Auth rate limiting (Redis counters with TTL)
- CORS with explicit origins (no wildcard)
- Health endpoint (no auth required)
- Notification service + audit log middleware
- 29 tests, 26 ACs, all passing
- Coverage: 62% (infrastructure modules pending coverage in later tasks)
This commit is contained in:
leocrm-bot
2026-06-29 00:10:10 +02:00
parent 3cc0b2e1b4
commit 7a7daf8100
137 changed files with 3866 additions and 10195 deletions
+162 -215
View File
@@ -1,232 +1,179 @@
"""Auth tests: covers all 9 FR-1 acceptance criteria."""
"""Auth tests — ACs 1-9: login, logout, me, switch-tenant, password reset, CSRF."""
from __future__ import annotations
import time
import pytest
from httpx import AsyncClient
from jose import jwt
from app.core.config import get_settings
settings = get_settings()
from tests.conftest import ORIGIN_HEADER, seed_tenant_and_users, login_client
# === FR-1.1 / FR-1.2 / Akzeptanzkriterium 1: register success ===
@pytest.mark.asyncio
class TestAuthLogin:
"""ACs 1-3: Login valid, invalid, me without session."""
async def test_register_success(client: AsyncClient) -> None:
"""AC #1: POST /api/v1/auth/register mit gültigem Payload → 201 + User-Objekt + JWT."""
payload = {
"email": "alice@example.com",
"password": "SecurePass123!",
"name": "Alice",
}
resp = await client.post("/api/v1/auth/register", json=payload)
assert resp.status_code == 201, resp.text
data = resp.json()
assert "user" in data
assert "access_token" in data
assert data["token_type"] == "bearer"
assert data["expires_in"] > 0
# User object has the expected fields (no password_hash leaked)
user = data["user"]
assert user["email"] == "alice@example.com"
assert user["name"] == "Alice"
assert "password_hash" not in user
assert "id" in user
assert "org_id" in user
# === FR-1.1 / Akzeptanzkriterium 2: register duplicate email ===
async def test_register_duplicate_email(client: AsyncClient, registered_user: dict) -> None:
"""AC #2: POST /api/v1/auth/register mit existierender Email → 409."""
# registered_user already exists; trying again with same email (and 2nd user
# would also be blocked by bootstrap). 409 is correct because of the email conflict.
# But bootstrap is also blocked → 403 is also acceptable. We accept either.
payload = {
"email": registered_user["email"],
"password": "AnotherPass123!",
"name": "Dup User",
}
resp = await client.post("/api/v1/auth/register", json=payload)
assert resp.status_code in (403, 409), (
f"Expected 403 (bootstrap) or 409 (email), got {resp.status_code}: {resp.text}"
)
async def test_register_bootstrap_blocked_after_first(
client: AsyncClient, registered_user: dict
) -> None:
"""AC: Zweiter POST /api/v1/auth/register nach erfolgreichem ersten → 403."""
payload = {
"email": "other@example.com",
"password": "AnotherPass123!",
"name": "Other User",
}
resp = await client.post("/api/v1/auth/register", json=payload)
assert resp.status_code == 403, (
f"Bootstrap should be blocked after first user, got {resp.status_code}: {resp.text}"
)
# === FR-1.2 / Akzeptanzkriterium 3: register weak password ===
async def test_register_weak_password(client: AsyncClient) -> None:
"""AC #3: Schwaches Passwort (< 8 Zeichen) → 422."""
payload = {
"email": "weak@example.com",
"password": "short", # < 8 chars
"name": "Weak",
}
resp = await client.post("/api/v1/auth/register", json=payload)
assert resp.status_code == 422, resp.text
# === FR-1.2 / Akzeptanzkriterium 4: login success ===
async def test_login_success(client: AsyncClient, registered_user: dict) -> None:
"""AC #4: POST /api/v1/auth/login mit korrekten Credentials → 200 + JWT."""
resp = await client.post(
"/api/v1/auth/login",
data={
"username": registered_user["email"],
"password": registered_user["password"],
},
)
assert resp.status_code == 200, resp.text
data = resp.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
assert data["expires_in"] > 0
# === FR-1.2 / Akzeptanzkriterium 5: login wrong password ===
async def test_login_wrong_password(client: AsyncClient, registered_user: dict) -> None:
"""AC #5: POST /api/v1/auth/login mit falschem Passwort → 401."""
resp = await client.post(
"/api/v1/auth/login",
data={
"username": registered_user["email"],
"password": "WrongPassword123!",
},
)
assert resp.status_code == 401, resp.text
# === FR-1.2 / Akzeptanzkriterium 6: login nonexistent user ===
async def test_login_nonexistent_user(client: AsyncClient) -> None:
"""AC #6: POST /api/v1/auth/login mit nicht existierendem User → 401."""
resp = await client.post(
"/api/v1/auth/login",
data={"username": "nobody@example.com", "password": "AnyPass123!"},
)
assert resp.status_code == 401, resp.text
# === FR-1.6 / Akzeptanzkriterium 7: get /me with valid JWT ===
async def test_get_me_with_valid_jwt(
client: AsyncClient, auth_headers: dict[str, str], registered_user: dict
) -> None:
"""AC #7: GET /api/v1/users/me mit gültigem JWT → 200 + User-Daten (ohne password_hash)."""
resp = await client.get("/api/v1/users/me", headers=auth_headers)
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["email"] == registered_user["email"]
assert data["name"] == registered_user["name"]
assert "password_hash" not in data
# === FR-1.6 / Akzeptanzkriterium 8: get /me without JWT ===
async def test_get_me_without_jwt(client: AsyncClient) -> None:
"""AC #8: GET /api/v1/users/me ohne JWT → 401."""
resp = await client.get("/api/v1/users/me")
assert resp.status_code == 401, resp.text
# === FR-1.6 / Akzeptanzkriterium 9: get /me with expired JWT ===
async def test_get_me_with_expired_jwt(client: AsyncClient) -> None:
"""AC #9: GET /api/v1/users/me mit expired JWT → 401 + Hinweis 'token_expired'."""
# Forge an expired token using the same secret/algorithm
expired_payload = {
"sub": "1",
"org_id": 1,
"role": "admin",
"exp": int(time.time()) - 3600, # 1h in the past
"iat": int(time.time()) - 7200,
}
expired_token = jwt.encode(
expired_payload, settings.AUTH_SECRET, algorithm=settings.JWT_ALGORITHM
)
resp = await client.get(
"/api/v1/users/me",
headers={"Authorization": f"Bearer {expired_token}"},
)
assert resp.status_code == 401, resp.text
# The 401 body should signal token is invalid (we use 'token_expired_or_invalid')
body = resp.json()
assert "detail" in body
assert (
"token" in body["detail"].lower()
or "expired" in body["detail"].lower()
or "credential" in body["detail"].lower()
), f"Expected token-related 401 detail, got: {body}"
# === Bonus: password is stored hashed, not plaintext ===
async def test_db_user_has_hashed_password(
client: AsyncClient, registered_user: dict, session_factory
) -> None:
"""AC: DB-User wird mit gehashtem password_hash angelegt (kein Klartext)."""
from sqlalchemy import select
from app.models.user import User
async with session_factory() as session:
result = await session.execute(select(User).where(User.email == registered_user["email"]))
user = result.scalar_one()
# bcrypt hashes start with $2b$ (or $2a$ for passlib), never plain text
assert user.password_hash.startswith("$"), (
f"Password hash should be a bcrypt string, got: {user.password_hash!r}"
async def test_login_valid_returns_200_and_cookie(self, client: AsyncClient, db_session):
"""AC 1: POST /api/v1/auth/login valid -> 200 + Set-Cookie leocrm_session."""
await seed_tenant_and_users(db_session)
resp = await client.post(
"/api/v1/auth/login",
json={"email": "admin@tenanta.com", "password": "TestPass123!"},
headers=ORIGIN_HEADER,
)
assert user.password_hash != registered_user["password"]
assert len(user.password_hash) > 50, (
f"Bcrypt hash should be ~60 chars long, got {len(user.password_hash)}"
assert resp.status_code == 200
assert "leocrm_session" in resp.headers.get("set-cookie", "").lower() or \
"leocrm_session" in str(resp.cookies)
data = resp.json()
assert data["email"] == "admin@tenanta.com"
assert data["role"] == "admin"
async def test_login_invalid_returns_401(self, client: AsyncClient, db_session):
"""AC 2: POST /api/v1/auth/login invalid -> 401."""
await seed_tenant_and_users(db_session)
resp = await client.post(
"/api/v1/auth/login",
json={"email": "admin@tenanta.com", "password": "WrongPassword!"},
headers=ORIGIN_HEADER,
)
assert resp.status_code == 401
async def test_me_without_session_returns_401(self, client: AsyncClient):
"""AC 3: GET /api/v1/auth/me without session -> 401."""
resp = await client.get("/api/v1/auth/me")
assert resp.status_code == 401
# === Bonus: no default admin bootstrap on startup ===
@pytest.mark.asyncio
class TestAuthMe:
"""AC 4: me with valid session."""
async def test_me_with_valid_session_returns_200(self, client: AsyncClient, db_session):
"""AC 4: GET /api/v1/auth/me with valid session -> 200 + user+tenant JSON."""
await seed_tenant_and_users(db_session)
await login_client(client, "admin@tenanta.com")
resp = await client.get("/api/v1/auth/me")
assert resp.status_code == 200
data = resp.json()
assert data["email"] == "admin@tenanta.com"
assert data["role"] == "admin"
assert "tenant_id" in data
assert "tenant_name" in data
async def test_no_default_admin_on_startup(client: AsyncClient, session_factory) -> None:
"""AC: KEIN admin/admin Bootstrap-User beim App-Start (Frisch-DB = leer)."""
from sqlalchemy import func, select
@pytest.mark.asyncio
class TestAuthLogout:
"""AC 5: logout."""
from app.models.user import User
async def test_logout_returns_200_and_invalidates_session(self, client: AsyncClient, db_session):
"""AC 5: POST /api/v1/auth/logout -> 200, session invalidated."""
await seed_tenant_and_users(db_session)
await login_client(client, "admin@tenanta.com")
# Verify we're logged in
resp = await client.get("/api/v1/auth/me")
assert resp.status_code == 200
# Logout
resp = await client.post("/api/v1/auth/logout", headers=ORIGIN_HEADER)
assert resp.status_code == 200
# Verify session is invalidated
resp = await client.get("/api/v1/auth/me")
assert resp.status_code == 401
# Fresh DB → no users
async with session_factory() as session:
result = await session.execute(select(func.count()).select_from(User))
count = result.scalar_one()
assert count == 0, f"Fresh DB should have 0 users, found {count}"
# Also check: no user with role=admin and well-known email
result = await session.execute(select(User).where(User.role == "admin"))
admins = result.scalars().all()
assert len(admins) == 0, f"Fresh DB should have no admin users, found {len(admins)}"
@pytest.mark.asyncio
class TestPasswordReset:
"""ACs 6-8: password reset request, confirm valid, confirm expired."""
async def test_password_reset_request_always_200(self, client: AsyncClient, db_session):
"""AC 6: POST /api/v1/auth/password-reset/request -> always 200 (no user enumeration)."""
await seed_tenant_and_users(db_session)
# Existing email
resp = await client.post(
"/api/v1/auth/password-reset/request",
json={"email": "admin@tenanta.com"},
headers=ORIGIN_HEADER,
)
assert resp.status_code == 200
# Non-existing email — still 200
resp = await client.post(
"/api/v1/auth/password-reset/request",
json={"email": "nonexistent@example.com"},
headers=ORIGIN_HEADER,
)
assert resp.status_code == 200
async def test_password_reset_confirm_valid_token(self, client: AsyncClient, db_session):
"""AC 7: POST /api/v1/auth/password-reset/confirm valid token -> 200."""
from app.services.auth_service import auth_service
await seed_tenant_and_users(db_session)
raw_token = await auth_service.get_password_reset_token_raw(db_session, "admin@tenanta.com")
await db_session.commit()
assert raw_token is not None
resp = await client.post(
"/api/v1/auth/password-reset/confirm",
json={"token": raw_token, "new_password": "NewPass456!"},
headers=ORIGIN_HEADER,
)
assert resp.status_code == 200
async def test_password_reset_confirm_expired_token(self, client: AsyncClient, db_session):
"""AC 8: POST /api/v1/auth/password-reset/confirm expired token -> 400."""
from app.services.auth_service import auth_service
await seed_tenant_and_users(db_session)
raw_token = await auth_service.create_expired_reset_token(db_session, "admin@tenanta.com")
await db_session.commit()
assert raw_token is not None
resp = await client.post(
"/api/v1/auth/password-reset/confirm",
json={"token": raw_token, "new_password": "NewPass456!"},
headers=ORIGIN_HEADER,
)
assert resp.status_code == 400
@pytest.mark.asyncio
class TestSwitchTenant:
"""AC 9: switch-tenant."""
async def test_switch_tenant_returns_200(self, client: AsyncClient, db_session):
"""AC 9: POST /api/v1/auth/switch-tenant -> 200, session tenant_id updated."""
await seed_tenant_and_users(db_session)
await login_client(client, "admin@tenanta.com")
# Get initial tenant
resp = await client.get("/api/v1/auth/me")
assert resp.status_code == 200
initial_tenant = resp.json()["tenant_id"]
# Get tenant B ID
from app.models.tenant import Tenant
from sqlalchemy import select
q = select(Tenant).where(Tenant.slug == "tenant-b")
result = await db_session.execute(q)
tenant_b = result.scalar_one()
# Switch to tenant B
resp = await client.post(
"/api/v1/auth/switch-tenant",
json={"tenant_id": str(tenant_b.id)},
headers=ORIGIN_HEADER,
)
assert resp.status_code == 200
assert resp.json()["tenant_id"] == str(tenant_b.id)
assert resp.json()["tenant_id"] != initial_tenant
@pytest.mark.asyncio
class TestCSRF:
"""AC 23: CSRF — POST without Origin header -> 403."""
async def test_post_without_origin_returns_403(self, client: AsyncClient, db_session):
"""AC 23: POST without Origin header -> 403."""
await seed_tenant_and_users(db_session)
resp = await client.post(
"/api/v1/auth/login",
json={"email": "admin@tenanta.com", "password": "TestPass123!"},
# No Origin header
)
assert resp.status_code == 403