feat(server): add project RBAC and guarded workflows
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
|
||||
from app.auth.project_dependencies import ProjectContext, get_project_context
|
||||
|
||||
WEBGIS_VIEW = "webgis.view"
|
||||
WEBGIS_EDIT = "webgis.edit"
|
||||
SCADA_VIEW = "scada.view"
|
||||
SCADA_CLEAN = "scada.clean"
|
||||
SIMULATION_VIEW = "simulation.view"
|
||||
SIMULATION_RUN = "simulation.run"
|
||||
BURST_VIEW = "burst.view"
|
||||
BURST_RUN = "burst.run"
|
||||
RISK_VIEW = "risk.view"
|
||||
RISK_RUN = "risk.run"
|
||||
OPTIMIZATION_VIEW = "optimization.view"
|
||||
OPTIMIZATION_RUN = "optimization.run"
|
||||
MODEL_IMPORT = "model.import"
|
||||
AUDIT_VIEW = "audit.view"
|
||||
ENVIRONMENT_MANAGE = "environment.manage"
|
||||
MEMBERSHIP_MANAGE = "membership.manage"
|
||||
|
||||
PROJECT_MEMBER_PERMISSIONS = frozenset(
|
||||
{
|
||||
WEBGIS_VIEW,
|
||||
WEBGIS_EDIT,
|
||||
SCADA_VIEW,
|
||||
SCADA_CLEAN,
|
||||
SIMULATION_VIEW,
|
||||
SIMULATION_RUN,
|
||||
BURST_VIEW,
|
||||
BURST_RUN,
|
||||
RISK_VIEW,
|
||||
RISK_RUN,
|
||||
OPTIMIZATION_VIEW,
|
||||
OPTIMIZATION_RUN,
|
||||
}
|
||||
)
|
||||
|
||||
PROJECT_VIEWER_PERMISSIONS = frozenset(
|
||||
{
|
||||
WEBGIS_VIEW,
|
||||
SCADA_VIEW,
|
||||
SIMULATION_VIEW,
|
||||
}
|
||||
)
|
||||
|
||||
SYSTEM_ADMIN_PERMISSIONS = frozenset(
|
||||
{
|
||||
MODEL_IMPORT,
|
||||
AUDIT_VIEW,
|
||||
ENVIRONMENT_MANAGE,
|
||||
MEMBERSHIP_MANAGE,
|
||||
}
|
||||
)
|
||||
|
||||
PROJECT_ROLE_PERMISSIONS: dict[str, frozenset[str]] = {
|
||||
"member": PROJECT_MEMBER_PERMISSIONS,
|
||||
"viewer": PROJECT_VIEWER_PERMISSIONS,
|
||||
}
|
||||
|
||||
|
||||
def resolve_permissions(
|
||||
*,
|
||||
project_role: str | None,
|
||||
system_role: str,
|
||||
is_superuser: bool,
|
||||
) -> frozenset[str]:
|
||||
permissions = set(PROJECT_ROLE_PERMISSIONS.get(project_role or "", frozenset()))
|
||||
if is_superuser or system_role == "admin":
|
||||
permissions.update(SYSTEM_ADMIN_PERMISSIONS)
|
||||
return frozenset(permissions)
|
||||
|
||||
|
||||
def permissions_for_context(ctx: ProjectContext) -> frozenset[str]:
|
||||
return resolve_permissions(
|
||||
project_role=ctx.project_role,
|
||||
system_role=ctx.system_role,
|
||||
is_superuser=ctx.is_superuser,
|
||||
)
|
||||
|
||||
|
||||
def _permission_denied(permission: str) -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail={
|
||||
"code": "permission_denied",
|
||||
"permission": permission,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _enforce_project_scope(request: Request, ctx: ProjectContext) -> None:
|
||||
requested_network = (
|
||||
request.path_params.get("network")
|
||||
or request.query_params.get("network")
|
||||
)
|
||||
if not requested_network:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
if content_type.startswith("application/json"):
|
||||
try:
|
||||
payload = await request.json()
|
||||
except (ValueError, RuntimeError):
|
||||
payload = None
|
||||
if isinstance(payload, dict):
|
||||
requested_network = payload.get("network")
|
||||
|
||||
if requested_network and str(requested_network) != ctx.project_code:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail={
|
||||
"code": "project_scope_denied",
|
||||
"project_id": str(ctx.project_id),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def require_permission(
|
||||
permission: str,
|
||||
) -> Callable[..., Awaitable[ProjectContext]]:
|
||||
async def dependency(
|
||||
request: Request,
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
) -> ProjectContext:
|
||||
if permission not in permissions_for_context(ctx):
|
||||
raise _permission_denied(permission)
|
||||
await _enforce_project_scope(request, ctx)
|
||||
return ctx
|
||||
|
||||
return dependency
|
||||
|
||||
|
||||
def require_method_permission(
|
||||
*,
|
||||
read_permission: str,
|
||||
write_permission: str,
|
||||
) -> Callable[..., Awaitable[ProjectContext]]:
|
||||
async def dependency(
|
||||
request: Request,
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
) -> ProjectContext:
|
||||
permission = (
|
||||
read_permission
|
||||
if request.method.upper() in {"GET", "HEAD", "OPTIONS"}
|
||||
else write_permission
|
||||
)
|
||||
if permission not in permissions_for_context(ctx):
|
||||
raise _permission_denied(permission)
|
||||
await _enforce_project_scope(request, ctx)
|
||||
return ctx
|
||||
|
||||
return dependency
|
||||
|
||||
|
||||
def has_permission(user: Any, project_role: str | None, permission: str) -> bool:
|
||||
return permission in resolve_permissions(
|
||||
project_role=project_role,
|
||||
system_role=str(getattr(user, "role", "user")),
|
||||
is_superuser=bool(getattr(user, "is_superuser", False)),
|
||||
)
|
||||
@@ -1,18 +1,21 @@
|
||||
import logging
|
||||
from collections.abc import AsyncGenerator
|
||||
from dataclasses import dataclass
|
||||
from typing import AsyncGenerator
|
||||
from uuid import UUID
|
||||
|
||||
import logging
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from psycopg import AsyncConnection
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.keycloak_dependencies import get_current_keycloak_sub
|
||||
from app.auth.metadata_dependencies import get_current_metadata_user
|
||||
from app.core.config import settings
|
||||
from app.infra.db.dynamic_manager import project_connection_manager
|
||||
from app.infra.db.metadb.database import get_metadata_session
|
||||
from app.infra.db.metadb.repositories.metadata_repository import MetadataRepository
|
||||
from app.infra.db.metadb.repositories.metadata_repository import (
|
||||
MetadataRepository,
|
||||
ProjectDbRouting,
|
||||
)
|
||||
|
||||
DB_ROLE_BIZ_DATA = "biz_data"
|
||||
DB_ROLE_IOT_DATA = "iot_data"
|
||||
@@ -28,6 +31,8 @@ class ProjectContext:
|
||||
project_code: str
|
||||
user_id: UUID
|
||||
project_role: str
|
||||
system_role: str = "user"
|
||||
is_superuser: bool = False
|
||||
|
||||
|
||||
async def get_metadata_repository(
|
||||
@@ -36,10 +41,10 @@ async def get_metadata_repository(
|
||||
return MetadataRepository(session)
|
||||
|
||||
|
||||
async def get_project_context(
|
||||
x_project_id: str = Header(..., alias="X-Project-Id"),
|
||||
keycloak_sub: UUID = Depends(get_current_keycloak_sub),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
async def resolve_project_context(
|
||||
x_project_id: str,
|
||||
current_user,
|
||||
metadata_repo: MetadataRepository,
|
||||
) -> ProjectContext:
|
||||
try:
|
||||
project_uuid = UUID(x_project_id)
|
||||
@@ -59,17 +64,9 @@ async def get_project_context(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Project is not active"
|
||||
)
|
||||
|
||||
user = await metadata_repo.get_user_by_keycloak_id(keycloak_sub)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="User not registered"
|
||||
)
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user"
|
||||
)
|
||||
|
||||
membership_role = await metadata_repo.get_membership_role(project_uuid, user.id)
|
||||
membership_role = await metadata_repo.get_membership_role(
|
||||
project_uuid, current_user.id
|
||||
)
|
||||
if not membership_role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="No access to project"
|
||||
@@ -87,38 +84,65 @@ async def get_project_context(
|
||||
return ProjectContext(
|
||||
project_id=project.id,
|
||||
project_code=project.code,
|
||||
user_id=user.id,
|
||||
user_id=current_user.id,
|
||||
project_role=membership_role,
|
||||
system_role=current_user.role,
|
||||
is_superuser=current_user.is_superuser,
|
||||
)
|
||||
|
||||
|
||||
async def get_project_context(
|
||||
x_project_id: str = Header(..., alias="X-Project-Id"),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> ProjectContext:
|
||||
return await resolve_project_context(x_project_id, current_user, metadata_repo)
|
||||
|
||||
|
||||
async def _get_project_routing(
|
||||
metadata_repo: MetadataRepository,
|
||||
project_id: UUID,
|
||||
db_role: str,
|
||||
expected_db_type: str,
|
||||
database_label: str,
|
||||
) -> ProjectDbRouting:
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(project_id, db_role)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project %s routing DSN configuration",
|
||||
database_label,
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project {database_label} routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project {database_label} not configured",
|
||||
)
|
||||
if routing.db_type != expected_db_type:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project {database_label} type mismatch",
|
||||
)
|
||||
return routing
|
||||
|
||||
|
||||
async def get_project_pg_session(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> AsyncGenerator[AsyncSession, None]:
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(
|
||||
ctx.project_id, DB_ROLE_BIZ_DATA
|
||||
)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project PostgreSQL routing DSN configuration",
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project PostgreSQL routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL not configured",
|
||||
)
|
||||
if routing.db_type != DB_TYPE_POSTGRES:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL type mismatch",
|
||||
)
|
||||
routing = await _get_project_routing(
|
||||
metadata_repo,
|
||||
ctx.project_id,
|
||||
DB_ROLE_BIZ_DATA,
|
||||
DB_TYPE_POSTGRES,
|
||||
"PostgreSQL",
|
||||
)
|
||||
|
||||
pool_min_size = routing.pool_min_size or settings.PROJECT_PG_POOL_SIZE
|
||||
pool_max_size = routing.pool_max_size or settings.PROJECT_PG_POOL_SIZE
|
||||
@@ -137,29 +161,13 @@ async def get_project_pg_connection(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> AsyncGenerator[AsyncConnection, None]:
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(
|
||||
ctx.project_id, DB_ROLE_BIZ_DATA
|
||||
)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project PostgreSQL routing DSN configuration",
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project PostgreSQL routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL not configured",
|
||||
)
|
||||
if routing.db_type != DB_TYPE_POSTGRES:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL type mismatch",
|
||||
)
|
||||
routing = await _get_project_routing(
|
||||
metadata_repo,
|
||||
ctx.project_id,
|
||||
DB_ROLE_BIZ_DATA,
|
||||
DB_TYPE_POSTGRES,
|
||||
"PostgreSQL",
|
||||
)
|
||||
|
||||
pool_min_size = routing.pool_min_size or settings.PROJECT_PG_POOL_SIZE
|
||||
pool_max_size = routing.pool_max_size or settings.PROJECT_PG_POOL_SIZE
|
||||
@@ -178,29 +186,13 @@ async def get_project_timescale_connection(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> AsyncGenerator[AsyncConnection, None]:
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(
|
||||
ctx.project_id, DB_ROLE_IOT_DATA
|
||||
)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project TimescaleDB routing DSN configuration",
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project TimescaleDB routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project TimescaleDB not configured",
|
||||
)
|
||||
if routing.db_type != DB_TYPE_TIMESCALE:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project TimescaleDB type mismatch",
|
||||
)
|
||||
routing = await _get_project_routing(
|
||||
metadata_repo,
|
||||
ctx.project_id,
|
||||
DB_ROLE_IOT_DATA,
|
||||
DB_TYPE_TIMESCALE,
|
||||
"TimescaleDB",
|
||||
)
|
||||
|
||||
pool_min_size = routing.pool_min_size or settings.PROJECT_TS_POOL_MIN_SIZE
|
||||
pool_max_size = routing.pool_max_size or settings.PROJECT_TS_POOL_MAX_SIZE
|
||||
|
||||
Reference in New Issue
Block a user