feat(request): add service accounts and unified authorization
This commit is contained in:
@@ -2,33 +2,48 @@
|
||||
|
||||
Permission Catalog and Effective Policy are owned by Module, not Platform.
|
||||
DB is the single source of truth for authorization.
|
||||
|
||||
Supports both User and ServiceAccount as Principal types.
|
||||
"""
|
||||
|
||||
from typing import Union
|
||||
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.service_account import ServiceAccount
|
||||
from request_app.models.permission import Permission
|
||||
from request_app.models.role_permission import RolePermission
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.service_account_role import ServiceAccountRole
|
||||
|
||||
router = APIRouter(tags=["Permissions"])
|
||||
|
||||
|
||||
def compute_effective_policy(user: User, db: Session) -> list[str]:
|
||||
"""Compute effective permissions for a user based on local roles.
|
||||
def compute_effective_policy(principal: Union[User, ServiceAccount], db: Session) -> list[str]:
|
||||
"""Compute effective permissions for a Principal based on local roles.
|
||||
|
||||
This is the Module-owned authorization engine.
|
||||
Module is the authority for its own permissions.
|
||||
Works with both User and ServiceAccount.
|
||||
DB is the single source of truth.
|
||||
"""
|
||||
permissions = set()
|
||||
|
||||
# Get user's local roles
|
||||
for user_role in user.user_roles:
|
||||
role_id = user_role.role_id
|
||||
# Get role IDs based on Principal type
|
||||
role_ids = []
|
||||
|
||||
# Get permissions for this role from DB
|
||||
if isinstance(principal, User):
|
||||
# User: get roles from UserRole
|
||||
role_ids = [ur.role_id for ur in principal.user_roles]
|
||||
elif isinstance(principal, ServiceAccount):
|
||||
# ServiceAccount: get roles from ServiceAccountRole
|
||||
role_ids = [sar.role_id for sar in principal.roles]
|
||||
else:
|
||||
return []
|
||||
|
||||
# Get permissions for each role from DB
|
||||
for role_id in role_ids:
|
||||
role_perms = (
|
||||
db.query(Permission.name)
|
||||
.join(RolePermission, RolePermission.permission_id == Permission.id)
|
||||
@@ -71,6 +86,7 @@ async def get_my_effective_policy(
|
||||
permissions = compute_effective_policy(user, db)
|
||||
return {
|
||||
"module_id": "request",
|
||||
"user_id": user.id,
|
||||
"principal_type": "user",
|
||||
"principal_id": user.id,
|
||||
"permissions": permissions,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
"""Service Account management API.
|
||||
|
||||
Module-owned API for Local Admin management.
|
||||
All endpoints require request.service_account.manage permission.
|
||||
Secret is returned only once at creation.
|
||||
List/Get never return credentials.
|
||||
"""
|
||||
|
||||
from typing import Optional, List
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import require_permission
|
||||
from request_app.core.service_account_auth import (
|
||||
create_credential,
|
||||
rotate_credential,
|
||||
revoke_credential,
|
||||
)
|
||||
from request_app.models.user import User
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_role import ServiceAccountRole
|
||||
from request_app.models.service_account_audit import ServiceAccountAuditEvent
|
||||
from request_app.models.role import Role
|
||||
|
||||
router = APIRouter(prefix="/service-accounts", tags=["Service Accounts"])
|
||||
|
||||
# Permission required for all management operations
|
||||
SA_MANAGE_PERMISSION = "request.service_account.manage"
|
||||
|
||||
|
||||
def _audit(db: Session, sa_id: int, event_type: str, message: str, performed_by: Optional[str] = None):
|
||||
"""Create audit event."""
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=sa_id,
|
||||
event_type=event_type,
|
||||
message=message,
|
||||
performed_by=performed_by,
|
||||
)
|
||||
db.add(audit)
|
||||
|
||||
|
||||
def _sa_to_dict(sa: ServiceAccount) -> dict:
|
||||
"""Convert ServiceAccount to dict (without secrets)."""
|
||||
return {
|
||||
"id": sa.id,
|
||||
"identifier": sa.identifier,
|
||||
"display_name": sa.display_name,
|
||||
"description": sa.description,
|
||||
"state": sa.state.value if hasattr(sa.state, 'value') else sa.state,
|
||||
"module_id": sa.module_id,
|
||||
"created_by": sa.created_by,
|
||||
"last_authenticated_at": sa.last_authenticated_at.isoformat() if sa.last_authenticated_at else None,
|
||||
"created_at": sa.created_at.isoformat() if sa.created_at else None,
|
||||
"updated_at": sa.updated_at.isoformat() if sa.updated_at else None,
|
||||
"roles": [r.role.name for r in sa.roles if r.role],
|
||||
}
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_service_account(
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""Create a new Service Account.
|
||||
|
||||
Returns credential ONLY at creation.
|
||||
Requires request.service_account.manage permission.
|
||||
"""
|
||||
identifier = data.get("identifier")
|
||||
display_name = data.get("display_name")
|
||||
description = data.get("description", "")
|
||||
|
||||
if not identifier or not display_name:
|
||||
raise HTTPException(status_code=400, detail="identifier and display_name required")
|
||||
|
||||
# Check unique identifier
|
||||
existing = db.query(ServiceAccount).filter(ServiceAccount.identifier == identifier).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="Identifier already exists")
|
||||
|
||||
# Create service account
|
||||
sa = ServiceAccount(
|
||||
identifier=identifier,
|
||||
display_name=display_name,
|
||||
description=description,
|
||||
state=ServiceAccountState.CREATED,
|
||||
module_id="request",
|
||||
created_by=current_user.email,
|
||||
)
|
||||
db.add(sa)
|
||||
db.flush()
|
||||
|
||||
# Create credential
|
||||
credential, secret = create_credential(db, sa, issued_by=current_user.email)
|
||||
|
||||
# Activate SA
|
||||
sa.state = ServiceAccountState.ACTIVE
|
||||
|
||||
# Audit
|
||||
_audit(db, sa.id, "created", f"Service Account created: {identifier}", current_user.email)
|
||||
_audit(db, sa.id, "activated", f"Service Account activated: {identifier}", current_user.email)
|
||||
|
||||
db.commit()
|
||||
db.refresh(sa)
|
||||
|
||||
return {
|
||||
"service_account": _sa_to_dict(sa),
|
||||
"credential": {
|
||||
"credential_id": credential.credential_id,
|
||||
"secret": secret, # SHOWN ONLY ONCE
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_service_accounts(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""List all Service Accounts. Never returns credentials."""
|
||||
sa_list = db.query(ServiceAccount).all()
|
||||
return {
|
||||
"service_accounts": [_sa_to_dict(sa) for sa in sa_list],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{sa_id}")
|
||||
async def get_service_account(
|
||||
sa_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""Get Service Account metadata. Never returns credentials."""
|
||||
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
|
||||
if not sa:
|
||||
raise HTTPException(status_code=404, detail="Service Account not found")
|
||||
return _sa_to_dict(sa)
|
||||
|
||||
|
||||
@router.post("/{sa_id}/disable")
|
||||
async def disable_service_account(
|
||||
sa_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""Disable Service Account (ACTIVE → DISABLED)."""
|
||||
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
|
||||
if not sa:
|
||||
raise HTTPException(status_code=404, detail="Service Account not found")
|
||||
|
||||
if not sa.can_transition_to(ServiceAccountState.DISABLED):
|
||||
raise HTTPException(status_code=400, detail=f"Cannot disable from state {sa.state}")
|
||||
|
||||
sa.state = ServiceAccountState.DISABLED
|
||||
_audit(db, sa.id, "disabled", f"Service Account disabled: {sa.identifier}", current_user.email)
|
||||
db.commit()
|
||||
|
||||
return _sa_to_dict(sa)
|
||||
|
||||
|
||||
@router.post("/{sa_id}/enable")
|
||||
async def enable_service_account(
|
||||
sa_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""Enable Service Account (DISABLED → ACTIVE)."""
|
||||
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
|
||||
if not sa:
|
||||
raise HTTPException(status_code=404, detail="Service Account not found")
|
||||
|
||||
if not sa.can_transition_to(ServiceAccountState.ACTIVE):
|
||||
raise HTTPException(status_code=400, detail=f"Cannot enable from state {sa.state}")
|
||||
|
||||
sa.state = ServiceAccountState.ACTIVE
|
||||
_audit(db, sa.id, "enabled", f"Service Account enabled: {sa.identifier}", current_user.email)
|
||||
db.commit()
|
||||
|
||||
return _sa_to_dict(sa)
|
||||
|
||||
|
||||
@router.post("/{sa_id}/revoke")
|
||||
async def revoke_service_account(
|
||||
sa_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""Revoke Service Account (terminal state)."""
|
||||
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
|
||||
if not sa:
|
||||
raise HTTPException(status_code=404, detail="Service Account not found")
|
||||
|
||||
if not sa.can_transition_to(ServiceAccountState.REVOKED):
|
||||
raise HTTPException(status_code=400, detail=f"Cannot revoke from state {sa.state}")
|
||||
|
||||
sa.state = ServiceAccountState.REVOKED
|
||||
_audit(db, sa.id, "revoked", f"Service Account revoked: {sa.identifier}", current_user.email)
|
||||
db.commit()
|
||||
|
||||
return _sa_to_dict(sa)
|
||||
|
||||
|
||||
@router.post("/{sa_id}/rotate-credential")
|
||||
async def rotate_sa_credential(
|
||||
sa_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""Rotate credential. Old credential is invalidated."""
|
||||
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
|
||||
if not sa:
|
||||
raise HTTPException(status_code=404, detail="Service Account not found")
|
||||
|
||||
if sa.state == ServiceAccountState.REVOKED:
|
||||
raise HTTPException(status_code=400, detail="Cannot rotate credential for revoked account")
|
||||
|
||||
credential, secret = rotate_credential(db, sa, issued_by=current_user.email)
|
||||
|
||||
return {
|
||||
"credential_id": credential.credential_id,
|
||||
"secret": secret, # SHOWN ONLY ONCE
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{sa_id}/roles")
|
||||
async def update_sa_roles(
|
||||
sa_id: int,
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_permission(SA_MANAGE_PERMISSION)),
|
||||
):
|
||||
"""Update Service Account roles."""
|
||||
sa = db.query(ServiceAccount).filter(ServiceAccount.id == sa_id).first()
|
||||
if not sa:
|
||||
raise HTTPException(status_code=404, detail="Service Account not found")
|
||||
|
||||
role_ids = data.get("role_ids", [])
|
||||
|
||||
# Remove existing roles
|
||||
db.query(ServiceAccountRole).filter(ServiceAccountRole.service_account_id == sa.id).delete()
|
||||
|
||||
# Add new roles
|
||||
for role_id in role_ids:
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if role:
|
||||
db.add(ServiceAccountRole(service_account_id=sa.id, role_id=role.id))
|
||||
_audit(db, sa.id, "role_assigned", f"Role assigned: {role.name}", current_user.email)
|
||||
|
||||
db.commit()
|
||||
db.refresh(sa)
|
||||
|
||||
return _sa_to_dict(sa)
|
||||
Reference in New Issue
Block a user