Spaces:
Running
Running
File size: 8,247 Bytes
c91c7db 3493993 c91c7db 3493993 c91c7db 3493993 c91c7db 3493993 c91c7db 3493993 1fed801 c91c7db 3493993 c91c7db 3493993 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from sqlalchemy import event, inspect, text
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
# Importing the generation models here guarantees that local SQLite metadata
# and production schema checks see the full security-owned domain even when a
# caller constructs SecurityDatabase without first building the application
# container.
from app.core.database_url import normalize_async_database_url
from app.security.models import Base
REQUIRED_SECURITY_TABLES = frozenset(
{
"api_keys",
"audit_logs",
"rate_limits",
"users",
"workspaces",
"workspace_memberships",
"api_key_principals",
"media_assets",
"media_asset_variants",
"audit_events",
"projects",
"project_generation_jobs",
"generation_requests",
"generation_jobs",
"generation_job_attempts",
"project_editor_states",
"project_render_jobs",
"copilot_runs",
"marketplace_templates",
"marketplace_template_versions",
"marketplace_template_applications",
"brand_kits",
"brand_kit_versions",
}
)
REQUIRED_POSTGRES_SECURITY_INDEXES = frozenset(
{
"uq_generation_job_provider_external",
"ix_projects_workspace",
"ix_projects_workspace_status",
"ix_projects_workspace_updated",
"ix_projects_created_by",
"ix_media_assets_workspace_project_created",
"ix_project_generation_jobs_workspace_project_created",
"uq_project_generation_job",
"uq_project_editor_state_project",
"ix_project_editor_states_workspace_project",
"uq_project_render_idempotency",
"ix_project_render_jobs_workspace_status",
"ix_project_render_jobs_project_created",
"ix_project_render_jobs_dispatch",
"ix_generation_requests_workspace_project_created",
"ix_generation_requests_workspace_surface_created",
"uq_copilot_run_workspace_idempotency",
"ix_copilot_runs_workspace_created",
"ix_copilot_runs_workspace_status",
"ix_copilot_runs_project_created",
"uq_marketplace_template_workspace_slug",
"ix_marketplace_templates_workspace_status",
"ix_marketplace_templates_discovery",
"uq_marketplace_template_version",
"ix_marketplace_template_versions_template",
"uq_marketplace_template_application_idempotency",
"ix_marketplace_template_applications_project",
"ix_marketplace_template_applications_template",
"ix_brand_kits_workspace_updated",
"ix_brand_kits_workspace_default",
"uq_brand_kits_one_default",
"uq_brand_kit_version",
"ix_brand_versions_kit_created",
}
)
class SecurityDatabase:
"""Owns the authentication database engine and short-lived async sessions."""
def __init__(self, database_url: str, *, auto_migrate: bool = False) -> None:
database_url = normalize_async_database_url(database_url)
self.database_url = database_url
self.auto_migrate = auto_migrate or database_url.startswith("sqlite")
self.engine: AsyncEngine = create_async_engine(
database_url,
pool_pre_ping=True,
)
if database_url.startswith("sqlite"):
event.listen(self.engine.sync_engine, "connect", self._configure_sqlite)
self.session_factory = async_sessionmaker(
self.engine, expire_on_commit=False, class_=AsyncSession
)
@staticmethod
def _configure_sqlite(dbapi_connection: object, _record: object) -> None:
cursor = dbapi_connection.cursor() # type: ignore[attr-defined]
cursor.execute("PRAGMA foreign_keys=ON")
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA busy_timeout=5000")
cursor.close()
async def initialize(self) -> None:
if not self.auto_migrate:
return
__import__("app.generation.models")
__import__("app.projects.models")
__import__("app.copilot.models")
__import__("app.templates.marketplace_models")
__import__("app.brand.models")
async with self.engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
async def close(self) -> None:
await self.engine.dispose()
@property
def is_postgres(self) -> bool:
return self.database_url.startswith(("postgresql", "postgres"))
async def verify_execution_boundary(self, *, expected_role: str, enforce_rls: bool) -> None:
"""Ensure tenancy administration never uses the public tenant role."""
if not self.is_postgres or not enforce_rls:
return
if not expected_role.strip():
raise RuntimeError(
"SECURITY_DATABASE_ROLE is required when SECURITY_ENFORCE_RLS is enabled."
)
async with self.engine.connect() as connection:
row = (
(
await connection.execute(
text(
"select current_user as role, r.rolbypassrls as bypass_rls, r.rolsuper as superuser "
"from pg_roles r where r.rolname = current_user"
)
)
)
.mappings()
.one_or_none()
)
if row is None or row["role"] != expected_role.strip():
raise RuntimeError("DATABASE_URL is not connected as SECURITY_DATABASE_ROLE.")
if not row["bypass_rls"] and not row["superuser"]:
raise RuntimeError(
"SECURITY_DATABASE_ROLE must be backend-only and able to administer forced-RLS tenancy tables."
)
async def schema_ready(self) -> bool:
return not await self.missing_schema_objects()
async def missing_schema_objects(self) -> list[str]:
"""Return missing production schema requirements, including safety indexes."""
async with self.engine.connect() as connection:
tables = await connection.run_sync(lambda sync: set(inspect(sync).get_table_names()))
if not self.is_postgres:
indexes: set[str] = set()
else:
rows = await connection.execute(
text("select indexname from pg_indexes " "where schemaname = current_schema()")
)
indexes = set(rows.scalars().all())
missing = sorted(REQUIRED_SECURITY_TABLES - tables)
if self.is_postgres:
missing.extend(
f"index:{name}" for name in sorted(REQUIRED_POSTGRES_SECURITY_INDEXES - indexes)
)
return missing
async def missing_tables(self) -> list[str]:
async with self.engine.connect() as connection:
tables = await connection.run_sync(lambda sync: set(inspect(sync).get_table_names()))
return sorted(REQUIRED_SECURITY_TABLES - tables)
@asynccontextmanager
async def session(self) -> AsyncIterator[AsyncSession]:
async with self.session_factory() as session:
yield session
@asynccontextmanager
async def tenant_session(
self, *, workspace_id: str, user_id: str
) -> AsyncIterator[AsyncSession]:
"""Explicit tenant context for RLS verification and scoped services."""
if not workspace_id or not user_id:
raise RuntimeError("A security tenant session requires workspace and user IDs.")
async with self.session_factory() as session:
if not self.engine.url.drivername.startswith("sqlite"):
await session.execute(
text("select set_config('app.workspace_id', :workspace_id, true)"),
{"workspace_id": workspace_id},
)
await session.execute(
text("select set_config('app.user_id', :user_id, true)"),
{"user_id": user_id},
)
yield session
|