Files
saas_backend/app/models/auth/identity_model.py
T
2026-08-31 20:39:41 -04:00

178 lines
6.1 KiB
Python

"""Signing in with somebody else's identity provider.
Until now "SSO" in this codebase meant the platform signing users *into modules*
— an outbound handoff. This is the other direction, and the one enterprise
customers mean: a workspace points at its own Azure AD, Okta or Google, and its
people sign in there rather than holding a password here.
Three tables:
- `identity_providers` — one per workspace per provider. Holds the OIDC issuer
and client credentials, and the endpoints discovered from it.
- `user_identities` — which account at the provider is which account here. Keyed
on the provider's `sub`, never on the email address, because an address can be
reassigned to a different person and `sub` cannot.
- `sso_login_states` — the in-flight half of a login: the PKCE verifier, the
nonce, and where to go afterwards. Short-lived and single-use.
"""
import enum
import uuid
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
String,
Text,
UniqueConstraint,
func,
)
from sqlalchemy.dialects.postgresql import UUID
from app.config.database import Base
class IdentityProviderKind(str, enum.Enum):
OIDC = "OIDC"
SAML = "SAML"
class IdentityProvider(Base):
"""A workspace's connection to its own identity provider."""
__tablename__ = "identity_providers"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id = Column(
UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"),
nullable=False, index=True,
)
kind = Column(String(10), nullable=False, default=IdentityProviderKind.OIDC.value)
name = Column(String(150), nullable=False)
slug = Column(String(100), nullable=False)
enabled = Column(Boolean, nullable=False, default=False)
issuer = Column(String(500), nullable=True)
client_id = Column(String(255), nullable=True)
client_secret_enc = Column(Text, nullable=True)
scopes = Column(String(500), nullable=False, default="openid email profile")
authorization_endpoint = Column(String(500), nullable=True)
token_endpoint = Column(String(500), nullable=True)
jwks_uri = Column(String(500), nullable=True)
discovered_at = Column(DateTime(timezone=True), nullable=True)
allowed_domains = Column(Text, nullable=True)
jit_provisioning = Column(Boolean, nullable=False, default=True)
default_role_id = Column(
UUID(as_uuid=True), ForeignKey("roles.id", ondelete="SET NULL"), nullable=True
)
link_existing_by_email = Column(Boolean, nullable=False, default=False)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
updated_at = Column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())
__table_args__ = (
UniqueConstraint("tenant_id", "slug", name="uq_identity_provider_slug"),
)
def domain_list(self) -> list[str]:
if not self.allowed_domains:
return []
return [d.strip().lower() for d in self.allowed_domains.split(",") if d.strip()]
@property
def client_secret(self) -> str | None:
from app.core.crypto import decrypt_json, is_encrypted
if not self.client_secret_enc:
return None
if is_encrypted(self.client_secret_enc):
return (decrypt_json(self.client_secret_enc) or {}).get("client_secret")
return None
@client_secret.setter
def client_secret(self, value: str | None) -> None:
from app.core.crypto import encrypt_json
self.client_secret_enc = (
encrypt_json({"client_secret": value}) if value else None
)
def __repr__(self) -> str:
return f"<IdentityProvider {self.slug} ({'on' if self.enabled else 'off'})>"
class UserIdentity(Base):
"""Which account at the provider is which account here.
Keyed on the provider's `sub`, never on the email address. An address can be
reassigned — somebody leaves, the address is given to their replacement —
and matching on it would hand the new person the old person's account.
"""
__tablename__ = "user_identities"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id = Column(
UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"),
nullable=False, index=True,
)
user_id = Column(
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True,
)
provider_id = Column(
UUID(as_uuid=True), ForeignKey("identity_providers.id", ondelete="CASCADE"),
nullable=False, index=True,
)
subject = Column(String(255), nullable=False)
last_login_at = Column(DateTime(timezone=True), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
__table_args__ = (
UniqueConstraint("provider_id", "subject", name="uq_user_identity_subject"),
)
def __repr__(self) -> str:
return f"<UserIdentity {self.subject} -> {self.user_id}>"
class SsoLoginState(Base):
"""A login that has started and not finished.
Holds what the callback needs and the browser must not carry: the PKCE
verifier, and the nonce the id_token has to echo. Single-use and short-lived
— a state that can be replayed is a login that can be replayed.
"""
__tablename__ = "sso_login_states"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
tenant_id = Column(
UUID(as_uuid=True), ForeignKey("tenants.id", ondelete="CASCADE"),
nullable=False, index=True,
)
provider_id = Column(
UUID(as_uuid=True), ForeignKey("identity_providers.id", ondelete="CASCADE"),
nullable=False, index=True,
)
state = Column(String(128), nullable=False, unique=True, index=True)
nonce = Column(String(128), nullable=False)
code_verifier = Column(String(256), nullable=False)
redirect_to = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
expires_at = Column(DateTime(timezone=True), nullable=False)
def __repr__(self) -> str:
return f"<SsoLoginState {self.state[:8]}…>"