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(integrations): connect to another posthog project and run tasks (#74179)

Tom Owersc551d590bf7c
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 5fb6363e57cf..63853707cb1b 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -6265,8 +6265,16 @@ const api = {
async list(): Promise<PaginatedResponse<IntegrationType>> {
return await new ApiRequest().integrations().get()
},
- authorizeUrl(params: { kind: string; next?: string }): string {
- return new ApiRequest().integrations().withAction('authorize').withQueryString(params).assembleFullUrl(true)
+ authorizeUrl(params: { kind: string; next?: string; extraParams?: Record<string, string> }): string {
+ // `kind` and `next` are common to every integration; anything kind-specific (e.g. the
+ // posthog connection's `region`/`scopes`) rides along in `extraParams` rather than
+ // bloating this shared signature.
+ const { extraParams, ...common } = params
+ return new ApiRequest()
+ .integrations()
+ .withAction('authorize')
+ .withQueryString({ ...common, ...extraParams })
+ .assembleFullUrl(true)
},
async slackChannels(
id: IntegrationType['id'],
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index c2642c6e3fd8..9cc43545ae12 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -422,6 +422,7 @@ export const FEATURE_FLAGS = {
POSTHOG_AI_CONVERSATION_FEEDBACK_LLMA_SESSIONS: 'posthog-ai-conversation-feedback-llma-sessions', // owner: #team-posthog-ai
POSTHOG_AI_QUEUE_MESSAGES_SYSTEM: 'posthog-ai-queue-messages-system', // owner: #team-posthog-ai
POSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-posthog-code
+ POSTHOG_CONNECT: 'posthog-connect', // owner: @Gilbert09, gates the "connect another PostHog project" personal integration
PRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analytics
PRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analytics
PRODUCT_ANALYTICS_HIDE_WEEKENDS: 'product-analytics-hide-weekends', // owner: @kliment-slice #team-irl-events
diff --git a/frontend/src/lib/integrations/PosthogConnect.tsx b/frontend/src/lib/integrations/PosthogConnect.tsx
new file mode 100644
index 000000000000..7aa7e652badb
--- /dev/null
+++ b/frontend/src/lib/integrations/PosthogConnect.tsx
@@ -0,0 +1,248 @@
+import { useActions, useValues } from 'kea'
+import { useMemo, useState } from 'react'
+
+import { IconLogomark, IconPlus, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonInput, LemonModal, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'
+import { TZLabel } from 'lib/components/TZLabel'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { API_SCOPES, scopesArrayToObject, scopesObjectToArray } from 'lib/scopes'
+import { userLogic } from 'scenes/userLogic'
+
+import { IntegrationType } from '~/types'
+
+type PosthogConnectRegion = 'US' | 'EU'
+
+const REGION_OPTIONS: { value: PosthogConnectRegion; label: string }[] = [
+ { value: 'US', label: 'United States (US)' },
+ { value: 'EU', label: 'European Union (EU)' },
+]
+
+// Only offer scopes an OAuth client can actually be granted (mirrors get_oauth_scopes_supported on
+// the backend, which excludes privileged/internal/hidden scopes). openid/email are added server-side.
+const GRANTABLE_SCOPES = API_SCOPES.filter((scope) => !scope.unprivilegedExcluded)
+
+const readAllScopes = (): string[] =>
+ GRANTABLE_SCOPES.filter((s) => !s.disabledActions?.includes('read')).map((s) => `${s.key}:read`)
+
+const fullAccessScopes = (): string[] =>
+ GRANTABLE_SCOPES.map((s) => (s.disabledActions?.includes('write') ? `${s.key}:read` : `${s.key}:write`))
+
+const SCOPE_PRESETS: { value: string; label: string; scopes: () => string[] }[] = [
+ { value: 'tasks', label: 'Tasks only (read and write)', scopes: () => ['task:read', 'task:write'] },
+ { value: 'read_only', label: 'Read-only (everything)', scopes: readAllScopes },
+ { value: 'full', label: 'Full access', scopes: fullAccessScopes },
+]
+
+function PosthogConnectionRow({ integration }: { integration: IntegrationType }): JSX.Element {
+ const { deleteIntegration } = useActions(integrationsLogic)
+ const region = (integration.config?.region as string | undefined) || 'Unknown'
+
+ const handleDisconnect = (): void => {
+ LemonDialog.open({
+ title: 'Disconnect this PostHog connection?',
+ description: (
+ <p>
+ PostHog will no longer be able to act in that project on your behalf. Anything using this connection
+ (for example dispatched tasks) will stop working.
+ </p>
+ ),
+ primaryButton: {
+ children: 'Disconnect',
+ status: 'danger',
+ onClick: () => deleteIntegration(integration.id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ return (
+ <div className="flex items-center gap-4 px-4 py-3">
+ <div className="shrink-0">
+ <div className="flex h-10 w-10 items-center justify-center rounded-md border bg-surface-secondary text-2xl">
+ <IconLogomark />
+ </div>
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="font-semibold">{integration.display_name || 'PostHog'}</span>
+ <span className="text-xs text-muted bg-surface-secondary px-1.5 py-0.5 rounded">
+ {region} region
+ </span>
+ </div>
+ <div className="mt-0.5 text-xs text-secondary">
+ {integration.created_at ? (
+ <>
+ Connected <TZLabel time={integration.created_at} className="align-baseline" />
+ </>
+ ) : (
+ 'Connected'
+ )}
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center">
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ icon={<IconTrash />}
+ onClick={handleDisconnect}
+ tooltip="Disconnect this connection"
+ />
+ </div>
+ </div>
+ )
+}
+
+function ConnectModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }): JSX.Element {
+ const [region, setRegion] = useState<PosthogConnectRegion>('EU')
+ const [scopes, setScopes] = useState<string[]>(['task:read', 'task:write'])
+ const [searchTerm, setSearchTerm] = useState<string>('')
+
+ const scopeActions = useMemo(() => scopesArrayToObject(scopes), [scopes])
+
+ const setScopeAction = (key: string, action: string): void => {
+ const next = scopesArrayToObject(scopes)
+ if (action === 'none') {
+ delete next[key]
+ } else {
+ next[key] = action
+ }
+ setScopes(scopesObjectToArray(next))
+ }
+
+ const filteredScopes = useMemo(() => {
+ const term = searchTerm.trim().toLowerCase()
+ return term ? GRANTABLE_SCOPES.filter((s) => s.objectName.toLowerCase().includes(term)) : GRANTABLE_SCOPES
+ }, [searchTerm])
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={onClose}
+ title="Connect a PostHog project"
+ description="You'll be sent to the target PostHog to sign in and approve the access below."
+ width={560}
+ footer={
+ <LemonButton
+ type="primary"
+ to={api.integrations.authorizeUrl({
+ kind: 'posthog',
+ next: window.location.pathname,
+ extraParams: { region, scopes: scopes.join(',') },
+ })}
+ disableClientSideRouting
+ disabledReason={scopes.length === 0 ? 'Select at least one scope' : undefined}
+ >
+ Connect {region}
+ </LemonButton>
+ }
+ >
+ <div className="flex flex-col gap-2 h-[60vh]">
+ <div className="flex flex-col gap-1">
+ <label className="font-semibold">PostHog region</label>
+ <LemonSelect<PosthogConnectRegion>
+ value={region}
+ onChange={(value) => setRegion(value ?? 'EU')}
+ options={REGION_OPTIONS}
+ />
+ </div>
+ <div className="flex flex-col gap-1 flex-1 min-h-0">
+ <div className="flex items-center justify-between gap-2">
+ <label className="font-semibold">Access to grant</label>
+ <LemonSelect
+ placeholder="Apply a preset"
+ size="small"
+ value={null}
+ onChange={(value) => {
+ const preset = SCOPE_PRESETS.find((p) => p.value === value)
+ if (preset) {
+ setScopes(preset.scopes())
+ }
+ }}
+ options={SCOPE_PRESETS.map((p) => ({ value: p.value, label: p.label }))}
+ dropdownMatchSelectWidth={false}
+ />
+ </div>
+ <LemonInput
+ type="search"
+ placeholder="Search scopes..."
+ value={searchTerm}
+ onChange={setSearchTerm}
+ size="small"
+ />
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ {filteredScopes.length === 0 ? (
+ <div className="text-muted text-sm py-2">No scopes match "{searchTerm}"</div>
+ ) : (
+ filteredScopes.map((scope) => (
+ <ScopeAccessRow
+ key={scope.key}
+ label={scope.objectName}
+ info={scope.info}
+ value={scopeActions[scope.key] ?? 'none'}
+ onChange={(value) => setScopeAction(scope.key, value)}
+ readDisabledReason={
+ scope.disabledActions?.includes('read')
+ ? 'Does not apply to this resource'
+ : undefined
+ }
+ writeDisabledReason={
+ scope.disabledActions?.includes('write')
+ ? 'Does not apply to this resource'
+ : undefined
+ }
+ />
+ ))
+ )}
+ </div>
+ </div>
+ </div>
+ </LemonModal>
+ )
+}
+
+export function PersonalPosthogConnections(): JSX.Element {
+ const { integrations, integrationsLoading } = useValues(integrationsLogic)
+ const { user } = useValues(userLogic)
+ const [modalOpen, setModalOpen] = useState(false)
+
+ if (integrationsLoading && !integrations) {
+ return <LemonSkeleton className="h-10" />
+ }
+
+ // A connection acts as the user who created it (the forward endpoint is creator-gated), so only
+ // show this user's own connections. `kind` is compared as a string because `posthog` lives in the
+ // generated integration types, not the legacy manual IntegrationKind union.
+ const connections = (integrations ?? []).filter(
+ (i) => (i.kind as string) === 'posthog' && i.created_by?.id === user?.id
+ )
+
+ return (
+ <div className="deprecated-space-y-2">
+ <div className="divide-y rounded border bg-surface-primary">
+ {connections.length === 0 ? (
+ <div className="px-4 py-6 text-center">
+ <p className="mb-1">No PostHog projects connected yet</p>
+ <p className="text-muted text-sm mb-0">
+ Connect another PostHog project to act in it through its API, for example to dispatch tasks
+ that must run there.
+ </p>
+ </div>
+ ) : (
+ connections.map((integration) => (
+ <PosthogConnectionRow key={integration.id} integration={integration} />
+ ))
+ )}
+ <div className="p-2">
+ <LemonButton type="secondary" icon={<IconPlus />} onClick={() => setModalOpen(true)}>
+ {connections.length === 0 ? 'Connect a PostHog project' : 'Connect another project'}
+ </LemonButton>
+ </div>
+ </div>
+ <ConnectModal isOpen={modalOpen} onClose={() => setModalOpen(false)} />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 73cfede5598e..7887a50c6905 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -17,6 +17,7 @@ import { BaseCurrency } from 'lib/components/BaseCurrency/BaseCurrency'
import { FlaggedFeature } from 'lib/components/FlaggedFeature'
import { FEATURE_SUPPORT } from 'lib/components/SupportedPlatforms/featureSupport'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
+import { PersonalPosthogConnections } from 'lib/integrations/PosthogConnect'
import { MAX_LOOKBACK_DAYS, MIN_LOOKBACK_DAYS } from 'scenes/experiments/constants'
import { DefaultMinimumDetectableEffect } from 'scenes/experiments/DefaultMinimumDetectableEffect'
import { GitHub, Linear, Slack } from 'scenes/integrations/definitions'
@@ -2136,6 +2137,15 @@ export const SETTINGS_MAP: SettingSection[] = [
keywords: ['slack', 'integration', 'identity', 'link', 'mention', 'personal'],
flag: 'SLACK_APP_OAUTH',
},
+ {
+ id: 'personal-integrations-posthog',
+ title: 'PostHog project',
+ description:
+ 'Connect another PostHog project (in another region or your own) to act in it through its API, for example to dispatch tasks that must run there.',
+ component: <PersonalPosthogConnections />,
+ keywords: ['posthog', 'integration', 'connect', 'region', 'cross-region', 'task', 'personal'],
+ flag: 'POSTHOG_CONNECT',
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index dbc2366c8678..c31356c4e98f 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -221,6 +221,7 @@ export type SettingId =
| 'personal-api-keys'
| 'personal-integrations-github'
| 'personal-integrations-slack'
+ | 'personal-integrations-posthog'
| 'persons-join-mode'
| 'reminders'
| 'persons-on-events'
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index fb39fdfc234d..c69136a33e37 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -8,6 +8,7 @@ from urllib.parse import urlencode
from django.conf import settings
from django.core.cache import cache
from django.db import transaction
+from django.db.models import Q, QuerySet
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils import timezone
@@ -49,6 +50,10 @@ from posthog.models.integration import (
ANTHROPIC_WORKSPACE_LABEL_MAX_LENGTH,
ERROR_TOKEN_REFRESH_FAILED,
GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS,
+ POSTHOG_CONNECT_ALLOWED_REGIONS,
+ POSTHOG_CONNECT_DEFAULT_SCOPES,
+ POSTHOG_CONNECT_GRANTABLE_SCOPES,
+ POSTHOG_CONNECT_KIND,
SLACK_INTEGRATION_KINDS,
AnthropicIntegration,
ApplePushIntegration,
@@ -980,6 +985,14 @@ class IntegrationViewSet(
filter_backends = [DjangoFilterBackend]
filterset_fields = ["kind"]
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ # A `posthog` connection holds the creator's delegated grant into another project plus personal
+ # target metadata (account email, region, scopes) in its config, and is only usable by its
+ # creator. Unlike team-shared integrations, don't expose other members' connections in
+ # list/retrieve — scope `posthog` rows to the requesting user. Other kinds stay team-visible.
+ user_id = getattr(self.request.user, "id", None)
+ return queryset.exclude(Q(kind=POSTHOG_CONNECT_KIND) & ~Q(created_by_id=user_id))
+
def handle_exception(self, exc: Exception) -> Response:
# GitHub rate limits surface from any GitHub-backed action (teams, repos, branches, refresh);
# map them to 429 + Retry-After once here instead of per action.
@@ -1095,8 +1108,26 @@ class IntegrationViewSet(
token = os.urandom(33).hex()
if kind in OauthIntegration.supported_kinds:
+ region: str | None = None
+ scopes: list[str] | None = None
+ if kind == "posthog":
+ region = (request.GET.get("region") or "").upper()
+ if region not in POSTHOG_CONNECT_ALLOWED_REGIONS:
+ raise ValidationError(f"region must be one of {', '.join(POSTHOG_CONNECT_ALLOWED_REGIONS)}")
+ raw_scopes = (request.GET.get("scopes") or "").strip()
+ if raw_scopes == "full":
+ scopes = sorted(POSTHOG_CONNECT_GRANTABLE_SCOPES)
+ elif raw_scopes == "read_only":
+ scopes = sorted(s for s in POSTHOG_CONNECT_GRANTABLE_SCOPES if s.endswith(":read"))
+ else:
+ scopes = [s for s in re.split(r"[,\s]+", raw_scopes) if s] or list(POSTHOG_CONNECT_DEFAULT_SCOPES)
+ invalid = [s for s in scopes if s not in POSTHOG_CONNECT_GRANTABLE_SCOPES]
+ if invalid:
+ raise ValidationError(f"Unsupported connection scopes: {', '.join(invalid)}")
try:
- auth_url = OauthIntegration.authorize_url(kind, next=next, token=token, team_id=self.team_id)
+ auth_url = OauthIntegration.authorize_url(
+ kind, next=next, token=token, region=region, scopes=scopes, team_id=self.team_id
+ )
response = redirect(auth_url)
# nosemgrep: python.django.security.audit.secure-cookies.django-secure-set-cookie (OAuth state, short-lived, needed for cross-site redirect)
response.set_cookie("ph_oauth_state", token, max_age=60 * 5)
diff --git a/posthog/api/posthog_connection.py b/posthog/api/posthog_connection.py
new file mode 100644
index 000000000000..24ae5a25a1ca
--- /dev/null
+++ b/posthog/api/posthog_connection.py
@@ -0,0 +1,270 @@
+"""Forward arbitrary API requests to another PostHog project through a `posthog` connection.
+
+A `posthog` integration (see `posthog.models.integration`) holds a user-consented, refreshable OAuth
+grant against another PostHog project, in another region or your own. This viewset lets the connecting
+user replay any request against that project's API — the server injects the stored token, so the
+caller (a browser, an agent sandbox, an MCP tool) never holds it.
+
+What the connection can do is bounded three ways: the scopes the user granted at consent, the target
+cell's OAuthApplication.allowed_scopes, and the target's normal per-request permission checks. This
+side only resolves the token and forwards; it does not re-implement or gate individual endpoints.
+"""
+
+import re
+import json
+from collections.abc import Iterator
+from contextlib import contextmanager
+from time import monotonic
+from typing import Any
+
+from django.core.cache import cache
+
+import requests
+import structlog
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.throttling import BaseThrottle
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.models.integration import POSTHOG_CONNECT_KIND, Integration, OauthIntegration, posthog_connect_base_url
+from posthog.permissions import get_authenticator_scopes
+from posthog.rate_limit import PostHogConnectionForwardThrottle
+
+logger = structlog.get_logger(__name__)
+
+CONNECTION_FORWARD_TIMEOUT_SECONDS = 30
+# Each forward holds an API worker open while it round-trips to the target, so bound how many can be
+# in flight per connection at once — the per-minute throttle only limits how fast they *start*, not
+# how many run concurrently. Best-effort via the shared cache: the slot key carries a TTL so a worker
+# that dies before releasing self-heals, and any cache error fails open so a limiter outage can't
+# break a legitimate forward.
+CONNECTION_MAX_INFLIGHT_PER_CONNECTION = 10
+# Read at most this much of the target's response into memory. The proxy holds the whole body to
+# re-serialize it, so cap it to keep an oversized upstream response from exhausting a worker.
+CONNECTION_MAX_RESPONSE_BYTES = 5 * 1024 * 1024
+# Header stamped on every forwarded request so the target (and this endpoint) can tell a request came
+# through a connection — used here to refuse a forwarded request being forwarded again.
+CONNECTION_MARKER_HEADER = "X-PostHog-Connection"
+_METHODS_WITH_BODY = ("POST", "PUT", "PATCH", "DELETE")
+_ALLOWED_METHODS = ("GET", *_METHODS_WITH_BODY)
+# A relative API path on the target, e.g. `api/projects/2/insights/`. The host comes from the fixed
+# per-region base URL (never from here), so the netloc can't be changed; this just keeps the path a
+# well-formed relative path and blocks obvious traversal.
+_SAFE_PATH = re.compile(r"^[A-Za-z0-9._~!$&'()*+,;=:@%/-]+$")
+
+
+def _connection_access_token(integration: Integration) -> str:
+ oauth = OauthIntegration(integration)
+ if oauth.access_token_expired():
+ oauth.refresh_access_token()
+ integration.refresh_from_db()
+ token = integration.sensitive_config.get("access_token")
+ if not token:
+ raise ValidationError("This PostHog connection has no usable access token — reconnect it.")
+ return token
+
+
+def _enforce_caller_covers_connection_scopes(request: Request, integration: Integration) -> None:
+ """A connection acts with the creator's stored grant, which may be broader than the API key making
+ this call. Require that key to itself carry the scopes the connection was granted, so a narrowly
+ scoped (or leaked) key can't wield the connection to exceed its own authority. Session auth and
+ full-access (`*`) keys already carry the user's full authority, so they pass."""
+ caller_scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if caller_scopes is None or "*" in caller_scopes:
+ return
+ granted = set(integration.config.get("granted_scopes") or [])
+ if not granted:
+ # We don't know what this connection can do — `granted_scopes` is only ever populated from the
+ # target's token-response `scope`, which is OPTIONAL per RFC 6749 §5.1. If the target omitted
+ # it, fail closed: a scoped (or leaked) key must not wield a grant whose reach we can't bound.
+ raise PermissionDenied(
+ "This PostHog connection's granted scopes are unknown, so it can only be used with a "
+ "full-access API key or a session. Reconnect it to record its scopes."
+ )
+ missing = granted - set(caller_scopes)
+ if missing:
+ raise PermissionDenied(
+ "Your API key must carry the scopes this connection was granted to use it. "
+ f"Missing: {', '.join(sorted(missing))}."
+ )
+
+
+def _validate_target_path(path: str) -> str:
+ raw = path or ""
+ stripped = raw.lstrip("/")
+ # Reject a leading `//` (protocol-relative-looking) even though the fixed base URL already fixes
+ # the host — it's never a legitimate API path, so refuse it rather than silently normalizing.
+ if not stripped or raw.startswith("//") or "://" in stripped or ".." in stripped or not _SAFE_PATH.match(stripped):
+ raise ValidationError("path must be a relative target API path, e.g. `api/projects/2/insights/`.")
+ return stripped
+
+
+@contextmanager
+def _inflight_slot(integration_id: int) -> Iterator[bool]:
+ """Bound concurrent forwards per connection, yielding whether a slot was acquired. Fails open on
+ any cache error so the limiter can never take the feature down; the slot key's TTL reclaims a
+ slot whose holder died before release."""
+ key = f"posthog_connection_inflight:{integration_id}"
+ # Keep the lease alive for the whole forward: the read is bounded by a wall-clock deadline of
+ # CONNECTION_FORWARD_TIMEOUT_SECONDS, plus up to one more socket-timeout window for the final
+ # blocking read, so a slot could legitimately be held for ~2x the timeout. TTL past that (rather
+ # than expiring mid-forward) is what makes the concurrency cap actually hold.
+ try:
+ cache.add(key, 0, timeout=2 * CONNECTION_FORWARD_TIMEOUT_SECONDS + 5)
+ current = cache.incr(key)
+ except Exception:
+ yield True
+ return
+ try:
+ yield current <= CONNECTION_MAX_INFLIGHT_PER_CONNECTION
+ finally:
+ try:
+ cache.decr(key)
+ except Exception:
+ pass
+
+
+class PostHogConnectionForwardSerializer(serializers.Serializer):
+ method = serializers.ChoiceField(
+ choices=list(_ALLOWED_METHODS), help_text="HTTP method to use against the target project's API."
+ )
+ path = serializers.CharField(
+ help_text="Relative target API path with no host or scheme, e.g. `api/projects/2/insights/`."
+ )
+ query = serializers.DictField(
+ required=False, child=serializers.CharField(), help_text="Query parameters to send to the target."
+ )
+ # `data` shadows Serializer.data (a property); the field is part of the API contract, so keep the
+ # name and silence the resulting attribute-type mismatch.
+ data = serializers.JSONField(required=False, help_text="JSON request body for write methods.") # type: ignore[assignment]
+
+
+class PostHogConnectionForwardResponseSerializer(serializers.Serializer):
+ status = serializers.IntegerField(help_text="HTTP status the target project returned.")
+ data = serializers.JSONField(help_text="The target project's response body, passed through.") # type: ignore[assignment]
+
+
+class PostHogConnectionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Replay requests against another PostHog project via a `posthog` connection you created."""
+
+ authentication_classes = [SessionAuthentication, PersonalAPIKeyAuthentication, OAuthAccessTokenAuthentication]
+ scope_object = "integration"
+ serializer_class = PostHogConnectionForwardSerializer
+
+ def get_throttles(self) -> list[BaseThrottle]:
+ if self.action == "forward":
+ return [PostHogConnectionForwardThrottle(), *super().get_throttles()]
+ return super().get_throttles()
+
+ def _get_connection(self, pk: str | None) -> Integration:
+ if pk is None:
+ raise NotFound("No PostHog connection with that id in this project.")
+ try:
+ integration = Integration.objects.get(team_id=self.team_id, id=pk, kind=POSTHOG_CONNECT_KIND)
+ except (Integration.DoesNotExist, ValueError, ValidationError):
+ raise NotFound("No PostHog connection with that id in this project.")
+ # A connection acts as the user who consented to it. Restrict use to that user so a broad,
+ # any-scope grant can't become a team-wide confused deputy in the target project.
+ if integration.created_by_id != getattr(self.request.user, "id", None):
+ raise PermissionDenied("You can only use a PostHog connection you created.")
+ return integration
+
+ @extend_schema(
+ request=PostHogConnectionForwardSerializer,
+ responses={200: OpenApiResponse(response=PostHogConnectionForwardResponseSerializer)},
+ summary="Forward a request through a PostHog connection",
+ description="Replay an API request against the connected PostHog project. The server injects the connection's token; the response is passed through.",
+ )
+ @action(detail=True, methods=["post"], url_path="forward", required_scopes=["integration:write"])
+ def forward(self, request: Request, pk: str | None = None, **kwargs: Any) -> Response:
+ # Refuse to forward a request that itself arrived through a connection, so a same-region (or
+ # cross-region) connection can't be chained into itself and tie up workers one hop at a time.
+ if request.headers.get(CONNECTION_MARKER_HEADER):
+ raise ValidationError("A request forwarded through a PostHog connection cannot be forwarded again.")
+
+ integration = self._get_connection(pk)
+ _enforce_caller_covers_connection_scopes(request, integration)
+
+ serializer = PostHogConnectionForwardSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ payload = serializer.validated_data
+
+ method = payload["method"]
+ path = _validate_target_path(payload["path"])
+ token = _connection_access_token(integration)
+ base = posthog_connect_base_url(integration.config.get("region"))
+
+ raw = bytearray()
+ timed_out = False
+ try:
+ with _inflight_slot(integration.id) as acquired:
+ if not acquired:
+ raise Throttled(detail="Too many concurrent requests through this PostHog connection.")
+ res = requests.request(
+ method,
+ f"{base}/{path}",
+ params=payload.get("query") or None,
+ json=payload.get("data") if method in _METHODS_WITH_BODY else None,
+ headers={"Authorization": f"Bearer {token}", CONNECTION_MARKER_HEADER: "1"},
+ timeout=CONNECTION_FORWARD_TIMEOUT_SECONDS,
+ # A compromised/misconfigured target must not be able to 30x us into resending the
+ # bearer token to another origin.
+ allow_redirects=False,
+ # Stream so an oversized body is capped below rather than fully buffered by requests.
+ stream=True,
+ )
+ with res:
+ # Bound the *total* time we hold a worker, not just each socket read. A target that
+ # trickles a long-lived stream (SSE keepalives, say) would otherwise keep this read
+ # alive past the in-flight lease below and defeat the concurrency cap. Stop at the
+ # size cap or the wall-clock deadline, whichever comes first.
+ deadline = monotonic() + CONNECTION_FORWARD_TIMEOUT_SECONDS
+ for chunk in res.iter_content(chunk_size=65536):
+ raw += chunk
+ if len(raw) > CONNECTION_MAX_RESPONSE_BYTES:
+ break
+ if monotonic() > deadline:
+ timed_out = True
+ break
+ except requests.RequestException as err:
+ logger.warning(
+ "posthog_connection_forward_unreachable",
+ integration_id=integration.id,
+ region=integration.config.get("region"),
+ error=str(err),
+ )
+ return Response(
+ {"status": status.HTTP_502_BAD_GATEWAY, "data": {"error": "The target project could not be reached."}},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ if timed_out:
+ return Response(
+ {
+ "status": status.HTTP_504_GATEWAY_TIMEOUT,
+ "data": {"error": "The target project took too long to respond."},
+ },
+ status=status.HTTP_504_GATEWAY_TIMEOUT,
+ )
+
+ if len(raw) > CONNECTION_MAX_RESPONSE_BYTES:
+ return Response(
+ {
+ "status": status.HTTP_502_BAD_GATEWAY,
+ "data": {"error": "The target project's response was too large."},
+ },
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ try:
+ body = json.loads(raw) if raw else None
+ except ValueError:
+ body = None
+ # Pass the target's status and body straight through. The target owns the residency policy for
+ # what its responses contain, so no scrub happens on this side.
+ return Response({"status": res.status_code, "data": body})
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 210e1b7c215f..76354b84efca 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -53,6 +53,7 @@ from . import (
organization_member,
organization_personal_api_key,
personal_api_key,
+ posthog_connection,
project_secret_api_key,
proxy_record,
query,
@@ -170,6 +171,12 @@ projects_router.register(
projects_router.register(r"integrations", integration.IntegrationViewSet, "project_integrations", ["team_id"])
+projects_router.register(
+ r"posthog_connections",
+ posthog_connection.PostHogConnectionViewSet,
+ "project_posthog_connections",
+ ["team_id"],
+)
projects_router.register(
r"ingestion_warnings",
ingestion_warnings.IngestionWarningsViewSet,
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 69362c6a9320..f53ebe211a55 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -5070,3 +5070,105 @@ class TestIntegrationMembershipPermissions(APIBaseTest):
existing.refresh_from_db()
assert existing.config["project_id"] == "original-project"
assert Integration.objects.filter(team=self.team, kind="google-cloud-service-account").count() == 1
+
+
+class TestPosthogConnectAuthorize:
+ @pytest.fixture(autouse=True)
+ def setup_environment(self, db):
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+
+ def _authorize(self, client: HttpClient, **params):
+ return client.get(f"/api/environments/{self.team.pk}/integrations/authorize/", {"kind": "posthog", **params})
+
+ def test_rejects_unknown_region(self, client: HttpClient):
+ client.force_login(self.user)
+ response = self._authorize(client, region="MARS", scopes="task:read")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "region must be one of" in response.json()["detail"]
+
+ def test_rejects_missing_region(self, client: HttpClient):
+ client.force_login(self.user)
+ response = self._authorize(client, scopes="task:read")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_rejects_unknown_scope(self, client: HttpClient):
+ client.force_login(self.user)
+ # A made-up scope is never user-grantable, so it is rejected regardless of the widened set.
+ response = self._authorize(client, region="EU", scopes="totally:fake")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Unsupported connection scopes" in response.json()["detail"]
+
+ @override_settings(
+ POSTHOG_CONNECT_BASE_URL_EU="https://eu.posthog.com",
+ POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU="eu-client-id",
+ POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU="eu-secret",
+ )
+ def test_valid_request_redirects_to_target_region(self, client: HttpClient):
+ client.force_login(self.user)
+ response = self._authorize(client, region="EU", scopes="task:read,task:write")
+ assert response.status_code == status.HTTP_302_FOUND
+ assert response.headers["Location"].startswith("https://eu.posthog.com/oauth/authorize?")
+ assert client.cookies.get("ph_oauth_state") is not None
+
+ @override_settings(
+ POSTHOG_CONNECT_BASE_URL_EU="https://eu.posthog.com",
+ POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU="eu-client-id",
+ POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU="eu-secret",
+ )
+ def test_read_only_preset_requests_only_read_scopes(self, client: HttpClient):
+ from urllib.parse import parse_qs, urlparse
+
+ client.force_login(self.user)
+ response = self._authorize(client, region="EU", scopes="read_only")
+ assert response.status_code == status.HTTP_302_FOUND
+ requested = parse_qs(urlparse(response.headers["Location"]).query)["scope"][0].split()
+ assert requested, "expected some scopes"
+ # Only :read scopes plus the auto-added identity scopes; no :write.
+ assert not any(s.endswith(":write") for s in requested)
+ assert "openid" in requested and "email" in requested
+
+
+class TestPosthogConnectionListScoping:
+ @pytest.fixture(autouse=True)
+ def setup_environment(self, db, settings):
+ # A `posthog` connection's display_name resolves its target region's OAuth config, so configure
+ # EU here (mirrors the authorize tests) or listing it 500s.
+ settings.POSTHOG_CONNECT_BASE_URL_EU = "https://eu.posthog.com"
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU = "eu-client-id"
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU = "eu-secret"
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.owner = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+ self.other = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+ self.connection = Integration.objects.create(
+ team=self.team, kind="posthog", integration_id="EU:owner", created_by=self.owner, config={"region": "EU"}
+ )
+ # A team-shared kind that any member is meant to see; github serializes without OAuth config.
+ self.github = Integration.objects.create(
+ team=self.team, kind="github", integration_id="gh-1", created_by=self.owner, config={"installation_id": "1"}
+ )
+
+ def _list_ids(self, client: HttpClient) -> set[int]:
+ response = client.get(f"/api/environments/{self.team.pk}/integrations/")
+ assert response.status_code == status.HTTP_200_OK
+ return {r["id"] for r in response.json()["results"]}
+
+ def test_other_member_cannot_see_another_users_connection(self, client: HttpClient):
+ # A `posthog` connection is only usable by its creator and carries their personal target
+ # metadata, so it must not leak to other members via the list endpoint. Team-shared kinds stay.
+ client.force_login(self.other)
+ ids = self._list_ids(client)
+ assert self.connection.id not in ids
+ assert self.github.id in ids
+
+ def test_creator_still_sees_their_connection(self, client: HttpClient):
+ client.force_login(self.owner)
+ assert self.connection.id in self._list_ids(client)
diff --git a/posthog/api/test/test_posthog_connection.py b/posthog/api/test/test_posthog_connection.py
new file mode 100644
index 000000000000..1c46143f7e1d
--- /dev/null
+++ b/posthog/api/test/test_posthog_connection.py
@@ -0,0 +1,219 @@
+import json
+import time
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test.client import Client as HttpClient
+
+from rest_framework import status
+
+from posthog.api.posthog_connection import CONNECTION_MAX_INFLIGHT_PER_CONNECTION
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.integration import Integration
+
+FORWARD_PATH = "posthog.api.posthog_connection.requests.request"
+
+
+def _mock_response(status_code: int, body: dict, chunks: list[bytes] | None = None) -> MagicMock:
+ # The view streams the body via res.iter_content(...), so drive that rather than res.json().
+ m = MagicMock(status_code=status_code)
+ m.__enter__.return_value = m
+ m.iter_content.return_value = iter(chunks) if chunks is not None else iter([json.dumps(body).encode()])
+ return m
+
+
+class TestPostHogConnectionForward:
+ @pytest.fixture(autouse=True)
+ def setup_environment(self, db, settings):
+ # pytest-style class (not a Django TestCase), so use the `settings` fixture rather than the
+ # override_settings class decorator, which only works on SimpleTestCase subclasses.
+ settings.POSTHOG_CONNECT_BASE_URL_EU = "https://eu.posthog.com"
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU = "eu-client-id"
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU = "eu-secret"
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+ self.other_user = User.objects.create_and_join(
+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN
+ )
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="posthog",
+ integration_id="EU:user-uuid",
+ created_by=self.user,
+ config={"region": "EU", "refreshed_at": int(time.time()), "expires_in": 3600},
+ sensitive_config={"refresh_token": "RT", "access_token": "AT"},
+ )
+
+ def _forward_url(self) -> str:
+ return f"/api/environments/{self.team.pk}/posthog_connections/{self.integration.id}/forward/"
+
+ def test_forward_injects_token_and_passes_through(self, client: HttpClient):
+ client.force_login(self.user)
+ with patch(FORWARD_PATH) as mock_request:
+ mock_request.return_value = _mock_response(200, {"results": [1, 2, 3]})
+
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/", "query": {"limit": "5"}},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"status": 200, "data": {"results": [1, 2, 3]}}
+ method, url = mock_request.call_args[0][0], mock_request.call_args[0][1]
+ assert method == "GET"
+ assert url == "https://eu.posthog.com/api/projects/2/insights/"
+ assert mock_request.call_args[1]["headers"]["Authorization"] == "Bearer AT"
+ assert mock_request.call_args[1]["params"] == {"limit": "5"}
+ assert mock_request.call_args[1]["allow_redirects"] is False
+
+ def test_forward_sends_body_only_for_write_methods(self, client: HttpClient):
+ client.force_login(self.user)
+ with patch(FORWARD_PATH) as mock_request:
+ mock_request.return_value = _mock_response(201, {"id": "abc"})
+
+ client.post(
+ self._forward_url(),
+ {"method": "POST", "path": "api/projects/2/tasks/", "data": {"description": "hi"}},
+ content_type="application/json",
+ )
+
+ assert mock_request.call_args[1]["json"] == {"description": "hi"}
+
+ def test_forward_passes_through_target_error_status(self, client: HttpClient):
+ client.force_login(self.user)
+ with patch(FORWARD_PATH) as mock_request:
+ mock_request.return_value = _mock_response(403, {"detail": "nope"})
+
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"status": 403, "data": {"detail": "nope"}}
+
+ @pytest.mark.parametrize("bad_path", ["../etc", "https://evil.com/x", "api/../../secret", "//evil.com"])
+ def test_forward_rejects_unsafe_path(self, client: HttpClient, bad_path):
+ client.force_login(self.user)
+ with patch(FORWARD_PATH) as mock_request:
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": bad_path},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_request.assert_not_called()
+
+ def test_forward_rejects_non_creator(self, client: HttpClient):
+ client.force_login(self.other_user)
+ with patch(FORWARD_PATH) as mock_request:
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_request.assert_not_called()
+
+ def test_forward_unknown_connection_is_404(self, client: HttpClient):
+ client.force_login(self.user)
+ response = client.post(
+ f"/api/environments/{self.team.pk}/posthog_connections/nonexistent/forward/",
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_forward_unreachable_target_is_502(self, client: HttpClient):
+ import requests
+
+ client.force_login(self.user)
+ with patch(FORWARD_PATH, side_effect=requests.ConnectionError("down")):
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+
+ def test_forward_refuses_a_request_already_forwarded(self, client: HttpClient):
+ # A request that arrived through a connection carries the marker header; forwarding it again
+ # would let a connection be chained into itself.
+ client.force_login(self.user)
+ with patch(FORWARD_PATH) as mock_request:
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ HTTP_X_POSTHOG_CONNECTION="1",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_request.assert_not_called()
+
+ def test_forward_requires_caller_token_to_cover_connection_scopes(self, client: HttpClient):
+ # A scoped key that lacks the scopes the connection was granted can't wield the connection.
+ self.integration.config["granted_scopes"] = ["insight:read", "task:write"]
+ self.integration.save()
+ client.force_login(self.user)
+ with patch("posthog.api.posthog_connection.get_authenticator_scopes", return_value=["integration:write"]):
+ with patch(FORWARD_PATH) as mock_request:
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_request.assert_not_called()
+
+ def test_forward_refuses_scoped_caller_when_granted_scopes_unknown(self, client: HttpClient):
+ # If the target's token response omitted `scope`, `granted_scopes` is empty and we can't bound
+ # what the connection can do — a scoped key must be refused rather than passing by default.
+ self.integration.config["granted_scopes"] = []
+ self.integration.save()
+ client.force_login(self.user)
+ with patch("posthog.api.posthog_connection.get_authenticator_scopes", return_value=["integration:write"]):
+ with patch(FORWARD_PATH) as mock_request:
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_request.assert_not_called()
+
+ def test_forward_times_out_when_target_exceeds_deadline(self, client: HttpClient):
+ # A target that keeps trickling data past the wall-clock deadline is cut off with a 504 rather
+ # than holding a worker (and its in-flight slot) open past the lease.
+ client.force_login(self.user)
+ slow = _mock_response(200, {}, chunks=[b'{"a":1}', b"more"])
+ # deadline = 0 + timeout; the post-chunk check sees a clock already past it.
+ with patch("posthog.api.posthog_connection.monotonic", side_effect=[0.0, 10_000.0, 10_001.0]):
+ with patch(FORWARD_PATH, return_value=slow):
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_504_GATEWAY_TIMEOUT
+
+ def test_forward_rejects_when_connection_at_inflight_capacity(self, client: HttpClient):
+ # The per-minute throttle limits how fast forwards start, not how many run at once. When a
+ # connection is already at its in-flight cap, a new forward is refused before the outbound call.
+ client.force_login(self.user)
+ with patch(
+ "posthog.api.posthog_connection.cache.incr", return_value=CONNECTION_MAX_INFLIGHT_PER_CONNECTION + 1
+ ):
+ with patch(FORWARD_PATH) as mock_request:
+ response = client.post(
+ self._forward_url(),
+ {"method": "GET", "path": "api/projects/2/insights/"},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ mock_request.assert_not_called()
diff --git a/posthog/migrations/1280_alter_integration_kind.py b/posthog/migrations/1280_alter_integration_kind.py
new file mode 100644
index 000000000000..12b608f6dcae
--- /dev/null
+++ b/posthog/migrations/1280_alter_integration_kind.py
@@ -0,0 +1,62 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1279_drop_duckgresserverteam_table"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="integration",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("anthropic", "Anthropic"),
+ ("apns", "Apple Push"),
+ ("aws-s3", "Aws S3"),
+ ("azure-blob", "Azure Blob"),
+ ("bing-ads", "Bing Ads"),
+ ("clickup", "Clickup"),
+ ("customerio-app", "Customerio App"),
+ ("customerio-track", "Customerio Track"),
+ ("customerio-webhook", "Customerio Webhook"),
+ ("databricks", "Databricks"),
+ ("email", "Email"),
+ ("firebase", "Firebase"),
+ ("github", "Github"),
+ ("gitlab", "Gitlab"),
+ ("google-ads", "Google Ads"),
+ ("google-analytics", "Google Analytics"),
+ ("google-cloud-service-account", "Google Cloud Service Account"),
+ ("google-cloud-storage", "Google Cloud Storage"),
+ ("google-pubsub", "Google Pubsub"),
+ ("google-search-console", "Google Search Console"),
+ ("google-sheets", "Google Sheets"),
+ ("hubspot", "Hubspot"),
+ ("intercom", "Intercom"),
+ ("jira", "Jira"),
+ ("linear", "Linear"),
+ ("linkedin-ads", "Linkedin Ads"),
+ ("meta-ads", "Meta Ads"),
+ ("pardot", "Pardot"),
+ ("pinterest-ads", "Pinterest Ads"),
+ ("postgresql", "Postgresql"),
+ ("posthog", "Posthog"),
+ ("reddit-ads", "Reddit Ads"),
+ ("resend", "Resend"),
+ ("s3-compatible", "S3 Compatible"),
+ ("salesforce", "Salesforce"),
+ ("slack", "Slack"),
+ ("slack-posthog-code", "Slack Posthog Code"),
+ ("snapchat", "Snapchat"),
+ ("snowflake", "Snowflake"),
+ ("stripe", "Stripe"),
+ ("tiktok-ads", "Tiktok Ads"),
+ ("twilio", "Twilio"),
+ ("vercel", "Vercel"),
+ ],
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 071e5b0727a6..7e4437f8a8c0 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1279_drop_duckgresserverteam_table
+1280_alter_integration_kind
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index caecf5ee57b5..1a8dee5aacbe 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -57,6 +57,7 @@ from posthog.models.utils import IntegrityError, generate_random_oauth_access_to
from posthog.plugins.plugin_server_api import reload_integrations_on_workers
from posthog.rbac.decorators import field_access_control
from posthog.schema_enums import SlackIntegrationScope, SlackIntegrationScopeInReview
+from posthog.scopes import get_oauth_scopes_supported
from posthog.security.url_validation import is_url_allowed
from posthog.sync import database_sync_to_async
from posthog.utils import get_instance_region
@@ -472,6 +473,7 @@ class Integration(models.Model):
PARDOT = "pardot"
PINTEREST_ADS = "pinterest-ads"
POSTGRESQL = "postgresql"
+ POSTHOG = "posthog"
REDDIT_ADS = "reddit-ads"
RESEND = "resend"
S3_COMPATIBLE = "s3-compatible"
@@ -530,7 +532,8 @@ class Integration(models.Model):
# The OAuth id is a list of advertiser ids, so prefer whoever authorized the connection.
return self.config.get("user_email") or self.config.get("user_display_name") or self.integration_id
if self.kind in OauthIntegration.supported_kinds:
- oauth_config = OauthIntegration.oauth_config_for_kind(self.kind)
+ region = self.config.get("region") if self.kind == "posthog" else None
+ oauth_config = OauthIntegration.oauth_config_for_kind(self.kind, region)
return dot_get(self.config, oauth_config.name_path, self.integration_id)
if self.kind in GoogleCloudIntegration.supported_kinds:
return self.integration_id or "unknown ID"
@@ -662,9 +665,80 @@ def _salesforce_instance_host(instance_url: str | None) -> str | None:
SALESFORCE_OAUTH_KINDS = ("salesforce", "pardot")
+# PostHog connect. Unlike every other OAuth kind — which points at a fixed third-party provider —
+# the `posthog` kind points at *another PostHog project*, in a region chosen by the user at connect
+# time. That region may differ from the connecting project's or be the same one (same-region is just
+# region == your own). So its authorize/token/userinfo URLs and client credentials are resolved per
+# target region rather than baked into a static config. The connecting side is the OAuth client; the
+# target region is the authorization server (its /oauth/authorize, /oauth/token, /oauth/userinfo,
+# /oauth/revoke already exist). `openid`+`email` are always requested on top of the user-selected
+# scopes so /oauth/userinfo can identify the connected account (`sub`/`email`).
+POSTHOG_CONNECT_KIND = "posthog"
+# `DEV` points at a local/self-hosted cell (`POSTHOG_CONNECT_BASE_URL_DEV` defaults to
+# http://localhost:8000) and the token exchange is a server-side POST, so a production instance must
+# never treat `DEV` as a real, connectable region — otherwise an org member could point the backend
+# at a URL of their choosing. Gate it behind an explicit dev/test context rather than relying on the
+# client id/secret env vars being unset.
+_POSTHOG_CONNECT_ALLOW_DEV = bool(settings.DEBUG or settings.TEST or settings.E2E_TESTING)
+POSTHOG_CONNECT_ALLOWED_REGIONS = ("US", "EU", *(("DEV",) if _POSTHOG_CONNECT_ALLOW_DEV else ()))
+POSTHOG_CONNECT_DEFAULT_SCOPES = ("task:read", "task:write")
+POSTHOG_CONNECT_IDENTITY_SCOPES = ("openid", "email")
+# A connection can proxy any request the granted scopes allow, so the user may pick from the full set
+# of user-grantable OAuth scopes (the same set the consent screen advertises — excludes internal,
+# hidden, and privileged scopes). The real bound is enforced twice more downstream: the target cell's
+# OAuthApplication.allowed_scopes at consent time, and the target's per-request scope checks. Identity
+# scopes are auto-added and not part of this set.
+POSTHOG_CONNECT_GRANTABLE_SCOPES = frozenset(get_oauth_scopes_supported())
+
+
+def _posthog_connect_target(region: str | None) -> tuple[str, str, str]:
+ """Resolve (base_url, client_id, client_secret) for a remote target cell.
+
+ Raises NotImplementedError for an unknown or unconfigured region so the connect/refresh
+ paths fail closed (surfaced to the user as a reconnect error) rather than silently hitting
+ the wrong cell.
+ """
+ normalized = (region or "").upper()
+ if normalized == "DEV" and not _POSTHOG_CONNECT_ALLOW_DEV:
+ # Defense in depth: even if a `DEV` region row somehow reaches here in production, refuse to
+ # resolve it so the backend never POSTs a token exchange to the dev base URL.
+ raise NotImplementedError("PostHog connect DEV region is only available in dev/test")
+ targets = {
+ "US": (
+ settings.POSTHOG_CONNECT_BASE_URL_US,
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_US,
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US,
+ ),
+ "EU": (
+ settings.POSTHOG_CONNECT_BASE_URL_EU,
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU,
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU,
+ ),
+ "DEV": (
+ settings.POSTHOG_CONNECT_BASE_URL_DEV,
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV,
+ settings.POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV,
+ ),
+ }
+ if normalized not in targets:
+ raise NotImplementedError(f"PostHog connect OAuth not supported for region {region!r}")
+ base_url, client_id, client_secret = targets[normalized]
+ if not base_url or not client_id or not client_secret:
+ raise NotImplementedError(f"PostHog connect app not configured for region {normalized}")
+ return base_url.rstrip("/"), client_id, client_secret
+
+
+def posthog_connect_base_url(region: str | None) -> str:
+ """Public base URL of a remote target cell (e.g. https://eu.posthog.com), for callers that
+ need to reach its API with a `posthog` integration token. Raises for unknown/unconfigured regions."""
+ base_url, _, _ = _posthog_connect_target(region)
+ return base_url
+
+
class OauthIntegration:
supported_kinds = [
"slack",
+ "posthog",
"salesforce",
"hubspot",
"google-ads",
@@ -696,8 +770,11 @@ class OauthIntegration:
@classmethod
@cache_for(timedelta(minutes=5))
- def oauth_config_for_kind(cls, kind: str) -> OauthConfig:
- config = cls._build_oauth_config(kind)
+ def oauth_config_for_kind(cls, kind: str, region: str | None = None) -> OauthConfig:
+ # `region` only applies to the `posthog` remote kind, whose endpoints depend on the
+ # target cell. cache_for keys on all args, so each (kind, region) pair caches separately;
+ # every other kind is called without region and keeps its single cached entry.
+ config = cls._build_oauth_config(kind, region)
fallback = settings.OAUTH_CLIENT_FALLBACKS.get(kind)
if fallback and fallback.get("client_secret"):
config.client_secret_fallback = fallback["client_secret"]
@@ -705,7 +782,24 @@ class OauthIntegration:
return config
@classmethod
- def _build_oauth_config(cls, kind: str) -> OauthConfig:
+ def _build_oauth_config(cls, kind: str, region: str | None = None) -> OauthConfig:
+ if kind == "posthog":
+ base_url, client_id, client_secret = _posthog_connect_target(region)
+ return OauthConfig(
+ authorize_url=f"{base_url}/oauth/authorize",
+ token_url=f"{base_url}/oauth/token",
+ token_info_url=f"{base_url}/oauth/userinfo",
+ token_info_config_fields=["sub", "email"],
+ token_revoke_url=f"{base_url}/oauth/revoke",
+ client_id=client_id,
+ client_secret=client_secret,
+ # Default only; authorize_url overrides with the user-selected scopes (plus the
+ # identity scopes). Token exchange/refresh don't send scope, so this is unused there.
+ scope=" ".join([*POSTHOG_CONNECT_DEFAULT_SCOPES, *POSTHOG_CONNECT_IDENTITY_SCOPES]),
+ id_path="sub",
+ name_path="email",
+ pkce=True,
+ )
if kind == "slack":
from_settings = get_instance_settings(
[
@@ -1090,8 +1184,17 @@ class OauthIntegration:
return f"{settings.SITE_URL.replace('http://', 'https://')}/integrations/{kind}/callback"
@classmethod
- def authorize_url(cls, kind: str, token: str, next: str = "", team_id: int | None = None) -> str:
- oauth_config = cls.oauth_config_for_kind(kind)
+ def authorize_url(
+ cls,
+ kind: str,
+ token: str,
+ next: str = "",
+ *,
+ region: str | None = None,
+ scopes: list[str] | None = None,
+ team_id: int | None = None,
+ ) -> str:
+ oauth_config = cls.oauth_config_for_kind(kind, region)
# Carry the initiating team through the OAuth round-trip. The fixed callback URL is not
# project-scoped, so without this the SPA re-resolves to the user's default team on
@@ -1100,6 +1203,15 @@ class OauthIntegration:
if team_id is not None:
state_payload["team_id"] = str(team_id)
+ scope = oauth_config.scope
+ if kind == "posthog":
+ # The target cell is the authorization server, so the callback (which runs on the
+ # connecting cell) needs to know which region to exchange the code against — carry it
+ # in state. Always append the identity scopes so /oauth/userinfo can name the account.
+ state_payload["region"] = (region or "").upper()
+ requested = list(scopes) if scopes else list(POSTHOG_CONNECT_DEFAULT_SCOPES)
+ scope = " ".join(dict.fromkeys([*requested, *POSTHOG_CONNECT_IDENTITY_SCOPES]))
+
if kind == "tiktok-ads":
# TikTok uses different parameter names
query_params = {
@@ -1110,7 +1222,7 @@ class OauthIntegration:
else:
query_params = {
"client_id": oauth_config.client_id,
- "scope": oauth_config.scope,
+ "scope": scope,
"redirect_uri": cls.redirect_uri(kind),
"response_type": "code",
"state": urlencode(state_payload),
@@ -1134,7 +1246,13 @@ class OauthIntegration:
def integration_from_oauth_response(
cls, kind: str, team_id: int, created_by: User, params: dict[str, str]
) -> Integration:
- oauth_config = cls.oauth_config_for_kind(kind)
+ region: str | None = None
+ if kind == "posthog":
+ # The target region was stashed in state at authorize time; the token exchange must hit
+ # that same cell. Missing/invalid region fails closed via _posthog_connect_target.
+ region = (parse_qs(params.get("state", "")).get("region", [""])[0] or "").upper()
+
+ oauth_config = cls.oauth_config_for_kind(kind, region)
code_verifier: str | None = None
if oauth_config.pkce:
@@ -1147,6 +1265,10 @@ class OauthIntegration:
# requires PKCE). Log it so the gap is visible before we enforce PKCE provider-side.
if not code_verifier:
logger.warning("oauth_pkce_verifier_missing", kind=kind, has_state_token=bool(state_token))
+ # posthog is a first-party flow we control both ends of — a missing verifier is never
+ # a legacy-provider compat case here, so fail closed rather than exchanging without PKCE.
+ if kind == "posthog":
+ raise ValidationError("Remote authorization failed: missing PKCE verifier. Please retry.")
# Reddit uses HTTP Basic Auth https://github.com/reddit-archive/reddit/wiki/OAuth2 and requires a User-Agent header
if kind == "reddit-ads":
@@ -1280,12 +1402,16 @@ class OauthIntegration:
headers={"Authorization": f"Bearer {config['access_token']}"},
json={"query": oauth_config.token_info_graphql_query},
timeout=10,
+ # This call carries the access token; don't let a misconfigured/compromised
+ # provider 30x us into resending it to another origin (matches the exchange/refresh/revoke calls).
+ allow_redirects=False,
)
else:
token_info_res = requests.get(
oauth_config.token_info_url.replace(":access_token", config["access_token"]),
headers={"Authorization": f"Bearer {config['access_token']}"},
timeout=10,
+ allow_redirects=False,
)
if token_info_res.status_code == 200:
@@ -1411,6 +1537,17 @@ class OauthIntegration:
logger.exception("Failed to fetch Stripe account name")
config["account_name"] = str(integration_id)
+ # Persist the target region and namespace the dedup key by it, so the same PostHog account
+ # connected in two different cells yields two distinct integrations instead of colliding on
+ # `sub`. `region` also drives config/refresh/revoke lookups for the lifetime of the row.
+ if kind == "posthog" and integration_id:
+ config["region"] = region
+ integration_id = f"{region}:{integration_id}"
+ # Persist the resource scopes the target actually granted (obj:action only, dropping the
+ # openid/email identity scopes). The connection proxy uses this to require a caller's own
+ # token to cover these scopes before it will wield the connection's grant.
+ config["granted_scopes"] = sorted({s for s in (config.get("scope") or "").split() if ":" in s})
+
if isinstance(integration_id, int):
integration_id = str(integration_id)
elif isinstance(integration_id, list) and len(integration_id) > 0:
@@ -1507,7 +1644,8 @@ class OauthIntegration:
after a disconnect. Callers treat this as best-effort — the local deletion proceeds
regardless.
"""
- oauth_config = self.oauth_config_for_kind(self.integration.kind)
+ region = self.integration.config.get("region") if self.integration.kind == "posthog" else None
+ oauth_config = self.oauth_config_for_kind(self.integration.kind, region)
if not oauth_config.token_revoke_url:
return
@@ -1666,7 +1804,8 @@ class OauthIntegration:
"""
Refresh the access token for the integration if necessary
"""
- oauth_config = self.oauth_config_for_kind(self.integration.kind)
+ region = self.integration.config.get("region") if self.integration.kind == "posthog" else None
+ oauth_config = self.oauth_config_for_kind(self.integration.kind, region)
# Clear out previous token refreshing errors, as they'll be re-set below if another error occurs
self.integration.errors = ""
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index b5f944a71405..4a46fa5a10d0 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -4,7 +4,7 @@ import base64
import hashlib
from datetime import UTC, datetime, timedelta
from typing import Optional
-from urllib.parse import parse_qs
+from urllib.parse import parse_qs, urlencode
import pytest
from freezegun import freeze_time
@@ -33,6 +33,8 @@ from posthog.models.instance_setting import set_instance_setting
from posthog.models.integration import (
CONFIG_LEGACY_OAUTH_CLIENT,
MISSING_CERT_PATH,
+ POSTHOG_CONNECT_DEFAULT_SCOPES,
+ POSTHOG_CONNECT_IDENTITY_SCOPES,
TLS,
Authority,
AwsS3Integration,
@@ -1247,6 +1249,148 @@ class TestOauthIntegrationModel(BaseTest):
assert "is_sandbox" not in integration.config
+class TestPosthogConnectIntegration(BaseTest):
+ connect_settings = {
+ "POSTHOG_CONNECT_BASE_URL_US": "https://us.posthog.com",
+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_US": "us-client-id",
+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US": "us-secret",
+ "POSTHOG_CONNECT_BASE_URL_EU": "https://eu.posthog.com",
+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU": "eu-client-id",
+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU": "eu-secret",
+ "POSTHOG_CONNECT_BASE_URL_DEV": "http://localhost:8000",
+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV": "dev-client-id",
+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV": "dev-secret",
+ }
+
+ @parameterized.expand(
+ [
+ ("US", "https://us.posthog.com/oauth/authorize", "us-client-id"),
+ ("EU", "https://eu.posthog.com/oauth/authorize", "eu-client-id"),
+ ("DEV", "http://localhost:8000/oauth/authorize", "dev-client-id"),
+ ]
+ )
+ def test_authorize_url_targets_selected_region(self, region, expected_base, expected_client_id):
+ with self.settings(**self.connect_settings):
+ url = OauthIntegration.authorize_url(
+ "posthog", token="tok", next="/projects/test", region=region, scopes=["task:read", "task:write"]
+ )
+ base, _, query = url.partition("?")
+ params = {k: v[0] for k, v in parse_qs(query).items()}
+ assert base == expected_base
+ assert params["client_id"] == expected_client_id
+ # User-selected scopes plus the always-appended identity scopes needed for /oauth/userinfo.
+ assert params["scope"] == "task:read task:write openid email"
+ # Host comes from SITE_URL, which differs by environment; assert the stable callback suffix.
+ assert params["redirect_uri"].endswith("/integrations/posthog/callback")
+ # posthog uses PKCE
+ assert params["code_challenge_method"] == "S256"
+ # Region is carried in state so the callback (on the connecting cell) exchanges the code
+ # against the correct target cell.
+ state = {k: v[0] for k, v in parse_qs(params["state"]).items()}
+ assert state["region"] == region
+ assert state["token"] == "tok"
+
+ def test_authorize_url_lowercases_region_input(self):
+ with self.settings(**self.connect_settings):
+ url = OauthIntegration.authorize_url("posthog", token="tok", region="eu", scopes=["task:read"])
+ assert url.startswith("https://eu.posthog.com/oauth/authorize")
+ outer = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}
+ state = {k: v[0] for k, v in parse_qs(outer["state"]).items()}
+ assert state["region"] == "EU"
+
+ def test_authorize_url_defaults_to_task_scopes_when_none_selected(self):
+ with self.settings(**self.connect_settings):
+ url = OauthIntegration.authorize_url("posthog", token="tok", region="US", scopes=None)
+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}
+ expected = " ".join([*POSTHOG_CONNECT_DEFAULT_SCOPES, *POSTHOG_CONNECT_IDENTITY_SCOPES])
+ assert params["scope"] == expected
+
+ def test_authorize_url_unknown_region_raises(self):
+ with self.settings(**self.connect_settings):
+ with pytest.raises(NotImplementedError):
+ OauthIntegration.authorize_url("posthog", token="tok", region="ASIA", scopes=["task:read"])
+
+ def test_authorize_url_unconfigured_region_raises(self):
+ unconfigured = {
+ **self.connect_settings,
+ "POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU": "",
+ "POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU": "",
+ }
+ with self.settings(**unconfigured):
+ with pytest.raises(NotImplementedError):
+ OauthIntegration.authorize_url("posthog", token="tok", region="EU", scopes=["task:read"])
+
+ @patch("posthog.models.integration.requests.get")
+ @patch("posthog.models.integration.requests.post")
+ def test_integration_from_oauth_response_persists_region_and_namespaces_id(self, mock_post, mock_get):
+ with self.settings(**self.connect_settings):
+ mock_post.return_value = MagicMock(status_code=200)
+ mock_post.return_value.json.return_value = {
+ "access_token": "AT",
+ "refresh_token": "RT",
+ "expires_in": 3600,
+ "scope": "task:read task:write openid email",
+ }
+ mock_get.return_value = MagicMock(status_code=200)
+ mock_get.return_value.json.return_value = {"sub": "user-uuid-123", "email": "[email protected]"}
+
+ # posthog is a PKCE flow; the authorize step caches a verifier keyed on the state token.
+ cache.set("oauth_pkce_verifier/tok", "the-verifier")
+ state = urlencode({"next": "/", "token": "tok", "region": "EU"})
+ integration = OauthIntegration.integration_from_oauth_response(
+ "posthog", self.team.id, self.user, {"code": "auth-code", "state": state}
+ )
+
+ # Token exchange must hit the region carried in state.
+ assert mock_post.call_args[0][0] == "https://eu.posthog.com/oauth/token"
+ assert integration.kind == "posthog"
+ assert integration.config["region"] == "EU"
+ # Dedup key is namespaced by region so the same account in two cells doesn't collide.
+ assert integration.integration_id == "EU:user-uuid-123"
+ assert integration.config["email"] == "[email protected]"
+ # Only the resource scopes are persisted (identity scopes dropped), for the caller-scope check.
+ assert integration.config["granted_scopes"] == ["task:read", "task:write"]
+ assert integration.sensitive_config["access_token"] == "AT"
+ assert integration.sensitive_config["refresh_token"] == "RT"
+
+ @patch("posthog.models.integration.requests.post")
+ def test_integration_from_oauth_response_fails_closed_without_pkce_verifier(self, mock_post):
+ # No cached verifier (as if the authorize step was skipped / replayed). A first-party posthog
+ # flow must fail closed rather than exchange the code without PKCE.
+ with self.settings(**self.connect_settings):
+ cache.delete("oauth_pkce_verifier/tok")
+ state = urlencode({"next": "/", "token": "tok", "region": "EU"})
+ with pytest.raises(ValidationError):
+ OauthIntegration.integration_from_oauth_response(
+ "posthog", self.team.id, self.user, {"code": "auth-code", "state": state}
+ )
+ mock_post.assert_not_called()
+
+ @patch("posthog.models.integration.requests.post")
+ def test_refresh_access_token_uses_persisted_region(self, mock_post):
+ with self.settings(**self.connect_settings):
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="posthog",
+ integration_id="EU:user-uuid-123",
+ config={"region": "EU", "refreshed_at": int(time.time()) - 4000, "expires_in": 3600},
+ sensitive_config={"refresh_token": "RT", "access_token": "OLD"},
+ )
+ mock_post.return_value = MagicMock(status_code=200)
+ mock_post.return_value.json.return_value = {
+ "access_token": "NEW",
+ "refresh_token": "RT2",
+ "expires_in": 3600,
+ }
+
+ OauthIntegration(integration).refresh_access_token()
+
+ # Refresh must target the persisted region's token endpoint, not a static one.
+ assert mock_post.call_args[0][0] == "https://eu.posthog.com/oauth/token"
+ integration.refresh_from_db()
+ assert integration.sensitive_config["access_token"] == "NEW"
+
+
class TestGoogleCloudIntegrationModel(BaseTest):
mock_keyfile = {
"type": "service_account",
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index afbaa3ddcff6..4f6e63ef7e3e 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1271,6 +1271,21 @@ class GitHubRepositoryRefreshThrottle(PersonalApiKeyOrUserRateThrottle):
return super().get_cache_key(request, view)
+class PostHogConnectionForwardThrottle(PersonalApiKeyOrUserRateThrottle):
+ # Rate limit the synchronous PostHog-connection forward proxy. Each forward holds an API worker
+ # open while it round-trips to another cell, so a burst of concurrent forwards to a slow target
+ # can tie workers up. Inheriting PersonalApiKeyOrUserRateThrottle throttles every auth method this
+ # endpoint accepts (session, personal API key, OAuth), not just personal keys. Keyed per
+ # connection so one connection's traffic can't starve another the same user created.
+ scope = "posthog_connection_forward"
+ rate = "60/minute"
+
+ def get_cache_key(self, request, view):
+ ident = request.user.pk if request.user and request.user.is_authenticated else self.get_ident(request)
+ pk = view.kwargs.get("pk")
+ return self.cache_format % {"scope": self.scope, "ident": f"{ident}:{pk}"}
+
+
class HealthIssueRefreshThrottle(PersonalApiKeyOrUserRateThrottle):
scope = "health_issue_refresh"
rate = "1/5minutes"
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index a199af3b4072..2e796a4a6795 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -150,6 +150,27 @@ HEATMAP_BROWSERLESS_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_TIMEOUT_MS",
HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS", 30000, type_cast=int)
HEATMAP_BROWSERLESS_BLOCK_ADS = get_from_env("HEATMAP_BROWSERLESS_BLOCK_ADS", False, type_cast=str_to_bool)
+# PostHog connect — lets a user connect (via the target's OAuth consent flow) to another PostHog
+# project to drive its APIs, e.g. dispatching a Task that must run in that project (including one in
+# another region, to reach region-resident data). The target may be in a different region OR the
+# same one as the connecting project — same-region is just "target region == your region". The
+# connecting side is the OAuth *client*: it redirects to the target region's /oauth/authorize and
+# exchanges the code against its /oauth/token, so it needs that region's registered app credentials
+# plus its public base URL. One entry per region a user may connect TO (your own included). Empty
+# defaults keep the app importable until the OAuthApplications are provisioned in each region, in
+# which case the connect flow fails closed for the unconfigured region.
+POSTHOG_CONNECT_OAUTH_CLIENT_ID_US = get_from_env("POSTHOG_CONNECT_OAUTH_CLIENT_ID_US", "")
+POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US = get_from_env("POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_US", "")
+POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU = get_from_env("POSTHOG_CONNECT_OAUTH_CLIENT_ID_EU", "")
+POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU = get_from_env("POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_EU", "")
+POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV = get_from_env("POSTHOG_CONNECT_OAUTH_CLIENT_ID_DEV", "")
+POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV = get_from_env("POSTHOG_CONNECT_OAUTH_CLIENT_SECRET_DEV", "")
+# Public base URL of each target cell's OAuth server. DEV points at the local instance so the flow
+# is exercisable end to end against a single dev stack; override via env for a custom dev host.
+POSTHOG_CONNECT_BASE_URL_US = get_from_env("POSTHOG_CONNECT_BASE_URL_US", "https://us.posthog.com")
+POSTHOG_CONNECT_BASE_URL_EU = get_from_env("POSTHOG_CONNECT_BASE_URL_EU", "https://eu.posthog.com")
+POSTHOG_CONNECT_BASE_URL_DEV = get_from_env("POSTHOG_CONNECT_BASE_URL_DEV", "http://localhost:8000")
+
# Legacy OAuth client credentials kept alive during an app or secret rotation.
# Refreshes fall back to these when the primary credentials fail, so tokens issued
# by a since-migrated app keep working until users reconnect.
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index 49626995e716..e6b621242758 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -179,6 +179,7 @@ export interface RoleLookupResponseApi {
* * `pardot` - Pardot
* * `pinterest-ads` - Pinterest Ads
* * `postgresql` - Postgresql
+ * * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
@@ -225,6 +226,7 @@ export const IntegrationKindEnumApi = {
Pardot: 'pardot',
PinterestAds: 'pinterest-ads',
Postgresql: 'postgresql',
+ Posthog: 'posthog',
RedditAds: 'reddit-ads',
Resend: 'resend',
S3Compatible: 's3-compatible',
@@ -462,6 +464,7 @@ export interface IntegrationAccessRequestApi {
* * `pardot` - Pardot
* * `pinterest-ads` - Pinterest Ads
* * `postgresql` - Postgresql
+ * * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
@@ -553,6 +556,7 @@ export type IntegrationsListParams = {
* * `pardot` - Pardot
* * `pinterest-ads` - Pinterest Ads
* * `postgresql` - Postgresql
+ * * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
@@ -610,6 +614,7 @@ export const IntegrationsListKind = {
Pardot: 'pardot',
PinterestAds: 'pinterest-ads',
Postgresql: 'postgresql',
+ Posthog: 'posthog',
RedditAds: 'reddit-ads',
Resend: 'resend',
S3Compatible: 's3-compatible',
diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.ts
index c522f4669416..337fb5268d5c 100644
--- a/products/integrations/frontend/generated/api.zod.ts
+++ b/products/integrations/frontend/generated/api.zod.ts
@@ -92,6 +92,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
'pardot',
'pinterest-ads',
'postgresql',
+ 'posthog',
'reddit-ads',
'resend',
's3-compatible',
@@ -106,7 +107,7 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -146,6 +147,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
'pardot',
'pinterest-ads',
'postgresql',
+ 'posthog',
'reddit-ads',
'resend',
's3-compatible',
@@ -161,7 +163,7 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -201,6 +203,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
'pardot',
'pinterest-ads',
'postgresql',
+ 'posthog',
'reddit-ads',
'resend',
's3-compatible',
@@ -215,7 +218,7 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -262,6 +265,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
'pardot',
'pinterest-ads',
'postgresql',
+ 'posthog',
'reddit-ads',
'resend',
's3-compatible',
@@ -276,7 +280,7 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
config: zod.unknown().optional(),
})
@@ -370,6 +374,7 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
'pardot',
'pinterest-ads',
'postgresql',
+ 'posthog',
'reddit-ads',
'resend',
's3-compatible',
@@ -384,10 +389,10 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({
'vercel',
])
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
)
.describe(
- "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel"
+ "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel"
),
reason: zod
.string()
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 29eb970f258f..d8b12cd4c05c 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -2856,9 +2856,10 @@ export const JsonrpcEnumApi = {
* * `queue_get` - queue_get
* * `queue_clear` - queue_clear
*/
-export type MethodEnumApi = (typeof MethodEnumApi)[keyof typeof MethodEnumApi]
+export type TaskRunCommandRequestMethodEnumApi =
+ (typeof TaskRunCommandRequestMethodEnumApi)[keyof typeof TaskRunCommandRequestMethodEnumApi]
-export const MethodEnumApi = {
+export const TaskRunCommandRequestMethodEnumApi = {
UserMessage: 'user_message',
Cancel: 'cancel',
Close: 'close',
@@ -2889,7 +2890,7 @@ export interface TaskRunCommandRequestApi {
* * `pi/rpc` - pi/rpc
* * `queue_get` - queue_get
* * `queue_clear` - queue_clear */
- method: MethodEnumApi
+ method: TaskRunCommandRequestMethodEnumApi
/** Parameters for the command */
params?: TaskRunCommandRequestApiParams
/** Optional JSON-RPC request ID (string or number) */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e8a908e67d29..718c9cdbe23a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -37223,6 +37223,7 @@ export namespace Schemas {
* * `pardot` - Pardot
* * `pinterest-ads` - Pinterest Ads
* * `postgresql` - Postgresql
+ * * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
@@ -37270,6 +37271,7 @@ export namespace Schemas {
Pardot: 'pardot',
PinterestAds: 'pinterest-ads',
Postgresql: 'postgresql',
+ Posthog: 'posthog',
RedditAds: 'reddit-ads',
Resend: 'resend',
S3Compatible: 's3-compatible',
@@ -37317,6 +37319,7 @@ export namespace Schemas {
* * `pardot` - Pardot
* * `pinterest-ads` - Pinterest Ads
* * `postgresql` - Postgresql
+ * * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
@@ -40770,32 +40773,6 @@ export namespace Schemas {
instance_id: string;
}
- /**
- * * `user_message` - user_message
- * * `cancel` - cancel
- * * `close` - close
- * * `permission_response` - permission_response
- * * `set_config_option` - set_config_option
- * * `mcp_response` - mcp_response
- * * `pi/rpc` - pi/rpc
- * * `queue_get` - queue_get
- * * `queue_clear` - queue_clear
- */
- export type MethodEnum = typeof MethodEnum[keyof typeof MethodEnum];
-
-
- export const MethodEnum = {
- UserMessage: 'user_message',
- Cancel: 'cancel',
- Close: 'close',
- PermissionResponse: 'permission_response',
- SetConfigOption: 'set_config_option',
- McpResponse: 'mcp_response',
- PiRpc: 'pi/rpc',
- QueueGet: 'queue_get',
- QueueClear: 'queue_clear',
- } as const;
-
/**
* * `up` - up
* * `down` - down
@@ -55971,6 +55948,53 @@ export namespace Schemas {
createdAt: string | null;
}
+ /**
+ * Query parameters to send to the target.
+ */
+ export type PostHogConnectionForwardQuery = {[key: string]: string};
+
+ /**
+ * * `GET` - GET
+ * * `POST` - POST
+ * * `PUT` - PUT
+ * * `PATCH` - PATCH
+ * * `DELETE` - DELETE
+ */
+ export type PostHogConnectionForwardMethodEnum = typeof PostHogConnectionForwardMethodEnum[keyof typeof PostHogConnectionForwardMethodEnum];
+
+
+ export const PostHogConnectionForwardMethodEnum = {
+ Get: 'GET',
+ Post: 'POST',
+ Put: 'PUT',
+ Patch: 'PATCH',
+ Delete: 'DELETE',
+ } as const;
+
+ export interface PostHogConnectionForward {
+ /** HTTP method to use against the target project's API.
+ *
+ * * `GET` - GET
+ * * `POST` - POST
+ * * `PUT` - PUT
+ * * `PATCH` - PATCH
+ * * `DELETE` - DELETE */
+ method: PostHogConnectionForwardMethodEnum;
+ /** Relative target API path with no host or scheme, e.g. `api/projects/2/insights/`. */
+ path: string;
+ /** Query parameters to send to the target. */
+ query?: PostHogConnectionForwardQuery;
+ /** JSON request body for write methods. */
+ data?: unknown;
+ }
+
+ export interface PostHogConnectionForwardResponse {
+ /** HTTP status the target project returned. */
+ status: number;
+ /** The target project's response body, passed through. */
+ data: unknown;
+ }
+
/**
* * `Postgres` - Postgres
*/
@@ -69911,6 +69935,32 @@ export namespace Schemas {
*/
export type TaskRunCommandRequestParams = { [key: string]: unknown };
+ /**
+ * * `user_message` - user_message
+ * * `cancel` - cancel
+ * * `close` - close
+ * * `permission_response` - permission_response
+ * * `set_config_option` - set_config_option
+ * * `mcp_response` - mcp_response
+ * * `pi/rpc` - pi/rpc
+ * * `queue_get` - queue_get
+ * * `queue_clear` - queue_clear
+ */
+ export type TaskRunCommandRequestMethodEnum = typeof TaskRunCommandRequestMethodEnum[keyof typeof TaskRunCommandRequestMethodEnum];
+
+
+ export const TaskRunCommandRequestMethodEnum = {
+ UserMessage: 'user_message',
+ Cancel: 'cancel',
+ Close: 'close',
+ PermissionResponse: 'permission_response',
+ SetConfigOption: 'set_config_option',
+ McpResponse: 'mcp_response',
+ PiRpc: 'pi/rpc',
+ QueueGet: 'queue_get',
+ QueueClear: 'queue_clear',
+ } as const;
+
/**
* JSON-RPC request to send a command to the agent server in the sandbox.
*/
@@ -69930,7 +69980,7 @@ export namespace Schemas {
* * `pi/rpc` - pi/rpc
* * `queue_get` - queue_get
* * `queue_clear` - queue_clear */
- method: MethodEnum;
+ method: TaskRunCommandRequestMethodEnum;
/** Parameters for the command */
params?: TaskRunCommandRequestParams;
/** Optional JSON-RPC request ID (string or number) */
@@ -79320,6 +79370,7 @@ export namespace Schemas {
* * `pardot` - Pardot
* * `pinterest-ads` - Pinterest Ads
* * `postgresql` - Postgresql
+ * * `posthog` - Posthog
* * `reddit-ads` - Reddit Ads
* * `resend` - Resend
* * `s3-compatible` - S3 Compatible
@@ -79378,6 +79429,7 @@ export namespace Schemas {
Pardot: 'pardot',
PinterestAds: 'pinterest-ads',
Postgresql: 'postgresql',
+ Posthog: 'posthog',
RedditAds: 'reddit-ads',
Resend: 'resend',
S3Compatible: 's3-compatible',
diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.ts
index 91c2f6a1d4b7..6975e8d5390c 100644
--- a/services/mcp/src/generated/integrations/api.ts
+++ b/services/mcp/src/generated/integrations/api.ts
@@ -49,6 +49,7 @@ export const IntegrationsListQueryParams = /* @__PURE__ */ zod.object({
'pardot',
'pinterest-ads',
'postgresql',
+ 'posthog',
'reddit-ads',
'resend',
's3-compatible',
@@ -64,7 +65,7 @@ export const IntegrationsListQueryParams = /* @__PURE__ */ zod.object({
])
.optional()
.describe(
- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'
),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
index 8ff687e3fa56..a35020c1caa5 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json
@@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"kind": {
- "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `reddit-ads` - Reddit Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel",
+ "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel",
"enum": [
"anthropic",
"apns",
@@ -34,6 +34,7 @@
"pardot",
"pinterest-ads",
"postgresql",
+ "posthog",
"reddit-ads",
"resend",
"s3-compatible",