Files
leocrm/app/core/visibility.py
T
Agent Zero 627360113f fix(permissions): fix 10 high-priority permission system issues
P8: Invalidate all Redis sessions when is_system_admin changes
- Added is_system_admin to UserUpdate schema and UserResponse
- Added invalidate_all_user_sessions call in users.py route
- Added is_system_admin param to user_service.update_user

P9: Remove no-op permission resolution strategies
- Only highest_wins supported, others removed as no-ops
- Updated tenant.py CheckConstraint to only allow highest_wins
- Added KI-Kommentar in permissions.py

P10: Remove legacy check_permission from auth.py
- Removed duplicate check_permission and filter_fields_by_permission
- Fixed ai_copilot_service.py to use permissions.check_permission
- Updated ai_copilot route to pass resolved permissions dict

P11: Verified — no guest_users remnants found

P12: Migrate ContactFolderPermission to EntityPermission
- contact_folder_permission_service now delegates to entity_permission_service
- contact_folder_service uses EntityPermission queries
- Removed ContactFolderPermission from models/__init__.py
- Created migration 0114 to migrate data and drop table

P13: Added RLS migration history comment in alembic/env.py

P14: Verified — services already apply visibility_filter
- saved_filters/views filter by user_id (personal data)
- workspaces are UI context only
- notifications already filter by entity access

P15: Split entity_permission_service.py (932 lines) into 4 modules
- permission_resolver.py: get_effective_access, get_visible_ids, etc.
- permission_cache.py: Redis caching functions
- permission_audit.py: Audit logging helpers
- entity_permission_service.py: CRUD operations + re-exports

P16: Centralize PERM_RANK in permissions.py
- Single source: app.core.permissions.PERM_RANK
- Updated all services to import from permissions.py

P17: Fix MIGRATION_DATABASE_URL to use crm_migration
- docker-compose.yaml defaults changed from crm_user to crm_migration
- .env.docker.example updated
- prestart.sh comment updated
2026-08-06 12:05:09 +02:00

242 lines
7.3 KiB
Python

"""Visibility filter helper — applies row-level security to SQLAlchemy queries.
This is the core function that ALL routes use to filter queries based on
the current user's permissions. It works alongside PostgreSQL RLS as a
Defense-in-Depth layer.
Usage:
from app.core.visibility import apply_visibility_filter
@router.get("/contacts")
async def list_contacts(db, current_user):
query = select(Contact).where(Contact.tenant_id == tenant_id)
query = await apply_visibility_filter(
db, query, "contact", Contact, user_id, tenant_id
)
result = await db.execute(query)
...
Architecture:
- System admin → no filter (sees everything)
- Non-admin → filter by: owner_id = user OR owner_id IS NULL OR shared via entity_permissions
- Uses EXISTS subquery for performance (better than IN)
- Works with any entity type that has owner_id column
"""
from __future__ import annotations
import logging
import uuid
from typing import Any
from sqlalchemy import and_, exists, or_, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import DeclarativeBase
from app.models.entity_permission import EntityPermission
from app.models.group import UserGroup
from app.models.user import User, UserTenant
logger = logging.getLogger(__name__)
from app.core.permissions import PERM_RANK as _PERM_RANK
def _rank(level: str) -> int:
return _PERM_RANK.get(level, 0)
async def _get_user_principals(
db: AsyncSession,
user_id: uuid.UUID,
tenant_id: uuid.UUID,
) -> tuple[list[uuid.UUID], uuid.UUID | None]:
"""Get user's group IDs and role ID for permission resolution."""
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]
role_q = await db.execute(
select(UserTenant.role_id)
.where(UserTenant.user_id == user_id)
.where(UserTenant.tenant_id == tenant_id)
)
role_id = role_q.scalar_one_or_none()
return group_ids, role_id
async def apply_visibility_filter(
db: AsyncSession,
query: Any,
entity_type: str,
model: type[DeclarativeBase],
user_id: uuid.UUID,
tenant_id: uuid.UUID,
is_system_admin: bool = False,
) -> Any:
"""Apply row-level visibility filter to a SQLAlchemy query.
This function modifies the query to only return rows that the user
is allowed to see based on:
1. System admin → no filter (sees everything)
2. Owner → rows where owner_id = user_id
3. Tenant-owned → rows where owner_id IS NULL
4. Shared → rows with entity_permissions entry for this user/group/role
Args:
db: Database session
query: SQLAlchemy select() query to filter
entity_type: Entity type string (e.g. 'contact', 'address')
model: SQLAlchemy model class (must have owner_id column)
user_id: Current user's UUID
tenant_id: Current tenant's UUID
is_system_admin: Whether user is system admin
Returns:
Modified query with visibility filter applied
"""
if is_system_admin:
return query # System admin sees everything
# Defense-in-Depth: Always filter by tenant_id first (P0.4 fix)
# This ensures cross-tenant data is never returned even if RLS is bypassed
if hasattr(model, 'tenant_id'):
query = query.where(model.tenant_id == tenant_id)
# Get user's groups and role
group_ids, role_id = await _get_user_principals(db, user_id, tenant_id)
# Build principal conditions for entity_permissions EXISTS subquery
principal_conditions = [
and_(
EntityPermission.principal_type == "user",
EntityPermission.principal_id == user_id,
),
]
if group_ids:
principal_conditions.append(
and_(
EntityPermission.principal_type == "group",
EntityPermission.principal_id.in_(group_ids),
)
)
if role_id:
principal_conditions.append(
and_(
EntityPermission.principal_type == "role",
EntityPermission.principal_id == role_id,
)
)
# Build EXISTS subquery for shared entities
# Uses EXISTS instead of IN for better PostgreSQL optimization
shared_exists = (
select(EntityPermission.id)
.where(EntityPermission.entity_type == entity_type)
.where(EntityPermission.entity_id == model.id)
.where(EntityPermission.tenant_id == tenant_id)
.where(EntityPermission.permission_level != "none")
.where(
or_(
EntityPermission.expires_at.is_(None),
EntityPermission.expires_at > text("NOW()"),
)
)
.where(or_(*principal_conditions))
.exists()
)
# Apply filter: owner OR tenant-owned OR shared
visibility_condition = or_(
model.owner_id == user_id, # Own entities
model.owner_id.is_(None), # Tenant-owned entities
shared_exists, # Shared via entity_permissions
)
return query.where(visibility_condition)
async def check_single_entity_access(
db: AsyncSession,
entity_type: str,
entity_id: uuid.UUID,
user_id: uuid.UUID,
tenant_id: uuid.UUID,
required_level: str = "read",
is_system_admin: bool = False,
) -> bool:
"""Check if user has at least the required access level on a single entity.
Used for GET/PUT/DELETE on individual entities.
"""
if is_system_admin:
return True
from app.services.entity_permission_service import get_effective_access
access = await get_effective_access(
db, tenant_id, user_id, entity_type, entity_id
)
return _rank(access) >= _rank(required_level)
async def filter_response_fields(
data: dict[str, Any],
field_permissions: dict[str, dict[str, str]],
module: str,
is_system_admin: bool = False,
) -> dict[str, Any]:
"""Filter response fields based on field-level permissions.
Removes fields marked as 'hidden', keeps others.
This is a convenience wrapper that can be used in any route.
"""
if is_system_admin:
return data
module_perms = field_permissions.get(module, {})
if not module_perms:
return data
return {
key: value
for key, value in data.items()
if module_perms.get(key, "read") != "hidden"
}
async def apply_visibility_filter_cached(
db: AsyncSession,
redis: Any,
query: Any,
entity_type: str,
model: type[DeclarativeBase],
user_id: uuid.UUID,
tenant_id: uuid.UUID,
is_system_admin: bool = False,
) -> Any:
"""Apply visibility filter using cached visible IDs from Redis.
This is an alternative to apply_visibility_filter() that uses
pre-computed visible IDs from Redis cache for better performance.
Use this for list queries where you need maximum performance.
"""
if is_system_admin:
return query
from app.services.entity_permission_service import get_cached_visible_ids
visible_ids, _ = await get_cached_visible_ids(
db, redis, tenant_id, user_id, entity_type
)
if not visible_ids:
# No visible entities — return empty result
return query.where(text("1 = 0"))
return query.where(model.id.in_(list(visible_ids)))