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(integrations): send help scout an oauth state it returns intact (#119558)

Daniel RC7fe433c507e0
diff --git a/frontend/src/lib/integrations/integrationsLogic.test.ts b/frontend/src/lib/integrations/integrationsLogic.test.ts
index 950155d0c034..bd55fe125b36 100644
--- a/frontend/src/lib/integrations/integrationsLogic.test.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.test.ts
@@ -456,19 +456,26 @@ describe('integrationsLogic', () => {
}
})
- it('does not create the integration when the OAuth state token no longer matches the cookie', async () => {
- // A stale/expired flow: the cookie minted at authorize time is gone or changed, so the token
- // carried in the state can't match. The callback must recover by redirecting back rather than
- // POST a create, so an expired (or forged) state can never link an integration.
+ // A stale/expired flow: the cookie minted at authorize time is gone or changed, so the token
+ // carried in the state can't match. The callback must recover by redirecting back rather than
+ // POST a create, so an expired (or forged) state can never link an integration. A crafted hex
+ // state that does not decode to text must take the same path instead of breaking the callback.
+ it.each([
+ [
+ 'a stale token',
+ 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok',
+ '/project/228502/settings/project-integrations',
+ ],
+ ['a hex state that is not valid UTF-8', 'ff80', `/project/${MOCK_TEAM_ID}/settings/project-integrations`],
+ ])('does not create the integration for %s', async (_name, state, expectedPathname) => {
document.cookie = 'ph_oauth_state=a-different-token'
- const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok'
await expectLogic(logic, () => {
logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })
}).toFinishAllListeners()
expect(createSpy).not.toHaveBeenCalled()
- expect(router.values.location.pathname).toBe('/project/228502/settings/project-integrations')
+ expect(router.values.location.pathname).toBe(expectedPathname)
document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
})
@@ -521,17 +528,26 @@ describe('integrationsLogic', () => {
document.cookie = 'ph_oauth_state=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
})
- it('creates the integration against the team carried in the OAuth state', async () => {
+ const plainState =
+ 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok&team_id=228502'
+
+ // Providers that do not return the state verbatim get it hex-encoded at authorize time, and
+ // the callback must decode it before it checks the token or posts the state.
+ it.each([
+ ['a plain state', plainState],
+ ['a hex-encoded state', Buffer.from(plainState).toString('hex')],
+ ])('creates the integration against the team carried in %s', async (_name, state) => {
// The callback is a full-page round-trip on a non-project-scoped URL, so the SPA's
// current team is the user's default team here (MOCK_TEAM_ID) — not team 228502,
// which the state says initiated the flow.
- const state = 'next=%2Fproject%2F228502%2Fsettings%2Fproject-integrations&token=csrf-tok&team_id=228502'
-
await expectLogic(logic, () => {
logic.actions.handleOauthCallback('slack' as IntegrationKind, { state, code: 'oauth-code' })
}).toFinishAllListeners()
- expect(createSpy).toHaveBeenCalledWith({ kind: 'slack', config: { state, code: 'oauth-code' } }, 228502)
+ expect(createSpy).toHaveBeenCalledWith(
+ { kind: 'slack', config: { state: plainState, code: 'oauth-code' } },
+ 228502
+ )
expect(requestedTeamIds).toEqual(['228502'])
expect(router.values.location.pathname).toBe('/project/228502/settings/project-integrations')
expect(router.values.searchParams.integration_id).toBe(7)
diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.ts
index 015ad0dd30aa..7a3dc2f0de55 100644
--- a/frontend/src/lib/integrations/integrationsLogic.ts
+++ b/frontend/src/lib/integrations/integrationsLogic.ts
@@ -67,6 +67,21 @@ function landsOnErrorAwarePage(pathname: string): boolean {
return segments.length === 2 && segments[0] === 'data-warehouse' && segments[1] === 'new-source'
}
+// The backend hex-encodes the state for a provider that does not return it verbatim (see
+// `opaque_state` on OauthConfig). A plain state always holds `next=`, so it never matches.
+function decodeOpaqueOAuthState(state: string | undefined): string | undefined {
+ if (!state || !/^(?:[0-9a-f]{2})+$/i.test(state)) {
+ return state
+ }
+ try {
+ return decodeURIComponent(state.replace(/../g, '%$&'))
+ } catch {
+ // A crafted hex state that is not valid UTF-8 carries no token, so the callback rejects it
+ // as an expired state instead of throwing before it can redirect.
+ return state
+ }
+}
+
// Search param the OAuth callback appends with the id of the integration it just created, so the
// page the user lands back on can select the connection they authorized rather than guessing.
// pinned: URL search param — the callback redirect and the landing page both read it.
@@ -1258,8 +1273,9 @@ export const integrationsLogic = kea<integrationsLogicType>([
return
}
- const { state, code, error, stripe_user_id, account_id, user_id } = searchParams
- const { next, token, source, server_id, team_id } = fromParamsGivenUrl(state)
+ const { code, error, stripe_user_id, account_id, user_id } = searchParams
+ const state = decodeOpaqueOAuthState(searchParams.state)
+ const { next, token, source, server_id, team_id } = fromParamsGivenUrl(state ?? '')
const resolvedKind = kind
let replaceUrl: string = next || urls.settings('project-integrations')
diff --git a/posthog/models/integration/oauth.py b/posthog/models/integration/oauth.py
index b829cb38c43f..aefb418ef77d 100644
--- a/posthog/models/integration/oauth.py
+++ b/posthog/models/integration/oauth.py
@@ -120,6 +120,9 @@ class OauthConfig:
pkce: bool = False
# When set, disconnecting the integration also revokes the grant at the provider
token_revoke_url: str | None = None
+ # When true, authorize_url hex-encodes the state for a provider that does not return it verbatim.
+ # The frontend callback decodes it before it reads the token.
+ opaque_state: bool = False
# Slack accepts comma-separated scopes on the OAuth authorize URL. The canonical list is the
@@ -672,6 +675,9 @@ class OauthIntegration:
id_path="id",
name_path="email",
token_info_config_fields=["id", "email"],
+ # Help Scout decodes the state one extra time and drops everything after the first `&`, so the
+ # token and team_id never come back. A hex string has no characters that it can change.
+ opaque_state=True,
)
elif kind == "linear":
if not settings.LINEAR_APP_CLIENT_ID or not settings.LINEAR_APP_CLIENT_SECRET:
@@ -930,12 +936,16 @@ class OauthIntegration:
requested = list(scopes) if scopes else list(POSTHOG_CONNECT_DEFAULT_SCOPES)
scope = " ".join(dict.fromkeys([*requested, *POSTHOG_CONNECT_IDENTITY_SCOPES]))
+ state = urlencode(state_payload)
+ if oauth_config.opaque_state:
+ state = state.encode().hex()
+
if kind == "tiktok-ads":
# TikTok uses different parameter names
query_params = {
"app_id": oauth_config.client_id,
"redirect_uri": cls.redirect_uri(kind),
- "state": urlencode(state_payload),
+ "state": state,
}
else:
query_params = {
@@ -943,7 +953,7 @@ class OauthIntegration:
"scope": scope,
"redirect_uri": cls.redirect_uri(kind),
"response_type": "code",
- "state": urlencode(state_payload),
+ "state": state,
**(oauth_config.additional_authorize_params or {}),
}
diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.py
index 0395171b3e6c..ef0fe3ebd832 100644
--- a/posthog/models/test/integration/test_oauth.py
+++ b/posthog/models/test/integration/test_oauth.py
@@ -69,6 +69,8 @@ class TestOauthIntegrationModel(BaseTest):
"TIKTOK_ADS_CLIENT_SECRET": "tiktok-secret",
"LINEAR_APP_CLIENT_ID": "linear-client-id",
"LINEAR_APP_CLIENT_SECRET": "linear-client-secret",
+ "HELPSCOUT_APP_CLIENT_ID": "helpscout-client-id",
+ "HELPSCOUT_APP_CLIENT_SECRET": "helpscout-client-secret",
}
def create_integration(
@@ -110,6 +112,20 @@ class TestOauthIntegrationModel(BaseTest):
state = {k: v[0] for k, v in parse_qs(params["state"]).items()}
assert state["team_id"] == "228502"
+ def test_authorize_url_sends_an_opaque_state_to_providers_that_mangle_it(self):
+ with self.settings(**self.mock_settings):
+ url = OauthIntegration.authorize_url(
+ "helpscout", token="state_token", next="/data-warehouse/new-source?kind=helpscout", team_id=228502
+ )
+ params = {k: v[0] for k, v in parse_qs(url.partition("?")[2]).items()}
+ assert all(char in "0123456789abcdef" for char in params["state"])
+ state = {k: v[0] for k, v in parse_qs(bytes.fromhex(params["state"]).decode()).items()}
+ assert state == {
+ "next": "/data-warehouse/new-source?kind=helpscout",
+ "token": "state_token",
+ "team_id": "228502",
+ }
+
def test_authorize_url_omits_team_id_when_not_provided(self):
with self.settings(**self.mock_settings):
url = OauthIntegration.authorize_url("salesforce", token="state_token", next="/projects/test")