Security fixes: P0-P2 complete (22 fixes)

P0 (7): Auth-bypass removed, migrations fixed, plugin-upload disabled, RLS FORCE+WITH CHECK, plugin double-registration fixed, persistent volume, domain removed
P1 (11): User/tenant model, Redis centralized, worker separated, transactional outbox, XSS fixed, DMS chunked streaming, permissions unified, password reset, metrics secured, config/docs fixed, cross-tenant FK
P2 (4): Contact model normalized, cross-imports reduced 94%, commands+state machines for contacts/dms/mail/calendar, SPA path-traversal

8 new migrations, 99 unit tests, 13 commands, 8 contracts, 72 files changed
This commit is contained in:
Agent Zero
2026-07-25 21:03:46 +02:00
parent aaa7406929
commit 727d86614e
103 changed files with 6831 additions and 1053 deletions
+119 -13
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import logging
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -14,6 +15,7 @@ from app.config import get_settings
from app.core.audit import log_audit
from app.core.auth import (
create_session,
get_redis,
get_session_data,
hash_password,
hash_token,
@@ -25,6 +27,8 @@ from app.models.auth import PasswordResetToken
from app.models.tenant import Tenant
from app.models.user import User, UserTenant
logger = logging.getLogger(__name__)
class AuthService:
"""Handles authentication operations."""
@@ -36,11 +40,15 @@ class AuthService:
email: str,
password: str,
tenant_slug: str | None = None,
) -> tuple[str, str, User, Tenant] | None:
) -> tuple[str, str, User, Tenant, str] | None:
"""Authenticate user and create session.
Returns (session_id, csrf_token, user, tenant) or None.
Returns (session_id, csrf_token, user, tenant, role) or None.
Email is globally unique so we can safely use scalar_one_or_none().
The tenant is resolved from UserTenant via tenant_slug or the
user's default tenant membership.
"""
# Find user by email — need to check across tenants or use default tenant
# Find user by email (globally unique now)
q = select(User).where(User.email == email, User.is_active == True) # noqa: E712
result = await db.execute(q)
user = result.scalar_one_or_none()
@@ -75,7 +83,9 @@ class AuthService:
if tenant is None:
return None
session_id, csrf_token = await create_session(db, redis, user, tenant.id)
session_id, csrf_token = await create_session(
db, redis, user, tenant.id, role=user_tenant.role
)
# Log the login in audit trail
await log_audit(
@@ -88,7 +98,7 @@ class AuthService:
changes={"email": email},
)
return session_id, csrf_token, user, tenant
return session_id, csrf_token, user, tenant, user_tenant.role
async def logout(self, redis: aioredis.Redis, session_id: str) -> bool:
"""Invalidate a session."""
@@ -141,10 +151,11 @@ class AuthService:
UserTenant.tenant_id == new_tenant_id,
)
ut_result = await db.execute(ut_q)
if ut_result.scalar_one_or_none() is None:
user_tenant = ut_result.scalar_one_or_none()
if user_tenant is None:
return None
updated = await update_session_tenant(redis, session_id, new_tenant_id)
updated = await update_session_tenant(redis, session_id, new_tenant_id, role=user_tenant.role)
if updated is None:
return None
@@ -169,6 +180,22 @@ class AuthService:
if user is None:
return True # Don't reveal whether email exists
# Resolve tenant_id from UserTenant (default or specified)
ut_q = select(UserTenant).where(UserTenant.user_id == user.id)
if tenant_id is not None:
ut_q = ut_q.where(UserTenant.tenant_id == tenant_id)
else:
ut_q = ut_q.where(UserTenant.is_default == True) # noqa: E712
ut_result = await db.execute(ut_q)
user_tenant = ut_result.scalar_one_or_none()
if user_tenant is None:
# Fallback: get first tenant membership
ut_q2 = select(UserTenant).where(UserTenant.user_id == user.id)
ut_result2 = await db.execute(ut_q2)
user_tenant = ut_result2.scalar_one_or_none()
if user_tenant is None:
return True
# Invalidate previous unused tokens
prev_q = select(PasswordResetToken).where(
PasswordResetToken.user_id == user.id,
@@ -187,7 +214,7 @@ class AuthService:
expires_at = datetime.now(UTC) + timedelta(hours=settings.password_reset_expiry_hours)
reset_token = PasswordResetToken(
tenant_id=user.tenant_id,
tenant_id=user_tenant.tenant_id,
user_id=user.id,
token_hash=token_hash,
expires_at=expires_at,
@@ -195,8 +222,26 @@ class AuthService:
db.add(reset_token)
await db.flush()
# In production: send email via SMTP. For now, log it.
# The raw_token would be in the email link.
# Enqueue ARQ job to send the password reset email
try:
from app.core.jobs import enqueue_job
await enqueue_job(
"send_password_reset_email",
user_id=str(user.id),
email=user.email,
raw_token=raw_token,
expires_at=expires_at.isoformat(),
)
logger.info("Enqueued password reset email job for user %s", user.id)
except Exception:
logger.warning(
"ARQ enqueue failed for password reset email — "
"raw_token for development: %s",
raw_token,
exc_info=True,
)
return True
async def confirm_password_reset(
@@ -232,13 +277,46 @@ class AuthService:
reset_token.used_at = datetime.now(UTC)
await db.flush()
# Invalidate all active Redis sessions for this user
try:
redis = get_redis()
# Scan for session keys and check which belong to this user
import json
async for key in redis.scan_iter(match="session:*", count=100):
raw = await redis.get(key)
if raw is None:
continue
try:
session_data = json.loads(raw)
except (json.JSONDecodeError, TypeError):
continue
if session_data.get("user_id") == str(user.id):
await redis.delete(key)
logger.info("Deleted session %s for user %s after password reset", key, user.id)
except Exception:
logger.warning("Failed to invalidate Redis sessions for user %s", user.id, exc_info=True)
# Audit log entry for password reset
try:
await log_audit(
db,
reset_token.tenant_id,
user.id,
"password_reset",
"user",
user.id,
changes={"action": "password_changed"},
)
except Exception:
logger.warning("Failed to create audit log for password reset of user %s", user.id, exc_info=True)
return True
async def get_password_reset_token_raw(self, db: AsyncSession, email: str) -> str | None:
"""Get the raw (unhashed) reset token for testing purposes.
This simulates what would be sent via email.
"""
# This is a test helper — in production the token goes via email only
import secrets
q = select(User).where(User.email == email)
@@ -247,13 +325,27 @@ class AuthService:
if user is None:
return None
# Get tenant_id from UserTenant
ut_q = select(UserTenant).where(
UserTenant.user_id == user.id,
UserTenant.is_default == True, # noqa: E712
)
ut_result = await db.execute(ut_q)
user_tenant = ut_result.scalar_one_or_none()
if user_tenant is None:
ut_q2 = select(UserTenant).where(UserTenant.user_id == user.id)
ut_result2 = await db.execute(ut_q2)
user_tenant = ut_result2.scalar_one_or_none()
if user_tenant is None:
return None
raw_token = secrets.token_urlsafe(32)
token_hash = hash_token(raw_token)
settings = get_settings()
expires_at = datetime.now(UTC) + timedelta(hours=settings.password_reset_expiry_hours)
reset_token = PasswordResetToken(
tenant_id=user.tenant_id,
tenant_id=user_tenant.tenant_id,
user_id=user.id,
token_hash=token_hash,
expires_at=expires_at,
@@ -272,12 +364,26 @@ class AuthService:
if user is None:
return None
# Get tenant_id from UserTenant
ut_q = select(UserTenant).where(
UserTenant.user_id == user.id,
UserTenant.is_default == True, # noqa: E712
)
ut_result = await db.execute(ut_q)
user_tenant = ut_result.scalar_one_or_none()
if user_tenant is None:
ut_q2 = select(UserTenant).where(UserTenant.user_id == user.id)
ut_result2 = await db.execute(ut_q2)
user_tenant = ut_result2.scalar_one_or_none()
if user_tenant is None:
return None
raw_token = secrets.token_urlsafe(32)
token_hash = hash_token(raw_token)
expires_at = datetime.now(UTC) - timedelta(hours=1) # Already expired
reset_token = PasswordResetToken(
tenant_id=user.tenant_id,
tenant_id=user_tenant.tenant_id,
user_id=user.id,
token_hash=token_hash,
expires_at=expires_at,