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.

fix(vercel): require a browser-bound state on the connect callback (#116411)

Matt Brookerb7a47a09ee27
diff --git a/docs/published/handbook/engineering/vercel-integration.md b/docs/published/handbook/engineering/vercel-integration.md
index 90f2b90ee6fa..45e9ed3cbf20 100644
--- a/docs/published/handbook/engineering/vercel-integration.md
+++ b/docs/published/handbook/engineering/vercel-integration.md
@@ -105,7 +105,11 @@ sequenceDiagram
participant PH as PostHog
User->>VM: Click "Link Existing Account"
- VM->>PH: GET /connect/vercel/callback (OAuth code)
+ VM->>PH: GET /connect/vercel/callback (OAuth code, no state)
+ PH-->>User: Redirect to Vercel's install page with a state, set a state cookie
+ User->>VM: Continue on the install page
+ VM->>PH: GET /connect/vercel/callback (OAuth code + same state)
+ PH->>PH: Reject unless the state matches this browser's cookie
PH->>PH: Exchange code for access token
PH->>PH: Store session in cache (10 min TTL)
diff --git a/ee/api/vercel/README.md b/ee/api/vercel/README.md
index af055e2f7168..3a732bc754a9 100644
--- a/ee/api/vercel/README.md
+++ b/ee/api/vercel/README.md
@@ -30,19 +30,28 @@ Create a `.env.vercel` file in the PostHog root directory with your ngrok URL (c
LOCAL_HTTPS=1
DEBUG=1
-# ngrok tunnel URLs for HTTPS local development (update with your ngrok URL)
+# ngrok tunnel URL for HTTPS local development (update with your ngrok URL)
SITE_URL=https://your-ngrok-tunnel.ngrok-free.dev
-JS_URL=https://your-ngrok-tunnel.ngrok-free.dev
+# Keep Vite on localhost: the browser loads dev assets from it directly, not through the tunnel
+JS_URL=http://localhost:8234
WEBPACK_HOT_RELOAD_HOST=0.0.0.0
+# Trust ngrok's X-Forwarded-Proto so Django treats tunneled requests as HTTPS
+IS_BEHIND_PROXY=1
+TRUST_ALL_PROXIES=1
+
# Vercel integration credentials (automatically loaded from 1Password)
VERCEL_CLIENT_INTEGRATION_ID="op://General/Vercel Client Integration Secret/client id"
VERCEL_CLIENT_INTEGRATION_SECRET="op://General/Vercel Client Integration Secret/client secret"
+
+# URL slug of your Vercel integration, from vercel.com/integrations/<slug> (defaults to the production slug "posthog")
+VERCEL_INTEGRATION_SLUG=your-integration-slug
```
**Notes**:
-- If you need to configure CORS for ngrok (e.g., for hot reload or asset loading), you can temporarily modify `frontend/vite.config.ts` to add your ngrok domain to the `cors.origin` array and `allowedHosts`. **Do not commit these changes** - they are for local development only.
+- The first time the tunneled page loads, Chrome asks to let the site access apps on this device. Allow it, or the page stays blank because the Vite requests to `localhost:8234` never start.
+- Start the stack inside flox so `pnpm` is on the path: `flox activate -- op run --env-file=.env.vercel -- hogli up -d`. The stack starts its own ngrok tunnel, so don't run a second one.
## Step 3: Configure Vercel Integration Settings
@@ -92,11 +101,13 @@ Vercel marketplace integrations have two separate flows:
When a user clicks "Link Existing Account" in the Vercel Marketplace:
1. Vercel opens a popup to our **Redirect URL** (`/connect/vercel/callback`) with an OAuth code
-2. PostHog exchanges the code for an access token via `POST /v2/oauth/access_token`
-3. If the user isn't logged in, they're redirected to `/login` first
-4. The user selects which PostHog organization to link
-5. An `OrganizationIntegration` record is created with `type=connectable`
-6. The popup closes and returns the user to Vercel
+2. The Marketplace request has no `state`, so PostHog sends the popup to Vercel's external install page (`https://vercel.com/integrations/{VERCEL_INTEGRATION_SLUG}/new`) with a random `state`, and stores the same value in a host-only `__Host-` cookie. PostHog keeps the Marketplace's `next` link for the return, and a browser holds at most a few pending `state` cookies
+3. Vercel returns to the Redirect URL with `source=external`, a new code, and the same `state`. PostHog rejects the request when the browser has no matching cookie, or when the request has no `state`
+4. PostHog exchanges the code for an access token via `POST /v2/oauth/access_token`
+5. If the user isn't logged in, they're redirected to `/login` first
+6. The user selects which PostHog organization to link
+7. An `OrganizationIntegration` record is created with `type=connectable`
+8. The popup closes and returns the user to Vercel
Billing stays with PostHog for connected accounts - no billing provider migration is needed.
@@ -240,6 +251,7 @@ Before releasing changes to the Vercel integration, manually verify the followin
**Expected**:
+- [ ] Popup passes through Vercel's install page once, then returns to `/connect/vercel/callback` with a `state` parameter
- [ ] Popup opens to PostHog login page (if not already logged in)
- [ ] After login, org selector is shown with orgs where user is admin/owner
- [ ] Already-linked orgs are not available for selection
diff --git a/ee/api/vercel/test/test_vercel_connect.py b/ee/api/vercel/test/test_vercel_connect.py
index 5adc96e560b8..0032b48997c4 100644
--- a/ee/api/vercel/test/test_vercel_connect.py
+++ b/ee/api/vercel/test/test_vercel_connect.py
@@ -4,7 +4,7 @@ from urllib.parse import parse_qs, urlparse
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.http import HttpResponse
+from django.http.response import HttpResponseBase
from django.test import Client, SimpleTestCase, override_settings
from parameterized import parameterized
@@ -20,9 +20,12 @@ from ee.api.vercel.crypto import encrypt_payload
from ee.api.vercel.vercel_connect import (
CONNECT_NONCE_COOKIE_PREFIX,
CONNECT_SALT,
+ INSTALL_STATE_COOKIE_PREFIX,
+ MAX_PENDING_INSTALL_STATES,
VercelImportError,
_browser_nonce_cookie_name,
_delete_orphaned_integration,
+ _install_state_cookie_name,
_load_connect_session,
_sign_connect_session,
_validate_next_url,
@@ -42,6 +45,7 @@ CACHED_SESSION_DATA = {
"next_url": "https://vercel.com/done",
}
+CALLBACK_URL = "/connect/vercel/callback"
BROWSER_NONCE = "nonce-set-in-this-browser"
OTHER_BROWSER_NONCE = "nonce-from-another-linking-flow"
REJECTED_BROWSER_COOKIES = [("missing_cookie", None), ("cookie_from_another_flow", OTHER_BROWSER_NONCE)]
@@ -53,6 +57,10 @@ REJECTED_SESSIONS = [
]
+def _state_from_install_redirect(response: HttpResponseBase) -> str:
+ return parse_qs(urlparse(response["Location"]).query)["state"][0]
+
+
def _session_token_from_redirect(location: str) -> str:
query = parse_qs(urlparse(location).query)
if "next" in query:
@@ -73,7 +81,7 @@ def _mock_vercel_client(mock_client_class: MagicMock) -> MagicMock:
return mock_client
-def _flow_cookie(response: HttpResponse) -> Morsel:
+def _flow_cookie(response: HttpResponseBase) -> Morsel:
[cookie] = [cookie for name, cookie in response.cookies.items() if name.startswith(CONNECT_NONCE_COOKIE_PREFIX)]
return cookie
@@ -88,6 +96,21 @@ class VercelConnectTestBase(APIBaseTest):
self._set_nonce_cookie(BROWSER_NONCE)
return _sign_connect_session(CACHED_SESSION_DATA, browser_nonce=BROWSER_NONCE)
+ def _callback_through_vercel_install(
+ self,
+ params: dict[str, str],
+ browser: Client | None = None,
+ host: str = "testserver",
+ marketplace_params: dict[str, str] | None = None,
+ ) -> HttpResponseBase:
+ browser = browser or self.client
+ install_redirect = browser.get(
+ CALLBACK_URL, {"code": "code_from_marketplace", **(marketplace_params or {})}, HTTP_HOST=host
+ )
+ return browser.get(
+ CALLBACK_URL, {**params, "state": _state_from_install_redirect(install_redirect)}, HTTP_HOST=host
+ )
+
def _set_nonce_cookie(self, flow_nonce: str | None, value: str | None = None) -> None:
for name in [name for name in self.client.cookies if name.startswith(CONNECT_NONCE_COOKIE_PREFIX)]:
del self.client.cookies[name]
@@ -125,13 +148,37 @@ class TestVercelConnectCallback(VercelConnectTestBase):
error_description="Code expired",
)
- response = self.client.get(self.url, {"code": "bad_code"})
+ response = self._callback_through_vercel_install({"code": "bad_code"})
assert response.status_code == status.HTTP_401_UNAUTHORIZED
+ @parameterized.expand(
+ [
+ ("next_on_install_return", {}, {"next": "https://vercel.com/done"}, "https://vercel.com/done"),
+ (
+ "install_return_omits_next",
+ {"next": "https://vercel.com/marketplace"},
+ {},
+ "https://vercel.com/marketplace",
+ ),
+ (
+ "install_return_sends_other_next",
+ {"next": "https://vercel.com/marketplace"},
+ {"next": "https://vercel.com/install-page"},
+ "https://vercel.com/marketplace",
+ ),
+ ]
+ )
@override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
@patch("ee.api.vercel.vercel_connect.VercelAPIClient")
- def test_successful_exchange_redirects_authenticated_user_to_link(self, mock_client_class):
+ def test_successful_exchange_redirects_authenticated_user_to_link(
+ self,
+ _name: str,
+ marketplace_params: dict[str, str],
+ return_params: dict[str, str],
+ expected_next_url: str,
+ mock_client_class: MagicMock,
+ ) -> None:
mock_client = MagicMock()
mock_client_class.return_value = mock_client
mock_client.oauth_token_exchange.return_value = OAuthTokenResponse(
@@ -142,7 +189,9 @@ class TestVercelConnectCallback(VercelConnectTestBase):
team_id="team_1",
)
- response = self.client.get(self.url, {"code": "good_code", "next": "https://vercel.com/done"})
+ response = self._callback_through_vercel_install(
+ {"code": "good_code", **return_params}, marketplace_params=marketplace_params
+ )
assert response.status_code == 302
location = response["Location"]
@@ -151,7 +200,7 @@ class TestVercelConnectCallback(VercelConnectTestBase):
assert "session" in parsed
assert "next" not in parsed
session_data = _load_connect_session(parsed["session"][0])
- assert session_data["next_url"] == "https://vercel.com/done"
+ assert session_data["next_url"] == expected_next_url
@parameterized.expand(
[
@@ -174,7 +223,7 @@ class TestVercelConnectCallback(VercelConnectTestBase):
user_id="usr_1",
)
- response = self.client.get(self.url, {"code": "good_code", "next": malicious_url})
+ response = self._callback_through_vercel_install({"code": "good_code", "next": malicious_url})
assert response.status_code == 302
parsed = parse_qs(urlparse(response["Location"]).query)
@@ -195,7 +244,7 @@ class TestVercelConnectCallback(VercelConnectTestBase):
user_id="usr_1",
)
- response = self.client.get(self.url, {"code": "good_code"})
+ response = self._callback_through_vercel_install({"code": "good_code"})
assert response.status_code == 302
assert response["Location"].startswith("/login?next=")
@@ -220,7 +269,7 @@ class TestVercelConnectCallback(VercelConnectTestBase):
self.client.logout()
_mock_vercel_client(mock_client_class)
- response = self.client.get(self.url, {"code": "good_code"}, HTTP_HOST=host)
+ response = self._callback_through_vercel_install({"code": "good_code"}, host=host)
cookie = _flow_cookie(response)
assert cookie["domain"] == expected_domain
@@ -230,6 +279,171 @@ class TestVercelConnectCallback(VercelConnectTestBase):
assert cookie["secure"] is True
assert cookie["samesite"] == "Lax"
+ @override_settings(
+ VERCEL_CLIENT_INTEGRATION_ID="client_id",
+ VERCEL_CLIENT_INTEGRATION_SECRET="secret",
+ VERCEL_INTEGRATION_SLUG="posthog-test",
+ SESSION_COOKIE_SECURE=False,
+ )
+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")
+ def test_callback_without_state_restarts_install_through_vercel(self, mock_client_class: MagicMock) -> None:
+ mock_client = _mock_vercel_client(mock_client_class)
+
+ response = self.client.get(
+ self.url,
+ {"code": "code_from_marketplace", "configurationId": "icfg_marketplace"},
+ HTTP_HOST="us.posthog.com",
+ )
+
+ assert response.status_code == 302
+ location = urlparse(response["Location"])
+ assert (
+ f"{location.scheme}://{location.netloc}{location.path}"
+ == "https://vercel.com/integrations/posthog-test/new"
+ )
+ state = _state_from_install_redirect(response)
+ cookie = response.cookies[_install_state_cookie_name(state)]
+ assert cookie.key.startswith("__Host-")
+ assert cookie.value == state
+ assert cookie["path"] == "/"
+ assert cookie["secure"] is True
+ assert cookie["domain"] == ""
+ assert cookie["httponly"] is True
+ assert cookie["samesite"] == "Lax"
+ mock_client.oauth_token_exchange.assert_not_called()
+
+ @override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")
+ def test_callback_without_state_caps_pending_install_cookies(self, mock_client_class: MagicMock) -> None:
+ _mock_vercel_client(mock_client_class)
+ for flow in range(MAX_PENDING_INSTALL_STATES + 3):
+ self.client.cookies[_install_state_cookie_name(f"pending-{flow}")] = f"pending-{flow}"
+
+ self.client.get(self.url, {"code": "unvalidated_code"})
+
+ pending = [
+ name
+ for name, cookie in self.client.cookies.items()
+ if name.startswith(INSTALL_STATE_COOKIE_PREFIX) and cookie.value
+ ]
+ assert len(pending) == MAX_PENDING_INSTALL_STATES
+
+ @parameterized.expand(
+ [
+ ("marketplace", {"source": "marketplace"}, status.HTTP_302_FOUND, []),
+ ("source_absent", {}, status.HTTP_302_FOUND, []),
+ (
+ "returned_from_install",
+ {"source": "external"},
+ status.HTTP_400_BAD_REQUEST,
+ ["missing_state_after_install_redirect"],
+ ),
+ ]
+ )
+ @override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
+ @patch("ee.api.vercel.vercel_connect.capture_exception")
+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")
+ def test_callback_without_state_leaves_pending_install_usable(
+ self,
+ _name: str,
+ params: dict[str, str],
+ expected_status: int,
+ expected_reasons: list[str],
+ mock_client_class: MagicMock,
+ mock_capture_exception: MagicMock,
+ ) -> None:
+ mock_client = _mock_vercel_client(mock_client_class)
+ pending_state = _state_from_install_redirect(
+ self.client.get(self.url, {"code": "code_from_marketplace", "source": "marketplace"})
+ )
+
+ response = self.client.get(self.url, {"code": "code_without_state", **params})
+ pending_install = self.client.get(
+ self.url, {"code": "code_from_install", "source": "external", "state": pending_state}
+ )
+
+ assert [response.status_code, pending_install.status_code] == [expected_status, status.HTTP_302_FOUND]
+ assert [call.kwargs["code"] for call in mock_client.oauth_token_exchange.call_args_list] == [
+ "code_from_install"
+ ]
+ assert [call.args[1]["reason"] for call in mock_capture_exception.call_args_list] == expected_reasons
+
+ @parameterized.expand(
+ [
+ ("state_from_another_browser", None, "missing_state_cookie"),
+ ("cookie_value_differs", "value-set-by-another-site", "state_mismatch"),
+ ]
+ )
+ @override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
+ @patch("ee.api.vercel.vercel_connect.capture_exception")
+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")
+ def test_rejects_state_this_browser_was_not_given(
+ self,
+ _name: str,
+ cookie_value: str | None,
+ expected_reason: str,
+ mock_client_class: MagicMock,
+ mock_capture_exception: MagicMock,
+ ) -> None:
+ mock_client = _mock_vercel_client(mock_client_class)
+ other_browser = Client()
+ state = _state_from_install_redirect(other_browser.get(self.url, {"code": "code_from_marketplace"}))
+ if cookie_value is not None:
+ self.client.cookies[_install_state_cookie_name(state)] = cookie_value
+
+ response = self.client.get(self.url, {"code": "code_for_other_installation", "state": state})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_client.oauth_token_exchange.assert_not_called()
+ assert mock_capture_exception.call_args.args[1]["reason"] == expected_reason
+
+ @override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")
+ def test_install_state_works_once(self, mock_client_class: MagicMock) -> None:
+ mock_client = _mock_vercel_client(mock_client_class)
+ state = _state_from_install_redirect(self.client.get(self.url, {"code": "code_from_marketplace"}))
+
+ first = self.client.get(self.url, {"code": "first_code", "state": state})
+ replay = self.client.get(self.url, {"code": "second_code", "state": state})
+
+ assert [first.status_code, replay.status_code] == [302, status.HTTP_400_BAD_REQUEST]
+ assert mock_client.oauth_token_exchange.call_count == 1
+
+ @override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")
+ def test_retry_after_failed_exchange_keeps_marketplace_next(self, mock_client_class: MagicMock) -> None:
+ mock_client = _mock_vercel_client(mock_client_class)
+ mock_client.oauth_token_exchange.side_effect = [
+ OAuthTokenResponse(access_token="", token_type="", installation_id="", user_id="", error="server_error"),
+ mock_client.oauth_token_exchange.return_value,
+ ]
+ state = _state_from_install_redirect(
+ self.client.get(self.url, {"code": "code_from_marketplace", "next": "https://vercel.com/marketplace"})
+ )
+ install_return = {"code": "code_from_install", "source": "external", "state": state}
+
+ failed = self.client.get(self.url, install_return)
+ retried = self.client.get(self.url, install_return)
+
+ assert [failed.status_code, retried.status_code] == [status.HTTP_401_UNAUTHORIZED, 302]
+ session = _load_connect_session(_session_token_from_redirect(retried["Location"]))
+ assert session["next_url"] == "https://vercel.com/marketplace"
+
+ @override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
+ @patch("ee.api.vercel.vercel_connect.capture_exception")
+ @patch("ee.api.vercel.vercel_connect.VercelAPIClient")
+ def test_cache_failure_after_exchange_still_reaches_link_page(
+ self, mock_client_class: MagicMock, _mock_capture_exception: MagicMock
+ ) -> None:
+ _mock_vercel_client(mock_client_class)
+ state = _state_from_install_redirect(self.client.get(self.url, {"code": "code_from_marketplace"}))
+
+ with patch("ee.api.vercel.vercel_connect.cache.delete", side_effect=ConnectionError("cache unavailable")):
+ response = self.client.get(self.url, {"code": "code_from_install", "source": "external", "state": state})
+
+ assert response.status_code == 302
+ assert response["Location"].startswith("/connect/vercel/link?")
+
@override_settings(VERCEL_CLIENT_INTEGRATION_SECRET="secret")
class TestVercelConnectSessionInfo(VercelConnectTestBase):
@@ -803,10 +1017,6 @@ class TestVercelConnectComplete(VercelConnectTestBase):
@override_settings(VERCEL_CLIENT_INTEGRATION_ID="client_id", VERCEL_CLIENT_INTEGRATION_SECRET="secret")
class TestVercelConnectEndToEnd(VercelConnectTestBase):
- def setUp(self):
- super().setUp()
- self.callback_url = "/connect/vercel/callback"
-
@parameterized.expand(
[
("same_host_signed_in", "testserver", "testserver", True, ""),
@@ -829,7 +1039,7 @@ class TestVercelConnectEndToEnd(VercelConnectTestBase):
if not signed_in_at_callback:
self.client.logout()
- callback_response = self.client.get(self.callback_url, {"code": "good_code"}, HTTP_HOST=callback_host)
+ callback_response = self._callback_through_vercel_install({"code": "good_code"}, host=callback_host)
session_token = _session_token_from_redirect(callback_response["Location"])
self.client.force_login(self.user)
@@ -864,7 +1074,7 @@ class TestVercelConnectEndToEnd(VercelConnectTestBase):
mock_client = _mock_vercel_client(mock_client_class)
attacker_browser = Client()
- callback_response = attacker_browser.get(self.callback_url, {"code": "attacker_code"})
+ callback_response = self._callback_through_vercel_install({"code": "attacker_code"}, browser=attacker_browser)
session_token = _session_token_from_redirect(callback_response["Location"])
session_response = self.client.get("/api/vercel/connect/session", {"session": session_token})
@@ -886,7 +1096,7 @@ class TestVercelConnectEndToEnd(VercelConnectTestBase):
def test_two_link_flows_in_one_browser_both_stay_usable(self, mock_client_class: MagicMock) -> None:
_mock_vercel_client(mock_client_class)
session_tokens = [
- _session_token_from_redirect(self.client.get(self.callback_url, {"code": code})["Location"])
+ _session_token_from_redirect(self._callback_through_vercel_install({"code": code})["Location"])
for code in ("first_code", "second_code")
]
@@ -899,7 +1109,7 @@ class TestVercelConnectEndToEnd(VercelConnectTestBase):
def test_token_survives_session_flush(self, mock_client_class, _mock_vercel_integration):
_mock_vercel_client(mock_client_class)
- response = self.client.get(self.callback_url, {"code": "good_code"})
+ response = self._callback_through_vercel_install({"code": "good_code"})
assert response.status_code == 302
parsed = parse_qs(urlparse(response["Location"]).query)
session_token = parsed["session"][0]
diff --git a/ee/api/vercel/vercel_connect.py b/ee/api/vercel/vercel_connect.py
index 1aebfdbdd838..4fc774b07b15 100644
--- a/ee/api/vercel/vercel_connect.py
+++ b/ee/api/vercel/vercel_connect.py
@@ -6,6 +6,7 @@ from uuid import UUID
from django.conf import settings
from django.core import signing
+from django.core.cache import cache
from django.db import connection, transaction
from django.http import HttpResponse, HttpResponseRedirect
@@ -42,6 +43,9 @@ CONNECT_SESSION_TIMEOUT = 600 # 10 minutes
CONNECT_SALT = "vercel_connect"
CONNECT_NONCE_COOKIE_PREFIX = "ph_vercel_connect_"
CONNECT_NONCE_COOKIE_PATH = "/api/vercel/connect"
+INSTALL_STATE_COOKIE_PREFIX = "__Host-ph_vercel_install_state_"
+MAX_PENDING_INSTALL_STATES = 5
+INSTALL_CONTINUATION_CACHE_PREFIX = "vercel_connect_install_next:"
SESSION_INVALID_MESSAGE = "Session expired or invalid. Please try linking again from Vercel."
_BROWSER_NONCE_KEY = "browser_nonce"
@@ -57,9 +61,13 @@ def _load_connect_session(token: str) -> dict:
raise signing.BadSignature("Invalid or expired token")
-def _browser_nonce_cookie_name(browser_nonce: str) -> str:
+def _per_flow_cookie_name(prefix: str, flow_secret: str) -> str:
# One cookie per link flow, so a second flow in the same browser does not replace the first flow's cookie.
- return CONNECT_NONCE_COOKIE_PREFIX + hashlib.sha256(browser_nonce.encode()).hexdigest()[:16]
+ return prefix + hashlib.sha256(flow_secret.encode()).hexdigest()[:16]
+
+
+def _browser_nonce_cookie_name(browser_nonce: str) -> str:
+ return _per_flow_cookie_name(CONNECT_NONCE_COOKIE_PREFIX, browser_nonce)
def _set_browser_nonce_cookie(request: Request, response: HttpResponse, browser_nonce: str) -> None:
@@ -110,6 +118,88 @@ def _load_browser_bound_session(request: Request, token: str) -> dict:
raise exceptions.ValidationError(SESSION_INVALID_MESSAGE)
+def _install_state_cookie_name(state: str) -> str:
+ return _per_flow_cookie_name(INSTALL_STATE_COOKIE_PREFIX, state)
+
+
+def _install_continuation_cache_key(state: str) -> str:
+ return INSTALL_CONTINUATION_CACHE_PREFIX + hashlib.sha256(state.encode()).hexdigest()
+
+
+def _install_continuation(state: str) -> str:
+ return cache.get(_install_continuation_cache_key(state), "")
+
+
+def _forget_install_continuation(state: str) -> None:
+ # Runs after Vercel's code is spent, so failing here would strand the user; the entry expires anyway.
+ try:
+ cache.delete(_install_continuation_cache_key(state))
+ except Exception as e:
+ capture_exception(e, {"reason": "install_continuation_cleanup_failed", "integration": "vercel"})
+
+
+def _drop_excess_install_state_cookies(request: Request, response: HttpResponse) -> None:
+ # Any code starts a flow before it is validated, and every request to this host carries these cookies.
+ pending = sorted(name for name in request.COOKIES if name.startswith(INSTALL_STATE_COOKIE_PREFIX))
+ for name in pending[MAX_PENDING_INSTALL_STATES - 1 :]:
+ response.delete_cookie(name, path="/", samesite="Lax")
+
+
+def _redirect_through_vercel_install(request: Request, next_url: str) -> HttpResponse:
+ # A Marketplace install calls back without a state, so nothing ties its code to this browser. Vercel's
+ # external install flow returns the state we send, and the state cookie ties that state to this browser.
+ state = secrets.token_urlsafe(32)
+ slug = quote(settings.VERCEL_INTEGRATION_SLUG, safe="")
+ response = HttpResponseRedirect(f"https://vercel.com/integrations/{slug}/new?{urlencode({'state': state})}")
+ if next_url:
+ cache.set(_install_continuation_cache_key(state), next_url, timeout=CONNECT_SESSION_TIMEOUT)
+ _drop_excess_install_state_cookies(request, response)
+ response.set_cookie(
+ _install_state_cookie_name(state),
+ state,
+ max_age=CONNECT_SESSION_TIMEOUT,
+ # The __Host- prefix stops a sibling posthog.com subdomain from setting a state cookie that passes the check.
+ # A host-only cookie is enough because Vercel sends both callback requests to the one configured Redirect URL.
+ path="/",
+ secure=True,
+ httponly=True,
+ samesite="Lax",
+ )
+ return response
+
+
+def _clear_install_state_cookie(response: HttpResponse, state: str) -> None:
+ response.delete_cookie(_install_state_cookie_name(state), path="/", samesite="Lax")
+
+
+def _reject_install_return_without_state(request: Request) -> None:
+ if request.query_params.get("source") != "external":
+ return
+
+ # Vercel's install page sent this request without the state we gave it, so another redirect could loop.
+ capture_exception(
+ Exception("Vercel connect: install returned without a state"),
+ {"reason": "missing_state_after_install_redirect", "integration": "vercel"},
+ )
+ raise exceptions.ValidationError(SESSION_INVALID_MESSAGE)
+
+
+def _require_install_state_from_this_browser(request: Request, state: str) -> None:
+ cookie_state = request.COOKIES.get(_install_state_cookie_name(state), "")
+ if not cookie_state:
+ reason = "missing_state_cookie"
+ elif secrets.compare_digest(cookie_state.encode(), state.encode()):
+ return
+ else:
+ reason = "state_mismatch"
+
+ capture_exception(
+ Exception("Vercel connect: install state used by a browser that did not start it"),
+ {"reason": reason, "integration": "vercel"},
+ )
+ raise exceptions.ValidationError(SESSION_INVALID_MESSAGE)
+
+
def _mark_token_used(jti: str) -> bool:
return mark_token_used(jti, ttl=CONNECT_SESSION_TIMEOUT)
@@ -222,6 +312,13 @@ class VercelConnectCallbackViewSet(viewsets.GenericViewSet):
capture_exception(Exception("Vercel connect: missing client configuration"))
raise exceptions.APIException("Vercel integration not configured")
+ state = request.query_params.get("state")
+ if not state:
+ _reject_install_return_without_state(request)
+ return _redirect_through_vercel_install(request, next_url)
+ _require_install_state_from_this_browser(request, state)
+ next_url = _install_continuation(state) or next_url
+
client = VercelAPIClient(bearer_token=None)
token_response = client.oauth_token_exchange(
code=code,
@@ -262,6 +359,8 @@ class VercelConnectCallbackViewSet(viewsets.GenericViewSet):
response = HttpResponseRedirect(redirect_to=link_url)
_set_browser_nonce_cookie(request, response, browser_nonce)
+ _clear_install_state_cookie(response, state)
+ _forget_install_continuation(state)
return response
diff --git a/ee/settings.py b/ee/settings.py
index 61fa72e93c5a..d122bb54d579 100644
--- a/ee/settings.py
+++ b/ee/settings.py
@@ -151,6 +151,7 @@ HARMONIC_BASE_URL = get_from_env("HARMONIC_BASE_URL", "https://api.harmonic.ai",
# Vercel Integration
VERCEL_CLIENT_INTEGRATION_ID = get_from_env("VERCEL_CLIENT_INTEGRATION_ID", "", type_cast=str)
VERCEL_CLIENT_INTEGRATION_SECRET = get_from_env("VERCEL_CLIENT_INTEGRATION_SECRET", "", type_cast=str)
+VERCEL_INTEGRATION_SLUG = get_from_env("VERCEL_INTEGRATION_SLUG", "posthog", type_cast=str)
BILLING_PROVIDER_WEBHOOK_SECRET = get_from_env("BILLING_PROVIDER_WEBHOOK_SECRET", "", type_cast=str)
# SCIM Configuration