a17772ade5
Vorher: require_active_plugin hing nicht an einer Auth-Dependency — FastAPI konnte die Plugin-Pruefung VOR der Authentisierung ausfuehren. Der Mandant wurde aus dem DB-Kontext gelesen (current_setting), der zu diesem Zeitpunkt oft fehlt → stiller Return = Plugin aktiv. Der Code trug sogar ein TODO: Fix in production. Astra-Repro: Endpunkt antwortete HTTP 200 ohne Mandantenkontext. Fix: - _check haengt an get_current_user_or_bearer (Cookie- UND Bearer-Auth) → FastAPI aufloesungsbedingt immer authentifiziert vor dem Gate - Mandant kommt aus dem authentifizierten User-Kontext, nie aus current_setting - Fehlender Mandanten-Kontext → 403 plugin_gate_no_tenant (fail-closed, war: stiller Durchlass) - Public-Routen (is_public) umgehen das Gate weiterhin korrekt Nebenwirkung positiv: Bearer-Clients (External-API, MCP) laufen nicht mehr gegen den Cookie-Zwang des Gates. Verifikation: Syntax OK, ruff clean, test_s1_security_guards + test_auth 21/21. Der Gate-Order-Beweis ist ein Integrationstest-Verhalten (HTTP) — Plugin-Inactive-Faelle werden bereits durch die permission_system_live-Suite abgedeckt.
537 lines
20 KiB
Python
537 lines
20 KiB
Python
"""FastAPI dependencies: auth, db, tenant context, RBAC."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import uuid
|
|
from typing import Any
|
|
|
|
import redis.asyncio as aioredis
|
|
from fastapi import Depends, Header, HTTPException, Request, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.config import get_settings
|
|
from app.core.auth import get_redis, get_session_data, refresh_session_ttl
|
|
from app.core.db import get_db, set_tenant_context, set_user_context
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Legacy fallback list — used by require_write() only when the permission
|
|
# registry is not initialized. The live source of truth is generated from
|
|
# the registry (see _get_write_permissions, ARCH-022).
|
|
_WRITE_PERMISSIONS = [
|
|
"users:write",
|
|
"roles:write",
|
|
"audit:write",
|
|
"attachments:write",
|
|
"workflows:write",
|
|
"sequences:write",
|
|
"addresses:write",
|
|
"taxes:write",
|
|
"currencies:write",
|
|
"notifications:write",
|
|
"import_export:write",
|
|
"user_preferences:write",
|
|
]
|
|
|
|
|
|
def _get_write_permissions() -> list[str]:
|
|
"""Return all known ``module:write`` permission keys (ARCH-022).
|
|
|
|
Generated from the permission registry so plugin write permissions are
|
|
picked up automatically without touching this file. Falls back to the
|
|
static legacy list when the registry is unavailable/uninitialized.
|
|
"""
|
|
try:
|
|
from app.core.permission_registry import get_permission_registry
|
|
|
|
registry = get_permission_registry()
|
|
if getattr(registry, "_initialized", False):
|
|
perms = [
|
|
entry["key"]
|
|
for entry in registry.get_all()
|
|
if entry["key"].endswith(":write")
|
|
]
|
|
if perms:
|
|
return sorted(perms)
|
|
except Exception:
|
|
pass
|
|
return list(_WRITE_PERMISSIONS)
|
|
|
|
|
|
async def get_redis_dep() -> aioredis.Redis:
|
|
"""FastAPI dependency for Redis client."""
|
|
return get_redis()
|
|
|
|
|
|
async def get_current_user(
|
|
request: Request,
|
|
db: AsyncSession = Depends(get_db),
|
|
redis: aioredis.Redis = Depends(get_redis_dep),
|
|
) -> dict[str, Any]:
|
|
"""Get the current authenticated user from session cookie.
|
|
|
|
Returns session data dict with user_id, tenant_id, email, name, role,
|
|
and resolved permissions from Redis cache.
|
|
"""
|
|
settings = get_settings()
|
|
|
|
session_id = request.cookies.get(settings.session_cookie_name)
|
|
if not session_id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={"detail": "Not authenticated", "code": "not_authenticated"},
|
|
)
|
|
|
|
session_data = await get_session_data(redis, session_id)
|
|
if session_data is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={"detail": "Session expired or invalid", "code": "session_invalid"},
|
|
)
|
|
|
|
# Sliding session: extend TTL on each authenticated request
|
|
# Best-effort during Redis outage — session still valid from DB fallback
|
|
try:
|
|
await refresh_session_ttl(redis, session_id)
|
|
except Exception:
|
|
logger.debug("refresh_session_ttl failed (Redis may be down) — continuing")
|
|
|
|
if not session_data.get("is_active", True):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={"detail": "User account deactivated", "code": "user_inactive"},
|
|
)
|
|
|
|
# Set RLS tenant context
|
|
tenant_id = uuid.UUID(session_data["tenant_id"])
|
|
await set_tenant_context(db, tenant_id)
|
|
|
|
# Set RLS user context for row-level security
|
|
user_id = uuid.UUID(session_data["user_id"])
|
|
from app.models.group import UserGroup
|
|
groups_q = await db.execute(
|
|
select(UserGroup.group_id)
|
|
.where(UserGroup.user_id == user_id)
|
|
.where(UserGroup.tenant_id == tenant_id)
|
|
)
|
|
group_ids = [row[0] for row in groups_q]
|
|
is_admin = session_data.get("is_system_admin", False)
|
|
await set_user_context(db, user_id, group_ids, is_admin)
|
|
|
|
# Check membership status and load role_id (P1.7: suspended membership should not be usable)
|
|
from app.models.user import UserTenant
|
|
membership_q = await db.execute(
|
|
select(UserTenant.status, UserTenant.role_id)
|
|
.where(UserTenant.user_id == user_id)
|
|
.where(UserTenant.tenant_id == tenant_id)
|
|
)
|
|
membership_row = membership_q.first()
|
|
membership_status = membership_row[0] if membership_row else None
|
|
role_id = membership_row[1] if membership_row else None
|
|
# F03 (Astra): a MISSING tenant membership must be rejected, not waved
|
|
# through. Previously `is not None` let membership-less sessions access
|
|
# the tenant's data via the RLS context set above.
|
|
if membership_status is None or membership_status != "active":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": (
|
|
f"Mitgliedschaft ist {membership_status}, Zugriff verweigert"
|
|
if membership_status
|
|
else "Keine aktive Mandanten-Mitgliedschaft, Zugriff verweigert"
|
|
),
|
|
"code": "membership_suspended",
|
|
},
|
|
)
|
|
|
|
# Cache user principals for this request — avoids N+1 queries in visibility.py
|
|
from app.core.principals import UserPrincipals, set_principals
|
|
set_principals(UserPrincipals(
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
group_ids=group_ids,
|
|
role_id=role_id,
|
|
))
|
|
|
|
# Load resolved permissions from cache (or DB on miss)
|
|
from app.core.permissions import get_cached_permissions
|
|
|
|
user_id = uuid.UUID(session_data["user_id"])
|
|
resolved = await get_cached_permissions(db, redis, user_id, tenant_id)
|
|
if not resolved:
|
|
resolved = {"permissions": [], "denied": [], "field_permissions": {}, "is_system_admin": False}
|
|
session_data["permissions"] = resolved.get("permissions", [])
|
|
session_data["denied_permissions"] = resolved.get("denied", [])
|
|
session_data["field_permissions"] = resolved.get("field_permissions", {})
|
|
session_data["is_system_admin"] = resolved.get("is_system_admin", False)
|
|
|
|
return session_data
|
|
|
|
|
|
async def get_current_user_bearer(
|
|
request: Request,
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> dict[str, Any]:
|
|
"""Get the current user from a Bearer API token.
|
|
|
|
Alternative to session-based auth for programmatic access (MCP, API clients).
|
|
Returns the same dict shape as get_current_user.
|
|
"""
|
|
auth_header = request.headers.get("Authorization", "")
|
|
if not auth_header.startswith("Bearer "):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={"detail": "Bearer token required", "code": "not_authenticated"},
|
|
)
|
|
|
|
token = auth_header[7:] # Strip "Bearer "
|
|
from app.core.api_token import verify_api_token
|
|
|
|
user_data = await verify_api_token(db, token)
|
|
if user_data is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail={"detail": "Invalid or expired token", "code": "token_invalid"},
|
|
)
|
|
|
|
# Set RLS tenant context
|
|
tenant_id = uuid.UUID(user_data["tenant_id"])
|
|
await set_tenant_context(db, tenant_id)
|
|
|
|
# Set RLS user context
|
|
user_id = uuid.UUID(user_data["user_id"])
|
|
from app.models.group import UserGroup
|
|
groups_q = await db.execute(
|
|
select(UserGroup.group_id)
|
|
.where(UserGroup.user_id == user_id)
|
|
.where(UserGroup.tenant_id == tenant_id)
|
|
)
|
|
group_ids = [row[0] for row in groups_q]
|
|
is_admin = user_data.get("is_system_admin", False)
|
|
await set_user_context(db, user_id, group_ids, is_admin)
|
|
|
|
# Load role_id and cache user principals for this request
|
|
from app.models.user import UserTenant
|
|
membership_q = await db.execute(
|
|
select(UserTenant.role_id)
|
|
.where(UserTenant.user_id == user_id)
|
|
.where(UserTenant.tenant_id == tenant_id)
|
|
)
|
|
role_id = membership_q.scalar_one_or_none()
|
|
|
|
from app.core.principals import UserPrincipals, set_principals
|
|
set_principals(UserPrincipals(
|
|
user_id=user_id,
|
|
tenant_id=tenant_id,
|
|
group_ids=group_ids,
|
|
role_id=role_id,
|
|
))
|
|
|
|
# Load resolved permissions
|
|
from app.core.permissions import get_cached_permissions
|
|
redis = get_redis()
|
|
resolved = await get_cached_permissions(db, redis, user_id, tenant_id)
|
|
user_data["permissions"] = resolved.get("permissions", [])
|
|
user_data["denied_permissions"] = resolved.get("denied", [])
|
|
user_data["field_permissions"] = resolved.get("field_permissions", {})
|
|
user_data["is_system_admin"] = resolved.get("is_system_admin", False)
|
|
|
|
return user_data
|
|
|
|
|
|
async def get_current_user_or_bearer(
|
|
request: Request,
|
|
db: AsyncSession = Depends(get_db),
|
|
redis: aioredis.Redis = Depends(get_redis_dep),
|
|
) -> dict[str, Any]:
|
|
"""Get current user from session cookie OR Bearer token.
|
|
|
|
Tries session auth first, falls back to Bearer token.
|
|
Used by MCP routes that accept both auth methods.
|
|
"""
|
|
auth_header = request.headers.get("Authorization", "")
|
|
if auth_header.startswith("Bearer "):
|
|
return await get_current_user_bearer(request, db)
|
|
return await get_current_user(request, db, redis)
|
|
|
|
|
|
async def require_admin(
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
) -> dict[str, Any]:
|
|
"""Require admin access via is_system_admin or *:* permission.
|
|
|
|
⚠️ Legacy Role Bypass entfernt — alle Admins müssen echte role_id haben
|
|
Legacy role string 'admin' no longer grants access. Users must have
|
|
is_system_admin=True or *:* permission through the RBAC system.
|
|
"""
|
|
if current_user.get("is_system_admin"):
|
|
return current_user
|
|
|
|
# New permission system check
|
|
from app.core.permissions import check_permission
|
|
|
|
if check_permission(current_user, "*:*"):
|
|
return current_user
|
|
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={"detail": "Admin access required", "code": "forbidden"},
|
|
)
|
|
|
|
|
|
async def require_write(
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
) -> dict[str, Any]:
|
|
"""Require write permission via is_system_admin or specific module:write permissions.
|
|
|
|
⚠️ Legacy Role Bypass entfernt — alle Admins müssen echte role_id haben
|
|
Legacy role strings 'admin'/'editor' no longer grant write access. Users must
|
|
have is_system_admin=True or specific module:write permissions through RBAC.
|
|
"""
|
|
if current_user.get("is_system_admin"):
|
|
return current_user
|
|
|
|
# Check via permission system for specific write permissions
|
|
from app.core.permissions import check_permission
|
|
|
|
for perm in _get_write_permissions():
|
|
if check_permission(current_user, perm):
|
|
return current_user
|
|
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={"detail": "Write access required", "code": "forbidden"},
|
|
)
|
|
|
|
|
|
def require_permission(permission: str):
|
|
"""FastAPI dependency factory: require a specific permission.
|
|
|
|
Enforces API token scopes (Problem 2 fix): when the request is authenticated
|
|
via a Bearer API token, ``_token_scopes`` is set on the user context. The
|
|
required permission must be present in the scopes (wildcard match supported).
|
|
Session-auth requests (no ``_token_scopes``) use the normal permission check.
|
|
|
|
Usage:
|
|
@router.get("/contacts", dependencies=[Depends(require_permission("contacts:read"))])
|
|
"""
|
|
async def _check(
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
) -> dict[str, Any]:
|
|
# API token scope enforcement (Problem 2 fix)
|
|
# F10 (Astra): token scopes are an UPPER BOUND, not a replacement —
|
|
# the user's own permissions must ALSO grant the permission. A token
|
|
# can never grant more than its owner has; revoking the user's
|
|
# permission takes effect on existing tokens.
|
|
token_scopes = current_user.get("_token_scopes")
|
|
if token_scopes is not None:
|
|
from app.core.permissions import _permission_matches_any
|
|
if not _permission_matches_any(set(token_scopes), permission):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": f"Token scope '{permission}' required",
|
|
"code": "insufficient_scope",
|
|
},
|
|
)
|
|
# fall through: the normal user-permission check applies too
|
|
|
|
if current_user.get("is_system_admin"):
|
|
return current_user
|
|
from app.core.permissions import check_permission
|
|
|
|
if check_permission(current_user, permission):
|
|
return current_user
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": f"Permission '{permission}' required",
|
|
"code": "forbidden",
|
|
},
|
|
)
|
|
|
|
return _check
|
|
|
|
|
|
def require_field_access(module: str, field: str, default: str = "read"):
|
|
"""FastAPI dependency factory: require field-level access.
|
|
|
|
Usage:
|
|
@router.get("/contacts/{id}", dependencies=[Depends(require_field_access("contacts", "annual_revenue"))])
|
|
"""
|
|
async def _check(
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
) -> dict[str, Any]:
|
|
if current_user.get("is_system_admin"):
|
|
return current_user
|
|
from app.core.permissions import check_field_access
|
|
|
|
access = check_field_access(current_user, module, field, default)
|
|
if access == "hidden":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": f"Field '{field}' is hidden",
|
|
"code": "field_hidden",
|
|
},
|
|
)
|
|
return current_user
|
|
|
|
return _check
|
|
|
|
|
|
async def get_tenant_id(
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
) -> uuid.UUID:
|
|
"""Extract tenant_id from current user session."""
|
|
return uuid.UUID(current_user["tenant_id"])
|
|
|
|
|
|
async def get_current_user_id(
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
) -> uuid.UUID:
|
|
"""Extract user_id from current user session."""
|
|
return uuid.UUID(current_user["user_id"])
|
|
|
|
|
|
def require_workspace_scope(module_key: str):
|
|
"""FastAPI dependency factory (Phase N3): resolve the active workspace
|
|
scope config for a module from the X-Workspace-ID header.
|
|
|
|
Returns the scope dict (e.g. ``{"folder_ids": [...]}``) or ``None``
|
|
when no restriction applies (no header, admin, unassigned, empty config).
|
|
Callers apply it as a pure AND-restriction — never a grant.
|
|
|
|
Usage:
|
|
scope: dict | None = Depends(require_workspace_scope("contacts"))
|
|
"""
|
|
|
|
async def _resolve(
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: dict[str, Any] = Depends(get_current_user),
|
|
x_workspace_id: str | None = Header(None, alias="X-Workspace-ID"),
|
|
) -> dict[str, Any] | None:
|
|
from app.services.workspace_scope_service import resolve_workspace_scope
|
|
|
|
return await resolve_workspace_scope(db, current_user, x_workspace_id, module_key)
|
|
|
|
return _resolve
|
|
|
|
|
|
def require_active_plugin(plugin_name: str):
|
|
"""FastAPI dependency factory: require that a plugin is active.
|
|
|
|
Checks both global activation (permission registry) and per-tenant
|
|
activation (tenant_plugin_activation table).
|
|
|
|
Uses the current_user dependency to get tenant_id — does NOT guess
|
|
the tenant from a new DB session via current_setting().
|
|
|
|
Uses Redis cache for per-tenant check to avoid DB query on every request.
|
|
Cache key: plugin-activation:{tenant_id}:{plugin_name}
|
|
TTL: 60 seconds. Invalidated on activate/deactivate.
|
|
|
|
Returns 403 if the plugin is not active.
|
|
Fails closed (503) on errors.
|
|
"""
|
|
async def _check(
|
|
db: AsyncSession = Depends(get_db),
|
|
current_user: dict[str, Any] = Depends(get_current_user_or_bearer),
|
|
) -> None:
|
|
"""F05 (Astra P1): the plugin gate runs AFTER authentication.
|
|
|
|
Depending on ``get_current_user_or_bearer`` guarantees FastAPI
|
|
resolves the authenticated user context BEFORE this check — the
|
|
previous version read the tenant from the DB session before auth
|
|
had run (context missing → silent allow). Both auth paths (cookie
|
|
and Bearer) set the tenant context on this same ``db`` session.
|
|
"""
|
|
from app.core.permission_registry import get_permission_registry
|
|
try:
|
|
registry = get_permission_registry()
|
|
if not registry.is_plugin_active(plugin_name):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": f"Plugin '{plugin_name}' is not active",
|
|
"code": "plugin_inactive",
|
|
},
|
|
)
|
|
# Tenant comes from the AUTHENTICATED user context — never from
|
|
# the DB session (which may not have the context set yet).
|
|
raw_tid = current_user.get("tenant_id")
|
|
if not raw_tid:
|
|
# Fail-closed: no authenticated tenant context → reject.
|
|
# (Previously this returned silently = plugin active.)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": "Plugin gate requires an authenticated tenant context",
|
|
"code": "plugin_gate_no_tenant",
|
|
},
|
|
)
|
|
tenant_id = uuid.UUID(str(raw_tid))
|
|
|
|
# Per-tenant activation check with Redis cache
|
|
import json
|
|
|
|
from sqlalchemy import text
|
|
|
|
from app.core.redis import get_redis
|
|
|
|
redis = get_redis()
|
|
if redis is not None:
|
|
cache_key = f"plugin-activation:{tenant_id}:{plugin_name}"
|
|
cached = await redis.get(cache_key)
|
|
if cached is not None:
|
|
is_active = json.loads(cached)
|
|
if not is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": f"Plugin '{plugin_name}' is not active for this tenant",
|
|
"code": "plugin_inactive_tenant",
|
|
},
|
|
)
|
|
return # Cache hit — plugin is active for this tenant
|
|
|
|
# Cache miss — query DB using the existing db session (tenant context already set)
|
|
result = await db.execute(
|
|
text("""
|
|
SELECT is_active FROM tenant_plugin_activation
|
|
WHERE plugin_name = :name
|
|
AND tenant_id = :tid
|
|
"""),
|
|
{"name": plugin_name, "tid": tenant_id},
|
|
)
|
|
row = result.first()
|
|
if row is not None:
|
|
is_active = row[0]
|
|
if redis is not None:
|
|
await redis.setex(cache_key, 60, json.dumps(is_active))
|
|
if not is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail={
|
|
"detail": f"Plugin '{plugin_name}' is not active for this tenant",
|
|
"code": "plugin_inactive_tenant",
|
|
},
|
|
)
|
|
else:
|
|
# No entry = default active (backward compatible)
|
|
if redis is not None:
|
|
await redis.setex(cache_key, 60, json.dumps(True))
|
|
except HTTPException:
|
|
raise
|
|
except Exception as exc:
|
|
# Fail-closed: if registry check fails, deny access (P1.2 fix)
|
|
logger.error("Plugin activation check failed for '%s': %s", plugin_name, exc)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail={"detail": "Plugin activation check failed", "code": "plugin_check_error"},
|
|
) from exc
|
|
|
|
return _check
|