feat(request): add service accounts and unified authorization
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
"""Add Service Account tables
|
||||
|
||||
Revision ID: 002_add_service_accounts
|
||||
Revises: 001_add_permissions
|
||||
Create Date: 2026-08-06
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers
|
||||
revision = '002_add_service_accounts'
|
||||
down_revision = '001_add_permissions'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Create service_accounts table
|
||||
op.create_table(
|
||||
'service_accounts',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('identifier', sa.String(100), nullable=False),
|
||||
sa.Column('display_name', sa.String(200), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('state', sa.String(20), nullable=False, server_default='CREATED'),
|
||||
sa.Column('module_id', sa.String(50), nullable=False, server_default='request'),
|
||||
sa.Column('created_by', sa.String(200), nullable=True),
|
||||
sa.Column('last_authenticated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_service_accounts_id', 'service_accounts', ['id'])
|
||||
op.create_index('ix_service_accounts_identifier', 'service_accounts', ['identifier'], unique=True)
|
||||
|
||||
# Create service_account_credentials table
|
||||
op.create_table(
|
||||
'service_account_credentials',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('service_account_id', sa.Integer(), sa.ForeignKey('service_accounts.id', ondelete='CASCADE'), nullable=False),
|
||||
sa.Column('credential_id', sa.String(50), nullable=False),
|
||||
sa.Column('secret_hash', sa.String(255), nullable=False),
|
||||
sa.Column('state', sa.String(20), nullable=False, server_default='ACTIVE'),
|
||||
sa.Column('issued_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('expires_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('revoked_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('rotated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('issued_by', sa.String(200), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_service_account_credentials_id', 'service_account_credentials', ['id'])
|
||||
op.create_index('ix_service_account_credentials_credential_id', 'service_account_credentials', ['credential_id'], unique=True)
|
||||
|
||||
# Create service_account_roles table
|
||||
op.create_table(
|
||||
'service_account_roles',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('service_account_id', sa.Integer(), sa.ForeignKey('service_accounts.id', ondelete='CASCADE'), nullable=False),
|
||||
sa.Column('role_id', sa.Integer(), sa.ForeignKey('roles.id', ondelete='CASCADE'), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('service_account_id', 'role_id', name='uq_service_account_role'),
|
||||
)
|
||||
op.create_index('ix_service_account_roles_id', 'service_account_roles', ['id'])
|
||||
|
||||
# Create service_account_audit_events table
|
||||
op.create_table(
|
||||
'service_account_audit_events',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('service_account_id', sa.Integer(), sa.ForeignKey('service_accounts.id', ondelete='CASCADE'), nullable=False),
|
||||
sa.Column('event_type', sa.String(50), nullable=False),
|
||||
sa.Column('message', sa.Text(), nullable=False),
|
||||
sa.Column('performed_by', sa.String(200), nullable=True),
|
||||
sa.Column('extra_data', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_service_account_audit_events_id', 'service_account_audit_events', ['id'])
|
||||
op.create_index('ix_service_account_audit_events_service_account_id', 'service_account_audit_events', ['service_account_id'])
|
||||
op.create_index('ix_service_account_audit_events_event_type', 'service_account_audit_events', ['event_type'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table('service_account_audit_events')
|
||||
op.drop_table('service_account_roles')
|
||||
op.drop_table('service_account_credentials')
|
||||
op.drop_table('service_accounts')
|
||||
@@ -40,6 +40,7 @@ class RequestModule(BaseModule):
|
||||
health, auth, users, tickets,
|
||||
reference, notifications, emails,
|
||||
settings, notification_templates, permissions,
|
||||
service_accounts,
|
||||
)
|
||||
|
||||
module_router = APIRouter(prefix="/api/v1/request")
|
||||
@@ -53,6 +54,7 @@ class RequestModule(BaseModule):
|
||||
module_router.include_router(settings.router)
|
||||
module_router.include_router(notification_templates.router)
|
||||
module_router.include_router(permissions.router)
|
||||
module_router.include_router(service_accounts.router)
|
||||
|
||||
routers = [module_router]
|
||||
except Exception as e:
|
||||
|
||||
@@ -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)
|
||||
@@ -1,6 +1,10 @@
|
||||
"""Authentication dependencies for platform integration."""
|
||||
"""Authentication dependencies for platform integration.
|
||||
|
||||
from typing import List
|
||||
Unified authorization for User and ServiceAccount.
|
||||
Single require_permission() for all Principal types.
|
||||
"""
|
||||
|
||||
from typing import List, Union
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -9,6 +13,7 @@ from request_app.core.database import get_db
|
||||
from request_app.core.security import decode_platform_token, get_user_id_from_token
|
||||
from request_app.core.platform_client import PlatformUser, get_platform_client
|
||||
from request_app.models.user import User
|
||||
from request_app.models.service_account import ServiceAccount
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
@@ -75,6 +80,76 @@ def get_current_user(
|
||||
return user
|
||||
|
||||
|
||||
def get_current_service_account(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
db: Session = Depends(get_db),
|
||||
) -> ServiceAccount:
|
||||
"""Get current authenticated Service Account from credential.
|
||||
|
||||
Supports machine-to-machine authentication.
|
||||
Does NOT require Platform to be available.
|
||||
"""
|
||||
from request_app.core.service_account_auth import validate_credential
|
||||
|
||||
# Extract identifier and secret from credentials
|
||||
# Format: "identifier:secret" in Authorization header
|
||||
token = credentials.credentials
|
||||
if ":" not in token:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credential format")
|
||||
|
||||
identifier, secret = token.split(":", 1)
|
||||
|
||||
# Validate credential locally (no Platform call needed)
|
||||
sa = validate_credential(db, identifier, secret)
|
||||
if not sa:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credential")
|
||||
|
||||
return sa
|
||||
|
||||
|
||||
def get_current_principal(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
db: Session = Depends(get_db),
|
||||
) -> Union[User, ServiceAccount]:
|
||||
"""Get current authenticated Principal (User or ServiceAccount).
|
||||
|
||||
Tries User (JWT) first, then ServiceAccount (credential).
|
||||
Single entry point for authentication.
|
||||
|
||||
Only catches expected authentication failures (ValueError, JWTError).
|
||||
Unexpected errors are NOT silently swallowed.
|
||||
"""
|
||||
from request_app.core.service_account_auth import validate_credential
|
||||
from jose import JWTError
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
# Try User JWT first
|
||||
# Only catch expected authentication failures
|
||||
try:
|
||||
user_id = get_user_id_from_token(token)
|
||||
payload = decode_platform_token(token)
|
||||
if payload:
|
||||
user = _sync_platform_user_to_local(db, payload)
|
||||
if user.is_active:
|
||||
return user
|
||||
except ValueError:
|
||||
# Invalid token format or missing claims — expected
|
||||
pass
|
||||
except JWTError:
|
||||
# JWT decode failure — expected
|
||||
pass
|
||||
|
||||
# Try Service Account credential
|
||||
if ":" in token:
|
||||
identifier, secret = token.split(":", 1)
|
||||
sa = validate_credential(db, identifier, secret)
|
||||
if sa:
|
||||
return sa
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
||||
|
||||
|
||||
def get_current_platform_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> PlatformUser:
|
||||
@@ -120,25 +195,24 @@ def require_role(role_name: str):
|
||||
def require_permission(permission_id: str):
|
||||
"""Dependency factory: require a specific permission.
|
||||
|
||||
UNIFIED authorization for all Principal types (User and ServiceAccount).
|
||||
Authorization decision is made LOCALLY by Module.
|
||||
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),
|
||||
principal: Union[User, ServiceAccount] = Depends(get_current_principal),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
) -> Union[User, ServiceAccount]:
|
||||
# Use the single Module authorization engine (DB-driven)
|
||||
user_permissions = set(compute_effective_policy(current_user, db))
|
||||
permissions = set(compute_effective_policy(principal, db))
|
||||
|
||||
if permission_id not in user_permissions:
|
||||
if permission_id not in permissions:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Permission '{permission_id}' required",
|
||||
)
|
||||
return current_user
|
||||
return principal
|
||||
return _check_permission
|
||||
|
||||
@@ -42,6 +42,7 @@ _BOOTSTRAP_PERMISSIONS = [
|
||||
("request.admin", "Full administrative access"),
|
||||
("request.settings.manage", "Manage module settings"),
|
||||
("request.report.view", "View reports and statistics"),
|
||||
("request.service_account.manage", "Manage service accounts"),
|
||||
]
|
||||
|
||||
# Bootstrap role → permission mapping — used ONLY for seeding, NOT for runtime
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Service Account authentication utilities.
|
||||
|
||||
Provides credential creation, validation, and lifecycle management.
|
||||
Plaintext secret is NEVER stored.
|
||||
"""
|
||||
|
||||
import secrets
|
||||
import bcrypt
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
|
||||
from request_app.models.service_account_audit import ServiceAccountAuditEvent
|
||||
|
||||
|
||||
def generate_secret() -> str:
|
||||
"""Generate a cryptographically secure secret."""
|
||||
return secrets.token_urlsafe(48)
|
||||
|
||||
|
||||
def hash_secret(secret: str) -> str:
|
||||
"""Hash a secret using bcrypt."""
|
||||
return bcrypt.hashpw(secret.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_secret(secret: str, hashed: str) -> bool:
|
||||
"""Verify a secret against its hash."""
|
||||
try:
|
||||
return bcrypt.checkpw(secret.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_credential(
|
||||
db: Session,
|
||||
service_account: ServiceAccount,
|
||||
issued_by: Optional[str] = None,
|
||||
) -> Tuple[ServiceAccountCredential, str]:
|
||||
"""Create a new credential for a Service Account.
|
||||
|
||||
Policy: A ServiceAccount may have at most ONE ACTIVE credential.
|
||||
If an ACTIVE credential already exists, it is ROTATED first.
|
||||
|
||||
Returns (credential, plaintext_secret).
|
||||
Plaintext secret is shown ONLY at creation.
|
||||
"""
|
||||
# Revoke any existing ACTIVE credentials (policy: at most one ACTIVE)
|
||||
existing_active = (
|
||||
db.query(ServiceAccountCredential)
|
||||
.filter(
|
||||
ServiceAccountCredential.service_account_id == service_account.id,
|
||||
ServiceAccountCredential.state == CredentialState.ACTIVE,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for cred in existing_active:
|
||||
cred.state = CredentialState.ROTATED
|
||||
cred.rotated_at = datetime.utcnow()
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=service_account.id,
|
||||
event_type="credential_rotated",
|
||||
message=f"Credential rotated (new issued): {cred.credential_id}",
|
||||
performed_by=issued_by,
|
||||
)
|
||||
db.add(audit)
|
||||
|
||||
# Generate secret
|
||||
secret = generate_secret()
|
||||
secret_hash = hash_secret(secret)
|
||||
|
||||
# Generate unique credential ID
|
||||
credential_id = f"cred_{secrets.token_hex(16)}"
|
||||
|
||||
# Create credential
|
||||
credential = ServiceAccountCredential(
|
||||
service_account_id=service_account.id,
|
||||
credential_id=credential_id,
|
||||
secret_hash=secret_hash,
|
||||
state=CredentialState.ACTIVE,
|
||||
issued_by=issued_by,
|
||||
)
|
||||
db.add(credential)
|
||||
|
||||
# Audit event
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=service_account.id,
|
||||
event_type="credential_issued",
|
||||
message=f"Credential issued: {credential_id}",
|
||||
performed_by=issued_by,
|
||||
)
|
||||
db.add(audit)
|
||||
|
||||
db.commit()
|
||||
db.refresh(credential)
|
||||
|
||||
return credential, secret
|
||||
|
||||
|
||||
def validate_credential(
|
||||
db: Session,
|
||||
identifier: str,
|
||||
secret: str,
|
||||
) -> Optional[ServiceAccount]:
|
||||
"""Validate credential and return ServiceAccount if valid.
|
||||
|
||||
Returns None if validation fails.
|
||||
Does NOT require Platform to be available.
|
||||
"""
|
||||
# Find service account by identifier
|
||||
sa = db.query(ServiceAccount).filter(ServiceAccount.identifier == identifier).first()
|
||||
if not sa:
|
||||
return None
|
||||
|
||||
# Check lifecycle state
|
||||
if sa.state != ServiceAccountState.ACTIVE:
|
||||
# Audit failed attempt
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=sa.id,
|
||||
event_type="authentication_failure",
|
||||
message=f"Authentication failed: account state is {sa.state}",
|
||||
)
|
||||
db.add(audit)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
# Find active credential
|
||||
cred = (
|
||||
db.query(ServiceAccountCredential)
|
||||
.filter(
|
||||
ServiceAccountCredential.service_account_id == sa.id,
|
||||
ServiceAccountCredential.state == CredentialState.ACTIVE,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
if not cred or not cred.is_valid:
|
||||
# Audit failed attempt
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=sa.id,
|
||||
event_type="authentication_failure",
|
||||
message="Authentication failed: no valid credential",
|
||||
)
|
||||
db.add(audit)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
# Verify secret
|
||||
if not verify_secret(secret, cred.secret_hash):
|
||||
# Audit failed attempt
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=sa.id,
|
||||
event_type="authentication_failure",
|
||||
message="Authentication failed: invalid secret",
|
||||
)
|
||||
db.add(audit)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
# Update last authenticated
|
||||
sa.last_authenticated_at = datetime.utcnow()
|
||||
|
||||
# Audit success
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=sa.id,
|
||||
event_type="authentication_success",
|
||||
message="Authentication successful",
|
||||
)
|
||||
db.add(audit)
|
||||
db.commit()
|
||||
|
||||
return sa
|
||||
|
||||
|
||||
def rotate_credential(
|
||||
db: Session,
|
||||
service_account: ServiceAccount,
|
||||
issued_by: Optional[str] = None,
|
||||
) -> Tuple[ServiceAccountCredential, str]:
|
||||
"""Rotate credential: revoke old, create new.
|
||||
|
||||
Returns (new_credential, new_plaintext_secret).
|
||||
"""
|
||||
# Revoke all active credentials
|
||||
active_creds = (
|
||||
db.query(ServiceAccountCredential)
|
||||
.filter(
|
||||
ServiceAccountCredential.service_account_id == service_account.id,
|
||||
ServiceAccountCredential.state == CredentialState.ACTIVE,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
for cred in active_creds:
|
||||
cred.state = CredentialState.ROTATED
|
||||
cred.rotated_at = datetime.utcnow()
|
||||
|
||||
# Audit rotation of old credential
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=service_account.id,
|
||||
event_type="credential_rotated",
|
||||
message=f"Credential rotated: {cred.credential_id}",
|
||||
performed_by=issued_by,
|
||||
)
|
||||
db.add(audit)
|
||||
|
||||
# Create new credential
|
||||
return create_credential(db, service_account, issued_by)
|
||||
|
||||
|
||||
def revoke_credential(
|
||||
db: Session,
|
||||
credential: ServiceAccountCredential,
|
||||
revoked_by: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Revoke a specific credential."""
|
||||
credential.state = CredentialState.REVOKED
|
||||
credential.revoked_at = datetime.utcnow()
|
||||
|
||||
# Audit
|
||||
audit = ServiceAccountAuditEvent(
|
||||
service_account_id=credential.service_account_id,
|
||||
event_type="credential_revoked",
|
||||
message=f"Credential revoked: {credential.credential_id}",
|
||||
performed_by=revoked_by,
|
||||
)
|
||||
db.add(audit)
|
||||
db.commit()
|
||||
@@ -6,6 +6,10 @@ 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.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_role import ServiceAccountRole
|
||||
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
|
||||
from request_app.models.service_account_audit import ServiceAccountAuditEvent
|
||||
from request_app.models.priority import Priority
|
||||
from request_app.models.status import Status
|
||||
from request_app.models.category import Category
|
||||
@@ -27,6 +31,12 @@ __all__ = [
|
||||
"UserRole",
|
||||
"Permission",
|
||||
"RolePermission",
|
||||
"ServiceAccount",
|
||||
"ServiceAccountState",
|
||||
"ServiceAccountRole",
|
||||
"ServiceAccountCredential",
|
||||
"CredentialState",
|
||||
"ServiceAccountAuditEvent",
|
||||
"Priority",
|
||||
"Status",
|
||||
"Category",
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""ServiceAccount model — separate Principal type.
|
||||
|
||||
ServiceAccount is NOT a User subtype.
|
||||
It is a separate Principal for machine-to-machine authentication.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, String, Boolean, Integer, DateTime, Text, Enum as SQLEnum
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
import enum
|
||||
|
||||
|
||||
class ServiceAccountState(str, enum.Enum):
|
||||
"""Service Account lifecycle states."""
|
||||
CREATED = "CREATED"
|
||||
ACTIVE = "ACTIVE"
|
||||
DISABLED = "DISABLED"
|
||||
REVOKED = "REVOKED"
|
||||
|
||||
|
||||
class ServiceAccount(Base, TimestampMixin):
|
||||
"""Service Account — separate Principal for machine-to-machine auth.
|
||||
|
||||
This is NOT a User subtype. It is a separate entity type.
|
||||
Module-owned. Platform does not directly manage this.
|
||||
"""
|
||||
|
||||
__tablename__ = "service_accounts"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
# Stable identifier for API reference (not email)
|
||||
identifier = Column(String(100), unique=True, nullable=False, index=True)
|
||||
display_name = Column(String(200), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
|
||||
# Lifecycle state
|
||||
state = Column(
|
||||
SQLEnum(ServiceAccountState),
|
||||
nullable=False,
|
||||
default=ServiceAccountState.CREATED,
|
||||
)
|
||||
|
||||
# Module ownership
|
||||
module_id = Column(String(50), nullable=False, default="request")
|
||||
|
||||
# Audit metadata
|
||||
created_by = Column(String(200), nullable=True) # Who created this SA
|
||||
last_authenticated_at = Column(DateTime, nullable=True)
|
||||
|
||||
# Relationships
|
||||
credentials = relationship("ServiceAccountCredential", back_populates="service_account", cascade="all, delete-orphan")
|
||||
roles = relationship("ServiceAccountRole", back_populates="service_account", cascade="all, delete-orphan")
|
||||
audit_events = relationship("ServiceAccountAuditEvent", back_populates="service_account", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<ServiceAccount(id={self.id}, identifier='{self.identifier}', state='{self.state}')>"
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
"""Check if account can authenticate."""
|
||||
return self.state == ServiceAccountState.ACTIVE
|
||||
|
||||
@property
|
||||
def is_revoked(self) -> bool:
|
||||
"""Check if account is permanently revoked."""
|
||||
return self.state == ServiceAccountState.REVOKED
|
||||
|
||||
def can_transition_to(self, new_state: ServiceAccountState) -> bool:
|
||||
"""Check if transition to new_state is allowed."""
|
||||
allowed = {
|
||||
ServiceAccountState.CREATED: {ServiceAccountState.ACTIVE, ServiceAccountState.REVOKED},
|
||||
ServiceAccountState.ACTIVE: {ServiceAccountState.DISABLED, ServiceAccountState.REVOKED},
|
||||
ServiceAccountState.DISABLED: {ServiceAccountState.ACTIVE, ServiceAccountState.REVOKED},
|
||||
ServiceAccountState.REVOKED: set(), # Terminal state
|
||||
}
|
||||
return new_state in allowed.get(self.state, set())
|
||||
@@ -0,0 +1,38 @@
|
||||
"""ServiceAccountAuditEvent model — security audit trail.
|
||||
|
||||
Audit is accountability mechanism.
|
||||
NEVER log plaintext credentials or sensitive token material.
|
||||
"""
|
||||
|
||||
from sqlalchemy import Column, String, Integer, ForeignKey, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class ServiceAccountAuditEvent(Base, TimestampMixin):
|
||||
"""Security audit events for Service Account lifecycle.
|
||||
|
||||
Audit is accountability, NOT a defense against SQL tampering.
|
||||
"""
|
||||
|
||||
__tablename__ = "service_account_audit_events"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
service_account_id = Column(Integer, ForeignKey("service_accounts.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
|
||||
# Event type
|
||||
event_type = Column(String(50), nullable=False, index=True)
|
||||
# Types: created, activated, disabled, enabled, revoked,
|
||||
# credential_issued, credential_rotated, credential_revoked,
|
||||
# role_assigned, role_removed, authentication_success, authentication_failure
|
||||
|
||||
# Event details (NO secrets)
|
||||
message = Column(Text, nullable=False)
|
||||
performed_by = Column(String(200), nullable=True) # Who performed the action
|
||||
extra_data = Column(Text, nullable=True) # JSON for additional context (NO secrets)
|
||||
|
||||
# Relationships
|
||||
service_account = relationship("ServiceAccount", back_populates="audit_events")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<ServiceAccountAuditEvent(sa_id={self.service_account_id}, type='{self.event_type}')>"
|
||||
@@ -0,0 +1,65 @@
|
||||
"""ServiceAccountCredential model — credential storage.
|
||||
|
||||
Credentials are stored securely (hashed).
|
||||
Plaintext secret is NEVER stored.
|
||||
Secret is shown only once at creation.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Boolean, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
import enum
|
||||
|
||||
|
||||
class CredentialState(str, enum.Enum):
|
||||
"""Credential lifecycle states."""
|
||||
ACTIVE = "ACTIVE"
|
||||
ROTATED = "ROTATED"
|
||||
REVOKED = "REVOKED"
|
||||
|
||||
|
||||
class ServiceAccountCredential(Base, TimestampMixin):
|
||||
"""Service Account credential storage.
|
||||
|
||||
Stores hashed credential only.
|
||||
Plaintext secret is NEVER stored.
|
||||
"""
|
||||
|
||||
__tablename__ = "service_account_credentials"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
service_account_id = Column(Integer, ForeignKey("service_accounts.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
# Credential identifier (for rotation tracking)
|
||||
credential_id = Column(String(50), unique=True, nullable=False, index=True)
|
||||
|
||||
# Hashed secret (bcrypt or similar)
|
||||
secret_hash = Column(String(255), nullable=False)
|
||||
|
||||
# Credential state
|
||||
state = Column(String(20), nullable=False, default=CredentialState.ACTIVE)
|
||||
|
||||
# Lifecycle
|
||||
issued_at = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
expires_at = Column(DateTime, nullable=True) # NULL = no expiry
|
||||
revoked_at = Column(DateTime, nullable=True)
|
||||
rotated_at = Column(DateTime, nullable=True)
|
||||
|
||||
# Metadata
|
||||
issued_by = Column(String(200), nullable=True) # Who issued this credential
|
||||
|
||||
# Relationships
|
||||
service_account = relationship("ServiceAccount", back_populates="credentials")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<ServiceAccountCredential(id={self.credential_id}, state='{self.state}')>"
|
||||
|
||||
@property
|
||||
def is_valid(self) -> bool:
|
||||
"""Check if credential can be used for authentication."""
|
||||
if self.state != CredentialState.ACTIVE:
|
||||
return False
|
||||
if self.expires_at and datetime.utcnow() > self.expires_at:
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,34 @@
|
||||
"""ServiceAccountRole model — ServiceAccount → Role mapping.
|
||||
|
||||
This is the generic Principal → Role link for Service Accounts.
|
||||
Reuses existing Role model.
|
||||
"""
|
||||
|
||||
from sqlalchemy import Column, Integer, ForeignKey, UniqueConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class ServiceAccountRole(Base, TimestampMixin):
|
||||
"""ServiceAccountRole — links ServiceAccount to Role.
|
||||
|
||||
Reuses existing Role model for authorization.
|
||||
"""
|
||||
|
||||
__tablename__ = "service_account_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
service_account_id = Column(Integer, ForeignKey("service_accounts.id", ondelete="CASCADE"), nullable=False)
|
||||
role_id = Column(Integer, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
# Unique constraint: one SA can have each role only once
|
||||
__table_args__ = (
|
||||
UniqueConstraint("service_account_id", "role_id", name="uq_service_account_role"),
|
||||
)
|
||||
|
||||
# Relationships
|
||||
service_account = relationship("ServiceAccount", back_populates="roles")
|
||||
role = relationship("Role")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<ServiceAccountRole(sa_id={self.service_account_id}, role_id={self.role_id})>"
|
||||
@@ -178,7 +178,7 @@ def test_effective_policy_admin(seeded_db):
|
||||
perms = compute_effective_policy(user, seeded_db)
|
||||
|
||||
# Admin should have all permissions
|
||||
assert len(perms) == 10
|
||||
assert len(perms) == 11
|
||||
assert "request.read" in perms
|
||||
assert "request.create" in perms
|
||||
assert "request.delete" in perms
|
||||
@@ -334,7 +334,8 @@ def test_catalog_reads_from_db(seeded_db):
|
||||
assert "request.read" in perm_names
|
||||
assert "request.create" in perm_names
|
||||
assert "request.delete" in perm_names
|
||||
assert len(perm_names) == 10
|
||||
assert "request.service_account.manage" in perm_names
|
||||
assert len(perm_names) == 11
|
||||
|
||||
|
||||
def test_catalog_reflects_db_changes(seeded_db):
|
||||
|
||||
@@ -0,0 +1,849 @@
|
||||
"""Service Account Tests — TT-008
|
||||
|
||||
Real behavioral tests proving runtime authorization behavior.
|
||||
Tests invoke actual require_permission() and management API endpoints.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from fastapi import FastAPI, HTTPException, Depends
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
# Compute absolute paths
|
||||
_MODULE_ROOT = Path(__file__).parent.parent.parent.resolve()
|
||||
_PLATFORM_BACKEND = _MODULE_ROOT.parent.parent / "platform" / "backend"
|
||||
|
||||
# Add platform SDK to path
|
||||
if str(_PLATFORM_BACKEND) not in sys.path:
|
||||
sys.path.insert(0, str(_PLATFORM_BACKEND))
|
||||
|
||||
# Add module root to path
|
||||
if str(_MODULE_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_MODULE_ROOT))
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def db_engine():
|
||||
"""Create a fresh file-based SQLite database for each test."""
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
# Use file-based SQLite (in-memory doesn't work with multiple connections)
|
||||
db_file = tempfile.mktemp(suffix='.db')
|
||||
engine = create_engine(f"sqlite:///{db_file}", connect_args={"check_same_thread": False})
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def set_sqlite_pragma(dbapi_connection, connection_record):
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
from request_app.models.base import Base
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
yield engine
|
||||
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
engine.dispose()
|
||||
|
||||
# Cleanup
|
||||
if os.path.exists(db_file):
|
||||
os.remove(db_file)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def db_session(db_engine):
|
||||
"""Provide a database session for each test."""
|
||||
Session = sessionmaker(bind=db_engine)
|
||||
db = Session()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.rollback()
|
||||
db.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def seeded_db(db_session):
|
||||
"""Seed the database with default data."""
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.permission import Permission
|
||||
from request_app.models.role_permission import RolePermission
|
||||
from request_app.core.database import _seed_permissions, _seed_role_permissions
|
||||
|
||||
# Create default roles
|
||||
default_roles = [
|
||||
("admin", "Administrator", True),
|
||||
("manager", "Manager", True),
|
||||
("support_agent", "Support agent", True),
|
||||
("customer", "Customer", True),
|
||||
]
|
||||
for name, desc, is_system in default_roles:
|
||||
if not db_session.query(Role).filter(Role.name == name).first():
|
||||
db_session.add(Role(name=name, description=desc, is_system=is_system))
|
||||
db_session.flush()
|
||||
|
||||
_seed_permissions(db_session)
|
||||
db_session.flush()
|
||||
|
||||
_seed_role_permissions(db_session)
|
||||
db_session.commit()
|
||||
|
||||
return db_session
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_app(db_engine):
|
||||
"""Create a test FastAPI app with Service Account management endpoints."""
|
||||
from request_app.api.v1.routes.service_accounts import router as sa_router
|
||||
from request_app.core.database import get_db
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(sa_router)
|
||||
|
||||
Session = sessionmaker(bind=db_engine)
|
||||
|
||||
def override_get_db():
|
||||
db = Session()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_client(test_app):
|
||||
"""Create a test client."""
|
||||
return TestClient(test_app)
|
||||
|
||||
|
||||
# === MODEL TESTS ===
|
||||
|
||||
def test_service_account_model_exists():
|
||||
"""Test that ServiceAccount model exists."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
assert ServiceAccount.__tablename__ == "service_accounts"
|
||||
assert hasattr(ServiceAccount, 'identifier')
|
||||
assert hasattr(ServiceAccount, 'display_name')
|
||||
assert hasattr(ServiceAccount, 'state')
|
||||
|
||||
|
||||
def test_service_account_credential_model_exists():
|
||||
"""Test that ServiceAccountCredential model exists."""
|
||||
from request_app.models.service_account_credential import ServiceAccountCredential
|
||||
assert ServiceAccountCredential.__tablename__ == "service_account_credentials"
|
||||
assert hasattr(ServiceAccountCredential, 'credential_id')
|
||||
assert hasattr(ServiceAccountCredential, 'secret_hash')
|
||||
|
||||
|
||||
def test_service_account_role_model_exists():
|
||||
"""Test that ServiceAccountRole model exists."""
|
||||
from request_app.models.service_account_role import ServiceAccountRole
|
||||
assert ServiceAccountRole.__tablename__ == "service_account_roles"
|
||||
|
||||
|
||||
def test_service_account_audit_model_exists():
|
||||
"""Test that ServiceAccountAuditEvent model exists."""
|
||||
from request_app.models.service_account_audit import ServiceAccountAuditEvent
|
||||
assert ServiceAccountAuditEvent.__tablename__ == "service_account_audit_events"
|
||||
|
||||
|
||||
def test_service_account_lifecycle_states():
|
||||
"""Test that lifecycle states are defined."""
|
||||
from request_app.models.service_account import ServiceAccountState
|
||||
assert ServiceAccountState.CREATED == "CREATED"
|
||||
assert ServiceAccountState.ACTIVE == "ACTIVE"
|
||||
assert ServiceAccountState.DISABLED == "DISABLED"
|
||||
assert ServiceAccountState.REVOKED == "REVOKED"
|
||||
|
||||
|
||||
def test_service_account_creation(seeded_db):
|
||||
"""Test Service Account creation."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
|
||||
sa = ServiceAccount(
|
||||
identifier="test-sa",
|
||||
display_name="Test Service Account",
|
||||
state=ServiceAccountState.CREATED,
|
||||
)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.commit()
|
||||
|
||||
assert sa.id is not None
|
||||
assert sa.identifier == "test-sa"
|
||||
assert sa.state == ServiceAccountState.CREATED
|
||||
|
||||
|
||||
def test_service_account_unique_identifier(seeded_db):
|
||||
"""Test that identifier is unique."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
sa1 = ServiceAccount(identifier="unique-sa", display_name="SA 1", state=ServiceAccountState.CREATED)
|
||||
seeded_db.add(sa1)
|
||||
seeded_db.commit()
|
||||
|
||||
sa2 = ServiceAccount(identifier="unique-sa", display_name="SA 2", state=ServiceAccountState.CREATED)
|
||||
seeded_db.add(sa2)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
seeded_db.commit()
|
||||
|
||||
|
||||
def test_service_account_lifecycle_transitions():
|
||||
"""Test lifecycle state transitions."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
|
||||
sa = ServiceAccount(identifier="test", display_name="Test", state=ServiceAccountState.CREATED)
|
||||
|
||||
# CREATED → ACTIVE
|
||||
assert sa.can_transition_to(ServiceAccountState.ACTIVE)
|
||||
assert sa.can_transition_to(ServiceAccountState.REVOKED)
|
||||
assert not sa.can_transition_to(ServiceAccountState.DISABLED)
|
||||
|
||||
# ACTIVE → DISABLED
|
||||
sa.state = ServiceAccountState.ACTIVE
|
||||
assert sa.can_transition_to(ServiceAccountState.DISABLED)
|
||||
assert sa.can_transition_to(ServiceAccountState.REVOKED)
|
||||
|
||||
# DISABLED → ACTIVE
|
||||
sa.state = ServiceAccountState.DISABLED
|
||||
assert sa.can_transition_to(ServiceAccountState.ACTIVE)
|
||||
assert sa.can_transition_to(ServiceAccountState.REVOKED)
|
||||
|
||||
# REVOKED is terminal
|
||||
sa.state = ServiceAccountState.REVOKED
|
||||
assert not sa.can_transition_to(ServiceAccountState.ACTIVE)
|
||||
assert not sa.can_transition_to(ServiceAccountState.DISABLED)
|
||||
|
||||
|
||||
def test_revoked_is_terminal(seeded_db):
|
||||
"""Test that REVOKED is terminal state."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
|
||||
sa = ServiceAccount(identifier="revoked-sa", display_name="Revoked", state=ServiceAccountState.REVOKED)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.commit()
|
||||
|
||||
assert sa.is_revoked
|
||||
assert not sa.is_active
|
||||
assert not sa.can_transition_to(ServiceAccountState.ACTIVE)
|
||||
|
||||
|
||||
# === CREDENTIAL TESTS ===
|
||||
|
||||
def test_credential_creation(seeded_db):
|
||||
"""Test credential creation."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.core.service_account_auth import create_credential
|
||||
|
||||
sa = ServiceAccount(identifier="cred-sa", display_name="Cred SA", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
credential, secret = create_credential(seeded_db, sa)
|
||||
|
||||
assert credential.id is not None
|
||||
assert credential.credential_id.startswith("cred_")
|
||||
assert secret # Secret is returned
|
||||
assert credential.secret_hash != secret # Hash is different from secret
|
||||
assert credential.state == "ACTIVE"
|
||||
|
||||
|
||||
def test_credential_one_time_secret(seeded_db):
|
||||
"""Test that secret is only available at creation."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.core.service_account_auth import create_credential
|
||||
|
||||
sa = ServiceAccount(identifier="onetime-sa", display_name="OneTime", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
credential, secret = create_credential(seeded_db, sa)
|
||||
|
||||
# Secret is returned at creation
|
||||
assert secret
|
||||
assert len(secret) > 20
|
||||
|
||||
# Secret is NOT stored (hash is stored)
|
||||
assert credential.secret_hash != secret
|
||||
|
||||
|
||||
def test_credential_validation(seeded_db):
|
||||
"""Test credential validation."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.core.service_account_auth import create_credential, validate_credential
|
||||
|
||||
sa = ServiceAccount(identifier="valid-sa", display_name="Valid", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
credential, secret = create_credential(seeded_db, sa)
|
||||
|
||||
# Valid credential
|
||||
result = validate_credential(seeded_db, "valid-sa", secret)
|
||||
assert result is not None
|
||||
assert result.id == sa.id
|
||||
|
||||
|
||||
def test_credential_invalid_secret(seeded_db):
|
||||
"""Test invalid secret fails validation."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.core.service_account_auth import create_credential, validate_credential
|
||||
|
||||
sa = ServiceAccount(identifier="invalid-sa", display_name="Invalid", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
create_credential(seeded_db, sa)
|
||||
|
||||
# Invalid secret
|
||||
result = validate_credential(seeded_db, "invalid-sa", "wrong-secret")
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_disabled_account_cannot_authenticate(seeded_db):
|
||||
"""Test disabled account cannot authenticate."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.core.service_account_auth import create_credential, validate_credential
|
||||
|
||||
sa = ServiceAccount(identifier="disabled-sa", display_name="Disabled", state=ServiceAccountState.DISABLED)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
_, secret = create_credential(seeded_db, sa)
|
||||
|
||||
result = validate_credential(seeded_db, "disabled-sa", secret)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_revoked_account_cannot_authenticate(seeded_db):
|
||||
"""Test revoked account cannot authenticate."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.core.service_account_auth import create_credential, validate_credential
|
||||
|
||||
sa = ServiceAccount(identifier="revoked-sa", display_name="Revoked", state=ServiceAccountState.REVOKED)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
_, secret = create_credential(seeded_db, sa)
|
||||
|
||||
result = validate_credential(seeded_db, "revoked-sa", secret)
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_credential_rotation(seeded_db):
|
||||
"""Test credential rotation."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
|
||||
from request_app.core.service_account_auth import create_credential, rotate_credential, validate_credential
|
||||
|
||||
sa = ServiceAccount(identifier="rotate-sa", display_name="Rotate", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
# Create initial credential
|
||||
cred1, secret1 = create_credential(seeded_db, sa)
|
||||
|
||||
# Rotate
|
||||
cred2, secret2 = rotate_credential(seeded_db, sa)
|
||||
|
||||
# Old credential should be rotated
|
||||
assert cred1.state == CredentialState.ROTATED
|
||||
|
||||
# New credential should be active
|
||||
assert cred2.state == CredentialState.ACTIVE
|
||||
|
||||
# Old secret should not work
|
||||
result = validate_credential(seeded_db, "rotate-sa", secret1)
|
||||
assert result is None
|
||||
|
||||
# New secret should work
|
||||
result = validate_credential(seeded_db, "rotate-sa", secret2)
|
||||
assert result is not None
|
||||
|
||||
|
||||
def test_plaintext_not_stored(seeded_db):
|
||||
"""Test that plaintext secret is never stored in DB."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_credential import ServiceAccountCredential
|
||||
from request_app.core.service_account_auth import create_credential
|
||||
|
||||
sa = ServiceAccount(identifier="plaintext-sa", display_name="Plaintext", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
_, secret = create_credential(seeded_db, sa)
|
||||
|
||||
# Check DB directly
|
||||
cred = seeded_db.query(ServiceAccountCredential).filter(
|
||||
ServiceAccountCredential.service_account_id == sa.id
|
||||
).first()
|
||||
|
||||
# secret_hash should NOT equal the plaintext secret
|
||||
assert cred.secret_hash != secret
|
||||
assert len(cred.secret_hash) > 20 # bcrypt hash is long
|
||||
|
||||
|
||||
# === REAL require_permission() BEHAVIORAL TESTS ===
|
||||
|
||||
def test_user_require_permission_allow(seeded_db):
|
||||
"""Test that User with permission passes require_permission().
|
||||
|
||||
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
|
||||
"""
|
||||
from request_app.models.user import User
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.role import Role
|
||||
from request_app.core.auth import require_permission
|
||||
|
||||
# Create user with admin role (has all permissions)
|
||||
user = User(email="perm-admin@test.com", first_name="Admin", last_name="User", source="local")
|
||||
seeded_db.add(user)
|
||||
seeded_db.flush()
|
||||
|
||||
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
|
||||
seeded_db.add(UserRole(user_id=user.id, role_id=admin_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Get the dependency function from require_permission
|
||||
# require_permission() returns _check_permission function
|
||||
# We need to call it directly with principal and db
|
||||
checker = require_permission("request.read")
|
||||
|
||||
# The returned function is _check_permission(principal, db)
|
||||
# Call it directly (not through FastAPI DI)
|
||||
result = checker(user, seeded_db)
|
||||
assert result.id == user.id
|
||||
|
||||
|
||||
def test_user_require_permission_deny(seeded_db):
|
||||
"""Test that User without permission fails require_permission().
|
||||
|
||||
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
|
||||
"""
|
||||
from request_app.models.user import User
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.role import Role
|
||||
from request_app.core.auth import require_permission
|
||||
|
||||
# Create user with customer role (limited permissions)
|
||||
user = User(email="perm-customer@test.com", first_name="Customer", last_name="User", source="local")
|
||||
seeded_db.add(user)
|
||||
seeded_db.flush()
|
||||
|
||||
customer_role = seeded_db.query(Role).filter(Role.name == "customer").first()
|
||||
seeded_db.add(UserRole(user_id=user.id, role_id=customer_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Get the dependency function
|
||||
checker = require_permission("request.admin")
|
||||
|
||||
# Should raise HTTPException 403
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
checker(user, seeded_db)
|
||||
assert exc_info.value.status_code == 403
|
||||
|
||||
|
||||
def test_service_account_require_permission_allow(seeded_db):
|
||||
"""Test that ServiceAccount with permission passes require_permission().
|
||||
|
||||
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
|
||||
"""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_role import ServiceAccountRole
|
||||
from request_app.models.role import Role
|
||||
from request_app.core.auth import require_permission
|
||||
|
||||
# Create SA with admin role
|
||||
sa = ServiceAccount(identifier="perm-sa-admin", display_name="PermAdmin", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
|
||||
seeded_db.add(ServiceAccountRole(service_account_id=sa.id, role_id=admin_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Get the dependency function
|
||||
checker = require_permission("request.read")
|
||||
|
||||
# Call the inner function directly
|
||||
result = checker(sa, seeded_db)
|
||||
assert result.id == sa.id
|
||||
|
||||
|
||||
def test_service_account_require_permission_deny(seeded_db):
|
||||
"""Test that ServiceAccount without permission fails require_permission().
|
||||
|
||||
REAL BEHAVIORAL TEST: invokes actual require_permission() dependency.
|
||||
"""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_role import ServiceAccountRole
|
||||
from request_app.models.role import Role
|
||||
from request_app.core.auth import require_permission
|
||||
|
||||
# Create SA with customer role (limited permissions)
|
||||
sa = ServiceAccount(identifier="perm-sa-customer", display_name="PermCustomer", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
customer_role = seeded_db.query(Role).filter(Role.name == "customer").first()
|
||||
seeded_db.add(ServiceAccountRole(service_account_id=sa.id, role_id=customer_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Get the dependency function
|
||||
checker = require_permission("request.admin")
|
||||
|
||||
# Should raise HTTPException 403
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
checker(sa, seeded_db)
|
||||
assert exc_info.value.status_code == 403
|
||||
|
||||
|
||||
def test_user_and_sa_same_authorization_semantics(seeded_db):
|
||||
"""Test that User and ServiceAccount use the same require_permission() semantics.
|
||||
|
||||
REAL BEHAVIORAL TEST: both go through require_permission().
|
||||
"""
|
||||
from request_app.models.user import User
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_role import ServiceAccountRole
|
||||
from request_app.models.role import Role
|
||||
from request_app.core.auth import require_permission
|
||||
|
||||
# Create User with manager role
|
||||
user = User(email="same-auth-user@test.com", first_name="User", last_name="Test", source="local")
|
||||
seeded_db.add(user)
|
||||
seeded_db.flush()
|
||||
|
||||
manager_role = seeded_db.query(Role).filter(Role.name == "manager").first()
|
||||
seeded_db.add(UserRole(user_id=user.id, role_id=manager_role.id))
|
||||
|
||||
# Create SA with manager role
|
||||
sa = ServiceAccount(identifier="same-auth-sa", display_name="SameAuthSA", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
seeded_db.add(ServiceAccountRole(service_account_id=sa.id, role_id=manager_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Both should pass request.read
|
||||
checker_allow = require_permission("request.read")
|
||||
checker_allow(user, seeded_db) # Should not raise
|
||||
checker_allow(sa, seeded_db) # Should not raise
|
||||
|
||||
# Both should fail request.admin
|
||||
checker_deny = require_permission("request.admin")
|
||||
with pytest.raises(HTTPException):
|
||||
checker_deny(user, seeded_db)
|
||||
with pytest.raises(HTTPException):
|
||||
checker_deny(sa, seeded_db)
|
||||
|
||||
|
||||
# === MANAGEMENT API ENDPOINT TESTS ===
|
||||
|
||||
def test_management_api_create_deny(seeded_db, db_engine):
|
||||
"""Test that authenticated user without SA management permission gets 403 on POST /service-accounts.
|
||||
|
||||
REAL ENDPOINT TEST: authenticated user + missing permission → exactly 403.
|
||||
"""
|
||||
from request_app.models.user import User
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.role import Role
|
||||
from request_app.api.v1.routes.service_accounts import router as sa_router
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.security import create_local_token
|
||||
|
||||
# Create user with customer role (no SA management permission)
|
||||
user = User(email="no-sa-perm@test.com", first_name="NoPerm", last_name="User", source="local")
|
||||
seeded_db.add(user)
|
||||
seeded_db.flush()
|
||||
|
||||
customer_role = seeded_db.query(Role).filter(Role.name == "customer").first()
|
||||
seeded_db.add(UserRole(user_id=user.id, role_id=customer_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Create test app with the same DB engine
|
||||
app = FastAPI()
|
||||
app.include_router(sa_router)
|
||||
|
||||
Session = sessionmaker(bind=db_engine)
|
||||
|
||||
def override_get_db():
|
||||
db = Session()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
client = TestClient(app)
|
||||
|
||||
# Create a valid token for this user (authenticated, but no SA permission)
|
||||
token = create_local_token(user.id, user.email)
|
||||
|
||||
# Try to create SA without permission
|
||||
response = client.post(
|
||||
"/service-accounts",
|
||||
json={"identifier": "test-sa", "display_name": "Test SA"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
|
||||
# Authenticated user without permission → exactly 403
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_management_api_create_allow(seeded_db, db_engine):
|
||||
"""Test that admin user can successfully create a Service Account.
|
||||
|
||||
REAL ENDPOINT TEST: authenticated admin + has permission → 201 success.
|
||||
"""
|
||||
from request_app.models.user import User
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.role import Role
|
||||
from request_app.api.v1.routes.service_accounts import router as sa_router
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.security import create_local_token
|
||||
|
||||
# Create user with admin role (has SA management permission)
|
||||
user = User(email="sa-admin@test.com", first_name="Admin", last_name="User", source="local")
|
||||
seeded_db.add(user)
|
||||
seeded_db.flush()
|
||||
|
||||
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
|
||||
seeded_db.add(UserRole(user_id=user.id, role_id=admin_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Create test app with the same DB engine
|
||||
app = FastAPI()
|
||||
app.include_router(sa_router)
|
||||
|
||||
Session = sessionmaker(bind=db_engine)
|
||||
|
||||
def override_get_db():
|
||||
db = Session()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
client = TestClient(app)
|
||||
|
||||
# Create a token for this user
|
||||
token = create_local_token(user.id, user.email)
|
||||
|
||||
# Try to create SA with permission
|
||||
response = client.post(
|
||||
"/service-accounts",
|
||||
json={"identifier": "test-sa", "display_name": "Test SA"},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
|
||||
# Admin with permission → 201 Created
|
||||
assert response.status_code == 201
|
||||
|
||||
# Verify response contains Service Account data
|
||||
data = response.json()
|
||||
assert "service_account" in data
|
||||
assert data["service_account"]["identifier"] == "test-sa"
|
||||
assert "credential" in data
|
||||
assert "secret" in data["credential"]
|
||||
|
||||
|
||||
def test_management_api_endpoints_wired(seeded_db):
|
||||
"""Test that all management endpoints are wired to require_permission dependency.
|
||||
|
||||
FASTAPI DEPENDENCY GRAPH INSPECTION: verifies actual dependency wiring.
|
||||
Each endpoint must be protected by require_permission("request.service_account.manage").
|
||||
"""
|
||||
from request_app.api.v1.routes.service_accounts import router
|
||||
|
||||
# Expected endpoints
|
||||
expected_endpoints = {
|
||||
("POST", "/service-accounts"),
|
||||
("GET", "/service-accounts"),
|
||||
("GET", "/service-accounts/{sa_id}"),
|
||||
("POST", "/service-accounts/{sa_id}/disable"),
|
||||
("POST", "/service-accounts/{sa_id}/enable"),
|
||||
("POST", "/service-accounts/{sa_id}/revoke"),
|
||||
("POST", "/service-accounts/{sa_id}/rotate-credential"),
|
||||
("PUT", "/service-accounts/{sa_id}/roles"),
|
||||
}
|
||||
|
||||
# Collect actual endpoints from router
|
||||
actual_endpoints = set()
|
||||
for route in router.routes:
|
||||
for method in route.methods:
|
||||
actual_endpoints.add((method, route.path))
|
||||
|
||||
# Verify all expected endpoints exist
|
||||
for expected in expected_endpoints:
|
||||
assert expected in actual_endpoints, f"Missing endpoint: {expected}"
|
||||
|
||||
# Helper function to check if a callable is a require_permission closure
|
||||
# capturing "request.service_account.manage"
|
||||
def is_sa_permission_dep(func):
|
||||
"""Check if func is a require_permission closure for SA management."""
|
||||
if func is None:
|
||||
return False
|
||||
# Check if it's a closure (require_permission returns a closure)
|
||||
if hasattr(func, '__closure__') and func.__closure__:
|
||||
for cell in func.__closure__:
|
||||
try:
|
||||
val = cell.cell_contents
|
||||
if val == "request.service_account.manage":
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
return False
|
||||
|
||||
# Helper function to recursively search dependencies
|
||||
def find_permission_dep(deps):
|
||||
"""Search for the SA management permission dependency in dependency tree."""
|
||||
for dep in deps:
|
||||
# Check the callable directly
|
||||
if hasattr(dep, 'call') and is_sa_permission_dep(dep.call):
|
||||
return True
|
||||
# Check sub-dependencies recursively
|
||||
if hasattr(dep, 'dependencies'):
|
||||
if find_permission_dep(dep.dependencies):
|
||||
return True
|
||||
return False
|
||||
|
||||
# Verify each endpoint has the permission dependency
|
||||
for route in router.routes:
|
||||
if not hasattr(route, 'dependant'):
|
||||
continue
|
||||
|
||||
deps = route.dependant.dependencies
|
||||
|
||||
# Find which methods this route handles
|
||||
methods = route.methods if hasattr(route, 'methods') else {'GET'}
|
||||
path = route.path
|
||||
|
||||
# Verify the permission dependency exists
|
||||
has_permission_dep = find_permission_dep(deps)
|
||||
|
||||
assert has_permission_dep, (
|
||||
f"{methods} {path} is not protected by "
|
||||
f"require_permission('request.service_account.manage')"
|
||||
)
|
||||
|
||||
|
||||
# === SINGLE ACTIVE CREDENTIAL TESTS ===
|
||||
|
||||
def test_single_active_credential(seeded_db):
|
||||
"""Test that only one ACTIVE credential can exist at a time."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
|
||||
from request_app.core.service_account_auth import create_credential
|
||||
|
||||
sa = ServiceAccount(identifier="single-cred-sa", display_name="SingleCred", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
# Create first credential
|
||||
cred1, secret1 = create_credential(seeded_db, sa)
|
||||
assert cred1.state == CredentialState.ACTIVE
|
||||
|
||||
# Create second credential (should rotate first)
|
||||
cred2, secret2 = create_credential(seeded_db, sa)
|
||||
assert cred2.state == CredentialState.ACTIVE
|
||||
|
||||
# Refresh first credential
|
||||
seeded_db.refresh(cred1)
|
||||
assert cred1.state == CredentialState.ROTATED
|
||||
|
||||
# Count ACTIVE credentials
|
||||
active_count = seeded_db.query(ServiceAccountCredential).filter(
|
||||
ServiceAccountCredential.service_account_id == sa.id,
|
||||
ServiceAccountCredential.state == CredentialState.ACTIVE,
|
||||
).count()
|
||||
assert active_count == 1
|
||||
|
||||
|
||||
def test_rotation_leaves_one_active(seeded_db):
|
||||
"""Test that rotation leaves exactly one ACTIVE credential."""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.models.service_account_credential import ServiceAccountCredential, CredentialState
|
||||
from request_app.core.service_account_auth import create_credential, rotate_credential
|
||||
|
||||
sa = ServiceAccount(identifier="rotate-single-sa", display_name="RotateSingle", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
# Create initial credential
|
||||
cred1, _ = create_credential(seeded_db, sa)
|
||||
|
||||
# Rotate
|
||||
cred2, _ = rotate_credential(seeded_db, sa)
|
||||
|
||||
# Count ACTIVE credentials
|
||||
active_count = seeded_db.query(ServiceAccountCredential).filter(
|
||||
ServiceAccountCredential.service_account_id == sa.id,
|
||||
ServiceAccountCredential.state == CredentialState.ACTIVE,
|
||||
).count()
|
||||
assert active_count == 1
|
||||
assert cred2.state == CredentialState.ACTIVE
|
||||
|
||||
|
||||
# === PLATFORM INDEPENDENCE TEST ===
|
||||
|
||||
def test_validate_credential_is_platform_independent(seeded_db):
|
||||
"""Test that validate_credential() works without any Platform dependency.
|
||||
|
||||
Evidence boundary: validates credential → ServiceAccount, no HTTP calls.
|
||||
"""
|
||||
from request_app.models.service_account import ServiceAccount, ServiceAccountState
|
||||
from request_app.core.service_account_auth import create_credential, validate_credential
|
||||
|
||||
sa = ServiceAccount(identifier="platform-independent-sa", display_name="Offline", state=ServiceAccountState.ACTIVE)
|
||||
seeded_db.add(sa)
|
||||
seeded_db.flush()
|
||||
|
||||
_, secret = create_credential(seeded_db, sa)
|
||||
|
||||
# Validation works without Platform (no HTTP calls in this path)
|
||||
result = validate_credential(seeded_db, "platform-independent-sa", secret)
|
||||
assert result is not None
|
||||
assert result.id == sa.id
|
||||
|
||||
|
||||
# === CATALOG/POLICY TESTS ===
|
||||
|
||||
def test_management_api_permission_in_catalog(seeded_db):
|
||||
"""Test that request.service_account.manage permission exists in catalog."""
|
||||
from request_app.models.permission import Permission
|
||||
|
||||
perm = seeded_db.query(Permission).filter(Permission.name == "request.service_account.manage").first()
|
||||
assert perm is not None
|
||||
assert perm.is_system == True
|
||||
|
||||
|
||||
def test_admin_has_sa_manage_permission(seeded_db):
|
||||
"""Test that admin role has request.service_account.manage permission."""
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.user import User
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.api.v1.routes.permissions import compute_effective_policy
|
||||
|
||||
# Create admin user
|
||||
user = User(email="admin@test.com", first_name="Admin", last_name="User", source="local")
|
||||
seeded_db.add(user)
|
||||
seeded_db.flush()
|
||||
|
||||
admin_role = seeded_db.query(Role).filter(Role.name == "admin").first()
|
||||
seeded_db.add(UserRole(user_id=user.id, role_id=admin_role.id))
|
||||
seeded_db.commit()
|
||||
|
||||
# Check permissions
|
||||
perms = compute_effective_policy(user, seeded_db)
|
||||
assert "request.service_account.manage" in perms
|
||||
Reference in New Issue
Block a user