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