feat(permissions): ABAC integration, principals caching, cache version validation
- Integrate ABAC policies into apply_visibility_filter() (allow/deny with priority) - Add field whitelist (ABAC_ALLOWED_FIELDS) for build_sql_condition() security - Add request-level ContextVar for user principals (group_ids, role_id) - Set principals in deps.py (session + bearer auth) - Use ContextVar in visibility.py and permission_resolver.py (N+1 fix) - Add version validation to get_cached_visible_ids() (cache strategy unification) - Deactivate delegation route (parked — not integrated into resolve_permissions) - Add 7 ABAC integration tests All 70 tests pass (7 ABAC + 63 existing). No regressions.
This commit is contained in:
@@ -6,6 +6,7 @@ Extracted from entity_permission_service.py for modularity.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
@@ -13,6 +14,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.services.permission_resolver import get_visible_ids
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CACHE_TTL = 300 # 5 minutes
|
||||
CACHE_PREFIX = "ep_vis" # entity permission visibility
|
||||
|
||||
@@ -40,25 +43,61 @@ async def get_cached_visible_ids(
|
||||
"""Get visible IDs from Redis cache or resolve from DB.
|
||||
|
||||
Cache key: ep_vis:{user_id}:{tenant_id}:{entity_type}
|
||||
Cache value: JSON {visible_ids: [str], access_map: {str: str}}
|
||||
Cache value: JSON {visible_ids: [str], access_map: {str: str}, version: int}
|
||||
TTL: 5 minutes
|
||||
|
||||
Validates cached permission_version against current DB version.
|
||||
If they differ, the cache entry is stale and will be re-resolved.
|
||||
"""
|
||||
cache_key = f"{CACHE_PREFIX}:{user_id}:{tenant_id}:{entity_type}"
|
||||
|
||||
raw = await redis.get(cache_key)
|
||||
if raw is not None:
|
||||
data = json.loads(raw)
|
||||
visible = {uuid.UUID(eid) for eid in data.get("visible_ids", [])}
|
||||
access_map = {uuid.UUID(eid): level for eid, level in data.get("access_map", {}).items()}
|
||||
return visible, access_map
|
||||
cached_version = data.get("version", -1)
|
||||
|
||||
# Cache miss — resolve from DB
|
||||
# Validate cached version against current DB version
|
||||
try:
|
||||
from app.core.permissions import _get_current_permission_version
|
||||
current_version = await _get_current_permission_version(db, user_id, tenant_id)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Failed to query permission_version for visible_ids cache validation "
|
||||
"(user=%s, tenant=%s) — invalidating cache and re-resolving",
|
||||
user_id, tenant_id,
|
||||
exc_info=True,
|
||||
)
|
||||
await redis.delete(cache_key)
|
||||
# Fall through to re-resolution below
|
||||
else:
|
||||
if cached_version == current_version:
|
||||
visible = {uuid.UUID(eid) for eid in data.get("visible_ids", [])}
|
||||
access_map = {uuid.UUID(eid): level for eid, level in data.get("access_map", {}).items()}
|
||||
return visible, access_map
|
||||
|
||||
logger.info(
|
||||
"visible_ids cache version mismatch for user=%s tenant=%s entity_type=%s "
|
||||
"(cached=%s, current=%s) — re-resolving",
|
||||
user_id, tenant_id, entity_type, cached_version, current_version,
|
||||
)
|
||||
await redis.delete(cache_key)
|
||||
|
||||
# Cache miss, stale, or version mismatch — resolve from DB
|
||||
visible, access_map = await get_visible_ids(db, tenant_id, user_id, entity_type)
|
||||
|
||||
# Get current permission version for cache stamping
|
||||
try:
|
||||
from app.core.permissions import _get_current_permission_version
|
||||
current_version = await _get_current_permission_version(db, user_id, tenant_id)
|
||||
except Exception:
|
||||
logger.warning("Failed to get permission_version for cache stamping — using 0")
|
||||
current_version = 0
|
||||
|
||||
# Store in cache
|
||||
cache_data = {
|
||||
"visible_ids": [str(eid) for eid in visible],
|
||||
"access_map": {str(eid): level for eid, level in access_map.items()},
|
||||
"version": current_version,
|
||||
}
|
||||
await redis.setex(cache_key, CACHE_TTL, json.dumps(cache_data))
|
||||
|
||||
|
||||
@@ -74,20 +74,27 @@ async def get_effective_access(
|
||||
if owner_id == user_id:
|
||||
return "owner"
|
||||
|
||||
# Get user's groups and role
|
||||
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]
|
||||
# Get user's groups and role — use ContextVar cache when available
|
||||
from app.core.principals import get_principals
|
||||
cached = get_principals()
|
||||
if cached is not None and cached.user_id == user_id and cached.tenant_id == tenant_id:
|
||||
group_ids = cached.group_ids
|
||||
role_id = cached.role_id
|
||||
else:
|
||||
# Fallback: load from DB (worker, tests, non-request context)
|
||||
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()
|
||||
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()
|
||||
|
||||
# Build principal conditions
|
||||
principal_conditions = [
|
||||
@@ -178,20 +185,27 @@ async def get_visible_ids(
|
||||
all_ids = {row[0] for row in all_q}
|
||||
return all_ids, {eid: "delete" for eid in all_ids}
|
||||
|
||||
# Get user's groups and role
|
||||
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]
|
||||
# Get user's groups and role — use ContextVar cache when available
|
||||
from app.core.principals import get_principals
|
||||
cached = get_principals()
|
||||
if cached is not None and cached.user_id == user_id and cached.tenant_id == tenant_id:
|
||||
group_ids = cached.group_ids
|
||||
role_id = cached.role_id
|
||||
else:
|
||||
# Fallback: load from DB (worker, tests, non-request context)
|
||||
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()
|
||||
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()
|
||||
|
||||
# 1. Owned entities
|
||||
model = _get_entity_model(entity_type)
|
||||
|
||||
@@ -30,6 +30,21 @@ _SUPPORTED_OPS = {
|
||||
"contains", "starts_with", "is_null", "is_not_null",
|
||||
}
|
||||
|
||||
# ─── ABAC Field Whitelist ──────────────────────────────────────────
|
||||
# Only these fields may be referenced in policy conditions per entity
|
||||
# type. Prevents policies from filtering on sensitive columns such as
|
||||
# tenant_id, password_hash, etc.
|
||||
ABAC_ALLOWED_FIELDS: dict[str, set[str]] = {
|
||||
"contact": {"status", "type", "country", "tags", "created_at", "updated_at", "owner_id"},
|
||||
"file": {"status", "size", "mime_type", "created_at"},
|
||||
"task": {"status", "priority", "due_date", "created_at"},
|
||||
"calendar_event": {"status", "start_time", "end_time", "created_at"},
|
||||
"mailbox": {"status", "created_at"},
|
||||
"address": {"country", "city", "created_at", "updated_at"},
|
||||
"contact_folder": {"name", "created_at"},
|
||||
"workflow": {"status", "created_at"},
|
||||
}
|
||||
|
||||
|
||||
def _serialize_policy(p: EntityPolicy) -> dict:
|
||||
return {
|
||||
@@ -51,6 +66,7 @@ def _serialize_policy(p: EntityPolicy) -> dict:
|
||||
def build_sql_condition(
|
||||
conditions: dict[str, Any],
|
||||
model: type,
|
||||
entity_type: str | None = None,
|
||||
) -> Any:
|
||||
"""Recursively translate a JSONB conditions block into a SQLAlchemy filter expression.
|
||||
|
||||
@@ -65,6 +81,11 @@ def build_sql_condition(
|
||||
}
|
||||
|
||||
Nested conditions are supported via rules that contain a nested conditions block.
|
||||
|
||||
When *entity_type* is provided, each rule's ``field`` is validated against
|
||||
the ABAC_ALLOWED_FIELDS whitelist for that entity type. Unknown fields are
|
||||
logged and skipped (not crashed) to prevent policies from filtering on
|
||||
sensitive columns such as ``tenant_id`` or ``password_hash``.
|
||||
"""
|
||||
if not conditions or "operator" not in conditions or "rules" not in conditions:
|
||||
return None
|
||||
@@ -80,7 +101,7 @@ def build_sql_condition(
|
||||
for rule in rules:
|
||||
# Nested conditions block
|
||||
if "operator" in rule and "rules" in rule:
|
||||
nested = build_sql_condition(rule, model)
|
||||
nested = build_sql_condition(rule, model, entity_type=entity_type)
|
||||
if nested is not None:
|
||||
clauses.append(nested)
|
||||
continue
|
||||
@@ -96,6 +117,17 @@ def build_sql_condition(
|
||||
logger.warning(f"Unsupported condition operator: {op}")
|
||||
continue
|
||||
|
||||
# ── Field whitelist check ──────────────────────────────────
|
||||
# Prevent policies from filtering on sensitive columns
|
||||
if entity_type is not None:
|
||||
allowed = ABAC_ALLOWED_FIELDS.get(entity_type)
|
||||
if allowed is not None and field_name not in allowed:
|
||||
logger.warning(
|
||||
f"ABAC field '{field_name}' not in whitelist for "
|
||||
f"entity_type '{entity_type}' — skipping rule"
|
||||
)
|
||||
continue
|
||||
|
||||
# Get the model attribute
|
||||
attr: InstrumentedAttribute | None = getattr(model, field_name, None)
|
||||
if attr is None:
|
||||
@@ -292,7 +324,7 @@ async def apply_policy_filter(
|
||||
deny_clauses.append(True)
|
||||
continue
|
||||
|
||||
condition = build_sql_condition(policy.conditions, model)
|
||||
condition = build_sql_condition(policy.conditions, model, entity_type=entity_type)
|
||||
if condition is None:
|
||||
continue
|
||||
|
||||
|
||||
Reference in New Issue
Block a user