c_agri_trade/project_code/backend/app/api/support.py

365 lines
14 KiB
Python

"""Privileged Support Access & Security Impersonation API Controller.
Fulfills:
- STORY-SUPPORT-001 (FR-TENANTSUPPORTSECURITY-001): End-to-End Tenant Resource Isolation (UC-020).
- STORY-SUPPORT-002 (FR-TENANTSUPPORTSECURITY-002): Controlled Privileged Support Access & Break-Glass (UC-020).
Adheres to LLD-001, LLD-002, and UP-AI v1.5 standards.
"""
from datetime import datetime, timezone, timedelta
import logging
from typing import Any, Dict, List, Optional
import uuid
from backend.app.api.auth import auth_controller
from backend.app.auth.tenant_context import (
TenantContext,
TenantContextResolutionError,
TenantContextResolver,
record_audit_event,
)
from backend.app.db.session import storage
from backend.app.models.support import (
PrivilegedSupportGrant,
MissingTenantContextException,
run_with_tenant_context,
SUPPORT_GRANT_STATUSES,
SUPPORT_ACCESS_SCOPES,
MIN_GRANT_MINUTES,
MAX_GRANT_MINUTES,
)
from sandbox.notification_mock import notification_mock
logger = logging.getLogger("atb.api.support")
class SupportController:
"""Manages privileged support grants, dual-authorization approvals, and emergency break-glass sessions."""
def __init__(self, store=storage, resolver=None, notifier=notification_mock):
self.store = store
self.resolver = resolver or TenantContextResolver(store=self.store)
self.notifier = notifier
def _authenticate_and_resolve(
self, auth_header: Optional[str], tenant_header: Optional[str]
) -> Dict[str, Any]:
"""Resolves verified caller session and active tenant context."""
session = auth_controller.get_session(auth_header)
if not session.get("authenticated"):
return {"authenticated": False, "error": session.get("error", "UNAUTHENTICATED"), "status_code": 401}
user_id = session.get("subject", "")
email = session.get("email", user_id)
user_roles = session.get("roles", [])
try:
ctx = self.resolver.resolve_context(
subject_id=user_id,
email=email,
user_roles=user_roles,
requested_tenant_id=tenant_header,
)
return {
"authenticated": True,
"context": ctx,
"user_id": user_id,
"email": email,
"roles": ctx.roles,
}
except TenantContextResolutionError as err:
return {"authenticated": False, "error": err.message, "code": err.code, "status_code": err.status_code}
def request_grant(
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/platform/support/grants"""
auth = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth["authenticated"]:
return auth
ctx: TenantContext = auth["context"]
tenant_id = payload.get("target_tenant_id") or ctx.tenant_id
email = auth["email"]
reason = payload.get("reason", "")
duration = int(payload.get("duration_minutes", 60))
scope = payload.get("access_scope", "FULL_SUPPORT")
try:
grant = PrivilegedSupportGrant(
tenant_id=tenant_id,
engineer_user_id=email,
requested_by=email,
reason=reason,
duration_minutes=duration,
access_scope=scope,
is_break_glass=False,
id=payload.get("id"),
)
except (ValueError, TypeError) as e:
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
self.store.insert("privileged_support_grants", tenant_id, grant.to_dict())
# Notify tenant administrator
self.notifier.record_event(
tenant_id=tenant_id,
event_type="SUPPORT_GRANT_REQUESTED",
payload={
"grant_id": grant.id,
"requested_by": email,
"reason": reason,
"duration_minutes": duration,
},
)
resp = grant.to_dict()
resp["status_code"] = 201
return resp
def approve_grant(
self, auth_header: Optional[str], tenant_header: Optional[str], grant_id: str, payload: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""POST /api/v1/platform/support/grants/{id}/approve (Mandatory Dual-Authorization)"""
auth = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth["authenticated"]:
return auth
ctx: TenantContext = auth["context"]
tenant_id = ctx.tenant_id
approver_email = auth["email"]
grant_dict = self.store.get("privileged_support_grants", tenant_id, grant_id)
if not grant_dict:
return {"error": "GRANT_NOT_FOUND", "message": f"Support grant '{grant_id}' not found", "status_code": 404}
# Dual authorization check: Requester cannot approve their own grant
requested_by = grant_dict.get("requested_by", "")
if approver_email.strip().lower() == requested_by.strip().lower():
return {
"error": "DUAL_AUTHORIZATION_REQUIRED",
"message": "Dual authorization policy violation: Requester cannot self-approve support grant. Approval must be performed by a designated Tenant Administrator.",
"status_code": 403,
}
if grant_dict.get("status") != "PENDING":
return {
"error": "INVALID_GRANT_STATE",
"message": f"Cannot approve grant in status '{grant_dict.get('status')}'. Must be 'PENDING'.",
"status_code": 409,
}
payload = payload or {}
duration_minutes = payload.get("duration_minutes")
if duration_minutes is not None:
try:
duration_minutes = int(duration_minutes)
if not (MIN_GRANT_MINUTES <= duration_minutes <= MAX_GRANT_MINUTES):
return {"error": "VALIDATION_ERROR", "message": f"Duration must be between {MIN_GRANT_MINUTES} and {MAX_GRANT_MINUTES} mins", "status_code": 422}
except (ValueError, TypeError):
return {"error": "VALIDATION_ERROR", "message": "Invalid duration minutes", "status_code": 422}
else:
duration_minutes = grant_dict.get("duration_minutes", 60)
now = datetime.now(timezone.utc)
expires_at = now + timedelta(minutes=duration_minutes)
token_jti = str(uuid.uuid4())
grant_dict["approved_by"] = approver_email
grant_dict["approved_at"] = now.isoformat()
grant_dict["duration_minutes"] = duration_minutes
grant_dict["expires_at"] = expires_at.isoformat()
grant_dict["status"] = "ACTIVE"
grant_dict["token_jti"] = token_jti
self.store.update("privileged_support_grants", tenant_id, grant_id, grant_dict)
# Emit audit event
record_audit_event(
store=self.store,
tenant_id=tenant_id,
actor_id=approver_email,
action="SUPPORT_GRANT_APPROVED",
entity_type="PRIVILEGED_SUPPORT_GRANT",
entity_id=grant_id,
details={"approved_duration": duration_minutes, "token_jti": token_jti},
)
resp = dict(grant_dict)
resp["ephemeral_token"] = f"mock-support-impersonation-token-{token_jti}"
resp["status_code"] = 200
return resp
def reject_grant(
self, auth_header: Optional[str], tenant_header: Optional[str], grant_id: str, payload: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""POST /api/v1/platform/support/grants/{id}/reject"""
auth = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth["authenticated"]:
return auth
ctx: TenantContext = auth["context"]
tenant_id = ctx.tenant_id
rejector_email = auth["email"]
grant_dict = self.store.get("privileged_support_grants", tenant_id, grant_id)
if not grant_dict:
return {"error": "GRANT_NOT_FOUND", "message": f"Support grant '{grant_id}' not found", "status_code": 404}
if grant_dict.get("status") != "PENDING":
return {
"error": "INVALID_GRANT_STATE",
"message": f"Cannot reject grant in status '{grant_dict.get('status')}'. Must be 'PENDING'.",
"status_code": 409,
}
grant_dict["status"] = "REJECTED"
grant_dict["approved_by"] = rejector_email
grant_dict["revoked_at"] = datetime.now(timezone.utc).isoformat()
self.store.update("privileged_support_grants", tenant_id, grant_id, grant_dict)
resp = dict(grant_dict)
resp["status_code"] = 200
return resp
def revoke_grant(
self, auth_header: Optional[str], tenant_header: Optional[str], grant_id: str
) -> Dict[str, Any]:
"""POST /api/v1/platform/support/grants/{id}/revoke"""
auth = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth["authenticated"]:
return auth
ctx: TenantContext = auth["context"]
tenant_id = ctx.tenant_id
revoker_email = auth["email"]
grant_dict = self.store.get("privileged_support_grants", tenant_id, grant_id)
if not grant_dict:
return {"error": "GRANT_NOT_FOUND", "message": f"Support grant '{grant_id}' not found", "status_code": 404}
if grant_dict.get("status") not in {"ACTIVE", "BREAK_GLASS_ACTIVE"}:
return {
"error": "INVALID_GRANT_STATE",
"message": f"Cannot revoke grant in status '{grant_dict.get('status')}'. Must be 'ACTIVE' or 'BREAK_GLASS_ACTIVE'.",
"status_code": 409,
}
grant_dict["status"] = "REVOKED"
grant_dict["revoked_at"] = datetime.now(timezone.utc).isoformat()
self.store.update("privileged_support_grants", tenant_id, grant_id, grant_dict)
record_audit_event(
store=self.store,
tenant_id=tenant_id,
actor_id=revoker_email,
action="SUPPORT_GRANT_REVOKED",
entity_type="PRIVILEGED_SUPPORT_GRANT",
entity_id=grant_id,
details={"revoked_by": revoker_email},
)
resp = dict(grant_dict)
resp["status_code"] = 200
return resp
def break_glass(
self, auth_header: Optional[str], tenant_header: Optional[str], payload: Dict[str, Any]
) -> Dict[str, Any]:
"""POST /api/v1/platform/support/grants/break-glass (Emergency Bypass)"""
auth = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth["authenticated"]:
return auth
ctx: TenantContext = auth["context"]
tenant_id = payload.get("target_tenant_id") or ctx.tenant_id
email = auth["email"]
justification = payload.get("emergency_justification") or payload.get("reason", "")
duration = int(payload.get("duration_minutes", 30))
try:
grant = PrivilegedSupportGrant(
tenant_id=tenant_id,
engineer_user_id=email,
requested_by=email,
reason=justification,
duration_minutes=duration,
access_scope="FULL_SUPPORT",
is_break_glass=True,
break_glass_justification=justification,
id=payload.get("id"),
)
except (ValueError, TypeError) as e:
return {"error": "VALIDATION_ERROR", "message": str(e), "status_code": 422}
self.store.insert("privileged_support_grants", tenant_id, grant.to_dict())
# Emit high-priority security alarm
self.notifier.record_event(
tenant_id=tenant_id,
event_type="EMERGENCY_BREAK_GLASS_ACTIVATED",
payload={
"grant_id": grant.id,
"actor": email,
"justification": justification,
"duration_minutes": duration,
"severity": "CRITICAL",
},
)
record_audit_event(
store=self.store,
tenant_id=tenant_id,
actor_id=email,
action="BREAK_GLASS_EMERGENCY_ACCESS",
entity_type="PRIVILEGED_SUPPORT_GRANT",
entity_id=grant.id,
details={"justification": justification, "token_jti": grant.token_jti},
)
resp = grant.to_dict()
resp["ephemeral_token"] = f"emergency-break-glass-token-{grant.token_jti}"
resp["status_code"] = 201
return resp
def list_grants(
self, auth_header: Optional[str], tenant_header: Optional[str]
) -> Dict[str, Any]:
"""GET /api/v1/platform/support/grants"""
auth = self._authenticate_and_resolve(auth_header, tenant_header)
if not auth["authenticated"]:
return auth
ctx: TenantContext = auth["context"]
tenant_id = ctx.tenant_id
grants = self.store.list("privileged_support_grants", tenant_id)
now = datetime.now(timezone.utc)
# Check and update expired grants dynamically
updated_grants = []
for g in grants:
g_dict = dict(g)
if g_dict.get("status") in {"ACTIVE", "BREAK_GLASS_ACTIVE"}:
exp_str = g_dict.get("expires_at")
if exp_str:
try:
exp = datetime.fromisoformat(exp_str)
if exp.tzinfo is None:
exp = exp.replace(tzinfo=timezone.utc)
if now >= exp:
g_dict["status"] = "EXPIRED"
self.store.update("privileged_support_grants", tenant_id, g_dict["id"], g_dict)
except (ValueError, TypeError):
pass
updated_grants.append(g_dict)
return {"grants": updated_grants, "count": len(updated_grants), "status_code": 200}
support_controller = SupportController()