Skip to content

Automate browser based workflows with AI

Stop HIPAA organizations from sending anything to PostHog from server code (SKY-18286) (#8910)

Shuchang Zheng268421be84e3
diff --git a/skyvern/analytics.py b/skyvern/analytics.py
index 50aedf477..2c525124c 100644
--- a/skyvern/analytics.py
+++ b/skyvern/analytics.py
@@ -6,6 +6,7 @@ import importlib.metadata
import platform
import threading
import traceback
+from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, Any
import structlog
@@ -53,6 +54,15 @@ _custom_posthog_clients: dict[tuple[str, str], Posthog] = {}
DISTINCT_ID = "oss"
+CaptureGate = Callable[[Mapping[str, Any], str | None], bool]
+_capture_gate: CaptureGate | None = None
+
+
+def set_capture_gate(gate: CaptureGate | None) -> None:
+ """Let a deployment veto events before they are sent; with no gate set, nothing is filtered."""
+ global _capture_gate
+ _capture_gate = gate
+
def get_oss_version() -> str:
# CI builds stamp skyvern/_version.py with the git SHA; prefer that.
@@ -132,7 +142,9 @@ def capture(
distinct_id: str | None = None,
api_key: str | None = None,
host: str | None = None,
+ organization_id: str | None = None,
) -> None:
+ """``organization_id`` is only handed to the capture gate; it is never added to the event."""
if not settings.SKYVERN_TELEMETRY:
return
@@ -142,6 +154,8 @@ def capture(
return
resolved_distinct_id = distinct_id or settings.ANALYTICS_ID
payload: dict[str, Any] = {**dynamic_analytics_metadata(), **(data or {})}
+ if _capture_gate is not None and not _capture_gate(payload, organization_id):
+ return
client.capture(distinct_id=resolved_distinct_id, event=event, properties=payload)
except Exception:
LOG.debug("analytics capture failed", event=event, exc_info=True)
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 9b5a59a6d..9d2141da9 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -9023,7 +9023,9 @@ class ForgeAgent:
# This allows multiple tasks with the same llm_key to share the same cache
# log the task status as an event
- analytics.capture("skyvern-oss-agent-task-status", {"status": task.status})
+ analytics.capture(
+ "skyvern-oss-agent-task-status", {"status": task.status}, organization_id=task.organization_id
+ )
# Add task completion tag to trace
otel_trace.get_current_span().set_attribute("task.completion_status", task.status.value)
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 349ed0773..d437af17d 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -361,7 +361,9 @@ async def run_task(
current_org = caller.organization
if run_request.webhook_url:
run_request.webhook_url = validate_webhook_url(run_request.webhook_url)
- analytics.capture("skyvern-oss-run-task", data={"url": run_request.url})
+ analytics.capture(
+ "skyvern-oss-run-task", data={"url": run_request.url}, organization_id=current_org.organization_id
+ )
await PermissionCheckerFactory.get_instance().check(current_org, browser_session_id=run_request.browser_session_id)
await app.RATE_LIMITER.rate_limit_submit_run(current_org.organization_id)
await _assert_files_attachable(run_request.file_ids, current_org.organization_id)
@@ -3960,7 +3962,9 @@ async def run_task_v1(
x_user_agent: Annotated[str | None, Header()] = None,
) -> CreateTaskResponse:
current_org = caller.organization
- analytics.capture("skyvern-oss-agent-task-create", data={"url": task.url})
+ analytics.capture(
+ "skyvern-oss-agent-task-create", data={"url": task.url}, organization_id=current_org.organization_id
+ )
await PermissionCheckerFactory.get_instance().check(current_org, browser_session_id=task.browser_session_id)
await app.RATE_LIMITER.rate_limit_submit_run(current_org.organization_id)
# Legacy TaskRequest has no engine field; CUA engine selection goes through /run/tasks.
@@ -6499,7 +6503,9 @@ async def run_task_v2(
raise HTTPException(
status_code=500, detail="Skyvern LLM failure to initialize task v2. Please try again later."
)
- analytics.capture("skyvern-oss-agent-task-v2", data={"url": task_v2.url})
+ analytics.capture(
+ "skyvern-oss-agent-task-v2", data={"url": task_v2.url}, organization_id=organization.organization_id
+ )
await AsyncExecutorFactory.get_executor().execute_task_v2(
request=request,
background_tasks=background_tasks,
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index e5b4bdf01..cd722b10f 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -15476,7 +15476,11 @@ class WorkflowService:
elif policy_run and not attempt_lookup_failed and attempt_rows and need_call_webhook:
# Never fall back to a newer attempt if a late cleanup cannot find its own row.
terminal_decision = RetryDecision(False, attempt_number, 0, True, "attempt_not_found")
- analytics.capture("skyvern-oss-agent-workflow-status", {"status": workflow_run.status})
+ analytics.capture(
+ "skyvern-oss-agent-workflow-status",
+ {"status": workflow_run.status},
+ organization_id=workflow_run.organization_id,
+ )
capture_workflow_run_ids = [workflow_run.workflow_run_id]
caller_cancelled = False
try:
diff --git a/tests/unit/test_analytics.py b/tests/unit/test_analytics.py
index 41af388b0..dcf71b83f 100644
--- a/tests/unit/test_analytics.py
+++ b/tests/unit/test_analytics.py
@@ -84,3 +84,26 @@ def test_capture_can_use_custom_posthog_client() -> None:
event="mcp_tool_call",
properties={"ok": True},
)
+
+
[email protected]("gate_allows", [None, True, False])
+def test_capture_gate_can_veto_an_event_and_never_adds_the_organization_id(
+ monkeypatch: pytest.MonkeyPatch, gate_allows: bool | None
+) -> None:
+ seen: list[str | None] = []
+
+ def gate(_: object, organization_id: str | None) -> bool:
+ seen.append(organization_id)
+ return bool(gate_allows)
+
+ monkeypatch.setattr(analytics, "_capture_gate", None if gate_allows is None else gate)
+ fake_capture = Mock()
+
+ with patch.object(analytics, "_resolve_posthog_client", return_value=SimpleNamespace(capture=fake_capture)):
+ analytics.capture("skyvern-oss-run-task", data={"url": "https://example.com"}, organization_id="org_1")
+
+ if gate_allows is False:
+ fake_capture.assert_not_called()
+ else:
+ assert "org_1" not in str(fake_capture.call_args)
+ assert seen == ([] if gate_allows is None else ["org_1"])