feat(request): add service accounts and unified authorization
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user