Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(streamlit-apps): add sandbox runtime, services, auth proxy (#54878)

Jovan Sakovic2a00d75dc547
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index eeba7d215f99..aedc2dd98ddd 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -155,7 +155,6 @@ SignalTeamConfig
SingleSessionSummary
SlackThreadTaskMapping
SourceBatch
-StreamlitApp
Subscription
SubscriptionDelivery
Survey
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 239633e24fff..627196cc9721 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -79,6 +79,13 @@ from products.feature_flags.backend.tasks import (
refresh_expiring_flags_cache_entries,
)
from products.logs.backend.tasks import logs_alert_events_cleanup_task
+from products.streamlit_apps.backend.facade.api import (
+ auto_restart_crashed_streamlit_sandboxes,
+ cleanup_deleted_streamlit_app_zips,
+ cleanup_expired_streamlit_oauth_tokens,
+ prune_old_streamlit_app_versions,
+ stop_idle_streamlit_sandboxes,
+)
TWENTY_FOUR_HOURS = 24 * 60 * 60
@@ -629,3 +636,39 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
flush_pending_email_replies.s(),
name="flush pending conversation email replies",
)
+ # Delete expired Streamlit bridge OAuth tokens.
+ sender.add_periodic_task(
+ # Hourly because tokens have a 1-hour TTL and every connect_info
+ # call mints a fresh one.
+ crontab(hour="*", minute="55"),
+ cleanup_expired_streamlit_oauth_tokens.s(),
+ name="cleanup expired streamlit oauth tokens",
+ )
+
+ # Hard-delete S3 zips for Streamlit apps past their soft-delete retention.
+ sender.add_periodic_task(
+ crontab(hour="4", minute="10"),
+ cleanup_deleted_streamlit_app_zips.s(),
+ name="cleanup deleted streamlit app zips",
+ )
+
+ # Stop streamlit sandboxes left idle past their inactivity window.
+ sender.add_periodic_task(
+ crontab(minute="*/5"),
+ stop_idle_streamlit_sandboxes.s(),
+ name="stop idle streamlit sandboxes",
+ )
+
+ # Restart streamlit sandboxes that died on their own (Modal TTL timeout).
+ sender.add_periodic_task(
+ crontab(minute="*"),
+ auto_restart_crashed_streamlit_sandboxes.s(),
+ name="auto restart crashed streamlit sandboxes",
+ )
+
+ # Prune non-active streamlit app versions past their retention window.
+ sender.add_periodic_task(
+ crontab(hour="3", minute="0"),
+ prune_old_streamlit_app_versions.s(),
+ name="prune old streamlit app versions",
+ )
diff --git a/products/streamlit_apps/backend/facade/__init__.py b/products/streamlit_apps/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/streamlit_apps/backend/facade/api.py b/products/streamlit_apps/backend/facade/api.py
new file mode 100644
index 000000000000..6c860d01596b
--- /dev/null
+++ b/products/streamlit_apps/backend/facade/api.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from django.db.models import QuerySet
+
+if TYPE_CHECKING:
+ from posthog.models.user import User
+
+from products.streamlit_apps.backend.facade.contracts import (
+ AppContract,
+ AppSandboxContract,
+ AppVersionContract,
+ ConnectInfoContract,
+)
+from products.streamlit_apps.backend.logic.app_runtime import (
+ AppRuntimeConcurrencyError,
+ AppRuntimeError,
+ AppRuntimeService,
+ _sync_sandbox_status,
+)
+from products.streamlit_apps.backend.logic.oauth import (
+ create_sandbox_bridge_token,
+ create_streamlit_access_token,
+ find_reusable_streamlit_access_token,
+)
+from products.streamlit_apps.backend.logic.zip_validator import validate_zip
+from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox, StreamlitAppVersion
+from products.streamlit_apps.backend.tasks import (
+ auto_restart_crashed_streamlit_sandboxes,
+ cleanup_deleted_streamlit_app_zips,
+ cleanup_expired_streamlit_oauth_tokens,
+ prune_old_streamlit_app_versions,
+ stop_idle_streamlit_sandboxes,
+)
+
+__all__ = [
+ "AppRuntimeConcurrencyError",
+ "AppRuntimeError",
+ "create_sandbox_bridge_token",
+ "validate_zip",
+ "list_apps",
+ "get_app",
+ "get_app_status",
+ "get_connect_info",
+ "auto_restart_crashed_streamlit_sandboxes",
+ "cleanup_deleted_streamlit_app_zips",
+ "cleanup_expired_streamlit_oauth_tokens",
+ "prune_old_streamlit_app_versions",
+ "stop_idle_streamlit_sandboxes",
+]
+
+
+def _version_to_contract(version: StreamlitAppVersion) -> AppVersionContract:
+ return AppVersionContract(
+ id=version.id,
+ version_number=version.version_number,
+ zip_file=version.zip_file,
+ zip_hash=version.zip_hash,
+ snapshot_id=version.snapshot_id,
+ created_by_id=version.created_by_id,
+ created_at=version.created_at,
+ )
+
+
+def _sandbox_to_contract(sandbox: StreamlitAppSandbox) -> AppSandboxContract:
+ return AppSandboxContract(
+ status=sandbox.status,
+ restart_count=sandbox.app.restart_count,
+ last_error=sandbox.last_error,
+ started_at=sandbox.started_at,
+ last_activity_at=sandbox.last_activity_at,
+ version_number=sandbox.version.version_number if sandbox.version else None,
+ )
+
+
+def _app_to_contract(app: StreamlitApp) -> AppContract:
+ try:
+ sandbox = _sandbox_to_contract(app.sandbox)
+ except StreamlitAppSandbox.DoesNotExist:
+ sandbox = None
+
+ return AppContract(
+ id=app.id,
+ short_id=app.short_id,
+ name=app.name,
+ description=app.description,
+ cpu_cores=app.cpu_cores,
+ memory_gb=app.memory_gb,
+ is_active=not app.deleted,
+ active_version=_version_to_contract(app.active_version) if app.active_version else None,
+ sandbox=sandbox,
+ created_by_id=app.created_by_id,
+ created_at=app.created_at,
+ updated_at=app.updated_at,
+ )
+
+
+def list_apps(team_id: int) -> QuerySet[StreamlitApp]:
+ return StreamlitApp.objects.for_team(team_id).filter(deleted=False)
+
+
+def get_app(team_id: int, short_id: str) -> StreamlitApp:
+ return StreamlitApp.objects.for_team(team_id).get(short_id=short_id, deleted=False)
+
+
+def get_app_status(app: StreamlitApp) -> AppSandboxContract | None:
+ try:
+ sandbox = app.sandbox
+ except StreamlitAppSandbox.DoesNotExist:
+ return None
+ sandbox = _sync_sandbox_status(sandbox)
+ return _sandbox_to_contract(sandbox)
+
+
+def get_connect_info(app: StreamlitApp, user: User, team_id: int) -> ConnectInfoContract:
+ token_obj = find_reusable_streamlit_access_token(user, team_id)
+ if token_obj is None:
+ token_obj = create_streamlit_access_token(user, team_id)
+
+ runtime = AppRuntimeService()
+ connect = runtime.get_connect_url(app, user_id=user.id, team_id=team_id)
+ if connect is None:
+ raise AppRuntimeError("App is not running.")
+
+ return ConnectInfoContract(
+ url=connect["url"],
+ token=token_obj.token,
+ expires_at=token_obj.expires,
+ )
diff --git a/products/streamlit_apps/backend/facade/contracts.py b/products/streamlit_apps/backend/facade/contracts.py
new file mode 100644
index 000000000000..6fa84cb4d575
--- /dev/null
+++ b/products/streamlit_apps/backend/facade/contracts.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+from uuid import UUID
+
+
+@dataclass(frozen=True)
+class AppVersionContract:
+ id: UUID
+ version_number: int
+ zip_file: str
+ zip_hash: str
+ snapshot_id: str | None
+ created_by_id: int | None
+ created_at: datetime
+
+
+@dataclass(frozen=True)
+class AppSandboxContract:
+ status: str
+ restart_count: int
+ last_error: str
+ started_at: datetime | None
+ last_activity_at: datetime | None
+ version_number: int | None
+
+
+@dataclass(frozen=True)
+class AppContract:
+ id: UUID
+ short_id: str
+ name: str
+ description: str
+ cpu_cores: float
+ memory_gb: float
+ is_active: bool
+ active_version: AppVersionContract | None
+ sandbox: AppSandboxContract | None
+ created_by_id: int | None
+ created_at: datetime
+ updated_at: datetime
+
+
+@dataclass(frozen=True)
+class ConnectInfoContract:
+ url: str
+ token: str
+ expires_at: datetime
+
+
+@dataclass(frozen=True)
+class CreateAppInput:
+ name: str
+ description: str = ""
+ cpu_cores: float = 0.5
+ memory_gb: float = 1
+
+
+@dataclass(frozen=True)
+class UpdateAppInput:
+ name: str | None = None
+ description: str | None = None
+ cpu_cores: float | None = None
+ memory_gb: float | None = None
diff --git a/products/streamlit_apps/backend/logic/__init__.py b/products/streamlit_apps/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/streamlit_apps/backend/logic/app_runtime.py b/products/streamlit_apps/backend/logic/app_runtime.py
new file mode 100644
index 000000000000..b750a655410b
--- /dev/null
+++ b/products/streamlit_apps/backend/logic/app_runtime.py
@@ -0,0 +1,563 @@
+from __future__ import annotations
+
+import os
+import time
+from collections.abc import Callable
+from io import BytesIO
+from urllib.parse import urlparse
+from zipfile import ZipFile
+
+from django.db import IntegrityError, transaction
+from django.db.models import F
+from django.utils import timezone
+
+import structlog
+
+from posthog.cloud_utils import is_cloud
+from posthog.ph_client import PH_EU_API_KEY, PH_EU_HOST, PH_US_API_KEY, PH_US_HOST
+from posthog.utils import get_instance_region
+
+from products.streamlit_apps.backend.logic.oauth import create_sandbox_bridge_token, get_streamlit_oauth_app
+from products.streamlit_apps.backend.logic.zip_validator import MAX_UNCOMPRESSED_SIZE, is_safe_zip_path
+from products.streamlit_apps.backend.models import (
+ MAX_CPU_CORES,
+ MAX_MEMORY_GB,
+ MIN_CPU_CORES,
+ MIN_MEMORY_GB,
+ StreamlitApp,
+ StreamlitAppSandbox,
+ StreamlitAppVersion,
+)
+from products.streamlit_apps.backend.tasks import reset_streamlit_app_restart_count_if_stable
+from products.tasks.backend.models import SandboxSnapshot
+from products.tasks.backend.services.sandbox import SandboxBase, SandboxConfig, SandboxTemplate, get_sandbox_class
+
+logger = structlog.get_logger(__name__)
+
+STREAMLIT_PORT = 8501
+AUTH_PROXY_PORT = 8080
+STREAMLIT_APP_PATH = "/app"
+BRIDGE_TOKEN_PATH = "/run/bridge_token"
+MAX_RESTART_COUNT = 3
+STARTING_TIMEOUT_SECONDS = 600
+# Wall-clock budgets for boot health checks; together they bound how long a
+# lifecycle task can occupy a Celery worker on a sandbox that never comes up.
+AUTH_PROXY_HEALTH_DEADLINE_SECONDS = 30
+STREAMLIT_HEALTH_DEADLINE_SECONDS = 60
+# Sandbox must stay RUNNING for this long before restart_count resets; shorter
+# lifecycles are treated as part of the same crash loop that incremented it.
+RESTART_COUNT_STABILITY_SECONDS = 5 * 60
+# Set on `last_error` when a Modal sandbox dies on its own (e.g. exceeds its
+# 24h TTL). The auto-restart task keys off this exact string to distinguish
+# crashes from user/idle stops.
+TTL_TIMEOUT_LAST_ERROR = "Sandbox terminated (TTL timeout)"
+
+
+class AppRuntimeError(Exception):
+ pass
+
+
+class AppRuntimeConcurrencyError(AppRuntimeError):
+ """Raised when a lifecycle action collides with one already in flight."""
+
+ pass
+
+
+def _get_sandbox_callback_url() -> str:
+ """URL that sandboxes use to call back to PostHog (OAuth introspect, bridge queries).
+
+ Docker sandboxes reach the host directly via host.docker.internal (applied by
+ DockerSandbox to SITE_URL), so they ignore STREAMLIT_SANDBOX_CALLBACK_URL — that
+ public-tunnel override exists only for Modal, whose cloud workers can't reach
+ localhost. Honoring a stale tunnel here would point a local Docker sandbox at a
+ dead URL and break token introspection.
+ """
+ from django.conf import settings
+
+ if getattr(settings, "SANDBOX_PROVIDER", None) == "docker":
+ return settings.SITE_URL
+
+ return os.environ.get("STREAMLIT_SANDBOX_CALLBACK_URL") or settings.SITE_URL
+
+
+def _get_otel_logs_config(callback_url: str) -> tuple[str, str]:
+ """Return (endpoint, token) for sandbox proxy OTEL log export.
+
+ Mirrors posthog.ph_client.get_regional_ph_client. On cloud, logs ship to
+ PH-on-PH; in dev/self-hosted they ship back via the callback URL.
+ """
+ if is_cloud():
+ region = get_instance_region()
+ if region == "EU":
+ return f"{PH_EU_HOST}/i/v1/logs", PH_EU_API_KEY
+ return f"{PH_US_HOST}/i/v1/logs", PH_US_API_KEY
+
+ # phc_local is the dev token that maps to team_id=1 in capture-logs.
+ return f"{callback_url.rstrip('/')}/i/v1/logs", "phc_local"
+
+
+def _outbound_allowlist(*urls: str) -> list[str] | None:
+ """Hostnames the sandbox may reach — everything else is fenced off by Modal.
+
+ User app code runs in the sandbox, so without this an app author could probe
+ internal/metadata endpoints on the runtime network. Loopback-style hosts are
+ dropped (Modal rejects them as invalid domains; the Docker provider has no
+ fence and ignores the field, so local dev is unaffected).
+ """
+ hosts: list[str] = []
+ for url in urls:
+ host = urlparse(url).hostname
+ if host and "." in host and host != "host.docker.internal" and host not in hosts:
+ hosts.append(host)
+ return hosts or None
+
+
+def _build_sandbox_config(app: StreamlitApp, version: StreamlitAppVersion) -> SandboxConfig:
+ callback_url = _get_sandbox_callback_url()
+ otel_endpoint, otel_token = _get_otel_logs_config(callback_url)
+ otel_resource_attrs = ",".join(
+ [
+ "service.name=streamlit-auth-proxy",
+ f"posthog.team_id={app.team_id}",
+ f"posthog.app_id={app.id}",
+ f"posthog.app_short_id={app.short_id}",
+ ]
+ )
+
+ config = SandboxConfig(
+ name=f"streamlit-{app.short_id}",
+ template=SandboxTemplate.STREAMLIT_BASE,
+ cpu_cores=min(max(app.cpu_cores, MIN_CPU_CORES), MAX_CPU_CORES),
+ memory_gb=min(max(app.memory_gb, MIN_MEMORY_GB), MAX_MEMORY_GB),
+ # TODO: Ideally we'd add a auto_suspend config the user can set that defines the TTL.
+ # After X minutes of inactivity, kill the sandbox.
+ ttl_seconds=60 * 15,
+ # Egress locked to the hosts the proxy itself needs (introspect/bridge +
+ # OTEL logs); per-app egress domains can be added as a feature later.
+ outbound_domain_allowlist=_outbound_allowlist(callback_url, otel_endpoint),
+ # TODO: We might need to allow the creator of the Streamlit to add more env vars.
+ environment_variables={
+ "POSTHOG_SITE_URL": callback_url,
+ # Per-sandbox team + app bindings; the auth proxy refuses tokens
+ # that don't match both, so leaks can't unlock this sandbox.
+ "POSTHOG_TEAM_ID": str(app.team_id),
+ "POSTHOG_STREAMLIT_CLIENT_ID": get_streamlit_oauth_app().client_id,
+ # Standard OTEL env vars — read directly by the SDK in the proxy.
+ "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": otel_endpoint,
+ "OTEL_EXPORTER_OTLP_HEADERS": f"authorization=Bearer {otel_token}",
+ "OTEL_RESOURCE_ATTRIBUTES": otel_resource_attrs,
+ },
+ )
+ if version.snapshot_id:
+ config.snapshot_id = version.snapshot_id
+ return config
+
+
+def _upload_app_files(sandbox: SandboxBase, zip_content: bytes) -> None:
+ """Upload zip contents to sandbox, bounded by actual bytes read (not zip metadata)."""
+ total_bytes = 0
+ files_to_write: list[tuple[str, bytes]] = []
+ requirements_seen = False
+ with ZipFile(BytesIO(zip_content)) as zf:
+ for info in zf.infolist():
+ if info.is_dir():
+ continue
+ if not is_safe_zip_path(info.filename):
+ raise AppRuntimeError(f"Unsafe file path in zip: {info.filename}")
+ normalized = os.path.normpath(info.filename)
+ if normalized == "requirements.txt":
+ requirements_seen = True
+ continue
+ content = zf.read(info.filename)
+ total_bytes += len(content)
+ if total_bytes > MAX_UNCOMPRESSED_SIZE:
+ raise AppRuntimeError(f"Zip uncompressed size exceeds limit ({MAX_UNCOMPRESSED_SIZE} bytes)")
+ files_to_write.append((f"{STREAMLIT_APP_PATH}/{normalized}", content))
+
+ for dest_path, content in files_to_write:
+ sandbox.write_file(dest_path, content)
+
+ if requirements_seen:
+ logger.info("streamlit_requirements_ignored")
+
+
+def _write_bridge_token(sandbox: SandboxBase, token: str) -> None:
+ """Drop the bridge bearer token at /run/bridge_token with mode 600.
+
+ MUST run before _start_auth_proxy — the proxy reads and unlinks the file
+ on boot, so a later write would race the unlink.
+ """
+ sandbox.write_file(BRIDGE_TOKEN_PATH, token.encode("utf-8"))
+ result = sandbox.execute(f"chmod 600 {BRIDGE_TOKEN_PATH}", timeout_seconds=5)
+ if result.exit_code != 0:
+ raise AppRuntimeError(f"Failed to chmod bridge token file: {result.stderr}")
+
+
+def _start_auth_proxy(sandbox: SandboxBase) -> None:
+ # setsid -f double-forks into a new session; exit 0 only means "spawned",
+ # so the real liveness check is _wait_for_health below.
+ result = sandbox.execute(
+ "setsid -f sh -c 'python /usr/local/bin/streamlit_auth_proxy.py >/tmp/auth_proxy.log 2>&1'",
+ timeout_seconds=10,
+ )
+ if result.exit_code != 0:
+ raise AppRuntimeError(f"Failed to start auth proxy: {result.stderr}")
+
+
+def _start_streamlit_process(sandbox: SandboxBase) -> None:
+ """Boot Streamlit as the non-root `streamlit` user.
+
+ Files land in /app root-owned, so we chown before launch. /run/bridge_token
+ stays root-owned mode 600 — the whole point is that this uid can't read it.
+ """
+ chown_result = sandbox.execute(
+ f"chown -R streamlit:streamlit {STREAMLIT_APP_PATH}",
+ timeout_seconds=5,
+ )
+ if chown_result.exit_code != 0:
+ raise AppRuntimeError(f"Failed to chown {STREAMLIT_APP_PATH} to streamlit user: {chown_result.stderr}")
+
+ # runuser (from util-linux) is a non-interactive "become user" wrapper —
+ # preferred over `su` because it doesn't load a login shell or need a tty.
+ result = sandbox.execute(
+ "setsid -f runuser -u streamlit -- sh -c '"
+ f"streamlit run {STREAMLIT_APP_PATH}/app.py "
+ f"--server.port {STREAMLIT_PORT} "
+ f"--server.headless true "
+ f">/tmp/streamlit.log 2>&1'",
+ timeout_seconds=10,
+ )
+ if result.exit_code != 0:
+ raise AppRuntimeError(f"Failed to start Streamlit: {result.stderr}")
+
+
+def _wait_for_health(
+ sandbox: SandboxBase, url: str, name: str, deadline_seconds: float, poll_interval_seconds: float = 1.0
+) -> bool:
+ """Poll the URL until it returns 200 or the wall-clock deadline passes.
+
+ Deadline-based rather than attempt-based: each attempt can cost up to ~6s
+ (5s curl budget + the sleep), so N attempts could otherwise occupy a
+ Celery worker for ~6N seconds on a sandbox that never becomes ready.
+ """
+ health_cmd = f"curl -s -o /dev/null -w '%{{http_code}}' {url}"
+ deadline = time.monotonic() + deadline_seconds
+ attempt = 0
+ while time.monotonic() < deadline:
+ attempt += 1
+ result = sandbox.execute(health_cmd, timeout_seconds=5)
+ if result.stdout.strip() == "200":
+ logger.info(f"{name} health check passed on attempt {attempt}")
+ return True
+ time.sleep(poll_interval_seconds)
+ return False
+
+
+def _schedule_restart_count_reset(app_id: str, team_id: int) -> None:
+ """Defer the restart_count reset so a brief RUNNING bounce can't wipe the counter."""
+ reset_streamlit_app_restart_count_if_stable.apply_async(
+ kwargs={"app_id": app_id, "team_id": team_id},
+ countdown=RESTART_COUNT_STABILITY_SECONDS,
+ )
+
+
+_SYNC_FAILURE_THRESHOLD = 3
+_SYNC_FAILURE_TTL_SECONDS = 600
+
+
+def _sync_failure_key(sandbox_record: StreamlitAppSandbox) -> str:
+ # Fall back to the PK while STARTING (no Modal handle assigned yet).
+ return f"streamlit_sandbox_sync_failures:{sandbox_record.sandbox_id or sandbox_record.id}"
+
+
+def _track_sync_failure(sandbox_record: StreamlitAppSandbox) -> int:
+ from django.core.cache import cache
+
+ key = _sync_failure_key(sandbox_record)
+ try:
+ new_value = cache.incr(key)
+ except ValueError:
+ cache.set(key, 1, _SYNC_FAILURE_TTL_SECONDS)
+ return 1
+ # Refresh TTL so slow-drip failures still trip the circuit.
+ try:
+ cache.touch(key, _SYNC_FAILURE_TTL_SECONDS)
+ except (AttributeError, NotImplementedError):
+ cache.set(key, new_value, _SYNC_FAILURE_TTL_SECONDS)
+ return new_value
+
+
+def _clear_sync_failures(sandbox_record: StreamlitAppSandbox) -> None:
+ from django.core.cache import cache
+
+ cache.delete(_sync_failure_key(sandbox_record))
+
+
+def _sync_sandbox_status(sandbox_record: StreamlitAppSandbox) -> StreamlitAppSandbox:
+ """Sync DB sandbox status with the Modal sandbox state.
+
+ Handles only RUNNING→STOPPED (died) and STARTING→ERROR (timed out).
+ Never promotes STARTING→RUNNING — that transition only happens in
+ start_app after both readiness probes pass. Consecutive failures
+ short-circuit to ERROR after _SYNC_FAILURE_THRESHOLD strikes.
+ """
+ if sandbox_record.status not in (StreamlitAppSandbox.Status.RUNNING, StreamlitAppSandbox.Status.STARTING):
+ return sandbox_record
+
+ if sandbox_record.status == StreamlitAppSandbox.Status.STARTING:
+ reference = sandbox_record.started_at or sandbox_record.created_at
+ age = (timezone.now() - reference).total_seconds()
+ if age > STARTING_TIMEOUT_SECONDS:
+ sandbox_record.status = StreamlitAppSandbox.Status.ERROR
+ sandbox_record.last_error = "Startup timed out"
+ sandbox_record.save(update_fields=["status", "last_error"])
+ return sandbox_record
+
+ try:
+ sandbox_class = get_sandbox_class()
+ sandbox = sandbox_class.get_by_id(sandbox_record.sandbox_id)
+ is_running = sandbox.is_running()
+
+ if sandbox_record.status == StreamlitAppSandbox.Status.RUNNING and not is_running:
+ sandbox_record.status = StreamlitAppSandbox.Status.STOPPED
+ sandbox_record.last_error = TTL_TIMEOUT_LAST_ERROR
+ sandbox_record.save(update_fields=["status", "last_error"])
+
+ _clear_sync_failures(sandbox_record)
+ except Exception:
+ failures = _track_sync_failure(sandbox_record)
+ logger.warning(
+ "sandbox_status_sync_failed",
+ sandbox_id=sandbox_record.sandbox_id,
+ app_id=str(sandbox_record.app_id),
+ consecutive_failures=failures,
+ exc_info=True,
+ )
+ if failures >= _SYNC_FAILURE_THRESHOLD:
+ sandbox_record.status = StreamlitAppSandbox.Status.ERROR
+ sandbox_record.last_error = f"Status sync failed {failures} times in a row."
+ sandbox_record.save(update_fields=["status", "last_error"])
+ _clear_sync_failures(sandbox_record)
+
+ return sandbox_record
+
+
+class AppRuntimeService:
+ def __init__(self, download_zip: Callable[[str], bytes] | None = None) -> None:
+ self._download_zip = download_zip
+
+ def start_app(self, app: StreamlitApp, zip_content: bytes | None = None) -> StreamlitAppSandbox:
+ version = app.active_version
+ if version is None:
+ raise AppRuntimeError("App has no active version")
+
+ with transaction.atomic():
+ existing = StreamlitAppSandbox.objects.select_for_update().filter(app=app).first()
+ if existing and existing.status in (
+ StreamlitAppSandbox.Status.RUNNING,
+ StreamlitAppSandbox.Status.STARTING,
+ ):
+ return existing
+
+ try:
+ sandbox_record, _ = StreamlitAppSandbox.objects.update_or_create(
+ app=app,
+ defaults={
+ "version": version,
+ "sandbox_id": "",
+ "status": StreamlitAppSandbox.Status.STARTING,
+ "last_error": "",
+ "started_at": timezone.now(),
+ },
+ )
+ except IntegrityError:
+ return StreamlitAppSandbox.objects.get(app=app)
+
+ sandbox = None
+ try:
+ config = _build_sandbox_config(app, version)
+ sandbox_class = get_sandbox_class()
+ sandbox = sandbox_class.create(config)
+ sandbox_record.sandbox_id = sandbox.id
+ sandbox_record.save(update_fields=["sandbox_id"])
+
+ is_warm_start = version.snapshot_id is not None
+
+ if not is_warm_start:
+ if zip_content is None and self._download_zip:
+ zip_content = self._download_zip(version.zip_file)
+ if zip_content is None:
+ raise AppRuntimeError("No zip content available for cold start")
+
+ _upload_app_files(sandbox, zip_content)
+
+ modal_image_id = sandbox.create_snapshot()
+
+ snapshot = SandboxSnapshot.objects.create(
+ external_id=modal_image_id,
+ status=SandboxSnapshot.Status.COMPLETE,
+ )
+ version.snapshot_id = str(snapshot.id)
+ version.snapshot_created_at = timezone.now()
+ version.save(update_fields=["snapshot_id", "snapshot_created_at"])
+
+ # Write before the proxy boots so it can read+unlink the file.
+ bridge_token = create_sandbox_bridge_token(user=app.created_by, team_id=app.team_id)
+ _write_bridge_token(sandbox, bridge_token)
+
+ _start_auth_proxy(sandbox)
+ _start_streamlit_process(sandbox)
+
+ proxy_url = f"http://localhost:{AUTH_PROXY_PORT}/healthz"
+ if not _wait_for_health(
+ sandbox, proxy_url, "Auth proxy", deadline_seconds=AUTH_PROXY_HEALTH_DEADLINE_SECONDS
+ ):
+ try:
+ tail_result = sandbox.execute(
+ "tail -n 20 /tmp/auth_proxy.log 2>/dev/null || true", timeout_seconds=5
+ )
+ tail = (tail_result.stdout or "").strip()
+ except Exception:
+ tail = ""
+ raise AppRuntimeError("Auth proxy failed to become ready" + (f": {tail}" if tail else ""))
+
+ # Streamlit's HTTP port opens a few seconds after the proxy is
+ # live; without this second gate the iframe 502s against upstream.
+ streamlit_url = f"http://localhost:{STREAMLIT_PORT}/_stcore/health"
+ if not _wait_for_health(
+ sandbox, streamlit_url, "Streamlit", deadline_seconds=STREAMLIT_HEALTH_DEADLINE_SECONDS
+ ):
+ raise AppRuntimeError("Streamlit failed to become ready")
+
+ now = timezone.now()
+ updated = StreamlitAppSandbox.objects.filter(id=sandbox_record.id).update(
+ status=StreamlitAppSandbox.Status.RUNNING,
+ started_at=now,
+ last_activity_at=now,
+ last_error="",
+ )
+ if updated:
+ sandbox_record.refresh_from_db()
+ else:
+ logger.warning("sandbox_record_deleted_during_start", app_id=str(app.id))
+
+ _schedule_restart_count_reset(str(app.id), app.team_id)
+
+ return sandbox_record
+
+ except Exception as e:
+ StreamlitAppSandbox.objects.filter(id=sandbox_record.id).update(
+ status=StreamlitAppSandbox.Status.ERROR,
+ last_error=str(e),
+ )
+ if sandbox is not None:
+ try:
+ sandbox.destroy()
+ except Exception:
+ logger.warning("orphaned_sandbox_destroy_failed", app_id=str(app.id))
+ raise
+
+ def stop_app(self, app: StreamlitApp) -> None:
+ with transaction.atomic():
+ sandbox_record = StreamlitAppSandbox.objects.select_for_update().filter(app=app).first()
+ if not sandbox_record:
+ return
+
+ sandbox_record.status = StreamlitAppSandbox.Status.STOPPING
+ sandbox_record.save(update_fields=["status"])
+
+ # Destroy outside the transaction — it hits Modal over the network.
+ destroy_error: str | None = None
+ if sandbox_record.sandbox_id:
+ try:
+ sandbox_class = get_sandbox_class()
+ sandbox = sandbox_class.get_by_id(sandbox_record.sandbox_id)
+ sandbox.destroy()
+ except Exception as exc:
+ destroy_error = str(exc) or "destroy() raised"
+ logger.exception(
+ "streamlit_sandbox_destroy_failed",
+ app_id=str(app.id),
+ sandbox_id=sandbox_record.sandbox_id,
+ )
+
+ if destroy_error is None:
+ sandbox_record.status = StreamlitAppSandbox.Status.STOPPED
+ sandbox_record.save(update_fields=["status"])
+ else:
+ # Modal may still be running; TTL or cleanup will reclaim it.
+ sandbox_record.status = StreamlitAppSandbox.Status.ERROR
+ sandbox_record.last_error = f"Stop failed: {destroy_error}"[:1000]
+ sandbox_record.save(update_fields=["status", "last_error"])
+
+ def get_status(self, app: StreamlitApp) -> dict:
+ sandbox_record = StreamlitAppSandbox.objects.filter(app=app).first()
+ if not sandbox_record:
+ return {
+ "status": "stopped",
+ "restart_count": app.restart_count,
+ }
+
+ sandbox_record = _sync_sandbox_status(sandbox_record)
+
+ return {
+ "status": sandbox_record.status,
+ "started_at": sandbox_record.started_at,
+ "restart_count": app.restart_count,
+ "last_error": sandbox_record.last_error or None,
+ }
+
+ def get_connect_url(self, app: StreamlitApp, user_id: int, team_id: int) -> dict | None:
+ """Get connect URL and token for authenticated access to the sandbox.
+
+ Modal connect tokens provide authenticated HTTP access to port 8080.
+ Returns {"url": str, "token": str} or None if sandbox is not running.
+ """
+ sandbox_record = StreamlitAppSandbox.objects.filter(app=app).first()
+ if not sandbox_record or not sandbox_record.sandbox_id:
+ return None
+
+ sandbox_record = _sync_sandbox_status(sandbox_record)
+ if sandbox_record.status != StreamlitAppSandbox.Status.RUNNING:
+ return None
+
+ try:
+ sandbox_class = get_sandbox_class()
+ sandbox = sandbox_class.get_by_id(sandbox_record.sandbox_id)
+ credentials = sandbox.get_connect_credentials()
+ return {"url": credentials.url, "token": credentials.token}
+ except Exception:
+ logger.exception("streamlit_connect_url_failed", extra={"app_id": str(app.id)})
+ return None
+
+ def restart_app(self, app: StreamlitApp, zip_content: bytes | None = None) -> StreamlitAppSandbox:
+ # Lock the app row so concurrent restart_count check+increment serialize.
+ with transaction.atomic():
+ StreamlitApp.objects.select_for_update().get(id=app.id)
+
+ sandbox_record = StreamlitAppSandbox.objects.filter(app=app).first()
+ if sandbox_record and sandbox_record.status in (
+ StreamlitAppSandbox.Status.STOPPING,
+ StreamlitAppSandbox.Status.STARTING,
+ ):
+ raise AppRuntimeConcurrencyError("Another restart is already in progress.")
+
+ current_count = StreamlitApp.objects.filter(id=app.id).values_list("restart_count", flat=True).first() or 0
+ if current_count >= MAX_RESTART_COUNT:
+ if sandbox_record:
+ sandbox_record.status = StreamlitAppSandbox.Status.ERROR
+ sandbox_record.last_error = f"Max restart count ({MAX_RESTART_COUNT}) exceeded"
+ sandbox_record.save(update_fields=["status", "last_error"])
+ raise AppRuntimeError(f"Max restart count ({MAX_RESTART_COUNT}) exceeded")
+
+ StreamlitApp.objects.filter(id=app.id).update(restart_count=F("restart_count") + 1)
+
+ # Stop+start run outside the app lock — they each take their own
+ # sandbox-row locks and hit Modal over the network.
+ try:
+ self.stop_app(app)
+ return self.start_app(app, zip_content=zip_content)
+ except Exception:
+ # Roll the counter back so a transient Modal flap doesn't eat the cap.
+ StreamlitApp.objects.filter(id=app.id).update(restart_count=F("restart_count") - 1)
+ raise
diff --git a/products/streamlit_apps/backend/logic/bridge.py b/products/streamlit_apps/backend/logic/bridge.py
new file mode 100644
index 000000000000..4a730be2c867
--- /dev/null
+++ b/products/streamlit_apps/backend/logic/bridge.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+import logging
+
+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.models import Team
+
+logger = logging.getLogger(__name__)
+
+# Tighter than HogQL defaults so a misbehaving sandbox can't exhaust a query node.
+BRIDGE_MAX_EXECUTION_TIME_SECONDS = 30
+BRIDGE_MAX_MEMORY_USAGE_BYTES = 256 * 1024 * 1024 # 256 MB
+BRIDGE_MAX_BYTES_TO_READ = 5 * 1024 * 1024 * 1024 # 5 GB
+
+
+def execute_bridge_query(query: str, team_id: int, client_query_id: str | None = None) -> dict:
+ from posthog.clickhouse.query_tagging import tag_queries
+
+ team = Team.objects.get(id=team_id)
+ tag_queries(
+ kind="streamlit_bridge",
+ team_id=team_id,
+ client_query_id=client_query_id or "",
+ )
+ response = execute_hogql_query(
+ query=query,
+ team=team,
+ limit_context=LimitContext.POSTHOG_AI,
+ settings=HogQLGlobalSettings(
+ max_execution_time=BRIDGE_MAX_EXECUTION_TIME_SECONDS,
+ max_memory_usage=BRIDGE_MAX_MEMORY_USAGE_BYTES,
+ max_bytes_to_read=BRIDGE_MAX_BYTES_TO_READ,
+ ),
+ )
+
+ if hasattr(response, "model_dump"):
+ payload = response.model_dump(exclude_none=True)
+ else:
+ payload = response.dict(exclude_none=True)
+
+ # TODO: Why are we reinventing the wheel here?
+ # Allow-list the response shape so user code never sees internal fields.
+ return {
+ "columns": payload.get("columns") or [],
+ "results": payload.get("results") or [],
+ "types": payload.get("types") or [],
+ }
diff --git a/products/streamlit_apps/backend/logic/oauth.py b/products/streamlit_apps/backend/logic/oauth.py
new file mode 100644
index 000000000000..5d29f39a76f5
--- /dev/null
+++ b/products/streamlit_apps/backend/logic/oauth.py
@@ -0,0 +1,107 @@
+from __future__ import annotations
+
+import secrets
+from datetime import timedelta
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.user import User
+from posthog.models.utils import generate_random_oauth_access_token
+
+logger = structlog.get_logger(__name__)
+
+STREAMLIT_OAUTH_APP_NAME = "PostHog Streamlit Apps"
+STREAMLIT_OAUTH_CLIENT_ID = "posthog-streamlit-apps-first-party"
+ACCESS_TOKEN_EXPIRY_SECONDS = 60 * 60 # 1 hour
+BRIDGE_TOKEN_EXPIRY_SECONDS = 60 * 20 # sandbox TTL + buffer
+
+# streamlit:iframe and streamlit:bridge suffixes let the proxy and the bridge
+# refuse tokens of the opposite type even if they leak between contexts.
+IFRAME_TOKEN_SCOPE = "streamlit:iframe"
+BRIDGE_TOKEN_SCOPE = "query:read streamlit:bridge"
+
+
+def get_streamlit_oauth_app() -> OAuthApplication:
+ """Return the Streamlit OAuth application, creating it if the seed row is missing.
+
+ Migration `0002_seed_streamlit_oauth_app` seeds the row, but
+ `TransactionTestCase`-style truncation in tests can wipe it without
+ re-running data migrations. Self-healing via get_or_create keeps the
+ helper robust without depending on a particular test-DB lifecycle.
+ The client_secret is regenerated on insert because the OAuth client
+ flow isn't actually used (is_first_party=True skips consent), so the
+ secret has no consumers to break.
+ """
+ app, _ = OAuthApplication.objects.get_or_create(
+ client_id=STREAMLIT_OAUTH_CLIENT_ID,
+ defaults={
+ "name": STREAMLIT_OAUTH_APP_NAME,
+ "client_secret": secrets.token_urlsafe(48),
+ "client_type": "confidential",
+ "authorization_grant_type": "authorization-code",
+ "redirect_uris": "https://localhost",
+ "algorithm": "RS256",
+ "is_first_party": True,
+ },
+ )
+ return app
+
+
+def create_streamlit_access_token(user: User, team_id: int) -> OAuthAccessToken:
+ """Mint an iframe OAuth access token scoped to the given team.
+
+ Returns the ORM object so callers can read the real `expires` timestamp
+ instead of reporting the minting TTL.
+ """
+ oauth_app = get_streamlit_oauth_app()
+ token_value = generate_random_oauth_access_token(None)
+
+ return OAuthAccessToken.objects.create(
+ application=oauth_app,
+ token=token_value,
+ user=user,
+ expires=timezone.now() + timedelta(seconds=ACCESS_TOKEN_EXPIRY_SECONDS),
+ scope=IFRAME_TOKEN_SCOPE,
+ scoped_teams=[team_id],
+ )
+
+
+def find_reusable_streamlit_access_token(
+ user: User, team_id: int, min_remaining_seconds: int = 300
+) -> OAuthAccessToken | None:
+ """Return a non-near-expiry iframe token for (user, team), or None.
+
+ Filters on IFRAME_TOKEN_SCOPE so bridge tokens can't be reused here.
+ """
+ oauth_app = get_streamlit_oauth_app()
+ cutoff = timezone.now() + timedelta(seconds=min_remaining_seconds)
+ return (
+ OAuthAccessToken.objects.filter(
+ application=oauth_app,
+ user=user,
+ scoped_teams=[team_id],
+ scope=IFRAME_TOKEN_SCOPE,
+ expires__gt=cutoff,
+ )
+ .order_by("-expires")
+ .first()
+ )
+
+
+def create_sandbox_bridge_token(user: User | None, team_id: int) -> str:
+ """Mint a long-TTL OAuth token for the sandbox→PostHog HogQL bridge hop."""
+ oauth_app = get_streamlit_oauth_app()
+ token_value = generate_random_oauth_access_token(None)
+
+ OAuthAccessToken.objects.create(
+ application=oauth_app,
+ token=token_value,
+ user=user,
+ expires=timezone.now() + timedelta(seconds=BRIDGE_TOKEN_EXPIRY_SECONDS),
+ scope=BRIDGE_TOKEN_SCOPE,
+ scoped_teams=[team_id],
+ )
+ return token_value
diff --git a/products/streamlit_apps/backend/logic/zip_validator.py b/products/streamlit_apps/backend/logic/zip_validator.py
new file mode 100644
index 000000000000..eb2e60cdecae
--- /dev/null
+++ b/products/streamlit_apps/backend/logic/zip_validator.py
@@ -0,0 +1,93 @@
+from __future__ import annotations
+
+import os
+import zipfile
+from dataclasses import dataclass, field
+from io import BytesIO
+
+MAX_ZIP_SIZE = 10 * 1024 * 1024 # 10 MB
+MAX_UNCOMPRESSED_SIZE = 100 * 1024 * 1024 # 100 MB
+MAX_FILE_COUNT = 500
+
+
+def _format_mb(size_bytes: int) -> str:
+ return f"{size_bytes / (1024 * 1024):.1f} MB"
+
+
+def is_safe_zip_path(filename: str) -> bool:
+ """Check if a zip entry filename is safe (no path traversal)."""
+ normalized = os.path.normpath(filename)
+ return not (normalized.startswith("..") or normalized.startswith("/"))
+
+
+@dataclass
+class ValidationResult:
+ valid: bool
+ errors: list[str] = field(default_factory=list)
+ files: list[str] = field(default_factory=list)
+
+
+def validate_zip(file: BytesIO) -> ValidationResult:
+ """Validate an uploaded zip file for Streamlit app structure."""
+ result = ValidationResult(valid=True)
+
+ file.seek(0, 2)
+ size = file.tell()
+ file.seek(0)
+ # Compressed (on-disk) size check; uncompressed size is validated below.
+ if size > MAX_ZIP_SIZE:
+ result.valid = False
+ result.errors.append(f"Zip file too large ({_format_mb(size)}, max {_format_mb(MAX_ZIP_SIZE)})")
+ return result
+
+ try:
+ with zipfile.ZipFile(file) as zf:
+ infolist = zf.infolist()
+
+ non_dir_entries = [info for info in infolist if not info.is_dir()]
+ total_uncompressed = sum(info.file_size for info in non_dir_entries)
+ if total_uncompressed > MAX_UNCOMPRESSED_SIZE:
+ result.valid = False
+ result.errors.append(
+ f"Total uncompressed size too large "
+ f"({_format_mb(total_uncompressed)}, max {_format_mb(MAX_UNCOMPRESSED_SIZE)})"
+ )
+ return result
+ if len(non_dir_entries) > MAX_FILE_COUNT:
+ result.valid = False
+ result.errors.append(f"Too many files: {len(non_dir_entries)} (max {MAX_FILE_COUNT})")
+ return result
+
+ for info in non_dir_entries:
+ if not is_safe_zip_path(info.filename):
+ result.valid = False
+ result.errors.append(f"Unsafe file path: {info.filename}")
+
+ if not result.valid:
+ return result
+
+ result.files = [os.path.normpath(info.filename) for info in non_dir_entries]
+
+ actual_total = 0
+ for info in non_dir_entries:
+ with zf.open(info.filename) as f:
+ while True:
+ chunk = f.read(65536)
+ if not chunk:
+ break
+ actual_total += len(chunk)
+ if actual_total > MAX_UNCOMPRESSED_SIZE:
+ result.valid = False
+ result.errors.append(
+ f"Total uncompressed size too large (exceeded {_format_mb(MAX_UNCOMPRESSED_SIZE)})"
+ )
+ return result
+
+ if "app.py" not in result.files:
+ result.valid = False
+ result.errors.append("Missing required Streamlit app file at root of the zip: app.py")
+ except zipfile.BadZipFile:
+ result.valid = False
+ result.errors.append("Invalid zip file")
+
+ return result
diff --git a/products/streamlit_apps/backend/management/__init__.py b/products/streamlit_apps/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/streamlit_apps/backend/management/commands/__init__.py b/products/streamlit_apps/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/streamlit_apps/backend/migrations/0003_alter_streamlitapp_options_and_more.py b/products/streamlit_apps/backend/migrations/0003_alter_streamlitapp_options_and_more.py
new file mode 100644
index 000000000000..cc115250c801
--- /dev/null
+++ b/products/streamlit_apps/backend/migrations/0003_alter_streamlitapp_options_and_more.py
@@ -0,0 +1,23 @@
+# Generated by Django 5.2.14 on 2026-06-11 17:18
+
+import django.db.models.manager
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("streamlit_apps", "0002_seed_streamlit_oauth_app"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="streamlitapp",
+ options={"default_manager_name": "all_teams"},
+ ),
+ migrations.AlterModelManagers(
+ name="streamlitapp",
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/streamlit_apps/backend/migrations/max_migration.txt b/products/streamlit_apps/backend/migrations/max_migration.txt
index 8bb03312f4da..00c4c804b9fb 100644
--- a/products/streamlit_apps/backend/migrations/max_migration.txt
+++ b/products/streamlit_apps/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0002_seed_streamlit_oauth_app
+0003_alter_streamlitapp_options_and_more
diff --git a/products/streamlit_apps/backend/models.py b/products/streamlit_apps/backend/models.py
index 1641990da797..70445bdb85de 100644
--- a/products/streamlit_apps/backend/models.py
+++ b/products/streamlit_apps/backend/models.py
@@ -2,10 +2,23 @@ import uuid
from django.db import models
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.utils import generate_short_id
+MIN_CPU_CORES = 0.25
+MAX_CPU_CORES = 8.0
+MIN_MEMORY_GB = 0.5
+MAX_MEMORY_GB = 16.0
+
+
+class StreamlitApp(TeamScopedRootMixin):
+ # `objects` (TeamScopedManager) inherited from TeamScopedRootMixin is fail-closed for
+ # explicit user code. `all_teams` is the unscoped sibling for Django framework internals
+ # (related-object access, prefetch_related, DRF class-body querysets) — Meta's
+ # default_manager_name routes _default_manager/_base_manager there. Same pattern as
+ # products/signals.
+ all_teams = models.Manager() # noqa: DJ012
-class StreamlitApp(models.Model):
# nosemgrep: prefer-uuid7-django-pk -- TODO: migrate to uuid7 or clarify intent
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
short_id = models.CharField(max_length=12, blank=True, default=generate_short_id)
@@ -35,6 +48,7 @@ class StreamlitApp(models.Model):
updated_at = models.DateTimeField(auto_now=True)
class Meta:
+ default_manager_name = "all_teams"
constraints = [
models.UniqueConstraint(
fields=["team", "short_id"],
diff --git a/products/streamlit_apps/backend/tasks/__init__.py b/products/streamlit_apps/backend/tasks/__init__.py
new file mode 100644
index 000000000000..40c179ae63a9
--- /dev/null
+++ b/products/streamlit_apps/backend/tasks/__init__.py
@@ -0,0 +1,20 @@
+# Re-export tasks for Celery autodiscover
+from products.streamlit_apps.backend.tasks.tasks import (
+ auto_restart_crashed_streamlit_sandboxes,
+ cleanup_deleted_streamlit_app_zips,
+ cleanup_expired_streamlit_oauth_tokens,
+ prune_old_streamlit_app_versions,
+ reset_streamlit_app_restart_count_if_stable,
+ run_streamlit_app_lifecycle,
+ stop_idle_streamlit_sandboxes,
+)
+
+__all__ = [
+ "auto_restart_crashed_streamlit_sandboxes",
+ "cleanup_deleted_streamlit_app_zips",
+ "cleanup_expired_streamlit_oauth_tokens",
+ "prune_old_streamlit_app_versions",
+ "reset_streamlit_app_restart_count_if_stable",
+ "run_streamlit_app_lifecycle",
+ "stop_idle_streamlit_sandboxes",
+]
diff --git a/products/streamlit_apps/backend/tasks/tasks.py b/products/streamlit_apps/backend/tasks/tasks.py
new file mode 100644
index 000000000000..c842ec746375
--- /dev/null
+++ b/products/streamlit_apps/backend/tasks/tasks.py
@@ -0,0 +1,315 @@
+from __future__ import annotations
+
+import uuid
+from typing import Literal
+
+import structlog
+from celery import shared_task
+from celery.exceptions import SoftTimeLimitExceeded
+
+from posthog.models.scoping import with_team_scope
+from posthog.scoping_audit import skip_team_scope_audit
+
+logger = structlog.get_logger(__name__)
+
+# soft_time_limit fires first so we can mark the sandbox as ERROR before celery kills us.
+_TASK_TIME_LIMIT = 600
+_TASK_SOFT_TIME_LIMIT = 540
+
+_OAUTH_CLEANUP_BATCH_SIZE = 10_000
+_DELETED_ZIP_RETENTION_DAYS = 7
+_IDLE_TIMEOUT_MINUTES = 30
+_VERSION_RETENTION_DAYS = 30
+
+
+def _mark_sandbox_error(app_id: str, message: str) -> None:
+ """Best-effort mark the sandbox as ERROR from a background task."""
+ try:
+ from products.streamlit_apps.backend.models import StreamlitAppSandbox
+
+ sandbox = StreamlitAppSandbox.objects.filter(app_id=uuid.UUID(app_id)).first()
+ if sandbox is None:
+ return
+ sandbox.status = StreamlitAppSandbox.Status.ERROR
+ sandbox.last_error = message[:1000]
+ sandbox.save(update_fields=["status", "last_error"])
+ except Exception:
+ logger.exception("streamlit_task_mark_error_failed", app_id=app_id)
+
+
+@shared_task(
+ ignore_result=True,
+ time_limit=_TASK_TIME_LIMIT,
+ soft_time_limit=_TASK_SOFT_TIME_LIMIT,
+ max_retries=0,
+)
+@with_team_scope()
+def run_streamlit_app_lifecycle(app_id: str, action: Literal["start", "restart"], team_id: int) -> None:
+ """Celery entry point for both start and restart."""
+ from posthog.storage import object_storage
+
+ from products.streamlit_apps.backend.logic.app_runtime import AppRuntimeConcurrencyError, AppRuntimeService
+ from products.streamlit_apps.backend.models import StreamlitApp
+
+ try:
+ app = StreamlitApp.objects.get(id=app_id, deleted=False)
+ except StreamlitApp.DoesNotExist:
+ logger.warning("streamlit_app_lifecycle_not_found", app_id=app_id, action=action)
+ return
+
+ if action == "start" and not app.active_version:
+ logger.warning("streamlit_app_lifecycle_no_version", app_id=app_id)
+ return
+
+ try:
+ zip_content = None
+ if app.active_version:
+ zip_content = object_storage.read_bytes(app.active_version.zip_file)
+
+ runtime = AppRuntimeService()
+ if action == "start":
+ runtime.start_app(app, zip_content=zip_content)
+ else:
+ runtime.restart_app(app, zip_content=zip_content)
+ except AppRuntimeConcurrencyError:
+ # Benign — another worker is handling it. Don't stamp ERROR.
+ logger.info("streamlit_app_lifecycle_concurrent_noop", app_id=app_id, action=action)
+ return
+ except SoftTimeLimitExceeded:
+ logger.exception("streamlit_app_lifecycle_timeout", app_id=app_id, action=action)
+ _mark_sandbox_error(app_id, f"{action.title()} exceeded time limit.")
+ raise
+ except Exception as exc:
+ logger.exception("streamlit_app_lifecycle_failed", app_id=app_id, action=action)
+ _mark_sandbox_error(app_id, f"{action.title()} failed: {exc}")
+ raise
+
+
+@shared_task(ignore_result=True, max_retries=0)
+@with_team_scope()
+def reset_streamlit_app_restart_count_if_stable(app_id: str, team_id: int) -> None:
+ """Reset restart_count to 0 only if the sandbox is still RUNNING and stable.
+
+ Deferred via countdown so a brief RUNNING bounce in a crash loop can't
+ wipe the counter and bypass MAX_RESTART_COUNT.
+ """
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from products.streamlit_apps.backend.logic.app_runtime import RESTART_COUNT_STABILITY_SECONDS
+ from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox
+
+ try:
+ app = StreamlitApp.objects.get(id=app_id, deleted=False)
+ except StreamlitApp.DoesNotExist:
+ return
+
+ sandbox = StreamlitAppSandbox.objects.filter(app=app).first()
+ if sandbox is None or sandbox.status != StreamlitAppSandbox.Status.RUNNING or sandbox.started_at is None:
+ return
+
+ if timezone.now() - sandbox.started_at < timedelta(seconds=RESTART_COUNT_STABILITY_SECONDS):
+ return
+
+ StreamlitApp.objects.filter(id=app_id).update(restart_count=0)
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit # genuinely cross-team housekeeping
+def cleanup_expired_streamlit_oauth_tokens() -> int:
+ """Delete expired OAuthAccessToken rows for the Streamlit app, in batches."""
+ from django.utils import timezone
+
+ from posthog.models.oauth import OAuthAccessToken
+
+ from products.streamlit_apps.backend.logic.oauth import get_streamlit_oauth_app
+
+ oauth_app = get_streamlit_oauth_app()
+
+ total_to_delete = OAuthAccessToken.objects.filter(
+ application=oauth_app,
+ expires__lt=timezone.now(),
+ ).count()
+
+ if total_to_delete == 0:
+ return 0
+
+ num_batches = -(-total_to_delete // _OAUTH_CLEANUP_BATCH_SIZE)
+ total_deleted = 0
+
+ for _ in range(num_batches):
+ ids = list(
+ OAuthAccessToken.objects.filter(
+ application=oauth_app,
+ expires__lt=timezone.now(),
+ ).values_list("id", flat=True)[:_OAUTH_CLEANUP_BATCH_SIZE]
+ )
+ if not ids:
+ break
+ deleted, _ = OAuthAccessToken.objects.filter(id__in=ids).delete()
+ total_deleted += deleted
+
+ if total_deleted:
+ logger.info("streamlit_oauth_tokens_cleaned_up", deleted=total_deleted)
+ return total_deleted
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit # genuinely cross-team housekeeping
+def cleanup_deleted_streamlit_app_zips() -> int:
+ """Hard-delete zip objects and version rows for soft-deleted apps past the retention window."""
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from posthog.storage import object_storage
+
+ from products.streamlit_apps.backend.models import StreamlitAppVersion
+
+ cutoff = timezone.now() - timedelta(days=_DELETED_ZIP_RETENTION_DAYS)
+ stale_versions = StreamlitAppVersion.objects.filter(
+ app__deleted=True,
+ app__deleted_at__lt=cutoff,
+ ).only("id", "zip_file")
+
+ deleted = 0
+ for version in stale_versions.iterator(chunk_size=200):
+ try:
+ object_storage.delete(version.zip_file)
+ except Exception:
+ logger.warning("streamlit_zip_cleanup_storage_delete_failed", version_id=str(version.id), exc_info=True)
+ # Leave the row so we retry next run.
+ continue
+ StreamlitAppVersion.objects.filter(id=version.id).delete()
+ deleted += 1
+
+ if deleted:
+ logger.info("streamlit_deleted_app_zips_cleaned_up", deleted=deleted)
+ return deleted
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit # genuinely cross-team housekeeping
+def stop_idle_streamlit_sandboxes() -> int:
+ """Stop sandboxes whose last_activity_at (or started_at, if no traffic yet)
+ is older than _IDLE_TIMEOUT_MINUTES. Saves Modal compute on apps left open
+ in a forgotten browser tab."""
+ from datetime import timedelta
+
+ from django.utils import timezone
+
+ from products.streamlit_apps.backend.logic.app_runtime import AppRuntimeService
+ from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox
+
+ cutoff = timezone.now() - timedelta(minutes=_IDLE_TIMEOUT_MINUTES)
+ # Apps with no traffic since boot are still idle — fall back to started_at
+ # via Coalesce so we don't leave never-used sandboxes running forever.
+ from django.db.models.functions import Coalesce
+
+ idle_sandboxes = (
+ StreamlitAppSandbox.objects.filter(status=StreamlitAppSandbox.Status.RUNNING)
+ .annotate(_idle_marker=Coalesce("last_activity_at", "started_at"))
+ .filter(_idle_marker__lt=cutoff)
+ .select_related("app")
+ )
+
+ runtime = AppRuntimeService()
+ stopped = 0
+ for sandbox in idle_sandboxes.iterator(chunk_size=100):
+ app: StreamlitApp = sandbox.app
+ try:
+ runtime.stop_app(app)
+ stopped += 1
+ logger.info(
+ "streamlit_idle_sandbox_stopped",
+ app_id=str(app.id),
+ idle_since=sandbox.last_activity_at or sandbox.started_at,
+ )
+ except Exception:
+ logger.warning("streamlit_idle_sandbox_stop_failed", app_id=str(app.id), exc_info=True)
+
+ return stopped
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit # genuinely cross-team housekeeping
+def auto_restart_crashed_streamlit_sandboxes() -> int:
+ """Restart sandboxes that died on their own (Modal TTL timeout), respecting
+ the MAX_RESTART_COUNT cap. Only acts on the exact `last_error` set by
+ `_sync_sandbox_status` — user-initiated stops, idle stops, and startup
+ failures leave a different string and are not restarted."""
+ from products.streamlit_apps.backend.logic.app_runtime import MAX_RESTART_COUNT, TTL_TIMEOUT_LAST_ERROR
+ from products.streamlit_apps.backend.models import StreamlitAppSandbox
+
+ crashed = StreamlitAppSandbox.objects.filter(
+ status=StreamlitAppSandbox.Status.STOPPED,
+ last_error=TTL_TIMEOUT_LAST_ERROR,
+ app__deleted=False,
+ app__restart_count__lt=MAX_RESTART_COUNT,
+ ).select_related("app")
+
+ restarted = 0
+ for sandbox in crashed.iterator(chunk_size=100):
+ app_id = str(sandbox.app_id)
+ try:
+ # Hand off to the existing lifecycle task so we don't block on
+ # Modal cold-starts here and the cap/lock logic stays in one place.
+ run_streamlit_app_lifecycle.delay(app_id, "restart", team_id=sandbox.app.team_id)
+ restarted += 1
+ logger.info("streamlit_crashed_sandbox_restart_dispatched", app_id=app_id)
+ except Exception:
+ logger.warning("streamlit_crashed_sandbox_restart_failed", app_id=app_id, exc_info=True)
+
+ return restarted
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit # genuinely cross-team housekeeping
+def prune_old_streamlit_app_versions() -> int:
+ """Hard-delete non-active versions older than _VERSION_RETENTION_DAYS for
+ apps that are NOT soft-deleted (those are handled by
+ cleanup_deleted_streamlit_app_zips). Drops the zip from object storage;
+ snapshot cleanup is intentionally deferred — see TODO below."""
+ from datetime import timedelta
+
+ from django.db.models import F
+ from django.utils import timezone
+
+ from posthog.storage import object_storage
+
+ from products.streamlit_apps.backend.models import StreamlitAppVersion
+
+ cutoff = timezone.now() - timedelta(days=_VERSION_RETENTION_DAYS)
+ stale = (
+ StreamlitAppVersion.objects.filter(
+ created_at__lt=cutoff,
+ app__deleted=False,
+ )
+ .exclude(id=F("app__active_version_id"))
+ .only("id", "zip_file", "snapshot_id")
+ )
+
+ deleted = 0
+ for version in stale.iterator(chunk_size=200):
+ try:
+ object_storage.delete(version.zip_file)
+ except Exception:
+ logger.warning(
+ "streamlit_version_prune_zip_delete_failed",
+ version_id=str(version.id),
+ exc_info=True,
+ )
+ # Leave the row so we retry on the next run.
+ continue
+
+ # TODO: delete Modal snapshot at version.snapshot_id once
+ # ModalSandbox exposes a snapshot delete API. Skipping silently is
+ # the correct trade-off today — snapshots are cheap and Modal cleans
+ # them up on a longer horizon.
+ StreamlitAppVersion.objects.filter(id=version.id).delete()
+ deleted += 1
+
+ if deleted:
+ logger.info("streamlit_old_versions_pruned", deleted=deleted)
+ return deleted
diff --git a/products/streamlit_apps/backend/tests/conftest.py b/products/streamlit_apps/backend/tests/conftest.py
new file mode 100644
index 000000000000..e274e4c78647
--- /dev/null
+++ b/products/streamlit_apps/backend/tests/conftest.py
@@ -0,0 +1,30 @@
+"""Test-suite fixtures for the streamlit_apps backend.
+
+`_streamlit_team_scope` auto-wraps every test that has a `self.team` (i.e. is
+built on `BaseTest`/`APIBaseTest`) in `team_scope(self.team.id)`. `StreamlitApp`
+uses `TeamScopedRootMixin`, so its default `.objects` manager is fail-closed and
+raises `TeamScopeError` when called outside a team context. Test setUp / body
+code that does `StreamlitApp.objects.create(...)` directly (without going
+through a DRF request that sets context via `TeamAndOrgViewSetMixin.initial`)
+would otherwise need an explicit `with team_scope(...)` wrapper everywhere.
+
+The fixture is a no-op for tests without a `team` attribute (pure unit tests
+like the auth-proxy and zip-validator suites). Same pattern as
+products/signals/backend/test/conftest.py.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from posthog.models.scoping import team_scope
+
+
[email protected](autouse=True)
+def _streamlit_team_scope(request: pytest.FixtureRequest):
+ instance = getattr(request, "instance", None)
+ if instance is None or getattr(instance, "team", None) is None:
+ yield
+ return
+ with team_scope(instance.team.id):
+ yield
diff --git a/products/streamlit_apps/backend/tests/test_app_runtime.py b/products/streamlit_apps/backend/tests/test_app_runtime.py
new file mode 100644
index 000000000000..dc654087b4e3
--- /dev/null
+++ b/products/streamlit_apps/backend/tests/test_app_runtime.py
@@ -0,0 +1,835 @@
+import zipfile
+from datetime import timedelta
+from io import BytesIO
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.streamlit_apps.backend.logic.app_runtime import (
+ MAX_RESTART_COUNT,
+ RESTART_COUNT_STABILITY_SECONDS,
+ AppRuntimeConcurrencyError,
+ AppRuntimeError,
+ AppRuntimeService,
+ _get_sandbox_callback_url,
+)
+from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox, StreamlitAppVersion
+
+
+def _make_zip_bytes(files: dict[str, str]) -> bytes:
+ buf = BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ for name, content in files.items():
+ zf.writestr(name, content)
+ return buf.getvalue()
+
+
+def _make_mock_sandbox():
+ sandbox = MagicMock()
+ sandbox.id = "modal-sandbox-123"
+ sandbox.execute.return_value = MagicMock(exit_code=0, stdout="200", stderr="")
+ sandbox.write_file.return_value = MagicMock(exit_code=0)
+ sandbox.create_snapshot.return_value = "snapshot-abc"
+ return sandbox
+
+
+def _make_mock_sandbox_class(sandbox=None):
+ if sandbox is None:
+ sandbox = _make_mock_sandbox()
+ cls = MagicMock()
+ cls.create.return_value = sandbox
+ cls.get_by_id.return_value = sandbox
+ return cls
+
+
+@patch("products.streamlit_apps.backend.logic.app_runtime._wait_for_health", return_value=True)
+@patch("products.streamlit_apps.backend.logic.app_runtime.get_sandbox_class")
+class TestAppRuntimeStartApp(BaseTest):
+ def _create_app_with_version(self, snapshot_id=None):
+ app = StreamlitApp.objects.create(team=self.team, name="Test App", created_by=self.user)
+ version = StreamlitAppVersion.objects.create(
+ app=app,
+ version_number=1,
+ zip_file="s3://bucket/app.zip",
+ zip_hash="abc123",
+ snapshot_id=snapshot_id,
+ )
+ app.active_version = version
+ app.save(update_fields=["active_version"])
+ return app, version
+
+ def test_cold_start_creates_sandbox_and_snapshot(self, mock_get_sandbox_class, _mock_wait):
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, version = self._create_app_with_version()
+ zip_content = _make_zip_bytes({"app.py": "import streamlit as st"})
+
+ service = AppRuntimeService()
+ record = service.start_app(app, zip_content=zip_content)
+
+ assert record.status == StreamlitAppSandbox.Status.RUNNING
+ assert record.sandbox_id == "modal-sandbox-123"
+ mock_sandbox.write_file.assert_called()
+ mock_sandbox.create_snapshot.assert_called_once()
+
+ version.refresh_from_db()
+ assert version.snapshot_id is not None
+ assert version.snapshot_created_at is not None
+
+ from products.tasks.backend.models import SandboxSnapshot
+
+ snapshot = SandboxSnapshot.objects.get(id=version.snapshot_id)
+ assert snapshot.external_id == "snapshot-abc"
+ assert snapshot.status == SandboxSnapshot.Status.COMPLETE
+
+ def test_cold_start_ignores_requirements_txt_in_zip(self, mock_get_sandbox_class, _mock_wait):
+ """requirements.txt support was deleted: a zip with one is accepted but
+ we never run `pip install` and the file is dropped on the way to the
+ sandbox so user code can't see it either."""
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._create_app_with_version()
+ zip_content = _make_zip_bytes({"app.py": "pass", "requirements.txt": "pandas\n"})
+
+ service = AppRuntimeService()
+ service.start_app(app, zip_content=zip_content)
+
+ pip_calls = [c for c in mock_sandbox.execute.call_args_list if "pip install" in str(c)]
+ assert pip_calls == []
+ # requirements.txt should NOT be uploaded into the sandbox
+ write_paths = [c.args[0] if c.args else c.kwargs.get("path") for c in mock_sandbox.write_file.call_args_list]
+ assert not any(p and "requirements.txt" in p for p in write_paths)
+
+ def test_warm_start_skips_upload_and_snapshot(self, mock_get_sandbox_class, _mock_wait):
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._create_app_with_version(snapshot_id="existing-snapshot")
+
+ service = AppRuntimeService()
+ record = service.start_app(app)
+
+ assert record.status == StreamlitAppSandbox.Status.RUNNING
+ # The bridge token write to /run/bridge_token still happens on warm
+ # starts (it's per-sandbox-boot, not per-cold-start), but no app-file
+ # uploads should happen and no snapshot should be created.
+ write_paths = [c.args[0] if c.args else c.kwargs.get("path") for c in mock_sandbox.write_file.call_args_list]
+ assert all(p and p.startswith("/run/bridge_token") for p in write_paths)
+ mock_sandbox.create_snapshot.assert_not_called()
+
+ def test_start_app_no_active_version_raises(self, mock_get_sandbox_class, _mock_wait):
+ app = StreamlitApp.objects.create(team=self.team, name="No Version")
+
+ service = AppRuntimeService()
+ with self.assertRaises(AppRuntimeError, msg="App has no active version"):
+ service.start_app(app)
+
+ def test_start_app_already_running_returns_existing(self, mock_get_sandbox_class, _mock_wait):
+ app, version = self._create_app_with_version(snapshot_id="snap")
+ existing = StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id="existing-id",
+ status=StreamlitAppSandbox.Status.RUNNING,
+ )
+
+ service = AppRuntimeService()
+ record = service.start_app(app)
+ assert record.id == existing.id
+
+ def test_start_app_error_sets_error_status(self, mock_get_sandbox_class, _mock_wait):
+ mock_sandbox = _make_mock_sandbox()
+ mock_sandbox.execute.side_effect = Exception("Boom")
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._create_app_with_version(snapshot_id="snap")
+
+ service = AppRuntimeService()
+ with self.assertRaises(Exception):
+ service.start_app(app)
+
+ record = StreamlitAppSandbox.objects.get(app=app)
+ assert record.status == StreamlitAppSandbox.Status.ERROR
+ assert "Boom" in record.last_error
+
+ def test_start_app_starts_auth_proxy_and_streamlit(self, mock_get_sandbox_class, _mock_wait):
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._create_app_with_version(snapshot_id="snap")
+
+ service = AppRuntimeService()
+ service.start_app(app)
+
+ execute_calls = [str(c) for c in mock_sandbox.execute.call_args_list]
+ proxy_calls = [c for c in execute_calls if "streamlit_auth_proxy" in c]
+ streamlit_calls = [c for c in execute_calls if "streamlit run" in c]
+ assert len(proxy_calls) == 1
+ assert len(streamlit_calls) == 1
+
+ def test_start_app_runs_streamlit_as_non_root(self, mock_get_sandbox_class, _mock_wait):
+ """Streamlit must be launched via `runuser -u streamlit` so user code
+ executes as a non-root uid. The auth proxy still runs as root so it can
+ read the mode-600 bridge token file, but the Streamlit process (which
+ runs arbitrary user code) must not have root privileges."""
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._create_app_with_version(snapshot_id="snap")
+
+ service = AppRuntimeService()
+ service.start_app(app)
+
+ execute_calls = [str(c) for c in mock_sandbox.execute.call_args_list]
+
+ # The streamlit-run invocation must go through runuser.
+ streamlit_calls = [c for c in execute_calls if "streamlit run" in c]
+ assert len(streamlit_calls) == 1
+ assert "runuser -u streamlit" in streamlit_calls[0]
+
+ # The auth proxy invocation must NOT go through runuser (it stays
+ # as root so it can read /run/bridge_token).
+ proxy_calls = [c for c in execute_calls if "streamlit_auth_proxy" in c]
+ assert len(proxy_calls) == 1
+ assert "runuser" not in proxy_calls[0]
+
+ # /app needs to be chown'd to streamlit before the streamlit process
+ # launches — otherwise the non-root user can't read uploaded files.
+ chown_calls = [c for c in execute_calls if "chown -R streamlit:streamlit /app" in c]
+ assert len(chown_calls) == 1
+
+ def test_start_app_fails_when_proxy_not_ready(self, mock_get_sandbox_class, mock_wait):
+ mock_wait.return_value = False
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._create_app_with_version(snapshot_id="snap")
+
+ service = AppRuntimeService()
+ with self.assertRaises(AppRuntimeError, msg="Auth proxy failed to become ready"):
+ service.start_app(app)
+
+
+@patch("products.streamlit_apps.backend.logic.app_runtime.get_sandbox_class")
+class TestAppRuntimeStopApp(BaseTest):
+ def test_stop_destroys_sandbox(self, mock_get_sandbox_class):
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(
+ app=app,
+ version_number=1,
+ zip_file="a.zip",
+ zip_hash="a",
+ )
+ StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id="modal-123",
+ status=StreamlitAppSandbox.Status.RUNNING,
+ )
+
+ service = AppRuntimeService()
+ service.stop_app(app)
+
+ record = StreamlitAppSandbox.objects.get(app=app)
+ assert record.status == StreamlitAppSandbox.Status.STOPPED
+ mock_sandbox.destroy.assert_called_once()
+
+ def test_stop_no_sandbox_is_noop(self, mock_get_sandbox_class):
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ service = AppRuntimeService()
+ service.stop_app(app)
+
+
+@patch("products.streamlit_apps.backend.logic.app_runtime.get_sandbox_class")
+class TestAppRuntimeGetStatus(BaseTest):
+ def test_get_status_no_sandbox(self, mock_get_sandbox_class):
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ service = AppRuntimeService()
+ status = service.get_status(app)
+ assert status["status"] == "stopped"
+
+ def test_get_status_error(self, mock_get_sandbox_class):
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ StreamlitAppSandbox.objects.create(
+ app=app, version=version, sandbox_id="modal-123", status=StreamlitAppSandbox.Status.ERROR
+ )
+ service = AppRuntimeService()
+ status = service.get_status(app)
+ assert status["status"] == "error"
+
+ def test_get_status_running_sandbox_still_alive(self, mock_get_sandbox_class):
+ mock_sandbox = _make_mock_sandbox()
+ mock_sandbox.is_running.return_value = True
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ StreamlitAppSandbox.objects.create(
+ app=app, version=version, sandbox_id="modal-123", status=StreamlitAppSandbox.Status.RUNNING
+ )
+
+ service = AppRuntimeService()
+ status = service.get_status(app)
+ assert status["status"] == "running"
+
+ def test_get_status_detects_timed_out_sandbox(self, mock_get_sandbox_class):
+ mock_sandbox = _make_mock_sandbox()
+ mock_sandbox.is_running.return_value = False
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ StreamlitAppSandbox.objects.create(
+ app=app, version=version, sandbox_id="modal-123", status=StreamlitAppSandbox.Status.RUNNING
+ )
+
+ service = AppRuntimeService()
+ status = service.get_status(app)
+ assert status["status"] == "stopped"
+
+ record = StreamlitAppSandbox.objects.get(app=app)
+ assert record.status == StreamlitAppSandbox.Status.STOPPED
+
+
+@patch("products.streamlit_apps.backend.logic.app_runtime._wait_for_health", return_value=True)
+@patch("products.streamlit_apps.backend.logic.app_runtime.get_sandbox_class")
+class TestAppRuntimeRestartApp(BaseTest):
+ def _make_restartable_app(self, restart_count: int = 0, sandbox_status=None):
+ app = StreamlitApp.objects.create(team=self.team, name="Test App", restart_count=restart_count)
+ version = StreamlitAppVersion.objects.create(
+ app=app,
+ version_number=1,
+ zip_file="a.zip",
+ zip_hash="a",
+ snapshot_id="snap",
+ )
+ app.active_version = version
+ app.save(update_fields=["active_version"])
+ if sandbox_status is not None:
+ StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id="old",
+ status=sandbox_status,
+ )
+ return app, version
+
+ def test_restart_increments_count_and_defers_reset(self, mock_get_sandbox_class, _mock_wait):
+ """A successful restart increments restart_count but does NOT reset
+ it inline. The reset is handed to a Celery task scheduled with a
+ stability countdown, so a crash-loop that briefly reaches RUNNING
+ before dying can't wipe the counter."""
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._make_restartable_app(sandbox_status=StreamlitAppSandbox.Status.ERROR)
+
+ service = AppRuntimeService()
+ with patch("products.streamlit_apps.backend.logic.app_runtime._schedule_restart_count_reset") as mock_schedule:
+ record = service.restart_app(app)
+
+ assert record.status == StreamlitAppSandbox.Status.RUNNING
+ app.refresh_from_db()
+ assert app.restart_count == 1
+ mock_schedule.assert_called_once_with(str(app.id), app.team_id)
+
+ def test_restart_count_rolls_back_on_failure(self, mock_get_sandbox_class, _mock_wait):
+ """When start_app raises mid-restart, restart_count decrements so a
+ transient Modal flap doesn't permanently ratchet the cap."""
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._make_restartable_app(restart_count=1, sandbox_status=StreamlitAppSandbox.Status.ERROR)
+
+ service = AppRuntimeService()
+ with patch.object(service, "start_app", side_effect=AppRuntimeError("boom")):
+ with self.assertRaises(AppRuntimeError):
+ service.restart_app(app)
+
+ app.refresh_from_db()
+ # Bumped from 1 → 2 inside restart_app, then rolled back to 1 on the
+ # start_app failure. The cap survives the blip.
+ assert app.restart_count == 1
+
+ def test_restart_count_race_does_not_exceed_cap(self, mock_get_sandbox_class, _mock_wait):
+ """Sequential restart_app calls serialize on the StreamlitApp row
+ lock, so N+1 restarts where the first N succeed must cap out on the
+ (N+1)-th without allowing more than MAX_RESTART_COUNT increments."""
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._make_restartable_app()
+
+ service = AppRuntimeService()
+ with patch("products.streamlit_apps.backend.logic.app_runtime._schedule_restart_count_reset"):
+ for _ in range(MAX_RESTART_COUNT):
+ service.restart_app(app)
+
+ app.refresh_from_db()
+ assert app.restart_count == MAX_RESTART_COUNT
+
+ with self.assertRaises(AppRuntimeError):
+ service.restart_app(app)
+
+ def test_restart_concurrency_raises_concurrency_error(self, mock_get_sandbox_class, _mock_wait):
+ """A second restart while a previous lifecycle is still STARTING or
+ STOPPING raises AppRuntimeConcurrencyError, not the generic runtime
+ error — the task wrapper uses the specific subclass to pass through
+ without stamping the sandbox ERROR."""
+ app, _version = self._make_restartable_app(sandbox_status=StreamlitAppSandbox.Status.STARTING)
+
+ service = AppRuntimeService()
+ with self.assertRaises(AppRuntimeConcurrencyError):
+ service.restart_app(app)
+
+ # Cap was untouched — the concurrent-restart path never entered the
+ # increment block.
+ app.refresh_from_db()
+ assert app.restart_count == 0
+
+ def test_restart_exceeds_max_raises(self, mock_get_sandbox_class, _mock_wait):
+ app, _version = self._make_restartable_app(
+ restart_count=MAX_RESTART_COUNT, sandbox_status=StreamlitAppSandbox.Status.ERROR
+ )
+
+ service = AppRuntimeService()
+ with self.assertRaises(AppRuntimeError, msg="Max restart count"):
+ service.restart_app(app)
+
+ def test_start_app_fails_when_streamlit_not_ready(self, mock_get_sandbox_class, _mock_wait):
+ """Even after the auth proxy is ready, the sandbox must not be
+ promoted to RUNNING until Streamlit itself passes its readiness
+ probe — otherwise the iframe opens on a 502."""
+ mock_sandbox = _make_mock_sandbox()
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _version = self._make_restartable_app()
+
+ service = AppRuntimeService()
+ with patch(
+ "products.streamlit_apps.backend.logic.app_runtime._wait_for_health",
+ side_effect=lambda sandbox, url, name, deadline_seconds, poll_interval_seconds=1.0: name == "Auth proxy",
+ ):
+ with self.assertRaises(AppRuntimeError, msg="Streamlit failed to become ready"):
+ service.start_app(app)
+
+
+class TestWaitForHealth(BaseTest):
+ def test_returns_true_on_200(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _wait_for_health
+
+ sandbox = MagicMock()
+ sandbox.execute.return_value = MagicMock(stdout="200")
+ assert _wait_for_health(sandbox, "http://x/healthz", "x", deadline_seconds=5) is True
+ assert sandbox.execute.call_count == 1
+
+ def test_stops_at_deadline_when_never_healthy(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _wait_for_health
+
+ sandbox = MagicMock()
+ sandbox.execute.return_value = MagicMock(stdout="502")
+ assert (
+ _wait_for_health(sandbox, "http://x/healthz", "x", deadline_seconds=0.05, poll_interval_seconds=0) is False
+ )
+ assert sandbox.execute.call_count >= 1
+
+
+class TestResetRestartCountIfStable(BaseTest):
+ """The deferred reset task fires after a stability window and only resets
+ restart_count if the sandbox is still RUNNING at fire time."""
+
+ def _make_sandbox(self, *, restart_count: int, status, started_at):
+ app = StreamlitApp.objects.create(team=self.team, name="T", restart_count=restart_count)
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id="sb",
+ status=status,
+ started_at=started_at,
+ )
+ return app
+
+ def test_reset_when_running_and_stable(self):
+ app = self._make_sandbox(
+ restart_count=2,
+ status=StreamlitAppSandbox.Status.RUNNING,
+ started_at=timezone.now() - timedelta(seconds=RESTART_COUNT_STABILITY_SECONDS + 10),
+ )
+
+ from products.streamlit_apps.backend.tasks import reset_streamlit_app_restart_count_if_stable
+
+ reset_streamlit_app_restart_count_if_stable(str(app.id), team_id=app.team_id)
+
+ app.refresh_from_db()
+ assert app.restart_count == 0
+
+ def test_skip_when_not_running(self):
+ app = self._make_sandbox(
+ restart_count=2,
+ status=StreamlitAppSandbox.Status.ERROR,
+ started_at=timezone.now() - timedelta(seconds=RESTART_COUNT_STABILITY_SECONDS + 10),
+ )
+
+ from products.streamlit_apps.backend.tasks import reset_streamlit_app_restart_count_if_stable
+
+ reset_streamlit_app_restart_count_if_stable(str(app.id), team_id=app.team_id)
+
+ app.refresh_from_db()
+ assert app.restart_count == 2
+
+ def test_skip_when_too_recent(self):
+ app = self._make_sandbox(
+ restart_count=2,
+ status=StreamlitAppSandbox.Status.RUNNING,
+ started_at=timezone.now() - timedelta(seconds=60),
+ )
+
+ from products.streamlit_apps.backend.tasks import reset_streamlit_app_restart_count_if_stable
+
+ reset_streamlit_app_restart_count_if_stable(str(app.id), team_id=app.team_id)
+
+ app.refresh_from_db()
+ assert app.restart_count == 2
+
+
+class TestSyncSandboxStatus(BaseTest):
+ """_sync_sandbox_status must never promote STARTING → RUNNING — that
+ path is reserved for start_app after both readiness probes pass."""
+
+ def test_sync_does_not_promote_starting_to_running(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _sync_sandbox_status
+
+ app = StreamlitApp.objects.create(team=self.team, name="T")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ sandbox_record = StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id="modal-123",
+ status=StreamlitAppSandbox.Status.STARTING,
+ )
+
+ with patch("products.streamlit_apps.backend.logic.app_runtime.get_sandbox_class") as mock_cls:
+ mock_sandbox = MagicMock()
+ mock_sandbox.is_running.return_value = True
+ mock_cls.return_value.get_by_id.return_value = mock_sandbox
+ result = _sync_sandbox_status(sandbox_record)
+
+ assert result.status == StreamlitAppSandbox.Status.STARTING
+
+ def test_sync_expires_stuck_starting_to_error(self):
+ from products.streamlit_apps.backend.logic.app_runtime import STARTING_TIMEOUT_SECONDS, _sync_sandbox_status
+
+ app = StreamlitApp.objects.create(team=self.team, name="T")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ # Backdate started_at past the startup budget: started_at is the
+ # reference _sync_sandbox_status uses for the STARTING age check,
+ # and start_app stamps it on every new attempt.
+ sandbox_record = StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id="",
+ status=StreamlitAppSandbox.Status.STARTING,
+ started_at=timezone.now() - timedelta(seconds=STARTING_TIMEOUT_SECONDS + 10),
+ )
+
+ result = _sync_sandbox_status(sandbox_record)
+ assert result.status == StreamlitAppSandbox.Status.ERROR
+ assert "timed out" in result.last_error.lower()
+
+ def test_sync_does_not_time_out_starting_record_with_stale_created_at(self):
+ """Regression: the OneToOne sandbox row is reused across lifecycles,
+ so created_at quickly becomes ancient. A STARTING record whose
+ created_at is hours old but whose started_at reflects a recent
+ attempt must NOT be marked as timed out — the age check uses
+ started_at which tracks this particular attempt.
+ """
+ from products.streamlit_apps.backend.logic.app_runtime import STARTING_TIMEOUT_SECONDS, _sync_sandbox_status
+
+ app = StreamlitApp.objects.create(team=self.team, name="T")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ now = timezone.now()
+ sandbox_record = StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id="sb-recent",
+ status=StreamlitAppSandbox.Status.STARTING,
+ started_at=now - timedelta(seconds=10),
+ )
+ # Push created_at way into the past to simulate a row reused
+ # across multiple sandbox lifecycles.
+ StreamlitAppSandbox.objects.filter(id=sandbox_record.id).update(
+ created_at=now - timedelta(seconds=STARTING_TIMEOUT_SECONDS + 3600)
+ )
+ sandbox_record.refresh_from_db()
+
+ result = _sync_sandbox_status(sandbox_record)
+
+ assert result.status == StreamlitAppSandbox.Status.STARTING
+ assert result.last_error == ""
+
+
+class TestBuildSandboxConfig(BaseTest):
+ def test_config_sets_snapshot_when_available(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(
+ app=app, version_number=1, zip_file="a.zip", zip_hash="a", snapshot_id="snap-123"
+ )
+
+ config = _build_sandbox_config(app, version)
+ assert config.snapshot_id == "snap-123"
+
+ def test_config_no_snapshot_when_absent(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+
+ config = _build_sandbox_config(app, version)
+ assert config.snapshot_id is None
+
+ @parameterized.expand(
+ [
+ (0.01, 64, 0.25, 16.0),
+ (100, 0.1, 8.0, 0.5),
+ (2, 4, 2.0, 4.0),
+ ]
+ )
+ def test_config_clamps_resources_to_server_side_bounds(self, cpu, memory, expected_cpu, expected_memory):
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App", cpu_cores=cpu, memory_gb=memory)
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+
+ config = _build_sandbox_config(app, version)
+ assert config.cpu_cores == expected_cpu
+ assert config.memory_gb == expected_memory
+
+ @override_settings(SITE_URL="https://us.posthog.com")
+ @patch.dict("os.environ", {"STREAMLIT_SANDBOX_CALLBACK_URL": ""})
+ def test_config_locks_outbound_egress_to_posthog_hosts(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+
+ config = _build_sandbox_config(app, version)
+ assert config.outbound_domain_allowlist == ["us.posthog.com"]
+
+ @override_settings(SITE_URL="http://localhost:8000")
+ @patch.dict("os.environ", {"STREAMLIT_SANDBOX_CALLBACK_URL": ""})
+ def test_config_skips_allowlist_for_loopback_hosts(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+
+ config = _build_sandbox_config(app, version)
+ assert config.outbound_domain_allowlist is None
+
+ def test_config_does_not_inject_bridge_env_vars(self):
+ """The bridge token is delivered via /run/bridge_token (file-based),
+ never as an env var. POSTHOG_BRIDGE_URL was removed too — the in-sandbox
+ shim talks to the localhost auth proxy instead.
+ """
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+
+ config = _build_sandbox_config(app, version)
+ assert config.environment_variables is not None
+ assert "POSTHOG_BRIDGE_URL" not in config.environment_variables
+ assert "POSTHOG_BRIDGE_TOKEN" not in config.environment_variables
+ assert config.environment_variables["POSTHOG_TEAM_ID"] == str(app.team_id)
+
+ def test_config_injects_streamlit_client_id(self):
+ """The proxy needs POSTHOG_STREAMLIT_CLIENT_ID to reject tokens minted
+ against other OAuth applications even when they carry matching
+ scoped_teams. Missing this env var makes the proxy refuse to start."""
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+ from products.streamlit_apps.backend.logic.oauth import STREAMLIT_OAUTH_CLIENT_ID
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+
+ config = _build_sandbox_config(app, version)
+ assert config.environment_variables is not None
+ assert config.environment_variables["POSTHOG_STREAMLIT_CLIENT_ID"] == STREAMLIT_OAUTH_CLIENT_ID
+
+ def test_config_includes_otel_env_vars(self):
+ from products.streamlit_apps.backend.logic.app_runtime import _build_sandbox_config
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+
+ config = _build_sandbox_config(app, version)
+ env = config.environment_variables
+ assert env is not None
+ # Endpoint points at the /i/v1/logs path on whatever callback URL we use
+ assert env["OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"].endswith("/i/v1/logs")
+ # Authorization header carries the bearer token
+ assert env["OTEL_EXPORTER_OTLP_HEADERS"].startswith("authorization=Bearer ")
+ # Resource attrs identify the service and the owning app
+ attrs = env["OTEL_RESOURCE_ATTRIBUTES"]
+ assert "service.name=streamlit-auth-proxy" in attrs
+ assert f"posthog.team_id={app.team_id}" in attrs
+ assert f"posthog.app_id={app.id}" in attrs
+
+
+class TestGetOtelLogsConfig(BaseTest):
+ @parameterized.expand(
+ [
+ ("dev_or_self_hosted", False, None, "https://example.ngrok.io/i/v1/logs", "phc_local"),
+ (
+ "cloud_us",
+ True,
+ "US",
+ "https://us.i.posthog.com/i/v1/logs",
+ "sTMFPsFhdP1Ssg",
+ ),
+ (
+ "cloud_eu",
+ True,
+ "EU",
+ "https://eu.i.posthog.com/i/v1/logs",
+ "phc_dZ4GK1LRjhB97XozMSkEwPXx7OVANaJEwLErkY1phUF",
+ ),
+ (
+ "cloud_unknown_region_defaults_to_us",
+ True,
+ None,
+ "https://us.i.posthog.com/i/v1/logs",
+ "sTMFPsFhdP1Ssg",
+ ),
+ ]
+ )
+ def test_endpoint_and_token(self, _name, is_cloud, region, expected_endpoint, expected_token):
+ from products.streamlit_apps.backend.logic import app_runtime
+
+ # Patch the bound names inside app_runtime, NOT the original module —
+ # `from posthog.cloud_utils import is_cloud` copies the reference into
+ # app_runtime's namespace, so patching the source has no effect.
+ with (
+ patch.object(app_runtime, "is_cloud", return_value=is_cloud),
+ patch.object(app_runtime, "get_instance_region", return_value=region),
+ ):
+ endpoint, token = app_runtime._get_otel_logs_config("https://example.ngrok.io")
+
+ assert endpoint == expected_endpoint
+ assert token == expected_token
+
+
+@patch("products.streamlit_apps.backend.logic.app_runtime.get_sandbox_class")
+class TestAppRuntimeConnectUrl(BaseTest):
+ def _create_running_app(self):
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ app.active_version = version
+ app.save(update_fields=["active_version"])
+ sandbox = StreamlitAppSandbox.objects.create(
+ app=app, version=version, sandbox_id="modal-123", status=StreamlitAppSandbox.Status.RUNNING
+ )
+ return app, sandbox
+
+ def test_get_connect_url_returns_url_and_token(self, mock_get_sandbox_class):
+ mock_sandbox = MagicMock()
+ creds = MagicMock()
+ creds.url = "https://abc.modal.run"
+ creds.token = "tok_abc123"
+ mock_sandbox.is_running.return_value = True
+ mock_sandbox.get_connect_credentials.return_value = creds
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _sandbox = self._create_running_app()
+ service = AppRuntimeService()
+ result = service.get_connect_url(app, user_id=1, team_id=1)
+ assert result == {"url": "https://abc.modal.run", "token": "tok_abc123"}
+
+ @parameterized.expand(
+ [
+ ("stopped", StreamlitAppSandbox.Status.STOPPED),
+ ("starting", StreamlitAppSandbox.Status.STARTING),
+ ("error", StreamlitAppSandbox.Status.ERROR),
+ ]
+ )
+ def test_get_connect_url_returns_none_for_non_running(self, mock_get_sandbox_class, _name, sandbox_status):
+ mock_get_sandbox_class.return_value.get_by_id.return_value.is_running.return_value = False
+
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ version = StreamlitAppVersion.objects.create(app=app, version_number=1, zip_file="a.zip", zip_hash="a")
+ StreamlitAppSandbox.objects.create(app=app, version=version, sandbox_id="modal-123", status=sandbox_status)
+
+ service = AppRuntimeService()
+ assert service.get_connect_url(app, user_id=1, team_id=1) is None
+
+ def test_get_connect_url_returns_none_when_no_sandbox(self, mock_get_sandbox_class):
+ app = StreamlitApp.objects.create(team=self.team, name="Test App")
+ service = AppRuntimeService()
+ assert service.get_connect_url(app, user_id=1, team_id=1) is None
+
+ def test_get_connect_url_calls_get_connect_credentials(self, mock_get_sandbox_class):
+ # The auth proxy inside the sandbox identifies the user via the OAuth
+ # access token injected into the URL, so we don't need to pass user
+ # metadata through the Modal connect token itself.
+ mock_sandbox = MagicMock()
+ creds = MagicMock()
+ creds.url = "https://x.modal.run"
+ creds.token = "tok"
+ mock_sandbox.is_running.return_value = True
+ mock_sandbox.get_connect_credentials.return_value = creds
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _sandbox = self._create_running_app()
+ service = AppRuntimeService()
+ service.get_connect_url(app, user_id=42, team_id=7)
+
+ mock_sandbox.get_connect_credentials.assert_called_once()
+
+ def test_get_connect_url_detects_timed_out_sandbox(self, mock_get_sandbox_class):
+ mock_sandbox = MagicMock()
+ mock_sandbox.is_running.return_value = False
+ mock_get_sandbox_class.return_value = _make_mock_sandbox_class(mock_sandbox)
+
+ app, _sandbox = self._create_running_app()
+ service = AppRuntimeService()
+ result = service.get_connect_url(app, user_id=1, team_id=1)
+
+ assert result is None
+ record = StreamlitAppSandbox.objects.get(app=app)
+ assert record.status == StreamlitAppSandbox.Status.STOPPED
+
+
+class TestSandboxCallbackUrl(BaseTest):
+ """Docker sandboxes reach the host via host.docker.internal (applied to
+ SITE_URL by DockerSandbox), so they must ignore the STREAMLIT_SANDBOX_CALLBACK_URL
+ tunnel override that only Modal needs. Honoring a stale tunnel here points a
+ Docker sandbox at a dead URL and breaks token introspection."""
+
+ @override_settings(SANDBOX_PROVIDER="docker", SITE_URL="http://localhost:8000")
+ @patch.dict("os.environ", {"STREAMLIT_SANDBOX_CALLBACK_URL": "https://stale-tunnel.ngrok.dev"})
+ def test_docker_ignores_tunnel_override(self):
+ assert _get_sandbox_callback_url() == "http://localhost:8000"
+
+ @override_settings(SANDBOX_PROVIDER="modal", SITE_URL="http://localhost:8000")
+ @patch.dict("os.environ", {"STREAMLIT_SANDBOX_CALLBACK_URL": "https://tunnel.ngrok.dev"})
+ def test_modal_uses_tunnel_override(self):
+ assert _get_sandbox_callback_url() == "https://tunnel.ngrok.dev"
+
+ @override_settings(SANDBOX_PROVIDER="modal", SITE_URL="http://localhost:8000")
+ @patch.dict("os.environ", {}, clear=True)
+ def test_modal_falls_back_to_site_url(self):
+ assert _get_sandbox_callback_url() == "http://localhost:8000"
diff --git a/products/streamlit_apps/backend/tests/test_bridge.py b/products/streamlit_apps/backend/tests/test_bridge.py
new file mode 100644
index 000000000000..1cda57224c1d
--- /dev/null
+++ b/products/streamlit_apps/backend/tests/test_bridge.py
@@ -0,0 +1,50 @@
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from products.streamlit_apps.backend.logic.bridge import execute_bridge_query
+
+
+class TestExecuteBridgeQuery(BaseTest):
+ @patch("products.streamlit_apps.backend.logic.bridge.execute_hogql_query")
+ def test_returns_whitelisted_response(self, mock_execute):
+ """Only the columns/results/types fields are surfaced — clickhouse SQL,
+ hogql AST, internal timings, and modifiers must NOT leak through."""
+ response = MagicMock()
+ response.model_dump.return_value = {
+ "results": [[1, "hello"]],
+ "columns": ["id", "name"],
+ "clickhouse": "SELECT ...",
+ "hogql": "SELECT ...",
+ "timings": {"total": 0.1},
+ "modifiers": {},
+ "types": [["Int64"], ["String"]],
+ }
+ mock_execute.return_value = response
+
+ result = execute_bridge_query(query="SELECT 1", team_id=self.team.id)
+
+ assert result["results"] == [[1, "hello"]]
+ assert result["columns"] == ["id", "name"]
+ assert result["types"] == [["Int64"], ["String"]]
+ assert "clickhouse" not in result
+ assert "hogql" not in result
+ assert "timings" not in result
+ assert "modifiers" not in result
+
+ @patch("products.streamlit_apps.backend.logic.bridge.execute_hogql_query")
+ def test_passes_query_and_team(self, mock_execute):
+ response = MagicMock()
+ response.model_dump.return_value = {"results": [], "columns": []}
+ mock_execute.return_value = response
+
+ execute_bridge_query(query="SELECT event FROM events", team_id=self.team.id)
+
+ mock_execute.assert_called_once()
+ call_kwargs = mock_execute.call_args
+ assert call_kwargs.kwargs["query"] == "SELECT event FROM events"
+ assert call_kwargs.kwargs["team"].id == self.team.id
+
+ def test_invalid_team_raises(self):
+ with pytest.raises(Exception):
+ execute_bridge_query(query="SELECT 1", team_id=999999)
diff --git a/products/streamlit_apps/backend/tests/test_proxy.py b/products/streamlit_apps/backend/tests/test_proxy.py
new file mode 100644
index 000000000000..3e53fcfa2032
--- /dev/null
+++ b/products/streamlit_apps/backend/tests/test_proxy.py
@@ -0,0 +1,348 @@
+"""Unit tests for the in-sandbox auth proxy (streamlit_auth_proxy.py).
+
+The proxy runs as a standalone Python process inside the Modal sandbox, so
+it isn't exercised end-to-end in CI. These tests exercise its helper
+functions directly — mainly the startup config check and the introspection
+validator — because they gate auth decisions and are the highest-risk code
+paths.
+"""
+
+import json
+
+import pytest
+from unittest import mock
+
+from products.tasks.backend.sandbox.images import streamlit_auth_proxy
+
+
+def _make_introspection_response(**overrides):
+ """Default 200 + active introspection payload with expected fields.
+
+ The default scope includes `streamlit:iframe` so existing "accept" tests
+ don't need to opt in to the scope check. Tests that exercise wrong-scope
+ rejection pass their own `scope=` override.
+ """
+ data = {
+ "active": True,
+ "token_type": "access_token",
+ "scope": "streamlit:iframe",
+ "scoped_teams": [42],
+ "client_id": "posthog-streamlit-apps-first-party",
+ "exp": 99999999999,
+ }
+ data.update(overrides)
+ return json.dumps(data).encode("utf-8")
+
+
+def _make_fake_session(*, status: int, body: bytes):
+ """Build a MagicMock aiohttp.ClientSession whose .post() returns an async
+ context manager yielding a response object with `.status` and `.read()`.
+ """
+ resp = mock.MagicMock()
+ resp.status = status
+ resp.read = mock.AsyncMock(return_value=body)
+
+ cm = mock.MagicMock()
+ cm.__aenter__ = mock.AsyncMock(return_value=resp)
+ cm.__aexit__ = mock.AsyncMock(return_value=None)
+
+ session = mock.MagicMock()
+ session.post = mock.MagicMock(return_value=cm)
+ return session
+
+
[email protected](autouse=True)
+def _reset_proxy_module_state(monkeypatch):
+ """Every test starts from a clean cache / circuit-breaker state and a
+ POSTHOG_SITE_URL set so _introspect_token doesn't short-circuit."""
+ streamlit_auth_proxy._introspection_cache.clear()
+ streamlit_auth_proxy._introspection_circuit.reset()
+ monkeypatch.setattr(streamlit_auth_proxy, "POSTHOG_SITE_URL", "https://app.posthog.test")
+ yield
+ streamlit_auth_proxy._introspection_cache.clear()
+ streamlit_auth_proxy._introspection_circuit.reset()
+
+
+# ---------- create_app() startup config validation ----------
+
+
+class TestCreateAppConfigValidation:
+ def test_raises_when_team_id_missing(self, monkeypatch):
+ monkeypatch.delenv("POSTHOG_TEAM_ID", raising=False)
+ monkeypatch.setenv("POSTHOG_STREAMLIT_CLIENT_ID", "posthog-streamlit-apps-first-party")
+
+ with pytest.raises(RuntimeError, match="POSTHOG_TEAM_ID"):
+ streamlit_auth_proxy.create_app()
+
+ def test_raises_when_team_id_is_zero(self, monkeypatch):
+ monkeypatch.setenv("POSTHOG_TEAM_ID", "0")
+ monkeypatch.setenv("POSTHOG_STREAMLIT_CLIENT_ID", "posthog-streamlit-apps-first-party")
+
+ with pytest.raises(RuntimeError, match="POSTHOG_TEAM_ID"):
+ streamlit_auth_proxy.create_app()
+
+ def test_raises_when_team_id_is_non_numeric(self, monkeypatch):
+ monkeypatch.setenv("POSTHOG_TEAM_ID", "not-a-number")
+ monkeypatch.setenv("POSTHOG_STREAMLIT_CLIENT_ID", "posthog-streamlit-apps-first-party")
+
+ with pytest.raises(RuntimeError, match="POSTHOG_TEAM_ID"):
+ streamlit_auth_proxy.create_app()
+
+ def test_raises_when_client_id_missing(self, monkeypatch):
+ monkeypatch.setenv("POSTHOG_TEAM_ID", "42")
+ monkeypatch.delenv("POSTHOG_STREAMLIT_CLIENT_ID", raising=False)
+
+ with pytest.raises(RuntimeError, match="POSTHOG_STREAMLIT_CLIENT_ID"):
+ streamlit_auth_proxy.create_app()
+
+ def test_raises_when_client_id_is_empty_string(self, monkeypatch):
+ monkeypatch.setenv("POSTHOG_TEAM_ID", "42")
+ monkeypatch.setenv("POSTHOG_STREAMLIT_CLIENT_ID", "")
+
+ with pytest.raises(RuntimeError, match="POSTHOG_STREAMLIT_CLIENT_ID"):
+ streamlit_auth_proxy.create_app()
+
+ def test_succeeds_with_valid_env(self, monkeypatch):
+ monkeypatch.setenv("POSTHOG_TEAM_ID", "42")
+ monkeypatch.setenv("POSTHOG_STREAMLIT_CLIENT_ID", "posthog-streamlit-apps-first-party")
+
+ app = streamlit_auth_proxy.create_app()
+
+ assert app["posthog_team_id"] == 42
+ assert app["posthog_streamlit_client_id"] == "posthog-streamlit-apps-first-party"
+
+
+# ---------- _introspect_token cross-app and team binding ----------
+
+
+class TestIntrospectTokenSecurity:
+ @pytest.mark.asyncio
+ async def test_accepts_token_with_matching_team_and_client_id(self):
+ session = _make_fake_session(
+ status=200,
+ body=_make_introspection_response(
+ scoped_teams=[42],
+ client_id="posthog-streamlit-apps-first-party",
+ ),
+ )
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "valid-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is not None
+ assert result["active"] is True
+
+ @pytest.mark.asyncio
+ async def test_rejects_token_from_other_application(self):
+ """A first-party OAuth token with matching team scope but a different
+ application client_id (e.g. the MCP app) must be rejected — otherwise
+ any token with query:read and the right team could unlock any sandbox.
+ """
+ session = _make_fake_session(
+ status=200,
+ body=_make_introspection_response(
+ scoped_teams=[42],
+ client_id="some-other-posthog-app",
+ ),
+ )
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "cross-app-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_rejects_token_with_missing_client_id(self):
+ """Defensive: if the introspection response omits client_id entirely,
+ reject (don't compare None == str and accept)."""
+ body = json.dumps(
+ {
+ "active": True,
+ "scope": "query:read",
+ "scoped_teams": [42],
+ # no client_id
+ }
+ ).encode("utf-8")
+ session = _make_fake_session(status=200, body=body)
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "missing-client-id-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_rejects_token_from_other_team(self):
+ session = _make_fake_session(
+ status=200,
+ body=_make_introspection_response(
+ scoped_teams=[99], # wrong team
+ client_id="posthog-streamlit-apps-first-party",
+ ),
+ )
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "cross-team-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_rejects_inactive_token(self):
+ session = _make_fake_session(
+ status=200,
+ body=_make_introspection_response(active=False),
+ )
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "inactive-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_rejects_token_when_introspection_returns_non_200(self):
+ session = _make_fake_session(status=500, body=b'{"error":"boom"}')
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "upstream-500-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_rejects_token_with_bridge_scope_on_iframe_path(self):
+ """A first-party OAuth token from the streamlit app with matching team
+ and client_id but carrying the BRIDGE scope (`streamlit:bridge`) must
+ be rejected on the iframe path. The B.2.5 scope split is meaningless
+ unless the proxy enforces it — without this check, a leaked bridge
+ token would unlock the iframe even though it was minted for the
+ sandbox→PostHog backchannel hop.
+ """
+ session = _make_fake_session(
+ status=200,
+ body=_make_introspection_response(
+ scope="query:read streamlit:bridge",
+ scoped_teams=[42],
+ client_id="posthog-streamlit-apps-first-party",
+ ),
+ )
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "bridge-scope-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is None
+
+ @pytest.mark.asyncio
+ async def test_rejects_token_with_only_query_read_scope(self):
+ """Defensive: a token with just `query:read` (no streamlit:iframe /
+ streamlit:bridge qualifier at all) must also be rejected on the
+ iframe path. This catches pre-scope-split tokens and any third-party
+ query:read token that happens to pass the client_id + team checks.
+ """
+ session = _make_fake_session(
+ status=200,
+ body=_make_introspection_response(
+ scope="query:read",
+ scoped_teams=[42],
+ client_id="posthog-streamlit-apps-first-party",
+ ),
+ )
+
+ result = await streamlit_auth_proxy._introspect_token(
+ session,
+ "plain-query-read-token",
+ team_id=42,
+ expected_client_id="posthog-streamlit-apps-first-party",
+ expected_scope_component="streamlit:iframe",
+ )
+
+ assert result is None
+
+
+class TestTokenInjectionHostScoping:
+ """The HTML rewrite must only append auth tokens to same-origin relative
+ URLs. A protocol-relative URL (//evil.com) or absolute URL points at a
+ foreign host, so appending _posthog_token there would leak the viewer's
+ token cross-origin."""
+
+ MODAL_TOKEN = "modal-secret"
+ POSTHOG_TOKEN = "posthog-secret"
+
+ def _inject(self, body: str) -> str:
+ return streamlit_auth_proxy._inject_token_into_html(
+ body.encode("utf-8"), self.MODAL_TOKEN, self.POSTHOG_TOKEN
+ ).decode("utf-8")
+
+ def test_appends_token_to_same_origin_relative_url(self):
+ out = self._inject('<html><head></head><body><img src="/static/logo.png"></body></html>')
+ assert "/static/logo.png?_modal_connect_token=" in out
+
+ def test_does_not_leak_token_to_protocol_relative_url(self):
+ out = self._inject('<html><head></head><body><script src="//evil.com/x.js"></script></body></html>')
+ assert "//evil.com/x.js?_modal_connect_token=" not in out
+
+ def test_does_not_leak_token_to_absolute_url(self):
+ out = self._inject('<html><head></head><body><img src="https://evil.com/x.png"></body></html>')
+ assert "https://evil.com/x.png?_modal_connect_token=" not in out
+
+
+class TestTokenInjectionWithoutModalToken:
+ """Docker sandboxes have no Modal connect token. The shim must still inject
+ the posthog token (gating on the modal token would leave every Streamlit
+ sub-request unauthenticated on Docker)."""
+
+ def test_injects_posthog_token_with_empty_modal_token(self):
+ out = streamlit_auth_proxy._inject_token_into_html(
+ b"<html><head></head><body><img src='/x.png'></body></html>", "", "ptok"
+ ).decode()
+ # posthog token still appended to relative URLs and JS shim present
+ assert "_posthog_token=ptok" in out
+ assert "<script>" in out
+ # no empty modal token param leaks in
+ assert "_modal_connect_token=" not in out
+
+ def test_includes_modal_token_when_present(self):
+ out = streamlit_auth_proxy._inject_token_into_html(
+ b"<html><head></head><body><img src='/x.png'></body></html>", "mtok", "ptok"
+ ).decode()
+ assert "_modal_connect_token=mtok" in out
+ assert "_posthog_token=ptok" in out
+
+
+class TestAuthExemptPrefixes:
+ def test_stcore_health_is_auth_exempt(self):
+ # Streamlit's liveness probe must not require the token, or the iframe
+ # 401s before the app loads.
+ assert any("/_stcore/health".startswith(p) for p in streamlit_auth_proxy._AUTH_EXEMPT_PREFIXES)
diff --git a/products/streamlit_apps/backend/tests/test_tasks.py b/products/streamlit_apps/backend/tests/test_tasks.py
new file mode 100644
index 000000000000..cdedae2b265f
--- /dev/null
+++ b/products/streamlit_apps/backend/tests/test_tasks.py
@@ -0,0 +1,266 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.streamlit_apps.backend.logic.app_runtime import MAX_RESTART_COUNT, TTL_TIMEOUT_LAST_ERROR
+from products.streamlit_apps.backend.models import StreamlitApp, StreamlitAppSandbox, StreamlitAppVersion
+from products.streamlit_apps.backend.tasks.tasks import (
+ _IDLE_TIMEOUT_MINUTES,
+ _VERSION_RETENTION_DAYS,
+ auto_restart_crashed_streamlit_sandboxes,
+ prune_old_streamlit_app_versions,
+ stop_idle_streamlit_sandboxes,
+)
+
+
+class _LifecycleTestMixin:
+ """Shared helpers to spin up app + version + sandbox rows."""
+
+ team: Team
+
+ def _make_app(self, **kwargs) -> StreamlitApp:
+ defaults = {"team": self.team, "name": "T"}
+ defaults.update(kwargs)
+ return StreamlitApp.objects.create(**defaults)
+
+ def _make_version(self, app: StreamlitApp, number: int = 1, **kwargs) -> StreamlitAppVersion:
+ defaults = {
+ "app": app,
+ "version_number": number,
+ "zip_file": f"streamlit_apps/{app.team_id}/{app.id}/v{number}.zip",
+ "zip_hash": f"hash_{number}",
+ }
+ defaults.update(kwargs)
+ return StreamlitAppVersion.objects.create(**defaults)
+
+ def _make_sandbox(self, app, version, *, status, last_activity_at=None, started_at=None, last_error=""):
+ return StreamlitAppSandbox.objects.create(
+ app=app,
+ version=version,
+ sandbox_id=f"sb_{app.short_id}",
+ status=status,
+ last_activity_at=last_activity_at,
+ started_at=started_at,
+ last_error=last_error,
+ )
+
+
+class TestStopIdleStreamlitSandboxes(_LifecycleTestMixin, BaseTest):
+ @patch("products.streamlit_apps.backend.logic.app_runtime.AppRuntimeService")
+ def test_idle_running_sandbox_gets_stopped(self, runtime_cls):
+ app = self._make_app()
+ v = self._make_version(app)
+ idle_at = timezone.now() - timedelta(minutes=_IDLE_TIMEOUT_MINUTES + 1)
+ self._make_sandbox(app, v, status=StreamlitAppSandbox.Status.RUNNING, last_activity_at=idle_at)
+
+ stopped = stop_idle_streamlit_sandboxes()
+
+ assert stopped == 1
+ runtime_cls.return_value.stop_app.assert_called_once_with(app)
+
+ @patch("products.streamlit_apps.backend.logic.app_runtime.AppRuntimeService")
+ def test_fresh_running_sandbox_is_left_alone(self, runtime_cls):
+ app = self._make_app()
+ v = self._make_version(app)
+ recent = timezone.now() - timedelta(minutes=_IDLE_TIMEOUT_MINUTES - 5)
+ self._make_sandbox(app, v, status=StreamlitAppSandbox.Status.RUNNING, last_activity_at=recent)
+
+ stopped = stop_idle_streamlit_sandboxes()
+
+ assert stopped == 0
+ runtime_cls.return_value.stop_app.assert_not_called()
+
+ @patch("products.streamlit_apps.backend.logic.app_runtime.AppRuntimeService")
+ def test_null_last_activity_falls_back_to_started_at(self, runtime_cls):
+ """A sandbox booted long ago that received zero proxy traffic should
+ still count as idle — otherwise `last_activity_at IS NULL` apps leak."""
+ app = self._make_app()
+ v = self._make_version(app)
+ started = timezone.now() - timedelta(minutes=_IDLE_TIMEOUT_MINUTES + 1)
+ self._make_sandbox(
+ app,
+ v,
+ status=StreamlitAppSandbox.Status.RUNNING,
+ last_activity_at=None,
+ started_at=started,
+ )
+
+ stopped = stop_idle_streamlit_sandboxes()
+
+ assert stopped == 1
+ runtime_cls.return_value.stop_app.assert_called_once_with(app)
+
+ @parameterized.expand(
+ [
+ (StreamlitAppSandbox.Status.STOPPED,),
+ (StreamlitAppSandbox.Status.STOPPING,),
+ (StreamlitAppSandbox.Status.STARTING,),
+ (StreamlitAppSandbox.Status.ERROR,),
+ ]
+ )
+ @patch("products.streamlit_apps.backend.logic.app_runtime.AppRuntimeService")
+ def test_non_running_sandboxes_are_skipped(self, sandbox_status, runtime_cls):
+ app = self._make_app()
+ v = self._make_version(app)
+ idle_at = timezone.now() - timedelta(minutes=_IDLE_TIMEOUT_MINUTES + 1)
+ self._make_sandbox(app, v, status=sandbox_status, last_activity_at=idle_at)
+
+ stopped = stop_idle_streamlit_sandboxes()
+
+ assert stopped == 0
+ runtime_cls.return_value.stop_app.assert_not_called()
+
+ @patch("products.streamlit_apps.backend.logic.app_runtime.AppRuntimeService")
+ def test_one_failure_does_not_block_other_stops(self, runtime_cls):
+ """A flaky Modal call on one sandbox shouldn't strand the rest of the batch."""
+ a = self._make_app(name="A")
+ b = self._make_app(name="B")
+ va, vb = self._make_version(a), self._make_version(b)
+ idle_at = timezone.now() - timedelta(minutes=_IDLE_TIMEOUT_MINUTES + 1)
+ self._make_sandbox(a, va, status=StreamlitAppSandbox.Status.RUNNING, last_activity_at=idle_at)
+ self._make_sandbox(b, vb, status=StreamlitAppSandbox.Status.RUNNING, last_activity_at=idle_at)
+
+ # Fail on A, succeed on B (order is non-deterministic; both legs must
+ # be tolerated).
+ def fake_stop(app):
+ if app.name == "A":
+ raise RuntimeError("Modal down")
+
+ runtime_cls.return_value.stop_app.side_effect = fake_stop
+
+ stopped = stop_idle_streamlit_sandboxes()
+ assert stopped == 1
+ assert runtime_cls.return_value.stop_app.call_count == 2
+
+
+class TestAutoRestartCrashedStreamlitSandboxes(_LifecycleTestMixin, BaseTest):
+ @patch("products.streamlit_apps.backend.tasks.run_streamlit_app_lifecycle.delay")
+ def test_ttl_crash_triggers_restart(self, lifecycle_delay):
+ app = self._make_app(restart_count=1)
+ v = self._make_version(app)
+ self._make_sandbox(app, v, status=StreamlitAppSandbox.Status.STOPPED, last_error=TTL_TIMEOUT_LAST_ERROR)
+
+ restarted = auto_restart_crashed_streamlit_sandboxes()
+
+ assert restarted == 1
+ lifecycle_delay.assert_called_once_with(str(app.id), "restart", team_id=app.team_id)
+
+ @patch("products.streamlit_apps.backend.tasks.run_streamlit_app_lifecycle.delay")
+ def test_user_stopped_sandbox_is_not_restarted(self, lifecycle_delay):
+ app = self._make_app()
+ v = self._make_version(app)
+ # Any last_error other than the TTL marker counts as non-crash.
+ self._make_sandbox(app, v, status=StreamlitAppSandbox.Status.STOPPED, last_error="")
+
+ restarted = auto_restart_crashed_streamlit_sandboxes()
+
+ assert restarted == 0
+ lifecycle_delay.assert_not_called()
+
+ @patch("products.streamlit_apps.backend.tasks.run_streamlit_app_lifecycle.delay")
+ def test_restart_count_cap_is_honored(self, lifecycle_delay):
+ app = self._make_app(restart_count=MAX_RESTART_COUNT)
+ v = self._make_version(app)
+ self._make_sandbox(app, v, status=StreamlitAppSandbox.Status.STOPPED, last_error=TTL_TIMEOUT_LAST_ERROR)
+
+ restarted = auto_restart_crashed_streamlit_sandboxes()
+
+ assert restarted == 0
+ lifecycle_delay.assert_not_called()
+
+ @patch("products.streamlit_apps.backend.tasks.run_streamlit_app_lifecycle.delay")
+ def test_deleted_app_is_skipped(self, lifecycle_delay):
+ app = self._make_app(deleted=True)
+ v = self._make_version(app)
+ self._make_sandbox(app, v, status=StreamlitAppSandbox.Status.STOPPED, last_error=TTL_TIMEOUT_LAST_ERROR)
+
+ restarted = auto_restart_crashed_streamlit_sandboxes()
+
+ assert restarted == 0
+ lifecycle_delay.assert_not_called()
+
+
+class TestPruneOldStreamlitAppVersions(_LifecycleTestMixin, BaseTest):
+ def _make_old_version(self, app, number, age_days):
+ v = self._make_version(app, number)
+ # auto_now_add can't be overridden in create(); update after the fact.
+ StreamlitAppVersion.objects.filter(id=v.id).update(created_at=timezone.now() - timedelta(days=age_days))
+ v.refresh_from_db()
+ return v
+
+ @patch("posthog.storage.object_storage")
+ def test_prunes_old_non_active_version(self, mock_storage):
+ app = self._make_app()
+ v1 = self._make_old_version(app, 1, _VERSION_RETENTION_DAYS + 1)
+ v2 = self._make_version(app, 2)
+ app.active_version = v2
+ app.save()
+
+ pruned = prune_old_streamlit_app_versions()
+
+ assert pruned == 1
+ mock_storage.delete.assert_called_once_with(v1.zip_file)
+ assert not StreamlitAppVersion.objects.filter(id=v1.id).exists()
+ assert StreamlitAppVersion.objects.filter(id=v2.id).exists()
+
+ @patch("posthog.storage.object_storage")
+ def test_keeps_active_version_even_if_old(self, mock_storage):
+ """Active version must survive pruning even past the retention window —
+ an app whose owner ran it once and never updated should still work."""
+ app = self._make_app()
+ v1 = self._make_old_version(app, 1, _VERSION_RETENTION_DAYS + 30)
+ app.active_version = v1
+ app.save()
+
+ pruned = prune_old_streamlit_app_versions()
+
+ assert pruned == 0
+ mock_storage.delete.assert_not_called()
+ assert StreamlitAppVersion.objects.filter(id=v1.id).exists()
+
+ @patch("posthog.storage.object_storage")
+ def test_keeps_recent_non_active_version(self, mock_storage):
+ app = self._make_app()
+ self._make_old_version(app, 1, _VERSION_RETENTION_DAYS - 1) # not yet old enough
+ v2 = self._make_version(app, 2)
+ app.active_version = v2
+ app.save()
+
+ pruned = prune_old_streamlit_app_versions()
+
+ assert pruned == 0
+ mock_storage.delete.assert_not_called()
+
+ @patch("posthog.storage.object_storage")
+ def test_skips_versions_on_deleted_apps(self, mock_storage):
+ """Deleted-app cleanup is owned by cleanup_deleted_streamlit_app_zips —
+ this task must not double-handle that path."""
+ app = self._make_app(deleted=True)
+ self._make_old_version(app, 1, _VERSION_RETENTION_DAYS + 1)
+
+ pruned = prune_old_streamlit_app_versions()
+
+ assert pruned == 0
+ mock_storage.delete.assert_not_called()
+
+ @patch("posthog.storage.object_storage")
+ def test_storage_failure_keeps_row_for_retry(self, mock_storage):
+ app = self._make_app()
+ v1 = self._make_old_version(app, 1, _VERSION_RETENTION_DAYS + 1)
+ v2 = self._make_version(app, 2)
+ app.active_version = v2
+ app.save()
+ mock_storage.delete.side_effect = RuntimeError("S3 unavailable")
+
+ pruned = prune_old_streamlit_app_versions()
+
+ assert pruned == 0
+ # Row survives so the next run can retry.
+ assert StreamlitAppVersion.objects.filter(id=v1.id).exists()
diff --git a/products/streamlit_apps/backend/tests/test_zip_validator.py b/products/streamlit_apps/backend/tests/test_zip_validator.py
new file mode 100644
index 000000000000..4dda83c4f9f4
--- /dev/null
+++ b/products/streamlit_apps/backend/tests/test_zip_validator.py
@@ -0,0 +1,54 @@
+import zipfile
+from io import BytesIO
+
+from posthog.test.base import BaseTest
+
+from products.streamlit_apps.backend.logic.zip_validator import MAX_ZIP_SIZE, validate_zip
+
+
+def _make_zip(files: dict[str, str]) -> BytesIO:
+ buf = BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ for name, content in files.items():
+ zf.writestr(name, content)
+ buf.seek(0)
+ return buf
+
+
+class TestValidateZip(BaseTest):
+ def test_valid_zip_with_app_py(self):
+ zf = _make_zip({"app.py": "import streamlit as st"})
+ result = validate_zip(zf)
+ assert result.valid is True
+ assert "app.py" in result.files
+
+ def test_valid_zip_with_requirements_does_not_fail(self):
+ """requirements.txt is no longer enforced — uploads with one are
+ accepted (the file is silently ignored at sandbox-write time)."""
+ zf = _make_zip({"app.py": "pass", "requirements.txt": "pandas\nflask\n"})
+ result = validate_zip(zf)
+ assert result.valid is True
+
+ def test_missing_app_py(self):
+ zf = _make_zip({"main.py": "pass"})
+ result = validate_zip(zf)
+ assert result.valid is False
+ assert any("app.py" in e for e in result.errors)
+
+ def test_too_large(self):
+ buf = BytesIO(b"x" * (MAX_ZIP_SIZE + 1))
+ result = validate_zip(buf)
+ assert result.valid is False
+ assert any("too large" in e for e in result.errors)
+
+ def test_invalid_zip(self):
+ buf = BytesIO(b"not a zip file")
+ result = validate_zip(buf)
+ assert result.valid is False
+ assert any("Invalid zip" in e for e in result.errors)
+
+ def test_extra_files_allowed(self):
+ zf = _make_zip({"app.py": "pass", "data/sample.csv": "a,b\n1,2", "assets/logo.png": "fake"})
+ result = validate_zip(zf)
+ assert result.valid is True
+ assert len(result.files) == 3
diff --git a/products/streamlit_apps/manifest.tsx b/products/streamlit_apps/manifest.tsx
new file mode 100644
index 000000000000..2cf8b7689671
--- /dev/null
+++ b/products/streamlit_apps/manifest.tsx
@@ -0,0 +1,7 @@
+import { ProductManifest } from '~/types'
+
+export const manifest: ProductManifest = {
+ name: 'Streamlit apps',
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/streamlit_apps/package.json b/products/streamlit_apps/package.json
index 07c56eb3f685..5f60d81ca4b8 100644
--- a/products/streamlit_apps/package.json
+++ b/products/streamlit_apps/package.json
@@ -1,6 +1,7 @@
{
"name": "@posthog/products-streamlit-apps",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
}
}
diff --git a/products/streamlit_apps/tsconfig.json b/products/streamlit_apps/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/streamlit_apps/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-streamlit b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-streamlit
new file mode 100644
index 000000000000..3341fa6d493e
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-streamlit
@@ -0,0 +1,55 @@
+FROM python:3.11-slim@sha256:f9fa7f851e38bfb19c9de3afbc4b86ae7176ea7aaf94535c31df5458d5849457
+
+ENV DEBIAN_FRONTEND=noninteractive
+
+# Glob-pinned: exact deb revisions vanish from mirrors on security point
+# releases, which would 404 the build; the upstream version stays fixed.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ "curl=8.14.1*" \
+ && rm -rf /var/lib/apt/lists/*
+
+# Dedicated non-root user for the Streamlit runtime. The auth proxy still
+# starts as root (it needs to read mode-600 /run/bridge_token on boot), but
+# `streamlit run` is launched as this user so that user code inside the app
+# cannot read the bridge token, touch /proc/1, or otherwise escalate via uid 0.
+RUN useradd --create-home --shell /bin/bash streamlit
+
+WORKDIR /app
+
+# aiohttp must stay >=3.10.11 for the 3.9.x header-injection CVE fix.
+RUN pip install --no-cache-dir \
+ streamlit==1.31.0 \
+ aiohttp==3.14.1 \
+ numpy==1.26.4 \
+ pandas==2.2.2 \
+ polars==0.20.31 \
+ plotly==5.22.0 \
+ matplotlib==3.9.0 \
+ seaborn==0.13.2 \
+ scipy==1.13.1 \
+ scikit-learn==1.5.0 \
+ pyarrow==24.0.0 \
+ duckdb==1.5.3 \
+ requests==2.32.3 \
+ beautifulsoup4==4.12.3 \
+ lxml==6.1.1 \
+ sqlalchemy==2.0.30 \
+ opentelemetry-sdk==1.27.0 \
+ opentelemetry-exporter-otlp-proto-http==1.27.0
+
+# Streamlit reads config from $HOME/.streamlit, so the config lives under the
+# streamlit user's home.
+COPY --chown=streamlit:streamlit products/tasks/backend/sandbox/images/streamlit_config.toml /home/streamlit/.streamlit/config.toml
+
+COPY products/tasks/backend/sandbox/images/streamlit_auth_proxy.py /usr/local/bin/streamlit_auth_proxy.py
+
+# In-sandbox shim. The shim talks to the local proxy on 127.0.0.1:8181, which
+# mediates the actual HogQL hop to PostHog using a token loaded from disk at
+# proxy startup. The user code never sees a bearer token.
+COPY products/tasks/backend/sandbox/images/posthog_apps /usr/local/lib/python3.11/site-packages/posthog_apps
+
+# Modal tunnels port 8080 (the auth proxy). Port 8181 is bound to 127.0.0.1
+# only and is NOT exposed externally — it serves the bridge endpoint used by
+# the in-sandbox posthog_apps.query() shim.
+EXPOSE 8501
+EXPOSE 8080
diff --git a/products/tasks/backend/sandbox/images/posthog_apps/__init__.py b/products/tasks/backend/sandbox/images/posthog_apps/__init__.py
new file mode 100644
index 000000000000..cbfe7d88f698
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/posthog_apps/__init__.py
@@ -0,0 +1,19 @@
+import pandas as _pd
+import requests as _requests
+
+_BRIDGE_URL = "http://127.0.0.1:8181/_bridge/query"
+
+
+def query(hogql: str) -> _pd.DataFrame:
+ """Run a HogQL query against PostHog from inside a Streamlit sandbox."""
+ resp = _requests.post(_BRIDGE_URL, json={"query": hogql}, timeout=60)
+ if resp.status_code != 200:
+ try:
+ err = resp.json().get("error", resp.text)
+ except Exception:
+ err = resp.text
+ raise RuntimeError("HogQL query failed: " + str(err))
+ data = resp.json()
+ columns = data.get("columns", [])
+ results = data.get("results", [])
+ return _pd.DataFrame(results, columns=columns)
diff --git a/products/tasks/backend/sandbox/images/streamlit_auth_proxy.py b/products/tasks/backend/sandbox/images/streamlit_auth_proxy.py
new file mode 100644
index 000000000000..1c6d0cf162e2
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/streamlit_auth_proxy.py
@@ -0,0 +1,744 @@
+"""Auth proxy for Streamlit apps in Modal sandboxes.
+
+Listens on port 8080 (Modal connect token port), reverse proxies to Streamlit on localhost:8501.
+Validates PostHog OAuth access tokens via the /oauth/introspect endpoint on every request,
+caching introspection results by token hash to avoid per-request overhead.
+
+Modal requires `_modal_connect_token` on every HTTP request through the tunnel, but strips
+it before forwarding to us. The backend duplicates the token as `_posthog_modal_token` which
+passes through. We capture that token PER REQUEST and inject a JS shim into HTML responses
+that patches fetch/XHR/WebSocket/script.src to add both `_modal_connect_token` AND
+`_posthog_token` to all same-host browser sub-requests. This keeps every request authenticated
+end-to-end (Modal tunnel AND our proxy) without relying on session cookies (which don't work
+reliably in cross-origin iframes).
+
+Bridge endpoint (port 8181, 127.0.0.1-only): exposes /_bridge/query, used by the in-sandbox
+posthog_apps.query() shim to run HogQL via PostHog. The bridge forwarder reads its bearer
+token from /run/bridge_token at startup, then unlinks the file. The token is never available
+through the tunneled port.
+"""
+
+import os
+import re
+import sys
+import html
+import json
+import time
+import asyncio
+import hashlib
+import logging
+from urllib.parse import parse_qs, urlencode
+
+from aiohttp import ClientSession, ClientTimeout, WSMsgType, web
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s [%(levelname)s] %(message)s",
+ handlers=[logging.StreamHandler(sys.stderr)],
+)
+log = logging.getLogger("auth_proxy")
+
+LISTEN_PORT = 8080
+BRIDGE_LISTEN_PORT = 8181 # 127.0.0.1-only; never tunneled by Modal
+STREAMLIT_UPSTREAM = "http://localhost:8501" # the Streamlit server this proxy fronts
+POSTHOG_SITE_URL = os.environ.get("POSTHOG_SITE_URL", "")
+BRIDGE_TOKEN_PATH = "/run/bridge_token"
+
+INTROSPECTION_CACHE_TTL = 60.0 # short revocation window, low per-request overhead
+INTROSPECTION_TIMEOUT = ClientTimeout(total=10)
+INTROSPECTION_CACHE_MAX_ENTRIES = 1000
+INTROSPECTION_CIRCUIT_THRESHOLD = 3
+INTROSPECTION_CIRCUIT_OPEN_SECONDS = 30.0
+STREAM_CHUNK_SIZE = 64 * 1024
+# Hard cap on proxied uploads so a 1 GB body can't sit resident per request.
+MAX_REQUEST_BODY_BYTES = 256 * 1024 * 1024 # 256 MB
+BRIDGE_QUERY_MAX_BODY_BYTES = 16 * 1024
+BRIDGE_QUERY_TIMEOUT = ClientTimeout(total=60)
+# Raised from aiohttp's 8190 default: localhost-served sandboxes receive PostHog's
+# large same-domain cookies on every request (see _run_both_apps).
+MAX_HEADER_BYTES = 64 * 1024
+
+OTEL_SERVICE_NAME_DEFAULT = "streamlit-auth-proxy"
+OTEL_LOG_PATH = "/i/v1/logs"
+
+# RFC 7230 hop-by-hop headers: connection-scoped, must not be forwarded by a
+# proxy in either direction (plus `host`, which we set per upstream request).
+HOP_BY_HOP = frozenset(
+ {
+ "connection",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailers",
+ "transfer-encoding",
+ "upgrade",
+ "host",
+ }
+)
+
+# Dropped upstream so user code can't read our tokens via document.referrer.
+# "referer" (one r) is the header's actual spelling per the HTTP spec.
+STRIP_UPSTREAM = frozenset({"referer"})
+
+# JS shim injected after <head> that patches fetch/XHR/WebSocket/element.src
+# setters to append both tokens on same-host requests. %s is filled via
+# json.dumps for safe JS string embedding.
+_TOKEN_INJECTION_JS_TEMPLATE = """<script>
+(function(){
+ var MK="_modal_connect_token",MV=%s,PK="_posthog_token",PV=%s;
+ function a(u){
+ try{var o=new URL(u,location.origin);
+ if(o.hostname===location.hostname){
+ if(MV&&!o.searchParams.has(MK)){o.searchParams.set(MK,MV)}
+ if(!o.searchParams.has(PK)){o.searchParams.set(PK,PV)}
+ }
+ return o.toString()}catch(e){return u}
+ }
+ var F=window.fetch;
+ window.fetch=function(i,n){
+ if(typeof i==="string"){i=a(i)}
+ else if(i instanceof Request){i=new Request(a(i.url),i)}
+ return F.call(this,i,n)};
+ var X=XMLHttpRequest.prototype.open;
+ XMLHttpRequest.prototype.open=function(m,u){arguments[1]=a(u);return X.apply(this,arguments)};
+ var W=window.WebSocket;
+ window.WebSocket=function(u,p){u=a(u);return p!==undefined?new W(u,p):new W(u)};
+ window.WebSocket.prototype=W.prototype;
+ window.WebSocket.CONNECTING=W.CONNECTING;
+ window.WebSocket.OPEN=W.OPEN;
+ window.WebSocket.CLOSING=W.CLOSING;
+ window.WebSocket.CLOSED=W.CLOSED;
+ function patchSrc(El,prop){
+ var d=Object.getOwnPropertyDescriptor(El.prototype,prop);
+ if(d&&d.set){Object.defineProperty(El.prototype,prop,{
+ set:function(v){d.set.call(this,a(v))},
+ get:d.get,configurable:true,enumerable:true
+ })}
+ }
+ patchSrc(HTMLScriptElement,"src");
+ patchSrc(HTMLLinkElement,"href");
+ patchSrc(HTMLImageElement,"src");
+ patchSrc(HTMLIFrameElement,"src");
+})();
+</script>"""
+
+_AUTH_EXEMPT_PREFIXES = ("/static/", "/favicon.", "/healthz", "/_stcore/host-config", "/_stcore/health")
+
+# token_hash -> (result_dict, expires_at_epoch). Hash-keyed so tokens don't hit memory dumps.
+_introspection_cache: dict[str, tuple[dict, float]] = {}
+
+
+class _IntrospectionCircuit:
+ """Fast-fail after N consecutive upstream failures; reopen after a cooldown."""
+
+ def __init__(self) -> None:
+ self.failures = 0
+ self.open_until = 0.0
+
+ def record_failure(self) -> None:
+ self.failures += 1
+ if self.failures >= INTROSPECTION_CIRCUIT_THRESHOLD:
+ self.open_until = time.monotonic() + INTROSPECTION_CIRCUIT_OPEN_SECONDS
+ log.warning("introspect: circuit opened after %d consecutive failures", self.failures)
+
+ def record_success(self) -> None:
+ self.failures = 0
+ self.open_until = 0.0
+
+ def is_open(self) -> bool:
+ return time.monotonic() < self.open_until
+
+ def reset(self) -> None:
+ self.failures = 0
+ self.open_until = 0.0
+
+
+_introspection_circuit = _IntrospectionCircuit()
+
+# Bridge token for the sandbox → PostHog HogQL hop. Loaded once at startup from
+# /run/bridge_token (file then unlinked) and kept only in process memory.
+_bridge_token: str | None = None
+
+# OTEL LoggerProvider, held so we can force_flush() on shutdown.
+_logger_provider: object | None = None
+
+
+def _resolve_otel_endpoint() -> str | None:
+ """Return the OTLP logs endpoint.
+
+ Preference: OTEL_EXPORTER_OTLP_LOGS_ENDPOINT (full URL, region-aware),
+ OTEL_EXPORTER_OTLP_ENDPOINT (base URL), then POSTHOG_SITE_URL fallback.
+ """
+ explicit = os.environ.get("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT")
+ if explicit:
+ return explicit
+ base = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
+ if base:
+ return base.rstrip("/") + OTEL_LOG_PATH
+ if POSTHOG_SITE_URL:
+ return POSTHOG_SITE_URL.rstrip("/") + OTEL_LOG_PATH
+ return None
+
+
+class _OtelAttributeSanitizer(logging.Filter):
+ """Stringify Mapping-valued LogRecord fields — OTEL attributes only accept scalars."""
+
+ def filter(self, record: logging.LogRecord) -> bool:
+ from collections.abc import Mapping
+
+ for key, value in list(record.__dict__.items()):
+ if isinstance(value, Mapping):
+ record.__dict__[key] = repr(value)
+ return True
+
+
+def _setup_otel_logging() -> None:
+ """Wire stdlib logging into OTLP. Safe to call once; all failures swallowed."""
+ global _logger_provider
+
+ endpoint = _resolve_otel_endpoint()
+ if endpoint is None:
+ log.info("otel: no endpoint configured, skipping log export")
+ return
+
+ try:
+ from opentelemetry._logs import set_logger_provider
+ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
+ from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
+ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
+ from opentelemetry.sdk.resources import Resource
+ except ImportError as exc:
+ log.warning("otel: SDK not available, skipping log export (%s)", exc)
+ return
+
+ try:
+ resource = Resource.create({"service.name": os.environ.get("OTEL_SERVICE_NAME", OTEL_SERVICE_NAME_DEFAULT)})
+ provider = LoggerProvider(resource=resource)
+ exporter = OTLPLogExporter(endpoint=endpoint)
+ provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
+ set_logger_provider(provider)
+
+ handler = LoggingHandler(level=logging.INFO, logger_provider=provider)
+ handler.addFilter(_OtelAttributeSanitizer())
+ logging.getLogger().addHandler(handler)
+
+ _logger_provider = provider
+ log.info("otel: logging enabled endpoint=%s", endpoint)
+ except Exception:
+ log.exception("otel: failed to initialize, falling back to stderr only")
+
+
+async def _shutdown_otel(app: web.Application) -> None:
+ """Flush pending log batches on graceful shutdown."""
+ if _logger_provider is not None:
+ try:
+ _logger_provider.force_flush(timeout_millis=5000) # type: ignore[attr-defined]
+ _logger_provider.shutdown() # type: ignore[attr-defined]
+ except Exception:
+ log.warning("otel: flush on shutdown failed", exc_info=True)
+
+
+def _load_bridge_token() -> None:
+ """Read the bridge bearer token from /run/bridge_token, then unlink it.
+
+ File (not env var) so the token doesn't leak via /proc/<pid>/environ.
+ Held only in process memory after load.
+ """
+ global _bridge_token
+
+ try:
+ with open(BRIDGE_TOKEN_PATH, "rb") as fh:
+ data = fh.read()
+ os.unlink(BRIDGE_TOKEN_PATH)
+ except FileNotFoundError:
+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs only the file path, never the token value
+ log.warning("bridge: token file missing at %s; /_bridge/query will return 503", BRIDGE_TOKEN_PATH)
+ return
+ except OSError:
+ log.exception("bridge: failed to load token file")
+ return
+
+ token = data.decode("utf-8", errors="replace").strip()
+ if not token:
+ log.warning("bridge: token file was empty")
+ return
+
+ _bridge_token = token
+ log.info("bridge: token loaded into memory and unlinked from disk")
+
+
+def _filter_headers(headers, *, upstream: bool = False) -> dict[str, str]:
+ deny = HOP_BY_HOP | STRIP_UPSTREAM if upstream else HOP_BY_HOP
+ return {k: v for k, v in headers.items() if k.lower() not in deny}
+
+
+_AUTH_PARAM_KEYS = ("_posthog_token", "_posthog_modal_token", "_modal_connect_token")
+
+
+def _strip_auth_params(query_string: str) -> str:
+ """Remove auth tokens from query string before proxying upstream."""
+ params = parse_qs(query_string, keep_blank_values=True)
+ for key in _AUTH_PARAM_KEYS:
+ params.pop(key, None)
+ flat = {k: v[0] if len(v) == 1 else v for k, v in params.items()}
+ return urlencode(flat, doseq=True)
+
+
+def _hash_token(token: str) -> str:
+ return hashlib.sha256(token.encode("utf-8")).hexdigest()
+
+
+def _evict_introspection_cache_if_full() -> None:
+ """Drop expired entries; if still full, drop 10% with the soonest expiry."""
+ if len(_introspection_cache) < INTROSPECTION_CACHE_MAX_ENTRIES:
+ return
+ now = time.monotonic()
+ expired = [k for k, (_, exp) in _introspection_cache.items() if exp <= now]
+ for key in expired:
+ _introspection_cache.pop(key, None)
+ if len(_introspection_cache) < INTROSPECTION_CACHE_MAX_ENTRIES:
+ return
+ by_expiry = sorted(_introspection_cache.items(), key=lambda kv: kv[1][1])
+ drop_count = max(1, INTROSPECTION_CACHE_MAX_ENTRIES // 10)
+ for key, _ in by_expiry[:drop_count]:
+ _introspection_cache.pop(key, None)
+
+
+async def _introspect_token(
+ session: ClientSession,
+ token: str,
+ *,
+ team_id: int,
+ expected_client_id: str,
+ expected_scope_component: str,
+) -> dict | None:
+ """Validate an OAuth token via PostHog /oauth/introspect (self-introspection), with caching.
+
+ Rejects tokens whose scoped_teams, client_id, or scope don't match the
+ caller-supplied expectations — per-sandbox team binding, cross-application
+ rejection, and per-purpose (iframe vs bridge) scope binding all run here.
+ """
+ if not POSTHOG_SITE_URL:
+ log.warning("introspect: POSTHOG_SITE_URL not set, rejecting token")
+ return None
+
+ now = time.monotonic()
+ token_hash = _hash_token(token)
+
+ cached = _introspection_cache.get(token_hash)
+ if cached is not None:
+ result, expires_at = cached
+ if now < expires_at:
+ log.debug("introspect: cache hit hash=%s", token_hash[:8])
+ return result
+ _introspection_cache.pop(token_hash, None)
+
+ if _introspection_circuit.is_open():
+ log.warning("introspect: circuit open, rejecting token without upstream call")
+ return None
+
+ url = f"{POSTHOG_SITE_URL}/oauth/introspect/"
+ # Token in both Bearer and body = self-introspection, which OAuthIntrospectTokenView
+ # allows without the `introspection` scope.
+ headers = {
+ "Authorization": f"Bearer {token}",
+ "Content-Type": "application/x-www-form-urlencoded",
+ }
+ body = f"token={token}"
+
+ log.debug("introspect: cache miss hash=%s, calling %s", token_hash[:8], url)
+ try:
+ async with session.post(url, headers=headers, data=body, timeout=INTROSPECTION_TIMEOUT) as resp:
+ raw_body = await resp.read()
+ if resp.status != 200:
+ log.warning("introspect: non-200 status=%d", resp.status)
+ _introspection_circuit.record_failure()
+ return None
+ try:
+ data = json.loads(raw_body)
+ except json.JSONDecodeError:
+ log.warning("introspect: invalid JSON")
+ _introspection_circuit.record_failure()
+ return None
+
+ # Upstream is healthy past this point — all rejections below count
+ # as "bad token", not "bad upstream", so record_success each time.
+ if not data.get("active"):
+ log.warning("introspect: token not active")
+ _introspection_circuit.record_success()
+ return None
+ scoped_teams = data.get("scoped_teams") or []
+ if not scoped_teams:
+ log.warning("introspect: token missing scoped_teams")
+ _introspection_circuit.record_success()
+ return None
+ # Per-sandbox team binding.
+ if team_id not in scoped_teams:
+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs team ids, never the token value
+ log.warning("introspect: token team mismatch expected=%d scoped=%s", team_id, scoped_teams)
+ _introspection_circuit.record_success()
+ return None
+ # Per-application binding — an MCP-app token with matching team
+ # scope must still be rejected.
+ token_client_id = data.get("client_id")
+ if token_client_id != expected_client_id:
+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs OAuth client ids, never the token value
+ log.warning(
+ "introspect: token client_id mismatch expected=%s got=%s", expected_client_id, token_client_id
+ )
+ _introspection_circuit.record_success()
+ return None
+ # Per-purpose scope binding — a leaked bridge token must not
+ # unlock the iframe (and vice versa).
+ scope_parts = set((data.get("scope") or "").split())
+ if expected_scope_component not in scope_parts:
+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs OAuth scope strings, never the token value
+ log.warning(
+ "introspect: token scope mismatch expected=%s got=%s",
+ expected_scope_component,
+ data.get("scope"),
+ )
+ _introspection_circuit.record_success()
+ return None
+ _evict_introspection_cache_if_full()
+ _introspection_cache[token_hash] = (data, now + INTROSPECTION_CACHE_TTL)
+ _introspection_circuit.record_success()
+ log.debug("introspect: success user_id=%s", data.get("user_id"))
+ return data
+ except Exception:
+ log.exception("introspect: request failed")
+ _introspection_circuit.record_failure()
+ return None
+
+
+def _inject_token_into_html(body: bytes, modal_token: str, posthog_token: str) -> bytes:
+ """Inject both tokens into Streamlit HTML so browser sub-requests carry them.
+
+ 1. Rewrite relative/absolute href/src attributes to include both tokens
+ 2. Inject a JS shim after <head> that patches fetch/XHR/WebSocket/element.src setters
+ """
+ text = body.decode("utf-8", errors="replace")
+
+ modal_token_attr = html.escape(modal_token, quote=True)
+ posthog_token_attr = html.escape(posthog_token, quote=True)
+
+ def _replace(m: re.Match) -> str:
+ attr = m.group(1)
+ quote = m.group(2)
+ url = m.group(3)
+ close_quote = m.group(4)
+ sep = "&" if "?" in url else "?"
+ token_qs = f"_posthog_token={posthog_token_attr}"
+ if modal_token_attr:
+ token_qs = f"_modal_connect_token={modal_token_attr}&{token_qs}"
+ return f"{attr}{quote}{url}{sep}{token_qs}{close_quote}"
+
+ # Match only same-origin relative URLs: "./foo" or "/foo", but NOT "//host"
+ # (protocol-relative) or "https://host" — appending the token to a foreign
+ # host would leak it cross-origin.
+ text = re.sub(r'((?:href|src)=)(["\'])(\./[^"\']*?|/(?!/)[^"\']*?)(\2)', _replace, text)
+
+ # json.dumps escapes quotes/backslashes; also escape </ to prevent </script> breakout
+ modal_js = json.dumps(modal_token).replace("</", "<\\/")
+ posthog_js = json.dumps(posthog_token).replace("</", "<\\/")
+ js_shim = _TOKEN_INJECTION_JS_TEMPLATE % (modal_js, posthog_js)
+ text = re.sub(r"(<head[^>]*>)", lambda m: m.group(1) + js_shim, text, count=1)
+
+ return text.encode("utf-8")
+
+
+async def healthz(request: web.Request) -> web.Response:
+ return web.Response(text="ok")
+
+
+async def proxy_handler(request: web.Request) -> web.StreamResponse:
+ path = request.path
+
+ # Static assets bypass auth; they're public Streamlit bundles.
+ if any(path.startswith(p) for p in _AUTH_EXEMPT_PREFIXES):
+ return await _proxy_to_upstream(request)
+
+ token = request.query.get("_posthog_token")
+ if not token:
+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs method and path of an unauthenticated request, no token present
+ log.warning("request: no _posthog_token in query (%s %s)", request.method, path)
+ return web.Response(status=401, text="Authentication required")
+
+ session = request.app["client_session"]
+ introspection = await _introspect_token(
+ session,
+ token,
+ team_id=request.app["posthog_team_id"],
+ expected_client_id=request.app["posthog_streamlit_client_id"],
+ expected_scope_component="streamlit:iframe",
+ )
+ if not introspection:
+ return web.Response(status=403, text="Invalid or expired token")
+
+ return await _proxy_to_upstream(request)
+
+
+async def _proxy_to_upstream(request: web.Request) -> web.StreamResponse:
+ path = request.match_info.get("path", "")
+ target = f"{STREAMLIT_UPSTREAM}/{path}"
+ qs = _strip_auth_params(request.query_string)
+ if qs:
+ target = f"{target}?{qs}"
+
+ if request.headers.get("Upgrade", "").lower() == "websocket":
+ return await _proxy_websocket(request, target)
+
+ return await _proxy_http(request, target)
+
+
+async def _proxy_http(request: web.Request, target: str) -> web.StreamResponse:
+ client_session: ClientSession = request.app["client_session"]
+ headers = _filter_headers(request.headers, upstream=True)
+ posthog_token = request.query.get("_posthog_token")
+ # Per-request capture — Modal forwards the connect token as
+ # _posthog_modal_token; we re-inject it into HTML responses.
+ modal_connect_token = request.query.get("_posthog_modal_token")
+
+ # Cheap guard before touching the body (advisory — chunked transfers have none).
+ content_length = request.content_length
+ if content_length is not None and content_length > MAX_REQUEST_BODY_BYTES:
+ return web.Response(status=413, text="Request body too large")
+
+ # Pass the body as a stream so large uploads are never fully resident in memory.
+ body_stream = request.content if request.can_read_body else None
+
+ async with client_session.request(
+ method=request.method,
+ url=target,
+ headers=headers,
+ data=body_stream,
+ allow_redirects=False,
+ ) as resp:
+ response_headers = _filter_headers(resp.headers)
+ # aiohttp auto-decompresses gzip; drop Content-Encoding accordingly.
+ response_headers.pop("Content-Encoding", None)
+ # Don't leak the token-bearing iframe URL via outbound Referer.
+ response_headers["Referrer-Policy"] = "no-referrer"
+
+ content_type = resp.headers.get("content-type", "")
+ is_html = "text/html" in content_type
+
+ # Inject whenever we have a posthog token; the modal token is optional
+ # (Docker sandboxes have none). Gating on the modal token would skip the
+ # shim entirely on Docker, leaving every Streamlit sub-request (health,
+ # WebSocket, assets) unauthenticated.
+ if is_html and posthog_token:
+ body = await resp.read()
+ body = _inject_token_into_html(body, modal_connect_token or "", posthog_token)
+ response_headers["Content-Length"] = str(len(body))
+ return web.Response(status=resp.status, body=body, headers=response_headers)
+
+ response_headers.pop("Content-Length", None)
+ stream = web.StreamResponse(status=resp.status, headers=response_headers)
+ await stream.prepare(request)
+ async for chunk in resp.content.iter_chunked(STREAM_CHUNK_SIZE):
+ await stream.write(chunk)
+ await stream.write_eof()
+ return stream
+
+
+async def _proxy_websocket(request: web.Request, target: str) -> web.WebSocketResponse:
+ protocols = request.headers.getall("Sec-WebSocket-Protocol", [])
+ all_protocols: list[str] = []
+ for p in protocols:
+ all_protocols.extend(s.strip() for s in p.split(",") if s.strip())
+
+ ws_client = web.WebSocketResponse(protocols=tuple(all_protocols))
+ await ws_client.prepare(request)
+
+ ws_target = target.replace("http://", "ws://", 1).replace("https://", "wss://", 1)
+
+ client_session: ClientSession = request.app["client_session"]
+ async with client_session.ws_connect(ws_target, protocols=tuple(all_protocols)) as ws_upstream:
+
+ async def forward_client_to_upstream():
+ async for msg in ws_client:
+ if msg.type == WSMsgType.TEXT:
+ await ws_upstream.send_str(msg.data)
+ elif msg.type == WSMsgType.BINARY:
+ await ws_upstream.send_bytes(msg.data)
+ elif msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR):
+ break
+
+ async def forward_upstream_to_client():
+ async for msg in ws_upstream:
+ if msg.type == WSMsgType.TEXT:
+ await ws_client.send_str(msg.data)
+ elif msg.type == WSMsgType.BINARY:
+ await ws_client.send_bytes(msg.data)
+ elif msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR):
+ break
+
+ await asyncio.gather(
+ forward_client_to_upstream(),
+ forward_upstream_to_client(),
+ return_exceptions=True,
+ )
+
+ return ws_client
+
+
+# ---------- Bridge sub-app (port 8181, 127.0.0.1-only) ----------
+
+
+async def _bridge_query_handler(request: web.Request) -> web.Response:
+ """Forward in-sandbox HogQL queries from posthog_apps.query() to PostHog.
+
+ The bearer token (loaded once at startup, file unlinked) is mediated here so
+ user code never sees it. The route is bound to 127.0.0.1 on a separate port
+ that is not tunneled by Modal.
+ """
+ if _bridge_token is None:
+ return web.json_response({"error": "Bridge not configured."}, status=503)
+ if not POSTHOG_SITE_URL:
+ return web.json_response({"error": "Bridge not configured."}, status=503)
+
+ body_bytes = await request.read()
+ if len(body_bytes) > BRIDGE_QUERY_MAX_BODY_BYTES:
+ return web.json_response({"error": "Request body too large."}, status=413)
+
+ try:
+ payload = json.loads(body_bytes)
+ except json.JSONDecodeError:
+ return web.json_response({"error": "Invalid JSON body."}, status=400)
+
+ query = payload.get("query")
+ if not isinstance(query, str) or not query.strip():
+ return web.json_response({"error": "Missing or empty 'query' field."}, status=400)
+
+ target = f"{POSTHOG_SITE_URL.rstrip('/')}/api/streamlit_bridge/query/"
+ headers = {
+ "Authorization": f"Bearer {_bridge_token}",
+ "Content-Type": "application/json",
+ }
+ client_session: ClientSession = request.app["client_session"]
+ try:
+ async with client_session.post(
+ target,
+ headers=headers,
+ data=json.dumps({"query": query}).encode("utf-8"),
+ timeout=BRIDGE_QUERY_TIMEOUT,
+ ) as resp:
+ data = await resp.read()
+ return web.Response(
+ status=resp.status,
+ body=data,
+ content_type=resp.headers.get("content-type", "application/json"),
+ )
+ except Exception:
+ log.exception("bridge: forward request failed")
+ return web.json_response({"error": "Bridge upstream failed."}, status=502)
+
+
+async def _bridge_healthz(request: web.Request) -> web.Response:
+ return web.Response(text="ok")
+
+
+def _create_bridge_app() -> web.Application:
+ bridge_app = web.Application()
+ bridge_app.router.add_get("/healthz", _bridge_healthz)
+ bridge_app.router.add_post("/_bridge/query", _bridge_query_handler)
+ _attach_client_session(bridge_app)
+ return bridge_app
+
+
+# ---------- Main proxy app (port 8080, tunneled) ----------
+
+
+async def _start_client_session(app: web.Application) -> None:
+ # nosemgrep: aiohttp-missing-trust-env -- runs inside the sandbox, not the Django app; mostly proxies the localhost Streamlit upstream, which must not route through proxy env vars
+ app["client_session"] = ClientSession()
+
+
+async def _close_client_session(app: web.Application) -> None:
+ session: ClientSession | None = app.get("client_session")
+ if session is not None:
+ await session.close()
+
+
+def _read_required_config() -> tuple[int, str]:
+ """Read POSTHOG_TEAM_ID and POSTHOG_STREAMLIT_CLIENT_ID, or RuntimeError at boot."""
+ team_id_raw = os.environ.get("POSTHOG_TEAM_ID", "").strip()
+ try:
+ team_id = int(team_id_raw)
+ except ValueError:
+ team_id = 0
+ if team_id <= 0:
+ raise RuntimeError(f"POSTHOG_TEAM_ID env var must be a positive integer (got {team_id_raw!r})")
+
+ client_id = os.environ.get("POSTHOG_STREAMLIT_CLIENT_ID", "").strip()
+ if not client_id:
+ raise RuntimeError("POSTHOG_STREAMLIT_CLIENT_ID env var must be set")
+
+ return team_id, client_id
+
+
+def _attach_client_session(app: web.Application) -> None:
+ app.on_startup.append(_start_client_session)
+ app.on_cleanup.append(_close_client_session)
+
+
+def create_app() -> web.Application:
+ _setup_otel_logging()
+ _load_bridge_token()
+ team_id, client_id = _read_required_config()
+
+ app = web.Application()
+ app["posthog_team_id"] = team_id
+ app["posthog_streamlit_client_id"] = client_id
+ app.router.add_get("/healthz", healthz)
+ app.router.add_route("*", "/{path:.*}", proxy_handler)
+ _attach_client_session(app)
+ app.on_cleanup.append(_shutdown_otel)
+ return app
+
+
+async def _run_both_apps(
+ main_app: web.Application,
+ bridge_app: web.Application,
+ main_port: int,
+ bridge_port: int,
+) -> None:
+ """Serve the main proxy on 0.0.0.0 and the bridge on 127.0.0.1 (not tunneled)."""
+ # aiohttp's default 8190-byte header cap is too small for local-dev: when the
+ # sandbox is served from localhost (Docker), the browser attaches PostHog's
+ # large same-domain analytics cookies to every proxied request, overflowing
+ # the limit. Raise both line and field caps so the request parses.
+ main_runner = web.AppRunner(main_app, max_line_size=MAX_HEADER_BYTES, max_field_size=MAX_HEADER_BYTES)
+ bridge_runner = web.AppRunner(bridge_app)
+ await main_runner.setup()
+ await bridge_runner.setup()
+
+ main_site = web.TCPSite(main_runner, host="0.0.0.0", port=main_port)
+ bridge_site = web.TCPSite(bridge_runner, host="127.0.0.1", port=bridge_port)
+ await main_site.start()
+ await bridge_site.start()
+ log.info(
+ "auth proxy listening on 0.0.0.0:%d, bridge on 127.0.0.1:%d SITE_URL=%s",
+ main_port,
+ bridge_port,
+ POSTHOG_SITE_URL,
+ )
+
+ try:
+ # Park forever; the sites serve in the background until the process is killed.
+ await asyncio.Event().wait()
+ finally:
+ await main_runner.cleanup()
+ await bridge_runner.cleanup()
+
+
+if __name__ == "__main__":
+ port = int(sys.argv[1]) if len(sys.argv) > 1 else LISTEN_PORT
+ main_app = create_app()
+ bridge_app = _create_bridge_app()
+ try:
+ asyncio.run(_run_both_apps(main_app, bridge_app, port, BRIDGE_LISTEN_PORT))
+ except KeyboardInterrupt:
+ pass
diff --git a/products/tasks/backend/sandbox/images/streamlit_config.toml b/products/tasks/backend/sandbox/images/streamlit_config.toml
new file mode 100644
index 000000000000..1992ff0b9cca
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/streamlit_config.toml
@@ -0,0 +1,15 @@
+[server]
+port = 8501
+headless = true
+enableCORS = false
+enableXsrfProtection = false
+
+[client]
+toolbarMode = "minimal"
+showSidebarNavigation = false
+
+[browser]
+gatherUsageStats = false
+
+[theme]
+base = "light"
diff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/services/docker_sandbox.py
index 661eeebf0557..930fcbd342c2 100644
--- a/products/tasks/backend/services/docker_sandbox.py
+++ b/products/tasks/backend/services/docker_sandbox.py
@@ -61,7 +61,24 @@ logger = logging.getLogger(__name__)
DEFAULT_IMAGE_NAME = "posthog-sandbox-base"
NOTEBOOK_IMAGE_NAME = "posthog-sandbox-notebook"
PI_IMAGE_NAME = "posthog-sandbox-pi"
+STREAMLIT_IMAGE_NAME = "posthog-sandbox-streamlit"
AGENT_SERVER_PORT = 47821 # Arbitrary high port unlikely to conflict with dev servers
+# Streamlit sandboxes expose their auth proxy (not the agent-server) on this port; the
+# host-published port maps to it so connect_info can reach the app across processes.
+
+STREAMLIT_AUTH_PROXY_PORT = 8080
+
+# Env vars holding a PostHog URL the sandbox must reach from inside the container.
+# localhost would resolve to the container itself, so they're rewritten to
+# host.docker.internal at `docker run` time (non-localhost hosts pass through).
+_DOCKER_URL_ENV_KEYS = frozenset(
+ {
+ "POSTHOG_API_URL",
+ "POSTHOG_SITE_URL",
+ "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
+ }
+)
# A failing `docker build` can emit megabytes of output. Stuffing all of it into a
# Temporal ApplicationError's details overflows the failure-payload size limit, and
@@ -82,6 +99,14 @@ class DockerSandbox(SandboxBase):
"""
Docker-based sandbox for local development and testing.
Implements the same interface as the Modal-based Sandbox.
+
+ Local dev requirements (set in .env.local, then restart ./bin/start so the
+ supervisor re-reads them — a per-process restart inherits the old env):
+ - SANDBOX_PROVIDER=docker — route sandboxes here instead of Modal.
+ - POSTHOG_DEV_SANDBOX=0 — REQUIRED. The dev Seatbelt sandbox
+ (bin/dev-sandbox.sb) deliberately denies the Docker socket as an escape
+ vector, so with it enabled the worker can't reach the daemon and every
+ create() fails with a generic "Failed to create Docker sandbox".
"""
id: str
@@ -250,6 +275,15 @@ class DockerSandbox(SandboxBase):
DockerSandbox._build_image_if_needed(NOTEBOOK_IMAGE_NAME, dockerfile_path)
return NOTEBOOK_IMAGE_NAME
+ # Streamlit ships its own standalone image (FROM python:3.11-slim with a `streamlit`
+ # user + auth proxy), so it doesn't build on top of the base image like PI does.
+ if template == SandboxTemplate.STREAMLIT_BASE:
+ dockerfile_path = os.path.join(
+ settings.BASE_DIR, "products/tasks/backend/sandbox/images/Dockerfile.sandbox-streamlit"
+ )
+ DockerSandbox._build_image_if_needed(STREAMLIT_IMAGE_NAME, dockerfile_path)
+ return STREAMLIT_IMAGE_NAME
+
dockerfile_path = os.path.join(
settings.BASE_DIR, "products/tasks/backend/sandbox/images/Dockerfile.sandbox-base"
)
@@ -318,12 +352,18 @@ class DockerSandbox(SandboxBase):
if config.environment_variables:
for key, value in config.environment_variables.items():
if value is not None:
- if key == "POSTHOG_API_URL":
+ if key in _DOCKER_URL_ENV_KEYS:
value = DockerSandbox._transform_url_for_docker(value)
env_args.extend(["-e", f"{key}={value}"])
host_port = DockerSandbox._find_available_port()
- port_args = ["-p", f"{host_port}:{AGENT_SERVER_PORT}"]
+ # Streamlit sandboxes are reached via their auth proxy (8080); everything else
+ # via the agent-server. Ports must be published at `docker run` time — the proxy
+ # boots later inside the container, so we publish 8080 up front regardless.
+ container_port = (
+ STREAMLIT_AUTH_PROXY_PORT if config.template == SandboxTemplate.STREAMLIT_BASE else AGENT_SERVER_PORT
+ )
+ port_args = ["-p", f"{host_port}:{container_port}"]
mount_map = parse_sandbox_repo_mount_map()
volume_args: list[str] = []
@@ -397,6 +437,24 @@ class DockerSandbox(SandboxBase):
cause=e,
)
+ @staticmethod
+ def _recover_published_host_port(container_id: str) -> int | None:
+ """Read the host port a container publishes, via `docker port`.
+
+ Output lines look like `8080/tcp -> 0.0.0.0:49153`; we return the first
+ host port found so a freshly-reconstructed sandbox can build its URL.
+ """
+ try:
+ result = DockerSandbox._run(["docker", "port", container_id])
+ except subprocess.CalledProcessError:
+ return None
+ for line in result.stdout.splitlines():
+ _, _, mapping = line.partition("->")
+ host_port = mapping.strip().rsplit(":", 1)[-1]
+ if host_port.isdigit():
+ return int(host_port)
+ return None
+
@staticmethod
def get_by_id(sandbox_id: str) -> DockerSandbox:
if sandbox_id in DockerSandbox._registry:
@@ -409,7 +467,10 @@ class DockerSandbox(SandboxBase):
)
full_id = result.stdout.strip()
config = SandboxConfig(name=f"sandbox-{sandbox_id}")
- return DockerSandbox(container_id=full_id, config=config)
+ # Recover the published host port so connect_info (which runs in a different
+ # process than create()) can build the connect URL.
+ host_port = DockerSandbox._recover_published_host_port(full_id)
+ return DockerSandbox(container_id=full_id, config=config, host_port=host_port)
except subprocess.CalledProcessError as e:
raise SandboxNotFoundError(
diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.py
index 26c5ac8c4a3f..142b1bc2b720 100644
--- a/products/tasks/backend/services/modal_sandbox.py
+++ b/products/tasks/backend/services/modal_sandbox.py
@@ -75,9 +75,12 @@ logger = logging.getLogger(__name__)
DEFAULT_MODAL_APP_NAME = "posthog-sandbox-default"
NOTEBOOK_MODAL_APP_NAME = "posthog-sandbox-notebook"
+STREAMLIT_MODAL_APP_NAME = "posthog-sandbox-streamlit"
+
SANDBOX_BASE_IMAGE = "ghcr.io/posthog/posthog-sandbox-base"
SANDBOX_NOTEBOOK_IMAGE = "ghcr.io/posthog/posthog-sandbox-notebook"
SANDBOX_VM_IMAGE = "ghcr.io/posthog/posthog-sandbox-vm"
+SANDBOX_STREAMLIT_IMAGE = "ghcr.io/posthog/posthog-sandbox-streamlit"
SANDBOX_IMAGE = SANDBOX_BASE_IMAGE
AGENT_SERVER_PORT = 8080 # Modal connect tokens require port 8080
AGENT_SERVER_HEALTH_MAX_ATTEMPTS = 240
@@ -98,6 +101,7 @@ LOCAL_MODAL_DOCKERFILES = {
SandboxTemplate.DEFAULT_BASE: Path("products/tasks/backend/sandbox/images/Dockerfile.sandbox-base"),
SandboxTemplate.NOTEBOOK_BASE: Path("products/tasks/backend/sandbox/images/Dockerfile.sandbox-notebook"),
SandboxTemplate.VM_BASE: Path("products/tasks/backend/sandbox/images/Dockerfile.sandbox-vm"),
+ SandboxTemplate.STREAMLIT_BASE: Path("products/tasks/backend/sandbox/images/Dockerfile.sandbox-streamlit"),
}
LOCAL_MODAL_INSTALL_SKILLS_SCRIPT = Path("products/tasks/backend/sandbox/images/install-skills.sh")
LOCAL_MODAL_GIT_GUARD_SCRIPT = Path("products/tasks/backend/sandbox/images/git-guard.sh")
@@ -226,6 +230,7 @@ def _get_template_image(template: SandboxTemplate) -> modal.Image:
SandboxTemplate.DEFAULT_BASE: SANDBOX_BASE_IMAGE,
SandboxTemplate.NOTEBOOK_BASE: SANDBOX_NOTEBOOK_IMAGE,
SandboxTemplate.VM_BASE: SANDBOX_VM_IMAGE,
+ SandboxTemplate.STREAMLIT_BASE: SANDBOX_STREAMLIT_IMAGE,
}.get(template)
if registry_image is None:
raise ValueError(f"Unknown template: {template}")
@@ -272,6 +277,15 @@ def _prepare_local_modal_build_context(template: SandboxTemplate) -> tuple[str,
LocalSkillsCache(base_dir).ensure_built()
populate_skills_directory(context_dir / LOCAL_BUILT_SKILLS_PATH, base_dir=base_dir)
+ elif template == SandboxTemplate.STREAMLIT_BASE:
+ # Copy all sibling files (streamlit_auth_proxy.py, etc.)
+ # needed by COPY instructions in the Dockerfile
+ source_images_dir = source_dockerfile_path.parent
+ dest_images_dir = destination_dockerfile_path.parent
+ for sibling in source_images_dir.iterdir():
+ if sibling.is_file() and sibling != source_dockerfile_path:
+ shutil.copy2(sibling, dest_images_dir / sibling.name)
+
return str(destination_dockerfile_path), str(context_dir)
@@ -311,11 +325,14 @@ class ModalSandbox(SandboxBase):
def _get_app_for_template(cls, template: SandboxTemplate) -> modal.App:
if template == SandboxTemplate.NOTEBOOK_BASE:
return modal.App.lookup(cls.NOTEBOOK_APP_NAME, create_if_missing=True)
+ if template == SandboxTemplate.STREAMLIT_BASE:
+ return modal.App.lookup(STREAMLIT_MODAL_APP_NAME, create_if_missing=True)
return cls._get_default_app()
@classmethod
def create(cls, config: SandboxConfig) -> ModalSandbox:
try:
+ modal.enable_output()
app = cls._get_app_for_template(config.template)
base_image = _get_template_image(config.template)
image = base_image
diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.py
index 6b9b7378fcb6..87987a32e71e 100644
--- a/products/tasks/backend/services/sandbox.py
+++ b/products/tasks/backend/services/sandbox.py
@@ -51,6 +51,8 @@ class SandboxTemplate(str, Enum):
PI_BASE = "pi_base"
VM_BASE = "vm_base"
+ STREAMLIT_BASE = "streamlit_base"
+
class ExecutionResult(BaseModel):
stdout: str
diff --git a/products/tasks/backend/services/test_docker_sandbox.py b/products/tasks/backend/services/test_docker_sandbox.py
index 280d2025ee5f..4dc232c28f67 100644
--- a/products/tasks/backend/services/test_docker_sandbox.py
+++ b/products/tasks/backend/services/test_docker_sandbox.py
@@ -141,6 +141,35 @@ class TestDockerSandboxUnit:
assert "POSTHOG_API_URL=http://host.docker.internal:8000" in env_args
assert "POSTHOG_PROJECT_ID=1" in env_args
+ @patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
+ @patch("products.tasks.backend.services.docker_sandbox.os.path.exists")
+ def test_create_transforms_callback_url_env_vars(self, mock_exists, mock_run):
+ # Streamlit sandboxes call back to PostHog via POSTHOG_SITE_URL and the
+ # OTEL endpoint. Inside Docker, localhost is the container itself, so
+ # these must be rewritten to host.docker.internal or introspection and
+ # bridge queries fail.
+ mock_exists.return_value = False
+ mock_run.return_value = MagicMock(stdout="abc123container", returncode=0)
+
+ config = SandboxConfig(
+ name="test-streamlit",
+ template=SandboxTemplate.STREAMLIT_BASE,
+ environment_variables={
+ "POSTHOG_SITE_URL": "http://localhost:8000",
+ "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT": "http://localhost:8000/i/v1/logs",
+ "POSTHOG_TEAM_ID": "1",
+ },
+ )
+
+ with patch.object(DockerSandbox, "_get_image", return_value="posthog-sandbox-streamlit"):
+ DockerSandbox.create(config)
+
+ env_args = " ".join(mock_run.call_args_list[-1][0][0])
+ assert "POSTHOG_SITE_URL=http://host.docker.internal:8000" in env_args
+ assert "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=http://host.docker.internal:8000/i/v1/logs" in env_args
+ # Non-URL env vars must pass through untouched.
+ assert "POSTHOG_TEAM_ID=1" in env_args
+
@patch("products.tasks.backend.services.docker_sandbox.subprocess.run")
def test_get_status_running(self, mock_run):
mock_run.return_value = MagicMock(stdout="true", returncode=0)
diff --git a/tach.toml b/tach.toml
index 68e800922e55..df6fbb541ecd 100644
--- a/tach.toml
+++ b/tach.toml
@@ -106,6 +106,7 @@ depends_on = [
"products.revenue_analytics",
"products.signals",
"products.slack_app",
+ "products.streamlit_apps",
"products.surveys",
"products.tasks",
"products.tracing",
@@ -429,6 +430,7 @@ layer = "modules"
path = "products.streamlit_apps"
depends_on = [
"posthog",
+ "products.tasks",
]
layer = "modules"