: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(integrations): flag bing ads connections on the legacy oauth app (#72719)
Javier Bahamondesddea02ae3107
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 66c0864f8851..44966c03e507 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -340,6 +340,7 @@ export const FEATURE_FLAGS = {INSIGHT_SUBSCRIBE_PROMINENT_BUTTON: 'insight-subscribe-prominent-button', // owner: @mattp #team-analytics-platform multivariate=control,testINTER_PROJECT_TRANSFERS: 'inter-project-transfers', // owner: @reecejones #team-platform-featuresJS_SNIPPET_VERSIONING: 'js-snippet-versioning', // owner: #team-client-libraries+ LEGACY_OAUTH_RECONNECT_WARNING: 'legacy-oauth-reconnect-warning', // owner: @jabahamondes #team-web-analytics — kill-switch for the retiring-OAuth-app reconnect bannerLINKS: 'links', // owner: @marconlp #team-link (team doesn't exist for now, maybe will come back in the future)LIVE_DEBUGGER: 'live-debugger', // owner: @marcecollLIVE_EVENTS_RICH_FILTERS: 'live-events-rich-filters', // owner: @jordanm-posthog #team-web-analyticsdiff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsxindex e42eecd65343..097e20ed9cb3 100644--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx@@ -25,6 +25,7 @@ import { ProductKey } from '~/queries/schema/schema-general'import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { LegacyOAuthReconnectBanner } from '../web-analytics/tabs/marketing-analytics/frontend/components/LegacyOAuthReconnectBanner'import { MarketingAnalyticsFilters } from '../web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters'import { MarketingAnalyticsSourceStatusBanner } from '../web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner'import {@@ -191,6 +192,7 @@ const MarketingAnalyticsDashboard = (): JSX.Element => {return (<>{feedbackBanner}+ <LegacyOAuthReconnectBanner /><MarketingAnalyticsSourceStatusBanner /><div className="mt-4 grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-x-4 gap-y-12">{marketingTiles?.map((tile, i) => (diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/LegacyOAuthReconnectBanner.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/LegacyOAuthReconnectBanner.tsxnew file mode 100644index 000000000000..6ce44f7f6a3e--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/LegacyOAuthReconnectBanner.tsx@@ -0,0 +1,55 @@+import { useValues } from 'kea'++import { LemonBanner } from '@posthog/lemon-ui'++import api from 'lib/api'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'+import { dayjs } from 'lib/dayjs'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { IntegrationKind, IntegrationType } from '~/types'++// Integrations still authenticated through a retiring OAuth app, with the date it stops working.+// The backend flags the affected connections on refresh (`oauth_uses_legacy_client`); reconnecting+// moves them to the current app and clears the flag.+const RETIRING_OAUTH_APPS: Partial<Record<IntegrationKind, { name: string; retiresOn: string }>> = {+ 'bing-ads': { name: 'Bing Ads', retiresOn: '2026-08-07' },+}++const usesRetiringApp = (integration: IntegrationType): boolean =>+ !!RETIRING_OAUTH_APPS[integration.kind] && !!integration.config?.oauth_uses_legacy_client++export const LegacyOAuthReconnectBanner = (): JSX.Element | null => {+ const { integrations } = useValues(integrationsLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ const affected = (integrations ?? []).find(usesRetiringApp)++ if (!affected || !featureFlags[FEATURE_FLAGS.LEGACY_OAUTH_RECONNECT_WARNING]) {+ return null+ }++ const app = RETIRING_OAUTH_APPS[affected.kind]!++ return (+ <LemonBanner+ type="warning"+ className="mb-2 mt-4"+ action={{+ children: 'Reconnect',+ disableClientSideRouting: true,+ to: api.integrations.authorizeUrl({ kind: affected.kind, next: window.location.pathname }),+ disabledReason: restrictedReason,+ }}+ >+ Your {app.name} connection stops working on {dayjs(app.retiresOn).format('MMMM D, YYYY')}. Reconnect it to+ keep your marketing data syncing. Nothing else about your setup changes.+ </LemonBanner>+ )+}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/MarketingAnalyticsSettings.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/MarketingAnalyticsSettings.tsxindex 0af91f920d0f..def46f6d2ea2 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/MarketingAnalyticsSettings.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/MarketingAnalyticsSettings.tsx@@ -9,6 +9,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { LegacyOAuthReconnectBanner } from '../LegacyOAuthReconnectBanner'import { AttributionSettings } from './AttributionSettings'import { ConversionGoalsConfiguration } from './ConversionGoalsConfiguration'import { ExternalDataSourceConfiguration } from './ExternalDataSourceConfiguration'@@ -32,6 +33,7 @@ export function MarketingAnalyticsSettings({}}/>)}+ <LegacyOAuthReconnectBanner /><ExternalDataSourceConfiguration /><SceneDivider /><ConversionGoalsConfiguration />diff --git a/posthog/management/commands/flag_legacy_oauth_integrations.py b/posthog/management/commands/flag_legacy_oauth_integrations.pynew file mode 100644index 000000000000..4bb3981629d2--- /dev/null+++ b/posthog/management/commands/flag_legacy_oauth_integrations.py@@ -0,0 +1,75 @@+from django.conf import settings+from django.core.management.base import BaseCommand, CommandError+from django.db.models import F, Func, JSONField, Value++import structlog++from posthog.models.integration import CONFIG_LEGACY_OAUTH_CLIENT, Integration, issuing_oauth_client_ids++logger = structlog.get_logger(__name__)++# Kinds whose current client id we can name, so `aud` can be compared against it.+CURRENT_CLIENT_ID_SETTING = {"bing-ads": "BING_ADS_CLIENT_ID"}++# JSON-level merges so a concurrent refresh's read-modify-write of `config` (backoff counters,+# refreshed_at) can't be clobbered by this pass, nor vice versa.+_FLAG_SET = Func(+ F("config"),+ Value(f"{{{CONFIG_LEGACY_OAUTH_CLIENT}}}"),+ function="jsonb_set",+ template="%(function)s(%(expressions)s::text[], 'true'::jsonb)",+ output_field=JSONField(),+)+_FLAG_CLEARED = Func(+ F("config"),+ Value(CONFIG_LEGACY_OAUTH_CLIENT),+ template="%(expressions)s",+ arg_joiner=" - ",+ output_field=JSONField(),+)+++class Command(BaseCommand):+ """Classify OAuth connections by the app they were established with.++ Safe to re-run, and worth re-running: the refresh sweep rewrites `config` wholesale, so a+ refresh whose in-memory snapshot predates this pass can overwrite the flag on that row with+ its own (equally valid) verdict. Both paths converge on the same answer, and a second pass+ settles any row that lost the race.+ """++ help = "Flag OAuth integrations still connected through a superseded client id, so the product can ask those teams to reconnect before the old app is retired."++ def add_arguments(self, parser):+ parser.add_argument("--kind", default="bing-ads", choices=sorted(CURRENT_CLIENT_ID_SETTING))+ parser.add_argument("--dry-run", action="store_true", help="Report the counts without writing")++ def handle(self, *args, **options):+ kind = options["kind"]+ dry_run = options["dry_run"]++ current_client_id = getattr(settings, CURRENT_CLIENT_ID_SETTING[kind], "")+ if not current_client_id:+ raise CommandError(f"{CURRENT_CLIENT_ID_SETTING[kind]} is not set, so nothing can be compared against it")++ counts = {"legacy": 0, "current": 0, "unknown": 0}+ for integration in Integration.objects.filter(kind=kind).iterator():+ client_ids = issuing_oauth_client_ids(integration)+ if not client_ids:+ # No id_token to read, so the refresh path stays the only signal for this row.+ counts["unknown"] += 1+ continue++ is_legacy = current_client_id not in client_ids+ counts["legacy" if is_legacy else "current"] += 1++ already_flagged = bool(integration.config.get(CONFIG_LEGACY_OAUTH_CLIENT))+ if already_flagged == is_legacy or dry_run:+ continue++ Integration.objects.filter(pk=integration.pk).update(config=_FLAG_SET if is_legacy else _FLAG_CLEARED)++ self.stdout.write(+ f"{kind}: {counts['legacy']} on a superseded client, {counts['current']} current, "+ f"{counts['unknown']} without an id_token to read" + (" (dry run, nothing written)" if dry_run else "")+ )diff --git a/posthog/management/commands/test/test_flag_legacy_oauth_integrations.py b/posthog/management/commands/test/test_flag_legacy_oauth_integrations.pynew file mode 100644index 000000000000..34f3797c9b47--- /dev/null+++ b/posthog/management/commands/test/test_flag_legacy_oauth_integrations.py@@ -0,0 +1,64 @@+import json+import base64++from posthog.test.base import BaseTest++from django.core.management import call_command+from django.test import override_settings++from parameterized import parameterized++from posthog.models.integration import CONFIG_LEGACY_OAUTH_CLIENT, Integration+++def _id_token(audience: str | list[str]) -> str:+ payload = base64.urlsafe_b64encode(json.dumps({"aud": audience, "oid": "user-oid"}).encode()).decode().rstrip("=")+ return f"header.{payload}.signature"+++@override_settings(BING_ADS_CLIENT_ID="current-app-id")+class TestFlagLegacyOauthIntegrations(BaseTest):+ @parameterized.expand(+ [+ # Connected through the superseded app: this is the population that breaks on retirement.+ ("legacy_client", _id_token("old-app-id"), False, True),+ # Already on the current app - a stale flag here would nag a team with nothing to do.+ ("current_client_clears_stale_flag", _id_token("current-app-id"), True, False),+ # `aud` is a string or a list per RFC 7519. Reading only the string shape would drop+ # list-shaped tokens into "unknown", silently leaving those teams out of the campaign.+ ("legacy_client_in_aud_list", _id_token(["old-app-id"]), False, True),+ ("current_client_in_aud_list", _id_token(["current-app-id", "other-audience"]), True, False),+ # Nothing to read, so the command must not guess either way.+ ("no_id_token", None, False, False),+ ]+ )+ def test_flags_integrations_by_issuing_client(self, _name, id_token, initial_flag, expected_flag):+ config = {"expires_in": 1000}+ if initial_flag:+ config[CONFIG_LEGACY_OAUTH_CLIENT] = True+ integration = Integration.objects.create(+ team=self.team,+ kind="bing-ads",+ integration_id="user-oid",+ config=config,+ sensitive_config={"access_token": "token", "id_token": id_token},+ )++ call_command("flag_legacy_oauth_integrations")++ integration.refresh_from_db()+ assert integration.config.get(CONFIG_LEGACY_OAUTH_CLIENT, False) == expected_flag++ def test_dry_run_reports_without_writing(self):+ integration = Integration.objects.create(+ team=self.team,+ kind="bing-ads",+ integration_id="user-oid",+ config={},+ sensitive_config={"access_token": "token", "id_token": _id_token("old-app-id")},+ )++ call_command("flag_legacy_oauth_integrations", "--dry-run")++ integration.refresh_from_db()+ assert CONFIG_LEGACY_OAUTH_CLIENT not in integration.configdiff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 727855d6cc6e..833c108ee5df 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -107,6 +107,9 @@ REFRESH_BACKOFF_BASE_SECONDS = 120REFRESH_BACKOFF_MAX_SECONDS = 3600REFRESH_TERMINAL_FAILURE_COUNT = 5+# `config` key flagging a grant that only the legacy fallback credentials can refresh.+CONFIG_LEGACY_OAUTH_CLIENT = "oauth_uses_legacy_client"+# Values for the counter's `reason` label, bucketed from the OAuth error response.REFRESH_FAILURE_REASON_INVALID_GRANT = "invalid_grant"REFRESH_FAILURE_REASON_INVALID_CLIENT = "invalid_client"@@ -181,6 +184,49 @@ def record_refresh_success(integration: "Integration") -> None:integration.config.pop(key, None)+def record_oauth_client_used(integration: "Integration", *, used_fallback: bool) -> None:+ """Track whether the grant still depends on the legacy (fallback) OAuth credentials.++ A refresh token minted by a since-migrated app can only be refreshed by that app's+ credentials, so a successful fallback refresh identifies exactly the connections that break+ when the legacy app is retired. The flag rides on `config`, which the API exposes, so the+ product can tell those teams to reconnect. Reconnecting mints a grant on the primary+ credentials and replaces `config` wholesale, which clears the flag.+ """+ if used_fallback:+ integration.config[CONFIG_LEGACY_OAUTH_CLIENT] = True+ else:+ integration.config.pop(CONFIG_LEGACY_OAUTH_CLIENT, None)+++def issuing_oauth_client_ids(integration: "Integration") -> list[str]:+ """The OAuth client ids the connection was established with. Empty when that can't be read.++ OIDC puts the client id in the id_token's `aud` claim, and we keep the id_token from the+ authorization exchange - refreshes only overwrite the access and refresh tokens. So this reads+ the app the customer actually connected through, which is knowable for connections that already+ exist, without waiting for a refresh to reveal it.++ `aud` is a string or a list of strings per RFC 7519, so both shapes are normalized here.+ Callers should test membership rather than assume a single value: treating a list-shaped+ audience as unreadable would silently drop those connections from the reconnect campaign.+ """+ id_token = integration.sensitive_config.get("id_token")+ if not id_token:+ return []+ try:+ claims = _decode_jwt_payload(id_token) or {}+ except Exception:+ logger.warning("Failed to decode id_token", integration_id=integration.id, kind=integration.kind)+ return []+ audience = claims.get("aud")+ if isinstance(audience, str):+ return [audience]+ if isinstance(audience, list):+ return [entry for entry in audience if isinstance(entry, str)]+ return []++def refresh_backoff_active(integration: "Integration") -> bool:"""Whether the refresh sweep should skip this integration. Reconnecting resets the state(the OAuth callback replaces `config` wholesale), and on-demand API refreshes bypass this."""@@ -1559,6 +1605,7 @@ class OauthIntegration:else:logger.info(f"Refreshed access token for {self}")record_refresh_success(self.integration)+ record_oauth_client_used(self.integration, used_fallback=used_fallback)self.integration.sensitive_config["access_token"] = config["access_token"]# Some providers (e.g. Atlassian/Jira) rotate refresh tokens — eachdiff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 1cab61dc2902..31f3a80aa9d6 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -31,6 +31,7 @@ from posthog.egress.limiter.policies import Priorityfrom posthog.models.github_integration_base import GITHUB_BRANCH_CACHE_TTL_SECONDS, GITHUB_REPOSITORY_CACHE_TTL_SECONDSfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.integration import (+ CONFIG_LEGACY_OAUTH_CLIENT,MISSING_CERT_PATH,TLS,Authority,@@ -608,21 +609,34 @@ class TestOauthIntegrationModel(BaseTest):@parameterized.expand([- # Primary works: the fallback must not fire, even when configured.- ("primary_ok", True, [(200, "primary-token")], "primary-token", "", 1),- # A token issued by the previous app only refreshes with the fallback pair.- ("fallback_rescues", True, [(401, None), (200, "fallback-token")], "fallback-token", "", 2),+ # Primary works: the fallback must not fire, even when configured, and the grant is no+ # longer tied to the legacy app - so the reconnect prompt must stop showing.+ ("primary_ok", True, [(200, "primary-token")], "primary-token", "", 1, True, False),+ # A token issued by the previous app only refreshes with the fallback pair. Flagging it+ # is what identifies the connections that break when the legacy app is retired.+ ("fallback_rescues", True, [(401, None), (200, "fallback-token")], "fallback-token", "", 2, False, True),# Both credentials failing still marks the integration errored so the reconnect banner shows.- ("both_fail", True, [(401, None), (401, None)], None, "TOKEN_REFRESH_FAILED", 2),+ ("both_fail", True, [(401, None), (401, None)], None, "TOKEN_REFRESH_FAILED", 2, True, True),# Without a fallback configured, behavior is identical to before: a single attempt, no retry.- ("no_fallback_no_retry", False, [(401, None)], None, "TOKEN_REFRESH_FAILED", 1),+ ("no_fallback_no_retry", False, [(401, None)], None, "TOKEN_REFRESH_FAILED", 1, False, False),])def test_refresh_falls_back_to_previous_credentials(- self, _name, has_fallback, responses, expected_token, expected_errors, expected_calls+ self,+ _name,+ has_fallback,+ responses,+ expected_token,+ expected_errors,+ expected_calls,+ initial_legacy_flag,+ expected_legacy_flag,):fallbacks = {"bing-ads": {"client_id": "old-app-id", "client_secret": "old-app-secret"}} if has_fallback else {}- integration = self.create_integration(kind="bing-ads", config={"expires_in": 1000})+ config = {"expires_in": 1000}+ if initial_legacy_flag:+ config[CONFIG_LEGACY_OAUTH_CLIENT] = True+ integration = self.create_integration(kind="bing-ads", config=config)with (self.settings(@@ -641,6 +655,7 @@ class TestOauthIntegrationModel(BaseTest):integration.refresh_from_db()assert mock_post.call_count == expected_callsassert integration.errors == expected_errors+ assert integration.config.get(CONFIG_LEGACY_OAUTH_CLIENT, False) == expected_legacy_flagif expected_token is not None:assert integration.sensitive_config["access_token"] == expected_token