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:
Agent Zero
2026-08-06 22:05:15 +02:00
parent 19ecc0cd71
commit 7c8f2a2222
8 changed files with 668 additions and 40 deletions
+44 -5
View File
@@ -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))