"""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"" @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