TT-007.2: establish DB-backed module authorization
This commit is contained in:
@@ -1,86 +1,74 @@
|
||||
"""Module-owned permission endpoints.
|
||||
|
||||
Permission Catalog and Effective Policy are owned by Module, not Platform.
|
||||
DB is the single source of truth for authorization.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from request_app.core.auth import get_current_user
|
||||
from request_app.core.database import get_db
|
||||
from request_app.models.user import User
|
||||
from request_app.models.permission import Permission
|
||||
from request_app.models.role_permission import RolePermission
|
||||
|
||||
router = APIRouter(tags=["Permissions"])
|
||||
|
||||
# Module Permission Catalog — stable, declared by Module
|
||||
MODULE_PERMISSION_CATALOG = [
|
||||
"request.read",
|
||||
"request.create",
|
||||
"request.update",
|
||||
"request.delete",
|
||||
"request.assign",
|
||||
"request.close",
|
||||
"request.comment",
|
||||
"request.admin",
|
||||
"request.settings.manage",
|
||||
"request.report.view",
|
||||
]
|
||||
|
||||
# Role → Permissions mapping (Module-owned)
|
||||
ROLE_PERMISSIONS = {
|
||||
"admin": MODULE_PERMISSION_CATALOG, # admin gets all
|
||||
"manager": [
|
||||
"request.read",
|
||||
"request.create",
|
||||
"request.update",
|
||||
"request.assign",
|
||||
"request.close",
|
||||
"request.comment",
|
||||
"request.report.view",
|
||||
],
|
||||
"user": [
|
||||
"request.read",
|
||||
"request.create",
|
||||
"request.comment",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def compute_effective_policy(user: User) -> list[str]:
|
||||
def compute_effective_policy(user: User, db: Session) -> list[str]:
|
||||
"""Compute effective permissions for a user based on local roles.
|
||||
|
||||
This is the Module-owned authorization engine.
|
||||
Module is the authority for its own permissions.
|
||||
DB is the single source of truth.
|
||||
"""
|
||||
permissions = set()
|
||||
|
||||
# Get user's local roles
|
||||
for user_role in user.user_roles:
|
||||
role_name = user_role.role.name
|
||||
role_perms = ROLE_PERMISSIONS.get(role_name, [])
|
||||
permissions.update(role_perms)
|
||||
role_id = user_role.role_id
|
||||
|
||||
# Get permissions for this role from DB
|
||||
role_perms = (
|
||||
db.query(Permission.name)
|
||||
.join(RolePermission, RolePermission.permission_id == Permission.id)
|
||||
.filter(RolePermission.role_id == role_id)
|
||||
.all()
|
||||
)
|
||||
|
||||
for (perm_name,) in role_perms:
|
||||
permissions.add(perm_name)
|
||||
|
||||
return sorted(permissions)
|
||||
|
||||
|
||||
@router.get("/permissions/catalog")
|
||||
async def get_permission_catalog():
|
||||
"""Return Module Permission Catalog.
|
||||
async def get_permission_catalog(db: Session = Depends(get_db)):
|
||||
"""Return Module Permission Catalog from DB.
|
||||
|
||||
This is NOT user-specific — it's the list of all permissions
|
||||
that this Module defines.
|
||||
DB is the single source of truth.
|
||||
"""
|
||||
perms = db.query(Permission).filter(Permission.module_id == "request").all()
|
||||
return {
|
||||
"module_id": "request",
|
||||
"permissions": MODULE_PERMISSION_CATALOG,
|
||||
"permissions": [p.name for p in perms],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/permissions/me")
|
||||
async def get_my_effective_policy(user: User = Depends(get_current_user)):
|
||||
async def get_my_effective_policy(
|
||||
user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Return effective policy for the current Principal.
|
||||
|
||||
Computed locally by Module authorization engine.
|
||||
Module is the authority for its own permissions.
|
||||
DB is the single source of truth.
|
||||
"""
|
||||
permissions = compute_effective_policy(user)
|
||||
permissions = compute_effective_policy(user, db)
|
||||
return {
|
||||
"module_id": "request",
|
||||
"user_id": user.id,
|
||||
|
||||
@@ -124,14 +124,16 @@ def require_permission(permission_id: str):
|
||||
Module is the authority for its own permissions.
|
||||
|
||||
Uses the single Module authorization engine from permissions.py.
|
||||
DB is the single source of truth.
|
||||
"""
|
||||
from request_app.api.v1.routes.permissions import compute_effective_policy
|
||||
|
||||
def _check_permission(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
# Use the single Module authorization engine
|
||||
user_permissions = set(compute_effective_policy(current_user))
|
||||
# Use the single Module authorization engine (DB-driven)
|
||||
user_permissions = set(compute_effective_policy(current_user, db))
|
||||
|
||||
if permission_id not in user_permissions:
|
||||
raise HTTPException(
|
||||
|
||||
@@ -30,6 +30,90 @@ def get_db() -> Generator[Session, None, None]:
|
||||
db.close()
|
||||
|
||||
|
||||
# Bootstrap permission catalog — used ONLY for seeding, NOT for runtime
|
||||
_BOOTSTRAP_PERMISSIONS = [
|
||||
("request.read", "View tickets and data"),
|
||||
("request.create", "Create new tickets"),
|
||||
("request.update", "Update existing tickets"),
|
||||
("request.delete", "Delete tickets"),
|
||||
("request.assign", "Assign tickets to users"),
|
||||
("request.close", "Close tickets"),
|
||||
("request.comment", "Add comments to tickets"),
|
||||
("request.admin", "Full administrative access"),
|
||||
("request.settings.manage", "Manage module settings"),
|
||||
("request.report.view", "View reports and statistics"),
|
||||
]
|
||||
|
||||
# Bootstrap role → permission mapping — used ONLY for seeding, NOT for runtime
|
||||
_BOOTSTRAP_ROLE_PERMISSIONS = {
|
||||
"admin": [p[0] for p in _BOOTSTRAP_PERMISSIONS], # admin gets all
|
||||
"manager": [
|
||||
"request.read",
|
||||
"request.create",
|
||||
"request.update",
|
||||
"request.assign",
|
||||
"request.close",
|
||||
"request.comment",
|
||||
"request.report.view",
|
||||
],
|
||||
"support_agent": [
|
||||
"request.read",
|
||||
"request.create",
|
||||
"request.update",
|
||||
"request.close",
|
||||
"request.comment",
|
||||
],
|
||||
"customer": [
|
||||
"request.read",
|
||||
"request.create",
|
||||
"request.comment",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _seed_permissions(db: Session):
|
||||
"""Seed permissions table idempotently."""
|
||||
from request_app.models.permission import Permission
|
||||
|
||||
for name, description in _BOOTSTRAP_PERMISSIONS:
|
||||
if not db.query(Permission).filter(Permission.name == name).first():
|
||||
db.add(Permission(
|
||||
name=name,
|
||||
description=description,
|
||||
module_id="request",
|
||||
is_system=True,
|
||||
))
|
||||
db.flush()
|
||||
|
||||
|
||||
def _seed_role_permissions(db: Session):
|
||||
"""Seed role_permissions table idempotently."""
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.permission import Permission
|
||||
from request_app.models.role_permission import RolePermission
|
||||
|
||||
for role_name, perm_names in _BOOTSTRAP_ROLE_PERMISSIONS.items():
|
||||
role = db.query(Role).filter(Role.name == role_name).first()
|
||||
if not role:
|
||||
continue
|
||||
|
||||
for perm_name in perm_names:
|
||||
perm = db.query(Permission).filter(Permission.name == perm_name).first()
|
||||
if not perm:
|
||||
continue
|
||||
|
||||
# Check if mapping already exists
|
||||
existing = db.query(RolePermission).filter(
|
||||
RolePermission.role_id == role.id,
|
||||
RolePermission.permission_id == perm.id,
|
||||
).first()
|
||||
|
||||
if not existing:
|
||||
db.add(RolePermission(role_id=role.id, permission_id=perm.id))
|
||||
|
||||
db.flush()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Initialize database - create all tables and default data."""
|
||||
from request_app.models import (
|
||||
@@ -38,6 +122,8 @@ def init_db():
|
||||
)
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.permission import Permission
|
||||
from request_app.models.role_permission import RolePermission
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
@@ -54,6 +140,14 @@ def init_db():
|
||||
if not db.query(Role).filter(Role.name == name).first():
|
||||
db.add(Role(name=name, description=description, is_system=is_system))
|
||||
db.commit()
|
||||
|
||||
# Seed permissions
|
||||
_seed_permissions(db)
|
||||
db.commit()
|
||||
|
||||
# Seed role → permission mappings
|
||||
_seed_role_permissions(db)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
from request_app.models.user import User
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.permission import Permission
|
||||
from request_app.models.role_permission import RolePermission
|
||||
from request_app.models.priority import Priority
|
||||
from request_app.models.status import Status
|
||||
from request_app.models.category import Category
|
||||
@@ -19,6 +23,10 @@ __all__ = [
|
||||
"Base",
|
||||
"TimestampMixin",
|
||||
"User",
|
||||
"Role",
|
||||
"UserRole",
|
||||
"Permission",
|
||||
"RolePermission",
|
||||
"Priority",
|
||||
"Status",
|
||||
"Category",
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Permission model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Permission(Base, TimestampMixin):
|
||||
"""Permission model — Module-owned permission catalog.
|
||||
|
||||
Permissions are defined by Module, not Platform.
|
||||
This table is the single source of truth for Module permissions.
|
||||
"""
|
||||
|
||||
__tablename__ = "permissions"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, nullable=False, index=True)
|
||||
description = Column(Text, nullable=True)
|
||||
module_id = Column(String(50), nullable=False, default="request")
|
||||
is_system = Column(Boolean, default=True)
|
||||
|
||||
# Relationships
|
||||
role_permissions = relationship("RolePermission", back_populates="permission", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Permission(id={self.id}, name='{self.name}')>"
|
||||
@@ -16,6 +16,7 @@ class Role(Base, TimestampMixin):
|
||||
is_system = Column(Boolean, default=False)
|
||||
|
||||
user_roles = relationship("UserRole", back_populates="role", cascade="all, delete-orphan")
|
||||
role_permissions = relationship("RolePermission", back_populates="role", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Role(id={self.id}, name='{self.name}')>"
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""RolePermission model."""
|
||||
|
||||
from sqlalchemy import Column, Integer, ForeignKey, UniqueConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class RolePermission(Base, TimestampMixin):
|
||||
"""RolePermission model — Role → Permission mapping.
|
||||
|
||||
This is the Module-owned authorization mapping.
|
||||
Module is the authority for its own Role → Permission assignments.
|
||||
"""
|
||||
|
||||
__tablename__ = "role_permissions"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
role_id = Column(Integer, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
|
||||
permission_id = Column(Integer, ForeignKey("permissions.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
# Unique constraint: one role can have each permission only once
|
||||
__table_args__ = (
|
||||
UniqueConstraint("role_id", "permission_id", name="uq_role_permission"),
|
||||
)
|
||||
|
||||
# Relationships
|
||||
role = relationship("Role", back_populates="role_permissions")
|
||||
permission = relationship("Permission", back_populates="role_permissions")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<RolePermission(role_id={self.role_id}, permission_id={self.permission_id})>"
|
||||
Reference in New Issue
Block a user