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(linkedin_ads): refresh expired OAuth token before syncing (#64731)

Tom Owersea3de3644fad
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
index fb8b728f3f6b..3c4f6534c768 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
@@ -9,7 +9,7 @@ import pyarrow as pa
import structlog
from structlog.types import FilteringBoundLogger
-from posthog.models.integration import Integration
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration
from posthog.temporal.data_imports.naming_convention import NamingConvention
from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat, PartitionMode, SourceResponse
@@ -114,6 +114,18 @@ def linkedin_ads_client(config: LinkedinAdsSourceConfig, team_id: int) -> Linked
# the read surfaces as `OperationalError: the connection is closed`.
close_old_connections()
integration = Integration.objects.get(id=config.linkedin_ads_integration_id, team_id=team_id)
+
+ # LinkedIn access tokens expire (~60 days). Refresh a stale-but-refreshable token here so it gets
+ # renewed instead of 401ing into a forced re-authorization. `access_token_expired` is a no-op when
+ # the integration has no refresh token or expiry metadata, leaving those integrations untouched.
+ oauth_integration = OauthIntegration(integration)
+ if oauth_integration.access_token_expired():
+ oauth_integration.refresh_access_token()
+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED:
+ raise Exception(
+ "Failed to refresh token for LinkedIn Ads integration. Please re-authorize the integration."
+ )
+
if not integration.access_token:
raise ValueError("LinkedIn Ads integration does not have an access token")
return LinkedinAdsClient(integration.access_token)
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/source.py b/posthog/temporal/data_imports/sources/linkedin_ads/source.py
index eb09df5db99e..0e84b573787a 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/source.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/source.py
@@ -43,6 +43,10 @@ class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResu
return {
"REVOKED_ACCESS_TOKEN": None,
"The token used in the request has expired": "Failed to refresh token for LinkedIn Ads integration. Please re-authorize the integration.",
+ # Raised by `linkedin_ads_client` when an expired access token can't be refreshed (revoked
+ # or expired refresh token). The only fix is the user re-authorizing, so stop retrying. The
+ # message is already user-facing, so map it to itself (None).
+ "Failed to refresh token for LinkedIn Ads integration. Please re-authorize the integration.": None,
# LinkedIn rejects a non-numeric Account ID with a 400 whose message names the offending
# key value (volatile) followed by this stable type-coercion phrase. The account id is a
# fixed config value, so retrying can't help — fail fast and tell the user to fix it.
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
index 101032f8ed79..9d51fdc3e4b6 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
@@ -7,7 +7,9 @@ import pytest
from unittest import mock
import pyarrow as pa
+from parameterized import parameterized
+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED
from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
from posthog.temporal.data_imports.sources.generated_configs import LinkedinAdsSourceConfig
from posthog.temporal.data_imports.sources.linkedin_ads.client import LinkedinAdsDailyRateLimitError
@@ -22,6 +24,7 @@ from posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads import (
linkedin_ads_client,
linkedin_ads_source,
)
+from posthog.temporal.data_imports.sources.linkedin_ads.source import LinkedInAdsSource
from products.data_warehouse.backend.types import IncrementalFieldType
@@ -356,6 +359,7 @@ class TestLinkedinAdsClientFunction:
"""Test client creation with no access token raises error."""
mock_integration = mock.MagicMock()
mock_integration.access_token = None
+ mock_integration.sensitive_config = {} # no refresh token → not expired, skips refresh
mock_integration_model.objects.get.return_value = mock_integration
config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456")
@@ -377,6 +381,7 @@ class TestLinkedinAdsClientFunction:
mock_integration = mock.MagicMock()
mock_integration.access_token = "token"
+ mock_integration.sensitive_config = {} # no refresh token → not expired, skips refresh
def fake_get(*args, **kwargs):
calls.append("Integration.objects.get")
@@ -390,6 +395,55 @@ class TestLinkedinAdsClientFunction:
assert calls == ["close_old_connections", "Integration.objects.get"]
[email protected]("posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads.OauthIntegration")
[email protected]("posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads.Integration")
+class TestLinkedinAdsClientTokenRefresh:
+ """Token refresh behaviour of linkedin_ads_client."""
+
+ config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456")
+
+ @parameterized.expand(
+ [
+ ("expired_token_is_refreshed", True),
+ ("valid_token_is_not_refreshed", False),
+ ]
+ )
+ def test_refreshes_only_when_token_is_expired(self, mock_integration_model, mock_oauth_cls, _name, token_expired):
+ integration = mock.MagicMock()
+ integration.access_token = "refreshed-token"
+ integration.errors = ""
+ mock_integration_model.objects.get.return_value = integration
+
+ oauth = mock_oauth_cls.return_value
+ oauth.access_token_expired.return_value = token_expired
+
+ client = linkedin_ads_client(self.config, team_id=789)
+
+ if token_expired:
+ oauth.refresh_access_token.assert_called_once()
+ else:
+ oauth.refresh_access_token.assert_not_called()
+ assert client.access_token == "refreshed-token"
+
+ def test_failed_refresh_raises_non_retryable_message(self, mock_integration_model, mock_oauth_cls):
+ integration = mock.MagicMock()
+ integration.access_token = "stale-token"
+ integration.errors = ERROR_TOKEN_REFRESH_FAILED
+ mock_integration_model.objects.get.return_value = integration
+
+ oauth = mock_oauth_cls.return_value
+ oauth.access_token_expired.return_value = True
+
+ with pytest.raises(Exception) as exc_info:
+ linkedin_ads_client(self.config, team_id=789)
+
+ message = str(exc_info.value)
+ assert "Failed to refresh token for LinkedIn Ads integration" in message
+ # The message must be classified non-retryable so a dead token stops the sync instead of looping.
+ patterns = LinkedInAdsSource().get_non_retryable_errors()
+ assert any(pattern in message for pattern in patterns)
+
+
@mock.patch("posthog.temporal.data_imports.sources.linkedin_ads.linkedin_ads.linkedin_ads_client")
class TestLinkedinAdsSource:
"""Test linkedin_ads_source function."""
diff --git a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py
index 2bcc52c22dfb..3641ff4269fd 100644
--- a/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py
+++ b/posthog/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py
@@ -23,6 +23,7 @@ class TestLinkedInAdsSource:
'LinkedIn API error (404): {"status":404,"code":"RESOURCE_NOT_FOUND","message":"No virtual resource found"}',
"REVOKED_ACCESS_TOKEN",
"The token used in the request has expired",
+ "Failed to refresh token for LinkedIn Ads integration. Please re-authorize the integration.",
'LinkedIn API error (401): {"status":401,"serviceErrorCode":65608,"code":"RESTRICTED_MEMBER","message":"Member is restricted"}',
],
)