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)
|
||||
@@ -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})>"
|
||||
Reference in New Issue
Block a user